neurotk 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.
neurotk-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
neurotk-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: neurotk
3
+ Version: 0.1.0
4
+ Summary: Dataset validation toolkit for neurology brain imaging (NIfTI)
5
+ Author-email: Sakshi Rathi <rathi036@umn.edu>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SakshiRa/neurotk
8
+ Project-URL: Source, https://github.com/SakshiRa/neurotk
9
+ Project-URL: Issues, https://github.com/SakshiRa/neurotk/issues
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy
18
+ Requires-Dist: nibabel
19
+ Requires-Dist: scipy
20
+ Requires-Dist: matplotlib
21
+ Dynamic: license-file
22
+
23
+ [![DOI](https://zenodo.org/badge/1134680274.svg)](https://doi.org/10.5281/zenodo.18252017)
24
+
25
+
26
+ # NeuroTK: Dataset Validation for Neurology Brain Imaging
27
+
28
+ ## Motivation
29
+ Neurology brain imaging datasets are heterogeneous and frequently contain inconsistencies. Geometry, spacing, orientation, and annotation issues occur commonly across CT and MRI collections. These problems often surface late in modeling, when remediation is costly and compromises reproducibility. NeuroTK surfaces issues early, explicitly, and reproducibly to support dataset hygiene prior to analysis.
30
+
31
+ ## Scope
32
+ NeuroTK focuses on dataset quality assurance prior to downstream analysis. It provides dataset-level and file-level validation with structural and geometric consistency checks, and assessment of annotation presence and integrity.
33
+
34
+ - Dataset-level and file-level validation
35
+ - Structural and geometric consistency checks
36
+ - Annotation presence and integrity assessment
37
+
38
+ NeuroTK does not modify scientific data.
39
+
40
+ ## Installation
41
+ ```sh
42
+ pip install neurotk
43
+ ```
44
+
45
+ ## Quickstart
46
+ ```sh
47
+ neurotk validate --images imagesTr --labels labelsTr --out report.json
48
+ ```
49
+
50
+ Inputs are expected as flat directories of NIfTI files, and filenames must match exactly for image–label pairing.
51
+
52
+ ```
53
+ dataset/
54
+ imagesTr/
55
+ case_001.nii.gz
56
+ case_002.nii.gz
57
+ labelsTr/
58
+ case_001.nii.gz
59
+ case_002.nii.gz
60
+ ```
61
+
62
+ ## Output
63
+ NeuroTK emits a JSON report containing a dataset-level summary, per-file diagnostics, and explicit listings of detected issues.
64
+
65
+ ```json
66
+ {
67
+ "summary": {"num_images": 100, "files_with_issues": 7},
68
+ "files": {"case_001.nii.gz": {"issues": ["label_missing"]}}
69
+ }
70
+ ```
71
+
72
+ ## Citation
73
+ If you use NeuroTK in your research, please cite it as follows:
74
+
75
+ ```bibtex
76
+ @software{neurotk,
77
+ title = {NeuroTK: Dataset Validation for Neurology Brain Imaging},
78
+ author = {Sakshi Rathi},
79
+ year = {2026},
80
+ url = {https://github.com/SakshiRa/neurotk},
81
+ note = {Open-source toolkit for dataset validation and quality assurance in neurology brain imaging}
82
+ }
83
+ ```
@@ -0,0 +1,61 @@
1
+ [![DOI](https://zenodo.org/badge/1134680274.svg)](https://doi.org/10.5281/zenodo.18252017)
2
+
3
+
4
+ # NeuroTK: Dataset Validation for Neurology Brain Imaging
5
+
6
+ ## Motivation
7
+ Neurology brain imaging datasets are heterogeneous and frequently contain inconsistencies. Geometry, spacing, orientation, and annotation issues occur commonly across CT and MRI collections. These problems often surface late in modeling, when remediation is costly and compromises reproducibility. NeuroTK surfaces issues early, explicitly, and reproducibly to support dataset hygiene prior to analysis.
8
+
9
+ ## Scope
10
+ NeuroTK focuses on dataset quality assurance prior to downstream analysis. It provides dataset-level and file-level validation with structural and geometric consistency checks, and assessment of annotation presence and integrity.
11
+
12
+ - Dataset-level and file-level validation
13
+ - Structural and geometric consistency checks
14
+ - Annotation presence and integrity assessment
15
+
16
+ NeuroTK does not modify scientific data.
17
+
18
+ ## Installation
19
+ ```sh
20
+ pip install neurotk
21
+ ```
22
+
23
+ ## Quickstart
24
+ ```sh
25
+ neurotk validate --images imagesTr --labels labelsTr --out report.json
26
+ ```
27
+
28
+ Inputs are expected as flat directories of NIfTI files, and filenames must match exactly for image–label pairing.
29
+
30
+ ```
31
+ dataset/
32
+ imagesTr/
33
+ case_001.nii.gz
34
+ case_002.nii.gz
35
+ labelsTr/
36
+ case_001.nii.gz
37
+ case_002.nii.gz
38
+ ```
39
+
40
+ ## Output
41
+ NeuroTK emits a JSON report containing a dataset-level summary, per-file diagnostics, and explicit listings of detected issues.
42
+
43
+ ```json
44
+ {
45
+ "summary": {"num_images": 100, "files_with_issues": 7},
46
+ "files": {"case_001.nii.gz": {"issues": ["label_missing"]}}
47
+ }
48
+ ```
49
+
50
+ ## Citation
51
+ If you use NeuroTK in your research, please cite it as follows:
52
+
53
+ ```bibtex
54
+ @software{neurotk,
55
+ title = {NeuroTK: Dataset Validation for Neurology Brain Imaging},
56
+ author = {Sakshi Rathi},
57
+ year = {2026},
58
+ url = {https://github.com/SakshiRa/neurotk},
59
+ note = {Open-source toolkit for dataset validation and quality assurance in neurology brain imaging}
60
+ }
61
+ ```
@@ -0,0 +1,6 @@
1
+ """NeuroTK package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __all__ = ["__version__"]
6
+ __version__ = "0.1.0"
@@ -0,0 +1,135 @@
1
+ """Command-line interface for dataset validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Dict, List, Optional, Tuple
9
+
10
+ from .report import build_summary
11
+ from .utils import nifti_stem
12
+ from .validate import validate_image, validate_label
13
+
14
+
15
+ def _is_nifti(path: Path) -> bool:
16
+ name = path.name.lower()
17
+ return name.endswith(".nii") or name.endswith(".nii.gz")
18
+
19
+
20
+ def list_nifti_files(directory: Path) -> List[Path]:
21
+ return sorted([p for p in directory.rglob("*") if p.is_file() and _is_nifti(p)])
22
+
23
+
24
+ def _build_label_index(label_files: List[Path]) -> Dict[str, Path]:
25
+ index: Dict[str, Path] = {}
26
+ for path in label_files:
27
+ index[nifti_stem(path.name)] = path
28
+ return index
29
+
30
+
31
+ def _parse_args() -> argparse.Namespace:
32
+ parser = argparse.ArgumentParser(prog="neurotk validate")
33
+ parser.add_argument("--images", required=True, type=Path)
34
+ parser.add_argument("--labels", required=False, type=Path)
35
+ parser.add_argument("--out", required=True, type=Path)
36
+ parser.add_argument("--max-samples", required=False, type=int, default=None)
37
+ return parser.parse_args()
38
+
39
+
40
+ def run() -> int:
41
+ args = _parse_args()
42
+ images_dir: Path = args.images
43
+ labels_dir: Optional[Path] = args.labels
44
+
45
+ if not images_dir.exists() or not images_dir.is_dir():
46
+ raise SystemExit(f"Images directory not found: {images_dir}")
47
+
48
+ image_files = list_nifti_files(images_dir)
49
+ if args.max_samples is not None:
50
+ image_files = image_files[: max(args.max_samples, 0)]
51
+
52
+ label_files: List[Path] = []
53
+ if labels_dir is not None:
54
+ if not labels_dir.exists() or not labels_dir.is_dir():
55
+ raise SystemExit(f"Labels directory not found: {labels_dir}")
56
+ label_files = list_nifti_files(labels_dir)
57
+
58
+ label_index = _build_label_index(label_files)
59
+
60
+ files_report: Dict[str, Dict[str, object]] = {}
61
+ warnings: List[str] = []
62
+ shapes: List[Tuple[int, int, int]] = []
63
+ spacings: List[Tuple[float, float, float]] = []
64
+ orientations: List[Tuple[str, str, str]] = []
65
+ missing_labels: List[str] = []
66
+
67
+ for image_path in image_files:
68
+ image_info, image_issues = validate_image(image_path)
69
+
70
+ shape = image_info.get("shape")
71
+ image_shape = None
72
+ if isinstance(shape, list) and len(shape) == 3:
73
+ image_shape = tuple(shape)
74
+ shapes.append(image_shape)
75
+ spacing = image_info.get("spacing")
76
+ if isinstance(spacing, list) and len(spacing) == 3:
77
+ spacings.append(tuple(float(x) for x in spacing))
78
+ orientation = image_info.get("orientation")
79
+ if isinstance(orientation, list) and len(orientation) == 3:
80
+ orientations.append(tuple(str(x) for x in orientation))
81
+
82
+ label_info = None
83
+ label_issues: List[str] = []
84
+ if labels_dir is not None:
85
+ stem = nifti_stem(image_path.name)
86
+ label_path = label_index.get(stem)
87
+ if label_path is None:
88
+ missing_labels.append(image_path.name)
89
+ label_info, label_issues = validate_label(
90
+ label_path, image_shape
91
+ )
92
+
93
+ issues = image_issues + label_issues
94
+ files_report[image_path.name] = {
95
+ "image": image_info,
96
+ "label": label_info,
97
+ "issues": issues,
98
+ }
99
+
100
+ label_stems = {nifti_stem(p.name) for p in label_files}
101
+ image_stems = {nifti_stem(p.name) for p in image_files}
102
+ missing_images = sorted(list(label_stems - image_stems))
103
+
104
+ files_with_issues = sum(
105
+ 1 for v in files_report.values() if v.get("issues")
106
+ )
107
+
108
+ summary = build_summary(
109
+ image_count=len(image_files),
110
+ label_count=len(label_files),
111
+ missing_labels=missing_labels,
112
+ missing_images=missing_images,
113
+ shapes=shapes,
114
+ spacings=spacings,
115
+ orientations=orientations,
116
+ files_with_issues=files_with_issues,
117
+ )
118
+
119
+ report = {"summary": summary, "files": files_report, "warnings": warnings}
120
+
121
+ args.out.parent.mkdir(parents=True, exist_ok=True)
122
+ with args.out.open("w", encoding="utf-8") as f:
123
+ json.dump(report, f, indent=2)
124
+
125
+ print("Validation complete")
126
+ return 0
127
+
128
+
129
+ def main() -> None:
130
+ """CLI entrypoint."""
131
+ raise SystemExit(run())
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
@@ -0,0 +1,17 @@
1
+ """NIfTI input helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Tuple
7
+
8
+ import nibabel as nib
9
+ import numpy as np
10
+
11
+
12
+ def load_nifti(path: Path) -> Tuple[nib.Nifti1Image, np.ndarray, np.dtype]:
13
+ """Load a NIfTI file and return image, float data, and original dtype."""
14
+ img = nib.load(str(path))
15
+ data = img.get_fdata(dtype=np.float64)
16
+ dtype = np.asarray(img.dataobj).dtype
17
+ return img, data, dtype
@@ -0,0 +1,65 @@
1
+ """Dataset-level aggregation and report formatting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from typing import Dict, Iterable, List, Optional, Tuple
7
+
8
+ import numpy as np
9
+
10
+
11
+ def _modal(values: Iterable[Tuple]) -> Optional[Tuple]:
12
+ items = list(values)
13
+ if not items:
14
+ return None
15
+ return Counter(items).most_common(1)[0][0]
16
+
17
+
18
+ def build_summary(
19
+ image_count: int,
20
+ label_count: int,
21
+ missing_labels: List[str],
22
+ missing_images: List[str],
23
+ shapes: List[Tuple[int, int, int]],
24
+ spacings: List[Tuple[float, float, float]],
25
+ orientations: List[Tuple[str, str, str]],
26
+ files_with_issues: int,
27
+ ) -> Dict[str, object]:
28
+ modal_shape = _modal(shapes)
29
+ shape_deviation_count = 0
30
+ if modal_shape is not None:
31
+ shape_deviation_count = sum(1 for s in shapes if s != modal_shape)
32
+
33
+ spacing_mean = None
34
+ spacing_std = None
35
+ if spacings:
36
+ spacing_arr = np.array(spacings, dtype=float)
37
+ spacing_mean = spacing_arr.mean(axis=0).tolist()
38
+ spacing_std = spacing_arr.std(axis=0).tolist()
39
+
40
+ orientation_modal = _modal(orientations)
41
+ orientation_deviation_count = 0
42
+ orientation_counts = None
43
+ if orientations:
44
+ orientation_counts = {
45
+ ",".join(k): v for k, v in Counter(orientations).items()
46
+ }
47
+ if orientation_modal is not None:
48
+ orientation_deviation_count = sum(
49
+ 1 for o in orientations if o != orientation_modal
50
+ )
51
+
52
+ return {
53
+ "num_images": image_count,
54
+ "num_labels": label_count,
55
+ "missing_label_images": missing_labels,
56
+ "missing_image_labels": missing_images,
57
+ "modal_shape": list(modal_shape) if modal_shape else None,
58
+ "shape_deviation_count": shape_deviation_count,
59
+ "spacing_mean": spacing_mean,
60
+ "spacing_std": spacing_std,
61
+ "orientation_modal": list(orientation_modal) if orientation_modal else None,
62
+ "orientation_counts": orientation_counts,
63
+ "orientation_deviation_count": orientation_deviation_count,
64
+ "files_with_issues": files_with_issues,
65
+ }
@@ -0,0 +1,55 @@
1
+ """Utility helpers for validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, Iterable, List, Optional, Tuple
6
+
7
+ import nibabel as nib
8
+ import numpy as np
9
+
10
+
11
+ def nifti_stem(path_name: str) -> str:
12
+ """Return filename stem without NIfTI extensions."""
13
+ if path_name.endswith(".nii.gz"):
14
+ return path_name[:-7]
15
+ if path_name.endswith(".nii"):
16
+ return path_name[:-4]
17
+ return path_name.rsplit(".", 1)[0]
18
+
19
+
20
+ def orientation_codes(affine: np.ndarray) -> Optional[Tuple[str, str, str]]:
21
+ """Return orientation codes from affine, or None on failure."""
22
+ try:
23
+ codes = nib.orientations.aff2axcodes(affine)
24
+ except Exception:
25
+ return None
26
+ return codes
27
+
28
+
29
+ def safe_stats(data: np.ndarray) -> Dict[str, Optional[float]]:
30
+ """Compute stats on finite values; return None when unavailable."""
31
+ finite = np.isfinite(data)
32
+ if not np.any(finite):
33
+ return {"min": None, "max": None, "mean": None, "std": None}
34
+ vals = data[finite]
35
+ return {
36
+ "min": float(np.min(vals)),
37
+ "max": float(np.max(vals)),
38
+ "mean": float(np.mean(vals)),
39
+ "std": float(np.std(vals)),
40
+ }
41
+
42
+
43
+ def spacing_from_header(img: nib.Nifti1Image) -> Optional[Tuple[float, float, float]]:
44
+ """Extract voxel spacing for the first three axes."""
45
+ zooms = img.header.get_zooms()
46
+ if len(zooms) < 3:
47
+ return None
48
+ return (float(zooms[0]), float(zooms[1]), float(zooms[2]))
49
+
50
+
51
+ def to_list(values: Optional[Iterable]) -> Optional[List]:
52
+ """Convert iterable to list, preserving None."""
53
+ if values is None:
54
+ return None
55
+ return list(values)
@@ -0,0 +1,161 @@
1
+ """Per-file validation logic for NIfTI datasets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ import numpy as np
9
+
10
+ from .io import load_nifti
11
+ from .utils import orientation_codes, safe_stats, spacing_from_header, to_list
12
+
13
+
14
+ def _image_info_template(path: Path) -> Dict[str, object]:
15
+ return {
16
+ "path": str(path),
17
+ "readable": False,
18
+ "dimensionality": None,
19
+ "shape": None,
20
+ "spacing": None,
21
+ "orientation": None,
22
+ "affine_determinant": None,
23
+ "dtype": None,
24
+ "has_nan": None,
25
+ "has_inf": None,
26
+ "stats": None,
27
+ }
28
+
29
+
30
+ def _label_info_template(path: Optional[Path]) -> Dict[str, object]:
31
+ return {
32
+ "path": str(path) if path else None,
33
+ "present": path is not None,
34
+ "readable": False,
35
+ "dimensionality": None,
36
+ "shape": None,
37
+ "shape_matches_image": None,
38
+ "integer_valued": None,
39
+ "unique_values": None,
40
+ "empty": None,
41
+ }
42
+
43
+
44
+ def validate_image(path: Path) -> Tuple[Dict[str, object], List[str]]:
45
+ """Validate a single image file."""
46
+ info = _image_info_template(path)
47
+ issues: List[str] = []
48
+ try:
49
+ img, data, dtype = load_nifti(path)
50
+ except Exception as exc:
51
+ info["readable"] = False
52
+ info["error"] = f"{type(exc).__name__}: {exc}"
53
+ issues.append("image_not_readable")
54
+ return info, issues
55
+
56
+ info["readable"] = True
57
+ info["dtype"] = str(dtype)
58
+ info["dimensionality"] = int(img.ndim)
59
+ info["shape"] = to_list(img.shape)
60
+
61
+ if img.ndim != 3:
62
+ issues.append("image_dimensionality_not_3")
63
+
64
+ spacing = spacing_from_header(img)
65
+ info["spacing"] = to_list(spacing)
66
+ if spacing is None:
67
+ issues.append("image_spacing_missing")
68
+
69
+ orientation = orientation_codes(img.affine)
70
+ info["orientation"] = to_list(orientation)
71
+ if orientation is None:
72
+ issues.append("image_orientation_missing")
73
+
74
+ try:
75
+ det = float(np.linalg.det(img.affine))
76
+ except Exception as exc:
77
+ det = None
78
+ info["affine_error"] = f"{type(exc).__name__}: {exc}"
79
+ info["affine_determinant"] = det
80
+ if det is None or det == 0.0:
81
+ issues.append("image_affine_singular")
82
+
83
+ try:
84
+ info["has_nan"] = bool(np.isnan(data).any())
85
+ info["has_inf"] = bool(np.isinf(data).any())
86
+ except Exception as exc:
87
+ info["nan_inf_error"] = f"{type(exc).__name__}: {exc}"
88
+ issues.append("image_nan_inf_check_failed")
89
+
90
+ if info.get("has_nan"):
91
+ issues.append("image_contains_nan")
92
+ if info.get("has_inf"):
93
+ issues.append("image_contains_inf")
94
+
95
+ try:
96
+ info["stats"] = safe_stats(data)
97
+ if info["stats"]["min"] is None:
98
+ issues.append("image_stats_no_finite")
99
+ except Exception as exc:
100
+ info["stats_error"] = f"{type(exc).__name__}: {exc}"
101
+ issues.append("image_stats_failed")
102
+
103
+ return info, issues
104
+
105
+
106
+ def validate_label(
107
+ path: Optional[Path], image_shape: Optional[Tuple[int, ...]]
108
+ ) -> Tuple[Dict[str, object], List[str]]:
109
+ """Validate a single label file."""
110
+ info = _label_info_template(path)
111
+ issues: List[str] = []
112
+ if path is None:
113
+ issues.append("label_missing")
114
+ return info, issues
115
+
116
+ try:
117
+ img, data, _dtype = load_nifti(path)
118
+ except Exception as exc:
119
+ info["readable"] = False
120
+ info["error"] = f"{type(exc).__name__}: {exc}"
121
+ issues.append("label_not_readable")
122
+ return info, issues
123
+
124
+ info["readable"] = True
125
+ info["dimensionality"] = int(img.ndim)
126
+ info["shape"] = to_list(img.shape)
127
+
128
+ if img.ndim != 3:
129
+ issues.append("label_dimensionality_not_3")
130
+
131
+ if image_shape is not None:
132
+ matches = tuple(img.shape) == tuple(image_shape)
133
+ info["shape_matches_image"] = matches
134
+ if not matches:
135
+ issues.append("label_shape_mismatch")
136
+
137
+ try:
138
+ finite = np.isfinite(data)
139
+ if not np.any(finite):
140
+ info["integer_valued"] = False
141
+ issues.append("label_no_finite_values")
142
+ else:
143
+ vals = data[finite]
144
+ info["integer_valued"] = bool(np.all(vals == np.round(vals)))
145
+ if not info["integer_valued"]:
146
+ issues.append("label_not_integer_valued")
147
+ except Exception as exc:
148
+ info["integer_error"] = f"{type(exc).__name__}: {exc}"
149
+ issues.append("label_integer_check_failed")
150
+
151
+ try:
152
+ unique_vals = np.unique(data)
153
+ info["unique_values"] = [int(v) for v in unique_vals.tolist()]
154
+ info["empty"] = bool(np.all(unique_vals == 0))
155
+ if info["empty"]:
156
+ issues.append("label_empty_mask")
157
+ except Exception as exc:
158
+ info["unique_error"] = f"{type(exc).__name__}: {exc}"
159
+ issues.append("label_unique_values_failed")
160
+
161
+ return info, issues
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: neurotk
3
+ Version: 0.1.0
4
+ Summary: Dataset validation toolkit for neurology brain imaging (NIfTI)
5
+ Author-email: Sakshi Rathi <rathi036@umn.edu>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/SakshiRa/neurotk
8
+ Project-URL: Source, https://github.com/SakshiRa/neurotk
9
+ Project-URL: Issues, https://github.com/SakshiRa/neurotk/issues
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy
18
+ Requires-Dist: nibabel
19
+ Requires-Dist: scipy
20
+ Requires-Dist: matplotlib
21
+ Dynamic: license-file
22
+
23
+ [![DOI](https://zenodo.org/badge/1134680274.svg)](https://doi.org/10.5281/zenodo.18252017)
24
+
25
+
26
+ # NeuroTK: Dataset Validation for Neurology Brain Imaging
27
+
28
+ ## Motivation
29
+ Neurology brain imaging datasets are heterogeneous and frequently contain inconsistencies. Geometry, spacing, orientation, and annotation issues occur commonly across CT and MRI collections. These problems often surface late in modeling, when remediation is costly and compromises reproducibility. NeuroTK surfaces issues early, explicitly, and reproducibly to support dataset hygiene prior to analysis.
30
+
31
+ ## Scope
32
+ NeuroTK focuses on dataset quality assurance prior to downstream analysis. It provides dataset-level and file-level validation with structural and geometric consistency checks, and assessment of annotation presence and integrity.
33
+
34
+ - Dataset-level and file-level validation
35
+ - Structural and geometric consistency checks
36
+ - Annotation presence and integrity assessment
37
+
38
+ NeuroTK does not modify scientific data.
39
+
40
+ ## Installation
41
+ ```sh
42
+ pip install neurotk
43
+ ```
44
+
45
+ ## Quickstart
46
+ ```sh
47
+ neurotk validate --images imagesTr --labels labelsTr --out report.json
48
+ ```
49
+
50
+ Inputs are expected as flat directories of NIfTI files, and filenames must match exactly for image–label pairing.
51
+
52
+ ```
53
+ dataset/
54
+ imagesTr/
55
+ case_001.nii.gz
56
+ case_002.nii.gz
57
+ labelsTr/
58
+ case_001.nii.gz
59
+ case_002.nii.gz
60
+ ```
61
+
62
+ ## Output
63
+ NeuroTK emits a JSON report containing a dataset-level summary, per-file diagnostics, and explicit listings of detected issues.
64
+
65
+ ```json
66
+ {
67
+ "summary": {"num_images": 100, "files_with_issues": 7},
68
+ "files": {"case_001.nii.gz": {"issues": ["label_missing"]}}
69
+ }
70
+ ```
71
+
72
+ ## Citation
73
+ If you use NeuroTK in your research, please cite it as follows:
74
+
75
+ ```bibtex
76
+ @software{neurotk,
77
+ title = {NeuroTK: Dataset Validation for Neurology Brain Imaging},
78
+ author = {Sakshi Rathi},
79
+ year = {2026},
80
+ url = {https://github.com/SakshiRa/neurotk},
81
+ note = {Open-source toolkit for dataset validation and quality assurance in neurology brain imaging}
82
+ }
83
+ ```
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ neurotk/__init__.py
5
+ neurotk/cli.py
6
+ neurotk/io.py
7
+ neurotk/report.py
8
+ neurotk/utils.py
9
+ neurotk/validate.py
10
+ neurotk.egg-info/PKG-INFO
11
+ neurotk.egg-info/SOURCES.txt
12
+ neurotk.egg-info/dependency_links.txt
13
+ neurotk.egg-info/entry_points.txt
14
+ neurotk.egg-info/requires.txt
15
+ neurotk.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ neurotk = neurotk.cli:main
@@ -0,0 +1,4 @@
1
+ numpy
2
+ nibabel
3
+ scipy
4
+ matplotlib
@@ -0,0 +1 @@
1
+ neurotk
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "neurotk"
7
+ version = "0.1.0"
8
+ description = "Dataset validation toolkit for neurology brain imaging (NIfTI)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+
13
+ authors = [
14
+ { name = "Sakshi Rathi", email = "rathi036@umn.edu" }
15
+ ]
16
+
17
+ dependencies = [
18
+ "numpy",
19
+ "nibabel",
20
+ "scipy",
21
+ "matplotlib"
22
+ ]
23
+
24
+ classifiers = [
25
+ "Programming Language :: Python :: 3",
26
+ "Intended Audience :: Science/Research",
27
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
28
+ "License :: OSI Approved :: Apache Software License"
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/SakshiRa/neurotk"
33
+ Source = "https://github.com/SakshiRa/neurotk"
34
+ Issues = "https://github.com/SakshiRa/neurotk/issues"
35
+
36
+ [project.scripts]
37
+ neurotk = "neurotk.cli:main"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+