bone-microarchitecture 0.2.4__tar.gz → 0.3.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.
Files changed (39) hide show
  1. bone_microarchitecture-0.3.0/CHANGELOG.md +27 -0
  2. bone_microarchitecture-0.3.0/PKG-INFO +135 -0
  3. bone_microarchitecture-0.3.0/README.md +94 -0
  4. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/pyproject.toml +2 -2
  5. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/batch.py +83 -12
  6. bone_microarchitecture-0.3.0/src/bone_microarchitecture/method.py +12 -0
  7. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/metrics.py +11 -4
  8. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/pipeline.py +22 -14
  9. bone_microarchitecture-0.3.0/src/bone_microarchitecture/pores.py +69 -0
  10. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/results.py +20 -7
  11. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/thickness.py +43 -16
  12. bone_microarchitecture-0.3.0/src/bone_microarchitecture.egg-info/PKG-INFO +135 -0
  13. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture.egg-info/SOURCES.txt +3 -0
  14. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture.egg-info/requires.txt +1 -1
  15. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_batch.py +23 -0
  16. bone_microarchitecture-0.3.0/tests/test_ipl_alignment.py +173 -0
  17. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_metrics.py +3 -2
  18. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_pipeline.py +12 -14
  19. bone_microarchitecture-0.2.4/CHANGELOG.md +0 -8
  20. bone_microarchitecture-0.2.4/PKG-INFO +0 -90
  21. bone_microarchitecture-0.2.4/README.md +0 -49
  22. bone_microarchitecture-0.2.4/src/bone_microarchitecture.egg-info/PKG-INFO +0 -90
  23. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/LICENSE +0 -0
  24. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/MANIFEST.in +0 -0
  25. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/setup.cfg +0 -0
  26. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/__init__.py +0 -0
  27. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/cli.py +0 -0
  28. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/geometry.py +0 -0
  29. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/metal.py +0 -0
  30. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture/opencl.py +0 -0
  31. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture.egg-info/dependency_links.txt +0 -0
  32. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture.egg-info/entry_points.txt +0 -0
  33. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/src/bone_microarchitecture.egg-info/top_level.txt +0 -0
  34. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_attribution.py +0 -0
  35. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_backends.py +0 -0
  36. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_geometry.py +0 -0
  37. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_package.py +0 -0
  38. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_results.py +0 -0
  39. {bone_microarchitecture-0.2.4 → bone_microarchitecture-0.3.0}/tests/test_thickness.py +0 -0
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ## 0.3.0 - 2026-10-07
6
+
7
+ ### Changed
8
+
9
+ - Replace cortical non-bone porosity with slice-seeded, longitudinally grown, five-voxel-cleaned intracortical pores; persist `Ct.Po.Mask` independently of pore diameter.
10
+ - Measure cortical compartment thickness rather than mineralized cortical thickness, and report Tb.N as reciprocal mean ridge spacing in both summaries and CSVs.
11
+ - Retain full-phase context for spacing/ridge extraction and suppress incomplete image-boundary spheres consistently across diameter backends.
12
+ - Restrict native maps to reporting regions without rerunning pore cleanup or thickness fitting. Record `ipl-aligned-v1` scientific provenance and invalidate pre-alignment caches.
13
+ - Document unvalidated native IPL operator conventions; these changes do not establish bitwise IPL equivalence.
14
+
15
+ ## 0.2.5 - 2026-10-02
16
+
17
+ ### Fixed
18
+
19
+ - Place imported/cropped compartment and common-region masks on the grayscale physical grid with nearest-neighbor resampling, including same-size images with different origins, spacings, or directions.
20
+ - Include the mask-grid policy in cache compatibility to invalidate maps calculated under the old equal-array assumption.
21
+
22
+ ## 0.2.4 - 2026-10-02
23
+
24
+ ### Fixed
25
+
26
+ - Recognize canonical `bone_segmentation`, `periosteal_mask`, `trabecular_mask`, and `cortical_mask` roles in shared contour batch inputs, including BoneContours sidecars.
27
+ - Record the current package version in batch derivative manifests.
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: bone-microarchitecture
3
+ Version: 0.3.0
4
+ Summary: Lightweight bone microarchitecture measurements from masks and calibrated grayscale arrays.
5
+ Author: Matthias Walle
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/wallematthias/bone-microarchitecture
8
+ Project-URL: Repository, https://github.com/wallematthias/bone-microarchitecture
9
+ Project-URL: Issues, https://github.com/wallematthias/bone-microarchitecture/issues
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: bone-imaging-derivatives>=0.1.7
22
+ Requires-Dist: numpy>=1.23
23
+ Requires-Dist: SimpleITK>=2.2
24
+ Requires-Dist: scipy>=1.10
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8; extra == "test"
27
+ Requires-Dist: pytest-cov; extra == "test"
28
+ Provides-Extra: dev
29
+ Requires-Dist: build; extra == "dev"
30
+ Requires-Dist: pytest>=8; extra == "dev"
31
+ Requires-Dist: pytest-cov; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Provides-Extra: mps
34
+ Requires-Dist: pyobjc-framework-Metal>=10; extra == "mps"
35
+ Provides-Extra: opencl
36
+ Requires-Dist: pyopencl>=2024.1; extra == "opencl"
37
+ Provides-Extra: gpu
38
+ Requires-Dist: pyobjc-framework-Metal>=10; sys_platform == "darwin" and extra == "gpu"
39
+ Requires-Dist: pyopencl>=2024.1; sys_platform != "darwin" and extra == "gpu"
40
+ Dynamic: license-file
41
+
42
+ <p align="center">
43
+ <img src="resources/bone-microarchitecture.png" alt="bone-microarchitecture icon" width="240">
44
+ </p>
45
+
46
+ # Bone Microarchitecture
47
+
48
+ Lightweight microarchitecture measurements from binary masks and optional calibrated grayscale arrays.
49
+
50
+ Author: Matthias Walle.
51
+
52
+ The array measurement API has no Slicer dependency and expects calibrated arrays
53
+ on a common grid. File-based batch workflows use SimpleITK (and aimio-py for AIM)
54
+ to load inputs and place cropped masks on the grayscale grid with nearest-neighbor
55
+ resampling using origin, spacing, and direction. This is grid reconciliation, not
56
+ registration; geometry-free arrays must already have the grayscale dimensions.
57
+ The grid policy participates in batch cache compatibility so older incompatible
58
+ maps are recomputed.
59
+
60
+ Batch discovery accepts canonical segmentation, periosteal, trabecular, and cortical roles from shared contour derivatives and their sidecars. See [CHANGELOG.md](CHANGELOG.md) for release notes.
61
+
62
+ ## GPU Backends
63
+
64
+ Exact Hildebrand sphere fitting supports three diameter-accumulation backends:
65
+
66
+ - `cpu`: NumPy/SciPy fallback.
67
+ - `mps`: native Apple Metal backend for macOS.
68
+ - `opencl`: OpenCL backend for Windows/Linux systems with `pyopencl` and a working GPU OpenCL runtime.
69
+
70
+ Use `thickness_backend="auto"` to select Metal on macOS when available, OpenCL on Windows/Linux when available, and CPU otherwise.
71
+
72
+ Optional installs:
73
+
74
+ ```bash
75
+ pip install "bone-microarchitecture[mps]"
76
+ pip install "bone-microarchitecture[opencl]"
77
+ pip install "bone-microarchitecture[gpu]"
78
+ ```
79
+
80
+ ## Parameter Definitions
81
+
82
+ - `Tb.BMD`: mean calibrated grayscale value inside the trabecular compartment.
83
+ - `Tb.BV/TV`: trabecular bone volume divided by trabecular total volume.
84
+ - `Tb.Th`: maximal-sphere local thickness of trabecular bone.
85
+ - `Tb.Sp`: maximal-sphere local thickness of non-bone space in the trabecular compartment.
86
+ - `Tb.N`: reciprocal of mean ridge-to-ridge spacing in the trabecular compartment (not mean reciprocal spacing).
87
+ - `Tb.1/N.SD`: standard deviation of ridge-to-ridge spacing.
88
+ - `Tb.BV`: trabecular bone volume.
89
+ - `Tb.TV`: trabecular compartment volume.
90
+ - `Ct.BMD`: mean calibrated grayscale value inside the cortical compartment.
91
+ - `Ct.Th`: maximal-sphere local thickness of the cortical compartment, including internal pores.
92
+ - `Ct.Po`: cortical pore volume divided by cortical total volume.
93
+ - `Ct.Po.V`: selected intracortical pore volume after connectivity and size cleanup.
94
+ - `Ct.Po.Dm`: maximal-sphere local diameter of the selected intracortical pores.
95
+ - `Ct.BV`: cortical bone volume.
96
+ - `Ct.TV`: cortical compartment volume.
97
+
98
+ ## IPL-aligned measurement definitions
99
+
100
+ The standard method is `ipl-aligned-v1`, replacing the previous definitions.
101
+ It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
102
+
103
+ - Pore selection uses enclosed XY seeds, Z-only hysteresis growth, a second XY
104
+ pass and removal of components smaller than five voxels. It does not classify
105
+ every non-bone cortical voxel as a pore or close longitudinal canals at scan
106
+ ends. The stages are described by [Burghardt et al., Bone 2010](https://pmc.ncbi.nlm.nih.gov/articles/PMC2926164/).
107
+ - `Ct.Th` uses the supplied cortical compartment, not only its mineralized phase.
108
+ `Ct.Po = selected pore volume / cortical compartment volume`, matching the
109
+ supplied script's denominator. `Ct.Po` is therefore not necessarily `1 - Ct.BV/Ct.TV`.
110
+ - `Tb.Sp` and ridge spacing retain the full bone-phase context before restricting
111
+ reporting to the trabecular compartment. `Tb.N` is inverse mean spacing.
112
+ - Hildebrand fitting excludes sphere centres whose radius reaches the image's
113
+ physical boundary. Complete spheres may still contribute to end slices; no
114
+ fixed slice strip is blanked. CPU, Metal and OpenCL use the same centre filter.
115
+ The optional `edt` preview remains a distance-transform approximation.
116
+
117
+ Native maps are computed before common-region or Functional Bone restrictions.
118
+ The additional `Ct.Po.Mask` map preserves pore membership independently of
119
+ diameter fitting. Cropping a reporting region does not repeat pore cleanup or
120
+ introduce new anatomical walls. `restrict_measurements` in the batch module
121
+ applies this same reporting rule to array/scene results.
122
+
123
+ Results and CSV JSON sidecars record the scientific method separately from the
124
+ package version. Batch hashes invalidate pre-alignment maps and measurements;
125
+ legacy results must be recalculated, not mixed into a new comparison. Ratios
126
+ remain fractions, not percentages. For `Tb.N`, the CSV Mean is inverse mean
127
+ spacing; its other distribution columns describe the local inverse-spacing map.
128
+
129
+ **Exact IPL parity is not validated.** The pore implementation explicitly uses
130
+ 8-connectivity in XY, 26-connectivity in 3D, a 5%-of-background-area XY cutoff,
131
+ and a compact XY crop with one-voxel margin. Native IPL percentage/rank and GOBJ
132
+ boundary conventions may differ. Ridge dominance and the existing half-voxel
133
+ radius correction remain approximations, not verified translations of IPL's
134
+ `assign_epsilon`. Validation requires identical input AIM masks and native IPL
135
+ pore/ridge/diameter maps, not comparison of final scalar tables alone.
@@ -0,0 +1,94 @@
1
+ <p align="center">
2
+ <img src="resources/bone-microarchitecture.png" alt="bone-microarchitecture icon" width="240">
3
+ </p>
4
+
5
+ # Bone Microarchitecture
6
+
7
+ Lightweight microarchitecture measurements from binary masks and optional calibrated grayscale arrays.
8
+
9
+ Author: Matthias Walle.
10
+
11
+ The array measurement API has no Slicer dependency and expects calibrated arrays
12
+ on a common grid. File-based batch workflows use SimpleITK (and aimio-py for AIM)
13
+ to load inputs and place cropped masks on the grayscale grid with nearest-neighbor
14
+ resampling using origin, spacing, and direction. This is grid reconciliation, not
15
+ registration; geometry-free arrays must already have the grayscale dimensions.
16
+ The grid policy participates in batch cache compatibility so older incompatible
17
+ maps are recomputed.
18
+
19
+ Batch discovery accepts canonical segmentation, periosteal, trabecular, and cortical roles from shared contour derivatives and their sidecars. See [CHANGELOG.md](CHANGELOG.md) for release notes.
20
+
21
+ ## GPU Backends
22
+
23
+ Exact Hildebrand sphere fitting supports three diameter-accumulation backends:
24
+
25
+ - `cpu`: NumPy/SciPy fallback.
26
+ - `mps`: native Apple Metal backend for macOS.
27
+ - `opencl`: OpenCL backend for Windows/Linux systems with `pyopencl` and a working GPU OpenCL runtime.
28
+
29
+ Use `thickness_backend="auto"` to select Metal on macOS when available, OpenCL on Windows/Linux when available, and CPU otherwise.
30
+
31
+ Optional installs:
32
+
33
+ ```bash
34
+ pip install "bone-microarchitecture[mps]"
35
+ pip install "bone-microarchitecture[opencl]"
36
+ pip install "bone-microarchitecture[gpu]"
37
+ ```
38
+
39
+ ## Parameter Definitions
40
+
41
+ - `Tb.BMD`: mean calibrated grayscale value inside the trabecular compartment.
42
+ - `Tb.BV/TV`: trabecular bone volume divided by trabecular total volume.
43
+ - `Tb.Th`: maximal-sphere local thickness of trabecular bone.
44
+ - `Tb.Sp`: maximal-sphere local thickness of non-bone space in the trabecular compartment.
45
+ - `Tb.N`: reciprocal of mean ridge-to-ridge spacing in the trabecular compartment (not mean reciprocal spacing).
46
+ - `Tb.1/N.SD`: standard deviation of ridge-to-ridge spacing.
47
+ - `Tb.BV`: trabecular bone volume.
48
+ - `Tb.TV`: trabecular compartment volume.
49
+ - `Ct.BMD`: mean calibrated grayscale value inside the cortical compartment.
50
+ - `Ct.Th`: maximal-sphere local thickness of the cortical compartment, including internal pores.
51
+ - `Ct.Po`: cortical pore volume divided by cortical total volume.
52
+ - `Ct.Po.V`: selected intracortical pore volume after connectivity and size cleanup.
53
+ - `Ct.Po.Dm`: maximal-sphere local diameter of the selected intracortical pores.
54
+ - `Ct.BV`: cortical bone volume.
55
+ - `Ct.TV`: cortical compartment volume.
56
+
57
+ ## IPL-aligned measurement definitions
58
+
59
+ The standard method is `ipl-aligned-v1`, replacing the previous definitions.
60
+ It follows the supplied `IPL_UPAT_CALGARY_EVAL_XT2_NOREG.COM` evaluation recipe:
61
+
62
+ - Pore selection uses enclosed XY seeds, Z-only hysteresis growth, a second XY
63
+ pass and removal of components smaller than five voxels. It does not classify
64
+ every non-bone cortical voxel as a pore or close longitudinal canals at scan
65
+ ends. The stages are described by [Burghardt et al., Bone 2010](https://pmc.ncbi.nlm.nih.gov/articles/PMC2926164/).
66
+ - `Ct.Th` uses the supplied cortical compartment, not only its mineralized phase.
67
+ `Ct.Po = selected pore volume / cortical compartment volume`, matching the
68
+ supplied script's denominator. `Ct.Po` is therefore not necessarily `1 - Ct.BV/Ct.TV`.
69
+ - `Tb.Sp` and ridge spacing retain the full bone-phase context before restricting
70
+ reporting to the trabecular compartment. `Tb.N` is inverse mean spacing.
71
+ - Hildebrand fitting excludes sphere centres whose radius reaches the image's
72
+ physical boundary. Complete spheres may still contribute to end slices; no
73
+ fixed slice strip is blanked. CPU, Metal and OpenCL use the same centre filter.
74
+ The optional `edt` preview remains a distance-transform approximation.
75
+
76
+ Native maps are computed before common-region or Functional Bone restrictions.
77
+ The additional `Ct.Po.Mask` map preserves pore membership independently of
78
+ diameter fitting. Cropping a reporting region does not repeat pore cleanup or
79
+ introduce new anatomical walls. `restrict_measurements` in the batch module
80
+ applies this same reporting rule to array/scene results.
81
+
82
+ Results and CSV JSON sidecars record the scientific method separately from the
83
+ package version. Batch hashes invalidate pre-alignment maps and measurements;
84
+ legacy results must be recalculated, not mixed into a new comparison. Ratios
85
+ remain fractions, not percentages. For `Tb.N`, the CSV Mean is inverse mean
86
+ spacing; its other distribution columns describe the local inverse-spacing map.
87
+
88
+ **Exact IPL parity is not validated.** The pore implementation explicitly uses
89
+ 8-connectivity in XY, 26-connectivity in 3D, a 5%-of-background-area XY cutoff,
90
+ and a compact XY crop with one-voxel margin. Native IPL percentage/rank and GOBJ
91
+ boundary conventions may differ. Ridge dominance and the existing half-voxel
92
+ radius correction remain approximations, not verified translations of IPL's
93
+ `assign_epsilon`. Validation requires identical input AIM masks and native IPL
94
+ pore/ridge/diameter maps, not comparison of final scalar tables alone.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "bone-microarchitecture"
7
- version = "0.2.4"
7
+ version = "0.3.0"
8
8
  description = "Lightweight bone microarchitecture measurements from masks and calibrated grayscale arrays."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -22,7 +22,7 @@ classifiers = [
22
22
  "Topic :: Scientific/Engineering :: Medical Science Apps.",
23
23
  ]
24
24
  dependencies = [
25
- "bone-imaging-derivatives>=0.1.4",
25
+ "bone-imaging-derivatives>=0.1.7",
26
26
  "numpy>=1.23",
27
27
  "SimpleITK>=2.2",
28
28
  "scipy>=1.10",
@@ -25,8 +25,9 @@ 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 .method import METHOD_METADATA
28
29
  from .metrics import compartment_metrics, masked_mean_sd
29
- from .results import write_measurement_csv
30
+ from .results import MicroarchitectureResult, write_measurement_csv
30
31
  from .thickness import summary
31
32
 
32
33
 
@@ -45,6 +46,7 @@ _MAP_ROLES = {
45
46
  "Tb.N": "trabecular_number_map",
46
47
  "Ct.Th": "cortical_thickness_map",
47
48
  "Ct.Po.Dm": "cortical_porosity_map",
49
+ "Ct.Po.Mask": "material_labelmap",
48
50
  "Tt.BMD": "material_map",
49
51
  "Tb.BMD": "material_map",
50
52
  "Ct.BMD": "material_map",
@@ -88,8 +90,9 @@ def run_microarchitecture_batch(
88
90
  """Measure every manifest-discovered case and write Microarchitecture outputs.
89
91
 
90
92
  The workflow intentionally only owns derivative discovery and output writing.
91
- It clips biological masks to the optional common scan-region mask before
92
- calling :func:`compute_microarchitecture`, which retains the one-case API.
93
+ It computes native biological maps first, then restricts their summaries to
94
+ the optional common scan-region mask without changing pore selection or
95
+ creating artificial thickness boundaries.
93
96
  Simple, unambiguous ``.npy`` filenames are accepted when manifests are not
94
97
  yet available, primarily for lightweight command-line workflows.
95
98
  """
@@ -139,7 +142,11 @@ def run_microarchitecture_batch(
139
142
  _emit(progress, subject_id, site, session_id, "measure", "reused", "Reused compatible measurements", reused.path)
140
143
  continue
141
144
 
142
- masks = {role: _load_record_volume(record).array for role, record in case.items() if role != "transformed_image"}
145
+ masks = {
146
+ role: _mask_on_reference_grid(_load_record_volume(record), image)
147
+ for role, record in case.items()
148
+ if role != "transformed_image" and (role != "scan_region_native_common" or use_common_region)
149
+ }
143
150
  common = masks.pop("scan_region_native_common", None) if use_common_region else None
144
151
  common_mask = np.asarray(common) > 0 if common is not None else None
145
152
 
@@ -197,13 +204,14 @@ def run_microarchitecture_batch(
197
204
  root, "Microarchitecture", subject_id, site, session_part, measurement_dir, filename
198
205
  )
199
206
  output_path.parent.mkdir(parents=True, exist_ok=True)
200
- write_measurement_csv(output_path, measurements, measurement_maps)
201
207
  record_metadata = {
208
+ **METHOD_METADATA,
202
209
  "use_common_region": common_mask is not None,
203
210
  "thickness_method": thickness_method,
204
211
  "thickness_backend": resolved_backend,
205
212
  "settings_hash": settings_hash,
206
213
  }
214
+ write_measurement_csv(output_path, measurements, measurement_maps, metadata=record_metadata)
207
215
  measurement_record = DerivativeRecord(
208
216
  derivative="Microarchitecture",
209
217
  role="measurements_table",
@@ -243,6 +251,7 @@ def run_microarchitecture_batch(
243
251
  source="generated",
244
252
  inputs=native_input_ids,
245
253
  metadata={
254
+ **METHOD_METADATA,
246
255
  "use_common_region": False,
247
256
  "thickness_method": thickness_method,
248
257
  "thickness_backend": resolved_backend,
@@ -263,7 +272,7 @@ def run_microarchitecture_batch(
263
272
  ]
264
273
  merged_records.extend(output_records)
265
274
  manifest = DerivativeManifest.create(
266
- "Microarchitecture", root, {"name": "bone-microarchitecture", "version": "0.2.4"},
275
+ "Microarchitecture", root, {"name": "bone-microarchitecture", "version": "0.3.0"},
267
276
  records=tuple(merged_records),
268
277
  )
269
278
  write_manifest(manifest, manifest_path(root, "Microarchitecture"))
@@ -754,6 +763,36 @@ def _load_record_volume(record: DerivativeRecord) -> _LoadedVolume:
754
763
  return _load_volume(record.path, scaling=scaling)
755
764
 
756
765
 
766
+ def _mask_on_reference_grid(volume: _LoadedVolume, reference: _LoadedVolume) -> np.ndarray:
767
+ """Place a native/cropped mask on the grayscale grid using physical coordinates.
768
+
769
+ Geometry-free arrays must already have the reference shape. This is not a
770
+ registration: it only reconciles grid/crop differences in one physical space.
771
+ """
772
+ mask = np.asarray(volume.array) > 0
773
+ if volume.sitk_image is None or reference.sitk_image is None:
774
+ if mask.shape != reference.array.shape:
775
+ raise ValueError("Mask without physical geometry must have the same shape as the grayscale image")
776
+ return mask
777
+ import SimpleITK as sitk
778
+
779
+ source = volume.sitk_image
780
+ target = reference.sitk_image
781
+ same_geometry = source.GetSize() == target.GetSize() and all(
782
+ np.allclose(left, right, rtol=0, atol=1e-6)
783
+ for left, right in ((source.GetSpacing(), target.GetSpacing()),
784
+ (source.GetOrigin(), target.GetOrigin()),
785
+ (source.GetDirection(), target.GetDirection()))
786
+ )
787
+ if same_geometry:
788
+ return mask
789
+ binary = sitk.GetImageFromArray(mask.astype(np.uint8))
790
+ binary.CopyInformation(source)
791
+ aligned = sitk.Resample(binary, target, sitk.Transform(3, sitk.sitkIdentity),
792
+ sitk.sitkNearestNeighbor, 0, sitk.sitkUInt8)
793
+ return sitk.GetArrayFromImage(aligned).astype(bool)
794
+
795
+
757
796
  def _load_aim_volume(path: Path, *, scaling: str = "bmd") -> _LoadedVolume:
758
797
  try:
759
798
  import py_aimio
@@ -952,6 +991,8 @@ def _output_case_key(record: DerivativeRecord) -> tuple[str, str, str | None, in
952
991
 
953
992
  def _compatibility_hash(input_ids, spacing, use_common_region, thickness_method, thickness_backend) -> str:
954
993
  payload = {
994
+ **METHOD_METADATA,
995
+ "mask_grid_policy": "physical-nearest-neighbor-v1",
955
996
  "inputs": list(input_ids),
956
997
  "spacing": [float(value) for value in spacing],
957
998
  "use_common_region": bool(use_common_region),
@@ -964,7 +1005,7 @@ def _compatibility_hash(input_ids, spacing, use_common_region, thickness_method,
964
1005
  def _expected_output_signatures(case: dict[str, DerivativeRecord]) -> set[tuple[str, str, str | None]]:
965
1006
  names = {"Tb.Th", "Tb.Sp", "Tb.N", "Tt.BMD", "Tb.BMD"}
966
1007
  if "cortical_mask" in case:
967
- names.update({"Ct.Th", "Ct.Po.Dm", "Ct.BMD"})
1008
+ names.update({"Ct.Th", "Ct.Po.Dm", "Ct.Po.Mask", "Ct.BMD"})
968
1009
  return {("measurements_table", "table", None)} | {
969
1010
  (_MAP_ROLES.get(name, "material_map"), "native", name) for name in names
970
1011
  }
@@ -1022,6 +1063,35 @@ def _load_native_maps_from_records(records: dict[str, DerivativeRecord]) -> dict
1022
1063
  return None
1023
1064
 
1024
1065
 
1066
+ def restrict_measurements(result, masks, region, spacing, *, grayscale=None) -> MicroarchitectureResult:
1067
+ """Summarize native maps in an aligned reporting region, without recomputing biology.
1068
+
1069
+ ``masks`` uses the batch semantic roles (bone_segmentation, periosteal_mask,
1070
+ trabecular_mask, optional cortical_mask). The selected native pore mask must
1071
+ remain intact until this step, even if the region leaves fewer than five
1072
+ voxels of a pore. If grayscale is omitted, existing BMD is summarized from
1073
+ the native Tt.BMD map; results without grayscale/BMD stay without BMD.
1074
+ """
1075
+ region = np.asarray(region, dtype=bool)
1076
+ if region.ndim != 3 or any(np.shape(mask) != region.shape for mask in masks.values()):
1077
+ raise ValueError("Analysis region and native masks must be aligned 3D arrays")
1078
+ if grayscale is None and any(name in result.measurements for name in ("Tt.BMD", "Tb.BMD", "Ct.BMD")):
1079
+ if "Tt.BMD" not in result.maps:
1080
+ raise ValueError("Existing BMD requires grayscale or a native Tt.BMD map")
1081
+ grayscale = result.maps["Tt.BMD"]
1082
+ if grayscale is not None and np.shape(grayscale) != region.shape:
1083
+ raise ValueError("Grayscale and analysis region must have the same shape")
1084
+ restricted_masks = {role: np.asarray(mask, dtype=bool) & region for role, mask in masks.items()}
1085
+ image = np.zeros(region.shape, dtype=np.float32) if grayscale is None else grayscale
1086
+ metrics = _summarize_measurements(image, restricted_masks, result.maps, spacing)
1087
+ metrics = {name: value for name, value in metrics.items() if name in result.measurements}
1088
+ return MicroarchitectureResult(
1089
+ measurements=metrics,
1090
+ maps=_masked_maps_for_measurements(result.maps, restricted_masks),
1091
+ metadata={**result.metadata, "reporting_region": "restricted-native-maps"},
1092
+ )
1093
+
1094
+
1025
1095
  def _summarize_measurements(grayscale, masks, maps, spacing) -> dict[str, float]:
1026
1096
  bone = np.asarray(masks["bone_segmentation"]) > 0
1027
1097
  peri = np.asarray(masks["periosteal_mask"]) > 0
@@ -1042,6 +1112,7 @@ def _summarize_measurements(grayscale, masks, maps, spacing) -> dict[str, float]
1042
1112
  cortical_mask=cort,
1043
1113
  spacing=spacing,
1044
1114
  mean_tb_th=tb_th["mean"],
1115
+ pore_mask=maps.get("Ct.Po.Mask"),
1045
1116
  )
1046
1117
  tb_sp_values = np.asarray(maps["Tb.Sp"])[trab_region & ~trab_bone]
1047
1118
  tb_sp = summary(tb_sp_values)
@@ -1061,7 +1132,7 @@ def _summarize_measurements(grayscale, masks, maps, spacing) -> dict[str, float]
1061
1132
  "Tb.Sp SD": tb_sp["sd"],
1062
1133
  "Tb.Sp Min": tb_sp["min"],
1063
1134
  "Tb.Sp Max": tb_sp["max"],
1064
- "Tb.N": tb_n["mean"],
1135
+ "Tb.N": 1.0 / tb_inverse_number["mean"] if tb_inverse_number["mean"] > 0 else 0.0,
1065
1136
  "Tb.N Median": tb_n["median"],
1066
1137
  "Tb.N SD": tb_n["sd"],
1067
1138
  "Tb.N P5": tb_n["p5"],
@@ -1078,9 +1149,9 @@ def _summarize_measurements(grayscale, masks, maps, spacing) -> dict[str, float]
1078
1149
  tb_mean, tb_sd = masked_mean_sd(image, trab_region)
1079
1150
  metrics.update({"Tt.BMD": tt_mean, "Tt.BMD SD": tt_sd, "Tb.BMD": tb_mean, "Tb.BMD SD": tb_sd})
1080
1151
  if cort_region is not None:
1081
- cort_bone = bone & cort_region
1082
- ct_th = summary(np.asarray(maps["Ct.Th"])[cort_bone])
1083
- pore_summary = summary(np.asarray(maps["Ct.Po.Dm"])[cort_region & ~cort_bone])
1152
+ ct_th = summary(np.asarray(maps["Ct.Th"])[cort_region])
1153
+ pores = np.asarray(maps["Ct.Po.Mask"]) > 0
1154
+ pore_summary = summary(np.asarray(maps["Ct.Po.Dm"])[cort_region & pores])
1084
1155
  ct_mean, ct_sd = masked_mean_sd(image, cort_region)
1085
1156
  metrics.update(
1086
1157
  {
@@ -1115,7 +1186,7 @@ def _masked_maps_for_measurements(maps, masks) -> dict[str, np.ndarray]:
1115
1186
  result["Tb.BMD"] = np.where(trab_region, maps["Tb.BMD"], 0)
1116
1187
  if cort is not None:
1117
1188
  cort_region = cort & peri
1118
- for name in ("Ct.Th", "Ct.Po.Dm", "Ct.BMD"):
1189
+ for name in ("Ct.Th", "Ct.Po.Dm", "Ct.Po.Mask", "Ct.BMD"):
1119
1190
  if name in maps:
1120
1191
  result[name] = np.where(cort_region, maps[name], 0)
1121
1192
  return result
@@ -0,0 +1,12 @@
1
+ """Scientific method identity, independent of packaging/backend versions."""
2
+
3
+ METHOD_ID = "ipl-aligned-v1"
4
+
5
+ METHOD_METADATA = {
6
+ "measurement_method": METHOD_ID,
7
+ "cortical_porosity_method": "slice-seeds-z-growth-five-voxel-cleanup",
8
+ "cortical_thickness_input": "cortical-compartment",
9
+ "trabecular_number_statistic": "inverse-mean-ridge-spacing",
10
+ "boundary_policy": "full-phase-context-complete-image-spheres",
11
+ "ipl_parity": "not-validated",
12
+ }
@@ -2,6 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  import numpy as np
4
4
 
5
+ from .pores import cortical_pore_mask
6
+
5
7
  from .geometry import voxel_volume
6
8
 
7
9
 
@@ -38,6 +40,7 @@ def compartment_metrics(
38
40
  cortical_mask=None,
39
41
  spacing: tuple[float, float, float],
40
42
  mean_tb_th: float = 0.0,
43
+ pore_mask=None,
41
44
  ) -> dict[str, float]:
42
45
  """Calculate scalar compartment measures from binary masks.
43
46
 
@@ -52,7 +55,7 @@ def compartment_metrics(
52
55
  ``Tb.BV/TV``: ``Tb.BV / Tb.TV``, as a fraction.
53
56
  ``Ct.BV``: cortical bone volume, in mm^3.
54
57
  ``Ct.TV``: cortical compartment volume, in mm^3.
55
- ``Ct.Po.V``: ``Ct.TV - Ct.BV``, in mm^3.
58
+ ``Ct.Po.V``: selected, cleaned intracortical pore volume, in mm^3.
56
59
  ``Ct.Po``: ``Ct.Po.V / Ct.TV``, as a fraction.
57
60
  ``Tb.N``: fallback scalar ``Tb.BV/TV / mean(Tb.Th)``. The pipeline
58
61
  replaces this with the map-based trabecular number estimate.
@@ -62,7 +65,7 @@ def compartment_metrics(
62
65
  bone = np.asarray(bone_mask) > 0 if bone_mask is not None else trab_region
63
66
  cort = np.asarray(cortical_mask) > 0 if cortical_mask is not None else np.zeros_like(trab_region)
64
67
  trab_region = trab_region & peri & ~cort
65
- cort_region = cort
68
+ cort_region = cort & peri
66
69
  trab_bone = bone & trab_region
67
70
  cortical_bone = bone & cort_region
68
71
  tb_bv = count_volume(trab_bone, spacing)
@@ -70,14 +73,18 @@ def compartment_metrics(
70
73
  ct_bv = count_volume(cortical_bone, spacing)
71
74
  ct_tv = count_volume(cort_region, spacing)
72
75
  bvtv = tb_bv / tb_tv if tb_tv else 0.0
73
- ct_po = max(ct_tv - ct_bv, 0.0) / ct_tv if ct_tv else 0.0
76
+ selected_pores = cortical_pore_mask(bone, cort_region) if pore_mask is None else np.asarray(pore_mask, dtype=bool)
77
+ if selected_pores.shape != cort_region.shape:
78
+ raise ValueError("Pore mask and cortical compartment must have the same shape")
79
+ pore_volume = count_volume(selected_pores & cort_region & ~bone, spacing)
80
+ ct_po = pore_volume / ct_tv if ct_tv else 0.0
74
81
  metrics = {
75
82
  "Tb.BV/TV": bvtv,
76
83
  "Tb.BV": tb_bv,
77
84
  "Tb.TV": tb_tv,
78
85
  "Ct.BV": ct_bv,
79
86
  "Ct.TV": ct_tv,
80
- "Ct.Po.V": max(ct_tv - ct_bv, 0.0),
87
+ "Ct.Po.V": pore_volume,
81
88
  "Ct.Po": ct_po,
82
89
  }
83
90
  metrics["Tb.N"] = bvtv / mean_tb_th if mean_tb_th else 0.0