bone-microarchitecture 0.3.0__tar.gz → 0.3.2__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.
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/CHANGELOG.md +16 -0
- {bone_microarchitecture-0.3.0/src/bone_microarchitecture.egg-info → bone_microarchitecture-0.3.2}/PKG-INFO +35 -12
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/README.md +34 -11
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/pyproject.toml +1 -1
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/__init__.py +2 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/batch.py +56 -36
- bone_microarchitecture-0.3.2/src/bone_microarchitecture/cache.py +60 -0
- bone_microarchitecture-0.3.2/src/bone_microarchitecture/case.py +156 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/method.py +2 -2
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/opencl.py +1 -3
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/pipeline.py +32 -10
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/thickness.py +55 -28
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2/src/bone_microarchitecture.egg-info}/PKG-INFO +35 -12
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture.egg-info/SOURCES.txt +5 -0
- bone_microarchitecture-0.3.2/tests/test_analysis_region.py +82 -0
- bone_microarchitecture-0.3.2/tests/test_backends.py +84 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_batch.py +51 -15
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_ipl_alignment.py +35 -4
- bone_microarchitecture-0.3.2/tests/test_region_cache.py +48 -0
- bone_microarchitecture-0.3.2/tests/test_region_case.py +93 -0
- bone_microarchitecture-0.3.0/tests/test_backends.py +0 -21
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/LICENSE +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/MANIFEST.in +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/setup.cfg +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/cli.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/geometry.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/metal.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/metrics.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/pores.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/results.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture.egg-info/dependency_links.txt +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture.egg-info/entry_points.txt +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture.egg-info/requires.txt +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture.egg-info/top_level.txt +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_attribution.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_geometry.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_metrics.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_package.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_pipeline.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_results.py +0 -0
- {bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/tests/test_thickness.py +0 -0
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.3.2 - 2026-11-25
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Constrain sphere centres to the requested common/functional region before fitting, retaining native distance/ridge context and cortical pore selection.
|
|
10
|
+
- Follow documented IPL `suppress_boundary=2` centre eligibility without the extra whole-sphere image-edge rejection, consistently on CPU, Metal and OpenCL. Keep ridge and radius-correction epsilon settings unchanged.
|
|
11
|
+
- Store common-region and Functional Bone maps in their own analysis folders. Reuse only compatible final outputs, fingerprint input contents/geometry and detect missing or rewritten maps; do not cache distance fields.
|
|
12
|
+
- Record scientific method `ipl-aligned-region-v3`, invalidating earlier post-hoc native-map summaries and maps made with whole-sphere image-edge rejection.
|
|
13
|
+
|
|
14
|
+
## 0.3.1 - 2026-10-14
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Prefer actual OpenCL GPU devices and compile the kernel before automatic selection. Fall back to CPU with an explicit reason if bindings, GPU drivers or kernel compilation are unavailable; explicit GPU requests still fail clearly.
|
|
19
|
+
- Log the diameter backend and device before batch calculations and retain device provenance in CSV sidecars and native-map manifests, including reused maps.
|
|
20
|
+
|
|
5
21
|
## 0.3.0 - 2026-10-07
|
|
6
22
|
|
|
7
23
|
### Changed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bone-microarchitecture
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Lightweight bone microarchitecture measurements from masks and calibrated grayscale arrays.
|
|
5
5
|
Author: Matthias Walle
|
|
6
6
|
License-Expression: MIT
|
|
@@ -69,6 +69,19 @@ Exact Hildebrand sphere fitting supports three diameter-accumulation backends:
|
|
|
69
69
|
|
|
70
70
|
Use `thickness_backend="auto"` to select Metal on macOS when available, OpenCL on Windows/Linux when available, and CPU otherwise.
|
|
71
71
|
|
|
72
|
+
Automatic OpenCL selection requires an actual GPU and a successfully compiled
|
|
73
|
+
kernel; a CPU OpenCL runtime is not considered GPU acceleration. Batch logs
|
|
74
|
+
identify the device and any CPU fallback reason before computation. CSV JSON
|
|
75
|
+
sidecars and map manifests record `thickness_backend`, `thickness_device`,
|
|
76
|
+
`thickness_gpu`, and `thickness_backend_reason`. Reused maps retain their original
|
|
77
|
+
backend provenance; reusing maps does not run the GPU again.
|
|
78
|
+
|
|
79
|
+
Only sphere-diameter accumulation is GPU-accelerated. Distance transforms,
|
|
80
|
+
ridge selection, statistics and image I/O remain on CPU. Installing
|
|
81
|
+
`bone-microarchitecture[gpu]` installs platform-specific Python bindings, not
|
|
82
|
+
the GPU manufacturer's driver/OpenCL runtime. Explicit GPU requests raise an
|
|
83
|
+
error when unavailable; `auto` keeps CPU-only systems usable.
|
|
84
|
+
|
|
72
85
|
Optional installs:
|
|
73
86
|
|
|
74
87
|
```bash
|
|
@@ -97,7 +110,7 @@ pip install "bone-microarchitecture[gpu]"
|
|
|
97
110
|
|
|
98
111
|
## IPL-aligned measurement definitions
|
|
99
112
|
|
|
100
|
-
The standard method is `ipl-aligned-
|
|
113
|
+
The standard method is `ipl-aligned-region-v3`, replacing the previous definitions.
|
|
101
114
|
It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
|
|
102
115
|
|
|
103
116
|
- Pore selection uses enclosed XY seeds, Z-only hysteresis growth, a second XY
|
|
@@ -109,18 +122,28 @@ It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
|
|
|
109
122
|
supplied script's denominator. `Ct.Po` is therefore not necessarily `1 - Ct.BV/Ct.TV`.
|
|
110
123
|
- `Tb.Sp` and ridge spacing retain the full bone-phase context before restricting
|
|
111
124
|
reporting to the trabecular compartment. `Tb.N` is inverse mean spacing.
|
|
112
|
-
- Hildebrand fitting
|
|
113
|
-
|
|
114
|
-
|
|
125
|
+
- Hildebrand fitting follows the documented IPL `suppress_boundary=2` policy:
|
|
126
|
+
distances and ridges use the full input phase, then sphere centres are
|
|
127
|
+
restricted to the reporting region. Spheres may extend beyond that region or
|
|
128
|
+
reach an acquired image face; output is clipped to the image and reporting
|
|
129
|
+
phase. No fixed slice strip is blanked. CPU, Metal and OpenCL share this policy.
|
|
115
130
|
The optional `edt` preview remains a distance-transform approximation.
|
|
116
131
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
132
|
+
Pass `analysis_mask` to constrain sphere centres and reporting to a common or
|
|
133
|
+
Functional Bone region. Distances and ridge extraction retain full native phase
|
|
134
|
+
context: the ROI is not a new bone/marrow wall. Native cortical pore selection
|
|
135
|
+
is preserved before intersection; `Ct.Po.Mask` records it independently of diameter.
|
|
136
|
+
|
|
137
|
+
Each analysis owns its final maps. Native batch maps remain in `xct/maps/`;
|
|
138
|
+
common-region maps are in `xct/registered_measurements/maps/`. The file-level
|
|
139
|
+
`bone_microarchitecture.case.run_microarchitecture_case` helper saves Functional
|
|
140
|
+
Bone maps in `output_dir/maps/`. Unchanged inputs, geometry, region and settings
|
|
141
|
+
reuse that analysis's complete final outputs. Changed input contents or missing/
|
|
142
|
+
rewritten maps invalidate reuse. Distance fields are recomputed, not cached.
|
|
143
|
+
`restrict_measurements` remains a post-hoc reporting helper; it cannot change
|
|
144
|
+
sphere eligibility and is not used for common/functional-region calculations.
|
|
145
|
+
|
|
146
|
+
Results and CSV JSON sidecars record `ipl-aligned-region-v3` separately from the
|
|
124
147
|
package version. Batch hashes invalidate pre-alignment maps and measurements;
|
|
125
148
|
legacy results must be recalculated, not mixed into a new comparison. Ratios
|
|
126
149
|
remain fractions, not percentages. For `Tb.N`, the CSV Mean is inverse mean
|
|
@@ -28,6 +28,19 @@ Exact Hildebrand sphere fitting supports three diameter-accumulation backends:
|
|
|
28
28
|
|
|
29
29
|
Use `thickness_backend="auto"` to select Metal on macOS when available, OpenCL on Windows/Linux when available, and CPU otherwise.
|
|
30
30
|
|
|
31
|
+
Automatic OpenCL selection requires an actual GPU and a successfully compiled
|
|
32
|
+
kernel; a CPU OpenCL runtime is not considered GPU acceleration. Batch logs
|
|
33
|
+
identify the device and any CPU fallback reason before computation. CSV JSON
|
|
34
|
+
sidecars and map manifests record `thickness_backend`, `thickness_device`,
|
|
35
|
+
`thickness_gpu`, and `thickness_backend_reason`. Reused maps retain their original
|
|
36
|
+
backend provenance; reusing maps does not run the GPU again.
|
|
37
|
+
|
|
38
|
+
Only sphere-diameter accumulation is GPU-accelerated. Distance transforms,
|
|
39
|
+
ridge selection, statistics and image I/O remain on CPU. Installing
|
|
40
|
+
`bone-microarchitecture[gpu]` installs platform-specific Python bindings, not
|
|
41
|
+
the GPU manufacturer's driver/OpenCL runtime. Explicit GPU requests raise an
|
|
42
|
+
error when unavailable; `auto` keeps CPU-only systems usable.
|
|
43
|
+
|
|
31
44
|
Optional installs:
|
|
32
45
|
|
|
33
46
|
```bash
|
|
@@ -56,7 +69,7 @@ pip install "bone-microarchitecture[gpu]"
|
|
|
56
69
|
|
|
57
70
|
## IPL-aligned measurement definitions
|
|
58
71
|
|
|
59
|
-
The standard method is `ipl-aligned-
|
|
72
|
+
The standard method is `ipl-aligned-region-v3`, replacing the previous definitions.
|
|
60
73
|
It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
|
|
61
74
|
|
|
62
75
|
- Pore selection uses enclosed XY seeds, Z-only hysteresis growth, a second XY
|
|
@@ -68,18 +81,28 @@ It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
|
|
|
68
81
|
supplied script's denominator. `Ct.Po` is therefore not necessarily `1 - Ct.BV/Ct.TV`.
|
|
69
82
|
- `Tb.Sp` and ridge spacing retain the full bone-phase context before restricting
|
|
70
83
|
reporting to the trabecular compartment. `Tb.N` is inverse mean spacing.
|
|
71
|
-
- Hildebrand fitting
|
|
72
|
-
|
|
73
|
-
|
|
84
|
+
- Hildebrand fitting follows the documented IPL `suppress_boundary=2` policy:
|
|
85
|
+
distances and ridges use the full input phase, then sphere centres are
|
|
86
|
+
restricted to the reporting region. Spheres may extend beyond that region or
|
|
87
|
+
reach an acquired image face; output is clipped to the image and reporting
|
|
88
|
+
phase. No fixed slice strip is blanked. CPU, Metal and OpenCL share this policy.
|
|
74
89
|
The optional `edt` preview remains a distance-transform approximation.
|
|
75
90
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
91
|
+
Pass `analysis_mask` to constrain sphere centres and reporting to a common or
|
|
92
|
+
Functional Bone region. Distances and ridge extraction retain full native phase
|
|
93
|
+
context: the ROI is not a new bone/marrow wall. Native cortical pore selection
|
|
94
|
+
is preserved before intersection; `Ct.Po.Mask` records it independently of diameter.
|
|
95
|
+
|
|
96
|
+
Each analysis owns its final maps. Native batch maps remain in `xct/maps/`;
|
|
97
|
+
common-region maps are in `xct/registered_measurements/maps/`. The file-level
|
|
98
|
+
`bone_microarchitecture.case.run_microarchitecture_case` helper saves Functional
|
|
99
|
+
Bone maps in `output_dir/maps/`. Unchanged inputs, geometry, region and settings
|
|
100
|
+
reuse that analysis's complete final outputs. Changed input contents or missing/
|
|
101
|
+
rewritten maps invalidate reuse. Distance fields are recomputed, not cached.
|
|
102
|
+
`restrict_measurements` remains a post-hoc reporting helper; it cannot change
|
|
103
|
+
sphere eligibility and is not used for common/functional-region calculations.
|
|
104
|
+
|
|
105
|
+
Results and CSV JSON sidecars record `ipl-aligned-region-v3` separately from the
|
|
83
106
|
package version. Batch hashes invalidate pre-alignment maps and measurements;
|
|
84
107
|
legacy results must be recalculated, not mixed into a new comparison. Ratios
|
|
85
108
|
remain fractions, not percentages. For `Tb.N`, the CSV Mean is inverse mean
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bone-microarchitecture"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.2"
|
|
8
8
|
description = "Lightweight bone microarchitecture measurements from masks and calibrated grayscale arrays."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
{bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/__init__.py
RENAMED
|
@@ -10,6 +10,7 @@ from .pipeline import compute_microarchitecture
|
|
|
10
10
|
from .results import MicroarchitectureResult, PARAMETER_DEFINITIONS
|
|
11
11
|
from .thickness import (
|
|
12
12
|
default_thickness_backend,
|
|
13
|
+
thickness_backend_status,
|
|
13
14
|
hildebrand_thickness_map,
|
|
14
15
|
local_thickness_map,
|
|
15
16
|
trabecular_number_map,
|
|
@@ -27,6 +28,7 @@ __all__ = [
|
|
|
27
28
|
"compute_microarchitecture",
|
|
28
29
|
"run_microarchitecture_batch",
|
|
29
30
|
"default_thickness_backend",
|
|
31
|
+
"thickness_backend_status",
|
|
30
32
|
"hildebrand_thickness_map",
|
|
31
33
|
"local_thickness_map",
|
|
32
34
|
"opencl_hildebrand_thickness_map",
|
{bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/batch.py
RENAMED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections.abc import Callable
|
|
6
|
-
from dataclasses import dataclass
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
7
|
from hashlib import sha256
|
|
8
8
|
import json
|
|
9
9
|
from pathlib import Path
|
|
@@ -25,10 +25,11 @@ from bone_imaging_derivatives import (
|
|
|
25
25
|
from bone_imaging_derivatives.layout import manifest_path, record_output_path, voi_token
|
|
26
26
|
|
|
27
27
|
from .pipeline import compute_microarchitecture
|
|
28
|
+
from .cache import input_fingerprints, output_file_states
|
|
28
29
|
from .method import METHOD_METADATA
|
|
29
30
|
from .metrics import compartment_metrics, masked_mean_sd
|
|
30
31
|
from .results import MicroarchitectureResult, write_measurement_csv
|
|
31
|
-
from .thickness import summary
|
|
32
|
+
from .thickness import summary, thickness_backend_status
|
|
32
33
|
|
|
33
34
|
|
|
34
35
|
_REQUIRED_ROLES = ("bone_segmentation", "periosteal_mask", "trabecular_mask")
|
|
@@ -90,9 +91,9 @@ def run_microarchitecture_batch(
|
|
|
90
91
|
"""Measure every manifest-discovered case and write Microarchitecture outputs.
|
|
91
92
|
|
|
92
93
|
The workflow intentionally only owns derivative discovery and output writing.
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
94
|
+
Each analysis computes its own region-constrained sphere maps, retaining
|
|
95
|
+
full native phase context and pore selection. Registered maps are stored
|
|
96
|
+
beside registered measurements, never substituted for native maps.
|
|
96
97
|
Simple, unambiguous ``.npy`` filenames are accepted when manifests are not
|
|
97
98
|
yet available, primarily for lightweight command-line workflows.
|
|
98
99
|
"""
|
|
@@ -124,15 +125,12 @@ def run_microarchitecture_batch(
|
|
|
124
125
|
if use_common_region and "scan_region_native_common" in case:
|
|
125
126
|
input_roles.append("scan_region_native_common")
|
|
126
127
|
input_ids = tuple(case[role].record_id for role in input_roles)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
native_input_ids = tuple(case[role].record_id for role in native_input_roles)
|
|
131
|
-
settings_hash = _compatibility_hash(input_ids, case_spacing, use_common_region, thickness_method, thickness_backend)
|
|
132
|
-
native_map_hash = _compatibility_hash(native_input_ids, case_spacing, False, thickness_method, thickness_backend)
|
|
128
|
+
fingerprints = input_fingerprints(case[role].path for role in input_roles)
|
|
129
|
+
has_common = "scan_region_native_common" in input_roles
|
|
130
|
+
settings_hash = _compatibility_hash(input_ids, case_spacing, has_common, thickness_method, thickness_backend, fingerprints)
|
|
133
131
|
case_key = _output_case_key(case["bone_segmentation"])
|
|
134
132
|
native_map_records = None if force else _find_compatible_native_map_records(
|
|
135
|
-
existing_records, case_key,
|
|
133
|
+
existing_records, case_key, input_ids, settings_hash, case
|
|
136
134
|
)
|
|
137
135
|
reused = None if force or native_map_records is None else _find_compatible_measurement_record(
|
|
138
136
|
existing_records, case_key, input_ids, settings_hash, case
|
|
@@ -153,6 +151,13 @@ def run_microarchitecture_batch(
|
|
|
153
151
|
native_maps = None if native_map_records is None else _load_native_maps_from_records(native_map_records)
|
|
154
152
|
if native_maps is None:
|
|
155
153
|
native_map_records = None
|
|
154
|
+
backend_status = thickness_backend_status("cpu" if thickness_method == "edt" else thickness_backend)
|
|
155
|
+
_emit(
|
|
156
|
+
progress, subject_id, site, session_id, "backend", "ready",
|
|
157
|
+
f"Diameter accumulation backend={backend_status['thickness_backend']}; "
|
|
158
|
+
f"device={backend_status['thickness_device']}; GPU={backend_status['thickness_gpu']}. "
|
|
159
|
+
f"{backend_status['thickness_backend_reason']}",
|
|
160
|
+
)
|
|
156
161
|
_emit(progress, subject_id, site, session_id, "measure", "started", "Computing microarchitecture")
|
|
157
162
|
result = compute_microarchitecture(
|
|
158
163
|
grayscale=image.array,
|
|
@@ -161,10 +166,10 @@ def run_microarchitecture_batch(
|
|
|
161
166
|
trabecular_mask=masks["trabecular_mask"],
|
|
162
167
|
cortical_mask=masks.get("cortical_mask"),
|
|
163
168
|
spacing=case_spacing,
|
|
169
|
+
analysis_mask=common_mask,
|
|
164
170
|
thickness_method=thickness_method,
|
|
165
|
-
thickness_backend=thickness_backend,
|
|
171
|
+
thickness_backend=backend_status["thickness_backend"],
|
|
166
172
|
)
|
|
167
|
-
native_measurements = result.measurements
|
|
168
173
|
native_maps = result.maps
|
|
169
174
|
resolved_backend = result.metadata["thickness_backend"]
|
|
170
175
|
else:
|
|
@@ -176,26 +181,19 @@ def run_microarchitecture_batch(
|
|
|
176
181
|
session_id,
|
|
177
182
|
"maps",
|
|
178
183
|
"reused",
|
|
179
|
-
"Reused
|
|
184
|
+
"Reused compatible analysis-region maps",
|
|
180
185
|
map_dir,
|
|
181
186
|
)
|
|
182
187
|
_emit(progress, subject_id, site, session_id, "measure", "started", "Summarizing existing microarchitecture maps")
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
)
|
|
189
|
-
resolved_backend = thickness_backend
|
|
188
|
+
backend_status = {
|
|
189
|
+
key: value for key, value in next(iter(native_map_records.values())).metadata.items()
|
|
190
|
+
if key.startswith("thickness_") and key != "thickness_method"
|
|
191
|
+
}
|
|
192
|
+
resolved_backend = backend_status.get("thickness_backend", "unknown")
|
|
190
193
|
measurement_masks = masks
|
|
191
194
|
if common_mask is not None:
|
|
192
195
|
measurement_masks = {role: (np.asarray(mask) > 0) & common_mask for role, mask in masks.items()}
|
|
193
|
-
measurements =
|
|
194
|
-
image.array,
|
|
195
|
-
measurement_masks,
|
|
196
|
-
native_maps,
|
|
197
|
-
case_spacing,
|
|
198
|
-
)
|
|
196
|
+
measurements = _summarize_measurements(image.array, measurement_masks, native_maps, case_spacing)
|
|
199
197
|
measurement_maps = _masked_maps_for_measurements(native_maps, measurement_masks)
|
|
200
198
|
session_part = f"ses-{session_id}" if session_id else "ses-unknown"
|
|
201
199
|
measurement_dir = "registered_measurements" if common_mask is not None else "measurements"
|
|
@@ -209,9 +207,12 @@ def run_microarchitecture_batch(
|
|
|
209
207
|
"use_common_region": common_mask is not None,
|
|
210
208
|
"thickness_method": thickness_method,
|
|
211
209
|
"thickness_backend": resolved_backend,
|
|
210
|
+
**backend_status,
|
|
212
211
|
"settings_hash": settings_hash,
|
|
212
|
+
"analysis_region": "common" if has_common else "native",
|
|
213
|
+
"input_fingerprints": fingerprints,
|
|
214
|
+
"input_paths": {role: str(case[role].path.resolve()) for role in input_roles},
|
|
213
215
|
}
|
|
214
|
-
write_measurement_csv(output_path, measurements, measurement_maps, metadata=record_metadata)
|
|
215
216
|
measurement_record = DerivativeRecord(
|
|
216
217
|
derivative="Microarchitecture",
|
|
217
218
|
role="measurements_table",
|
|
@@ -235,7 +236,8 @@ def run_microarchitecture_batch(
|
|
|
235
236
|
extension = ".nii.gz" if image.sitk_image is not None else ".npy"
|
|
236
237
|
map_filename = f"sub-{subject_id}_{session_part}_voi-{voi_token(site)}_map-{map_name.lower().replace('.', '-')}{extension}"
|
|
237
238
|
map_path = record_output_path(
|
|
238
|
-
root, "Microarchitecture", subject_id, site, session_part,
|
|
239
|
+
root, "Microarchitecture", subject_id, site, session_part,
|
|
240
|
+
"registered_measurements/maps" if has_common else "maps", map_filename
|
|
239
241
|
)
|
|
240
242
|
_write_map(map_path, map_array, image)
|
|
241
243
|
output_records.append(
|
|
@@ -249,19 +251,30 @@ def run_microarchitecture_batch(
|
|
|
249
251
|
space="native",
|
|
250
252
|
path=map_path,
|
|
251
253
|
source="generated",
|
|
252
|
-
inputs=
|
|
254
|
+
inputs=input_ids,
|
|
253
255
|
metadata={
|
|
254
256
|
**METHOD_METADATA,
|
|
255
|
-
"use_common_region":
|
|
257
|
+
"use_common_region": has_common,
|
|
256
258
|
"thickness_method": thickness_method,
|
|
257
259
|
"thickness_backend": resolved_backend,
|
|
258
|
-
|
|
260
|
+
**backend_status,
|
|
261
|
+
"settings_hash": settings_hash,
|
|
259
262
|
"map_name": map_name,
|
|
263
|
+
"file_state": output_file_states([map_path])[str(map_path.resolve())],
|
|
260
264
|
},
|
|
261
265
|
content_type="image",
|
|
262
|
-
settings_hash=
|
|
266
|
+
settings_hash=settings_hash,
|
|
263
267
|
)
|
|
264
268
|
)
|
|
269
|
+
cached_maps = list(native_map_records.values()) if native_map_records is not None else [
|
|
270
|
+
record for record in output_records
|
|
271
|
+
if record.settings_hash == settings_hash and record.content_type == "image"
|
|
272
|
+
]
|
|
273
|
+
record_metadata["output_file_states"] = output_file_states(record.path for record in cached_maps)
|
|
274
|
+
write_measurement_csv(output_path, measurements, measurement_maps, metadata=record_metadata)
|
|
275
|
+
updated_record = replace(measurement_record, metadata=record_metadata)
|
|
276
|
+
output_records[output_records.index(measurement_record)] = updated_record
|
|
277
|
+
measurement_records[-1] = updated_record
|
|
265
278
|
_emit(progress, subject_id, site, session_id, "measure", "completed", "Wrote measurements", output_path)
|
|
266
279
|
|
|
267
280
|
if output_records:
|
|
@@ -989,7 +1002,7 @@ def _output_case_key(record: DerivativeRecord) -> tuple[str, str, str | None, in
|
|
|
989
1002
|
return record.subject_id, record.site, record.session_id, record.stack_index
|
|
990
1003
|
|
|
991
1004
|
|
|
992
|
-
def _compatibility_hash(input_ids, spacing, use_common_region, thickness_method, thickness_backend) -> str:
|
|
1005
|
+
def _compatibility_hash(input_ids, spacing, use_common_region, thickness_method, thickness_backend, fingerprints=None) -> str:
|
|
993
1006
|
payload = {
|
|
994
1007
|
**METHOD_METADATA,
|
|
995
1008
|
"mask_grid_policy": "physical-nearest-neighbor-v1",
|
|
@@ -998,6 +1011,7 @@ def _compatibility_hash(input_ids, spacing, use_common_region, thickness_method,
|
|
|
998
1011
|
"use_common_region": bool(use_common_region),
|
|
999
1012
|
"thickness_method": str(thickness_method),
|
|
1000
1013
|
"thickness_backend": str(thickness_backend),
|
|
1014
|
+
"input_fingerprints": fingerprints,
|
|
1001
1015
|
}
|
|
1002
1016
|
return sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
|
|
1003
1017
|
|
|
@@ -1049,6 +1063,8 @@ def _find_compatible_native_map_records(existing, case_key, input_ids, settings_
|
|
|
1049
1063
|
and record.inputs == input_ids
|
|
1050
1064
|
and record.settings_hash == settings_hash
|
|
1051
1065
|
and record.path.is_file()
|
|
1066
|
+
and (record.metadata.get("file_state") is None or
|
|
1067
|
+
record.metadata["file_state"] == output_file_states([record.path])[str(record.path.resolve())])
|
|
1052
1068
|
]
|
|
1053
1069
|
by_signature = {_record_signature(record): record for record in matching}
|
|
1054
1070
|
if not required <= set(by_signature):
|
|
@@ -1064,7 +1080,11 @@ def _load_native_maps_from_records(records: dict[str, DerivativeRecord]) -> dict
|
|
|
1064
1080
|
|
|
1065
1081
|
|
|
1066
1082
|
def restrict_measurements(result, masks, region, spacing, *, grayscale=None) -> MicroarchitectureResult:
|
|
1067
|
-
"""Summarize
|
|
1083
|
+
"""Summarize existing maps in a subregion without changing sphere eligibility.
|
|
1084
|
+
|
|
1085
|
+
This post-hoc reporting helper is NOT a common/functional-region analysis.
|
|
1086
|
+
Use ``compute_microarchitecture(analysis_mask=...)`` for region-specific
|
|
1087
|
+
sphere fitting, as used by the scene and batch workflows.
|
|
1068
1088
|
|
|
1069
1089
|
``masks`` uses the batch semantic roles (bone_segmentation, periosteal_mask,
|
|
1070
1090
|
trabecular_mask, optional cortical_mask). The selected native pore mask must
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Final-output cache validation; distance fields are deliberately not cached."""
|
|
2
|
+
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def input_fingerprints(paths):
|
|
8
|
+
"""Hash input contents, including geometry headers, not just record IDs."""
|
|
9
|
+
result = {}
|
|
10
|
+
for path in paths:
|
|
11
|
+
path = Path(path).resolve()
|
|
12
|
+
with path.open("rb") as stream:
|
|
13
|
+
fingerprint = sha256_stream(stream)
|
|
14
|
+
if path.suffix.lower() in {".mhd", ".nhdr", ".hdr", ".img"}:
|
|
15
|
+
# Header-only hashing misses edits to detached pixel data. Let the
|
|
16
|
+
# image reader resolve payload names/LIST layouts, not our parser.
|
|
17
|
+
import SimpleITK as sitk
|
|
18
|
+
|
|
19
|
+
image = sitk.ReadImage(str(path))
|
|
20
|
+
digest = sha256(fingerprint.encode())
|
|
21
|
+
digest.update(
|
|
22
|
+
repr(
|
|
23
|
+
(image.GetSpacing(), image.GetOrigin(), image.GetDirection())
|
|
24
|
+
).encode()
|
|
25
|
+
)
|
|
26
|
+
digest.update(sitk.GetArrayViewFromImage(image))
|
|
27
|
+
fingerprint = digest.hexdigest()
|
|
28
|
+
result[str(path)] = fingerprint
|
|
29
|
+
return result
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def sha256_stream(stream):
|
|
33
|
+
digest = sha256()
|
|
34
|
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
|
35
|
+
digest.update(chunk)
|
|
36
|
+
return digest.hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def output_file_states(paths):
|
|
40
|
+
"""Detect missing, replaced, or partially rewritten final outputs cheaply."""
|
|
41
|
+
states = {}
|
|
42
|
+
for path in paths:
|
|
43
|
+
path = Path(path).resolve()
|
|
44
|
+
stat = path.stat()
|
|
45
|
+
states[str(path)] = [stat.st_size, stat.st_mtime_ns]
|
|
46
|
+
return states
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cache_is_current(metadata):
|
|
50
|
+
"""Validate recorded inputs/outputs; metadata without a cache is not certified."""
|
|
51
|
+
try:
|
|
52
|
+
inputs = metadata["input_fingerprints"]
|
|
53
|
+
outputs = metadata["output_file_states"]
|
|
54
|
+
return (
|
|
55
|
+
bool(inputs and outputs)
|
|
56
|
+
and inputs == input_fingerprints(inputs)
|
|
57
|
+
and outputs == output_file_states(outputs)
|
|
58
|
+
)
|
|
59
|
+
except (KeyError, OSError, TypeError, ValueError, RuntimeError):
|
|
60
|
+
return False
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""File-level functional-bone analysis with region-specific final-map caching."""
|
|
2
|
+
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from .batch import _load_volume, _mask_on_reference_grid, _write_map
|
|
10
|
+
from .cache import cache_is_current, input_fingerprints, output_file_states
|
|
11
|
+
from .method import METHOD_METADATA
|
|
12
|
+
from .pipeline import compute_microarchitecture
|
|
13
|
+
from .results import write_measurement_csv
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run_microarchitecture_case(
|
|
17
|
+
*,
|
|
18
|
+
image_path,
|
|
19
|
+
bone_mask_path,
|
|
20
|
+
periosteal_mask_path,
|
|
21
|
+
trabecular_mask_path,
|
|
22
|
+
cortical_mask_path,
|
|
23
|
+
output_dir,
|
|
24
|
+
prefix,
|
|
25
|
+
common_region_path=None,
|
|
26
|
+
voidspace_mask_path=None,
|
|
27
|
+
thickness_method="hildebrand",
|
|
28
|
+
thickness_backend="auto",
|
|
29
|
+
force=False,
|
|
30
|
+
):
|
|
31
|
+
"""Calculate a file-aligned region once, saving its maps beside its table.
|
|
32
|
+
|
|
33
|
+
The optional functional ROI is periosteal ∩ common ∩ not-voidspace. Full
|
|
34
|
+
native arrays remain the distance/pore context. Only complete compatible
|
|
35
|
+
final outputs are reused; no distance fields or native maps are cached here.
|
|
36
|
+
"""
|
|
37
|
+
paths = dict(
|
|
38
|
+
transformed_image=image_path,
|
|
39
|
+
bone_segmentation=bone_mask_path,
|
|
40
|
+
periosteal_mask=periosteal_mask_path,
|
|
41
|
+
trabecular_mask=trabecular_mask_path,
|
|
42
|
+
cortical_mask=cortical_mask_path,
|
|
43
|
+
)
|
|
44
|
+
if common_region_path is not None:
|
|
45
|
+
paths["scan_region_native_common"] = common_region_path
|
|
46
|
+
if voidspace_mask_path is not None:
|
|
47
|
+
paths["voidspace_mask"] = voidspace_mask_path
|
|
48
|
+
fingerprints = input_fingerprints(paths.values())
|
|
49
|
+
input_paths = {role: str(Path(path).resolve()) for role, path in paths.items()}
|
|
50
|
+
settings = {
|
|
51
|
+
**METHOD_METADATA,
|
|
52
|
+
"input_fingerprints": fingerprints,
|
|
53
|
+
"input_paths": input_paths,
|
|
54
|
+
"thickness_method": thickness_method,
|
|
55
|
+
"thickness_backend_request": thickness_backend,
|
|
56
|
+
"has_common": common_region_path is not None,
|
|
57
|
+
"has_voidspace": voidspace_mask_path is not None,
|
|
58
|
+
"mask_grid_policy": "physical-nearest-neighbor-v1",
|
|
59
|
+
}
|
|
60
|
+
settings_hash = sha256(json.dumps(settings, sort_keys=True).encode()).hexdigest()
|
|
61
|
+
output_dir = Path(output_dir)
|
|
62
|
+
output = output_dir / f"{prefix}_measurements.csv"
|
|
63
|
+
if not force and output.is_file():
|
|
64
|
+
try:
|
|
65
|
+
metadata = json.loads(output.with_suffix(".json").read_text())
|
|
66
|
+
if (
|
|
67
|
+
metadata.get("settings_hash") == settings_hash
|
|
68
|
+
and str(output.resolve()) in metadata.get("output_file_states", {})
|
|
69
|
+
and cache_is_current(metadata)
|
|
70
|
+
):
|
|
71
|
+
return output
|
|
72
|
+
except (OSError, ValueError, TypeError):
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
image = _load_volume(Path(image_path), scaling="bmd")
|
|
76
|
+
if image.spacing is None:
|
|
77
|
+
raise ValueError("Region microarchitecture needs image geometry/spacing")
|
|
78
|
+
masks = {
|
|
79
|
+
role: _mask_on_reference_grid(
|
|
80
|
+
_load_volume(Path(paths[role]), scaling="native"), image
|
|
81
|
+
)
|
|
82
|
+
for role in (
|
|
83
|
+
"bone_segmentation",
|
|
84
|
+
"periosteal_mask",
|
|
85
|
+
"trabecular_mask",
|
|
86
|
+
"cortical_mask",
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
analysis = masks["periosteal_mask"].copy()
|
|
90
|
+
if common_region_path is not None:
|
|
91
|
+
analysis &= _mask_on_reference_grid(
|
|
92
|
+
_load_volume(Path(common_region_path), scaling="native"), image
|
|
93
|
+
)
|
|
94
|
+
if voidspace_mask_path is not None:
|
|
95
|
+
analysis &= ~_mask_on_reference_grid(
|
|
96
|
+
_load_volume(Path(voidspace_mask_path), scaling="native"), image
|
|
97
|
+
)
|
|
98
|
+
result = compute_microarchitecture(
|
|
99
|
+
grayscale=image.array,
|
|
100
|
+
spacing=image.spacing,
|
|
101
|
+
bone_mask=masks["bone_segmentation"],
|
|
102
|
+
periosteal_mask=masks["periosteal_mask"],
|
|
103
|
+
trabecular_mask=masks["trabecular_mask"],
|
|
104
|
+
cortical_mask=masks["cortical_mask"],
|
|
105
|
+
analysis_mask=analysis,
|
|
106
|
+
thickness_method=thickness_method,
|
|
107
|
+
thickness_backend=thickness_backend,
|
|
108
|
+
)
|
|
109
|
+
print(
|
|
110
|
+
f"[microarchitecture] backend={result.metadata['thickness_backend']}; "
|
|
111
|
+
f"device={result.metadata.get('thickness_device')}; GPU={result.metadata.get('thickness_gpu')}",
|
|
112
|
+
flush=True,
|
|
113
|
+
)
|
|
114
|
+
maps_dir = output_dir / "maps"
|
|
115
|
+
extension = ".nii.gz" if image.sitk_image is not None else ".npy"
|
|
116
|
+
files = []
|
|
117
|
+
for name, array in result.maps.items():
|
|
118
|
+
path = maps_dir / f"{prefix}_map-{name.lower().replace('.', '-')}{extension}"
|
|
119
|
+
_write_map(path, array, image)
|
|
120
|
+
files.append(path)
|
|
121
|
+
label = "functional" if voidspace_mask_path is not None else "native"
|
|
122
|
+
if common_region_path is not None:
|
|
123
|
+
label = "functional-common" if voidspace_mask_path is not None else "common"
|
|
124
|
+
if voidspace_mask_path is not None:
|
|
125
|
+
path = output_dir / f"{prefix}_desc-functional-bone-analysis_mask{extension}"
|
|
126
|
+
_write_analysis_mask(path, analysis, image)
|
|
127
|
+
files.append(path)
|
|
128
|
+
metadata = {
|
|
129
|
+
**result.metadata,
|
|
130
|
+
"settings_hash": settings_hash,
|
|
131
|
+
"input_paths": input_paths,
|
|
132
|
+
"input_fingerprints": fingerprints,
|
|
133
|
+
"analysis_region": label,
|
|
134
|
+
"use_common_region": common_region_path is not None,
|
|
135
|
+
"functional_bone": voidspace_mask_path is not None,
|
|
136
|
+
}
|
|
137
|
+
# Publish cache metadata last: an interrupted calculation cannot certify a
|
|
138
|
+
# partial set of maps, or accidentally reuse an older result after a rerun.
|
|
139
|
+
write_measurement_csv(output, result.measurements, result.maps, metadata=metadata)
|
|
140
|
+
metadata["output_file_states"] = output_file_states([*files, output])
|
|
141
|
+
output.with_suffix(".json").write_text(
|
|
142
|
+
json.dumps(metadata, indent=2), encoding="utf-8"
|
|
143
|
+
)
|
|
144
|
+
return output
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _write_analysis_mask(path, array, reference):
|
|
148
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
149
|
+
if reference.sitk_image is None:
|
|
150
|
+
np.save(path, np.asarray(array, dtype=np.uint8))
|
|
151
|
+
else:
|
|
152
|
+
import SimpleITK as sitk
|
|
153
|
+
|
|
154
|
+
image = sitk.GetImageFromArray(np.asarray(array, dtype=np.uint8))
|
|
155
|
+
image.CopyInformation(reference.sitk_image)
|
|
156
|
+
sitk.WriteImage(image, str(path))
|
{bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/method.py
RENAMED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"""Scientific method identity, independent of packaging/backend versions."""
|
|
2
2
|
|
|
3
|
-
METHOD_ID = "ipl-aligned-
|
|
3
|
+
METHOD_ID = "ipl-aligned-region-v3"
|
|
4
4
|
|
|
5
5
|
METHOD_METADATA = {
|
|
6
6
|
"measurement_method": METHOD_ID,
|
|
7
7
|
"cortical_porosity_method": "slice-seeds-z-growth-five-voxel-cleanup",
|
|
8
8
|
"cortical_thickness_input": "cortical-compartment",
|
|
9
9
|
"trabecular_number_statistic": "inverse-mean-ridge-spacing",
|
|
10
|
-
"boundary_policy": "full-phase-context-
|
|
10
|
+
"boundary_policy": "full-phase-context-region-centres-ipl-suppress-boundary-2",
|
|
11
11
|
"ipl_parity": "not-validated",
|
|
12
12
|
}
|
{bone_microarchitecture-0.3.0 → bone_microarchitecture-0.3.2}/src/bone_microarchitecture/opencl.py
RENAMED
|
@@ -160,6 +160,4 @@ def _select_device(cl, *, prefer_gpu: bool):
|
|
|
160
160
|
return device
|
|
161
161
|
if fallback is not None and not prefer_gpu:
|
|
162
162
|
return fallback
|
|
163
|
-
|
|
164
|
-
return fallback
|
|
165
|
-
raise RuntimeError("No OpenCL devices are available.")
|
|
163
|
+
raise RuntimeError("No OpenCL GPU is available; check the GPU's OpenCL driver/runtime.")
|