morphogen 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,188 @@
1
+ """Named measurements used by configuration files and the command line.
2
+
3
+ Each measure maps a phase image (and the label image of tessellations and grain
4
+ structures) to a flat dictionary of numbers, so that results can be written as table
5
+ columns.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+
12
+ import numpy as np
13
+
14
+ from morphogen.analysis.anisotropy import covariance_minima, fabric_tensor
15
+ from morphogen.analysis.basic import phase_fractions, volume_fraction
16
+ from morphogen.analysis.cells import cell_neighbors, cell_volumes
17
+ from morphogen.analysis.connectivity import connected_components, wrapping
18
+ from morphogen.analysis.fractal import box_dimension
19
+ from morphogen.analysis.morphology import (
20
+ euler_characteristic,
21
+ geometric_tortuosity,
22
+ granulometry,
23
+ mean_chord_length,
24
+ minkowski,
25
+ )
26
+ from morphogen.analysis.particles import particle_sizes
27
+ from morphogen.analysis.percolation import _LATTICE_2D, directional_percolation
28
+ from morphogen.analysis.surface import DIRECTIONS_13, boundary_density, specific_surface
29
+ from morphogen.analysis.topology import betti_numbers
30
+ from morphogen.image import VoxelImage
31
+
32
+
33
+ def _volume_fraction(image: VoxelImage, labels=None) -> dict[str, float]:
34
+ return {"volume_fraction": volume_fraction(image, 1)}
35
+
36
+
37
+ def _phase_fractions(image: VoxelImage, labels=None) -> dict[str, float]:
38
+ return {f"fraction_{k}": v for k, v in phase_fractions(image).items()}
39
+
40
+
41
+ def _specific_surface(image: VoxelImage, labels=None) -> dict[str, float]:
42
+ return {"specific_surface": specific_surface(image, 1)}
43
+
44
+
45
+ def _connectivity(image: VoxelImage, labels=None) -> dict[str, float]:
46
+ comp = connected_components(image, 1)
47
+ out = {"n_components": float(comp.n_components), "spanning_fraction": comp.spanning_fraction}
48
+ axes = "xy" if image.shape[2] == 1 else "xyz" # a planar image: not along z, trivially
49
+ for axis in axes:
50
+ out[f"percolates_{axis}"] = float(comp.percolating[axis])
51
+ if isinstance(image, VoxelImage) and image.periodic: # around the box, not face to face
52
+ flags = wrapping(image, 1)
53
+ for axis in axes:
54
+ out[f"wraps_{axis}"] = float(flags[axis])
55
+ return out
56
+
57
+
58
+ def _directional_percolation(image: VoxelImage, labels=None) -> dict[str, float]:
59
+ """Along the axes and the diagonals of the grid, across the core of the image along each
60
+ (4 directions in 2-D, 13 in 3-D, named by their indices: ``percolates_1-10``)."""
61
+ planar = image.shape[2] == 1
62
+ lattice = [d[:2] for d in _LATTICE_2D] if planar else DIRECTIONS_13
63
+ result = directional_percolation(image, "lattice")
64
+ out = {}
65
+ for d, crossed, tortuosity in zip(lattice, result.percolates, result.tortuosity, strict=True):
66
+ name = "".join(str(int(c)) for c in d)
67
+ out[f"percolates_{name}"] = float(crossed)
68
+ out[f"tortuosity_{name}"] = float(tortuosity) # inf, then dropped: no crossing
69
+ return out
70
+
71
+
72
+ def _fractal_dimension(image: VoxelImage, labels=None) -> dict[str, float]:
73
+ return {"box_dimension": box_dimension(image, 1)}
74
+
75
+
76
+ def _cells(image: VoxelImage, labels=None) -> dict[str, float]:
77
+ if labels is None:
78
+ raise ValueError("the 'cells' measure needs cell labels (tessellations, grains)")
79
+ vol = cell_volumes(labels)
80
+ present = vol[vol > 0]
81
+ nb = cell_neighbors(labels)[vol > 0]
82
+ return {
83
+ "n_cells_present": float(len(present)),
84
+ "mean_cell_volume": float(present.mean()),
85
+ "cell_volume_cv2": float(present.var() / present.mean() ** 2),
86
+ "mean_neighbors": float(nb.mean()),
87
+ "boundary_density": boundary_density(labels),
88
+ }
89
+
90
+
91
+ def _chords(image: VoxelImage, labels=None) -> dict[str, float]:
92
+ return {f"mean_chord_{p}": mean_chord_length(image, p) for p in (0, 1)}
93
+
94
+
95
+ def _thickness(image: VoxelImage, labels=None) -> dict[str, float]:
96
+ out = {}
97
+ for p, name in ((1, "thickness"), (0, "pore_size")):
98
+ g = granulometry(image, p)
99
+ t = g.thickness[g.thickness > 0]
100
+ out[f"mean_{name}"] = float(t.mean()) if t.size else float("nan")
101
+ out[f"granulometry_radius_{p}"] = g.mean_radius
102
+ return out
103
+
104
+
105
+ def _euler(image: VoxelImage, labels=None) -> dict[str, float]:
106
+ volume = float(np.prod(np.asarray(image.shape) * np.asarray(image.spacing)))
107
+ return {f"euler_density_{p}": euler_characteristic(image, p) / volume for p in (0, 1)}
108
+
109
+
110
+ def _minkowski(image: VoxelImage, labels=None) -> dict[str, float]:
111
+ m = minkowski(image, 1)
112
+ return {
113
+ "V_V": m.volume_fraction,
114
+ "S_V": m.specific_surface,
115
+ "M_V": m.mean_curvature,
116
+ "chi_V": m.euler_density,
117
+ }
118
+
119
+
120
+ def _betti(image: VoxelImage, labels=None) -> dict[str, float]:
121
+ b = betti_numbers(image, 1)
122
+ volume = float(np.prod(np.asarray(image.shape) * np.asarray(image.spacing)))
123
+ return {
124
+ "betti_0": b.b0,
125
+ "betti_1": b.b1,
126
+ "betti_2": b.b2,
127
+ "connectivity_density": b.b1 / volume,
128
+ }
129
+
130
+
131
+ def _anisotropy(image: VoxelImage, labels=None) -> dict[str, float]:
132
+ f = fabric_tensor(image, 1)
133
+ out = {f"mil_{k + 1}": float(v) for k, v in enumerate(f.principal)}
134
+ out["degree_of_anisotropy"] = f.degree
135
+ return out
136
+
137
+
138
+ def _covariance_minima(image: VoxelImage, labels=None) -> dict[str, float]:
139
+ hole = covariance_minima(image, 1)
140
+ return {f"covariance_minimum_{'xyz'[a]}": float(hole.lags[a]) for a in range(3)}
141
+
142
+
143
+ def _particles(image: VoxelImage, labels=None) -> dict[str, float]:
144
+ """The particles of phase 1 in the volume (those that touch split by the watershed
145
+ of their distance map): their number per unit volume and the mean and the coefficient
146
+ of variation of their equivalent radii."""
147
+ p = particle_sizes(image, 1)
148
+ if not p.weights.sum() > 0:
149
+ return {"particle_density": 0.0}
150
+ return {
151
+ "particle_density": p.density(),
152
+ "particle_mean_radius": p.mean_radius(),
153
+ "particle_radius_cv": p.radius_cv(),
154
+ }
155
+
156
+
157
+ def _tortuosity(image: VoxelImage, labels=None) -> dict[str, float]:
158
+ return {f"tortuosity_{'xyz'[a]}": geometric_tortuosity(image, 1, a) for a in range(3)}
159
+
160
+
161
+ MEASURES: dict[str, Callable[..., dict[str, float]]] = {
162
+ "volume_fraction": _volume_fraction,
163
+ "phase_fractions": _phase_fractions,
164
+ "specific_surface": _specific_surface,
165
+ "connectivity": _connectivity,
166
+ "directional_percolation": _directional_percolation,
167
+ "fractal_dimension": _fractal_dimension,
168
+ "cells": _cells,
169
+ "chords": _chords,
170
+ "thickness": _thickness,
171
+ "euler": _euler,
172
+ "tortuosity": _tortuosity,
173
+ "particles": _particles,
174
+ "minkowski": _minkowski,
175
+ "betti": _betti,
176
+ "anisotropy": _anisotropy,
177
+ "covariance_minima": _covariance_minima,
178
+ }
179
+
180
+
181
+ def measure(image: VoxelImage, names, labels: VoxelImage | None = None) -> dict[str, float]:
182
+ """Evaluate the named measures and merge their results."""
183
+ out: dict[str, float] = {}
184
+ for name in names:
185
+ if name not in MEASURES:
186
+ raise ValueError(f"unknown measure {name!r}; available: {', '.join(MEASURES)}")
187
+ out.update(MEASURES[name](image, labels))
188
+ return {k: float(v) for k, v in out.items() if np.isfinite(v)}
@@ -0,0 +1,265 @@
1
+ """Chords, granulometry, local thickness, Euler characteristic and geometric tortuosity.
2
+
3
+ * *Chord lengths*: lengths of the runs of a phase along the lines of the grid (the
4
+ linear sections of the phase). On periodic images, runs wrap around the faces; on
5
+ other images, runs cut by the faces are left out.
6
+ * *Granulometry by openings*: fraction of the phase left by the opening with a ball of
7
+ radius r (erosion then dilation, both exact Euclidean balls through distance
8
+ transforms; Matheron 1975, Serra 1982). Its decrease with r is the size distribution of
9
+ the phase; the *local thickness* of a voxel is twice the largest radius of an opening
10
+ that keeps it (Hildebrand & Rüegsegger 1997): the pore sizes are the local thickness of
11
+ the pores.
12
+ * *Euler characteristic* of a phase (6-connected voxels): number of components - tunnels +
13
+ cavities, from the counts of voxels, pairs, squares and cubes of voxels (Ohser &
14
+ Mücklich 2000); its density, with the volume fraction and the specific surface, gives
15
+ three of the Minkowski functionals.
16
+ * *Geometric tortuosity*: shortest paths inside the phase (26-connected voxels, Euclidean
17
+ steps) from one face of the box to the opposite face, divided by the distance between
18
+ the faces.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from dataclasses import dataclass
24
+
25
+ import numpy as np
26
+ from scipy import ndimage
27
+
28
+ from morphogen.analysis.basic import indicator
29
+
30
+
31
+ def _periodic(image, periodic) -> bool:
32
+ if periodic is not None:
33
+ return bool(periodic)
34
+ return bool(getattr(image, "periodic", False))
35
+
36
+
37
+ def _spacing(image) -> np.ndarray:
38
+ return np.asarray(getattr(image, "spacing", (1.0, 1.0, 1.0)), dtype=float)
39
+
40
+
41
+ # -- chords ----------------------------------------------------------------------------------
42
+
43
+
44
+ def chord_lengths(image, phase: int = 1, axis: int = 0, *, periodic=None) -> np.ndarray:
45
+ """Lengths of the chords of ``phase`` along ``axis`` (physical units)."""
46
+ data = indicator(image, phase)
47
+ lines = np.moveaxis(data, axis, -1).reshape(-1, data.shape[axis])
48
+ n = lines.shape[1]
49
+ h = _spacing(image)[axis]
50
+ if _periodic(image, periodic):
51
+ full = lines.all(axis=1)
52
+ lines = lines[~full] # lines inside the phase: chords longer than the box
53
+ if not len(lines):
54
+ return np.zeros(0)
55
+ # start every line on a voxel outside the phase: no run wraps around
56
+ shift = np.argmin(lines, axis=1)
57
+ idx = (np.arange(n)[None, :] + shift[:, None]) % n
58
+ lines = np.take_along_axis(lines, idx, axis=1)
59
+ padded = np.pad(lines, ((0, 0), (1, 1)))
60
+ d = np.diff(padded.astype(np.int8), axis=1)
61
+ starts = np.nonzero(d == 1)
62
+ ends = np.nonzero(d == -1)
63
+ return (ends[1] - starts[1]).astype(float) * h
64
+ padded = np.pad(lines, ((0, 0), (1, 1)))
65
+ d = np.diff(padded.astype(np.int8), axis=1)
66
+ _, s_col = np.nonzero(d == 1)
67
+ _, e_col = np.nonzero(d == -1)
68
+ keep = (s_col > 0) & (e_col < n) # runs cut by the faces are left out
69
+ return (e_col[keep] - s_col[keep]).astype(float) * h
70
+
71
+
72
+ def mean_chord_length(image, phase: int = 1, *, periodic=None) -> float:
73
+ """Mean chord length of ``phase`` over the three axes (all chords pooled)."""
74
+ chords = np.concatenate([chord_lengths(image, phase, a, periodic=periodic) for a in range(3)])
75
+ return float(chords.mean()) if chords.size else float("nan")
76
+
77
+
78
+ # -- openings, granulometry, local thickness -------------------------------------------------------
79
+
80
+
81
+ def _distance(mask: np.ndarray, spacing, periodic: bool, pad: int) -> np.ndarray:
82
+ """Euclidean distance from every voxel of ``mask`` to the nearest voxel outside it
83
+ (periodic images: through the faces, up to ``pad`` voxels)."""
84
+ if periodic and pad > 0:
85
+ big = np.pad(mask, pad, mode="wrap")
86
+ dist = ndimage.distance_transform_edt(big, sampling=spacing)
87
+ return dist[pad:-pad, pad:-pad, pad:-pad]
88
+ return ndimage.distance_transform_edt(mask, sampling=spacing)
89
+
90
+
91
+ @dataclass
92
+ class Granulometry:
93
+ """Openings of a phase by balls of increasing radius."""
94
+
95
+ radii: np.ndarray # physical radii
96
+ fractions: np.ndarray # volume fraction of the phase kept by the opening of each radius
97
+ thickness: np.ndarray # local thickness (2 x largest opening radius) of each voxel
98
+
99
+ @property
100
+ def size_distribution(self) -> np.ndarray:
101
+ """Volume fraction of the phase whose largest opening radius is each radius."""
102
+ f = np.append(self.fractions, 0.0)
103
+ return f[:-1] - f[1:]
104
+
105
+ @property
106
+ def mean_radius(self) -> float:
107
+ """Mean of the radius of the largest ball (of the radii probed) containing a
108
+ point of the phase."""
109
+ dist = self.size_distribution
110
+ return float(np.sum(dist * self.radii) / dist.sum()) if dist.sum() > 0 else float("nan")
111
+
112
+
113
+ def granulometry(image, phase: int = 1, radii=None, *, periodic=None) -> Granulometry:
114
+ """Openings of ``phase`` by balls of the radii given (physical units; default: steps
115
+ of half a voxel up to the largest inscribed ball). The opening of radius r is the
116
+ union of the balls of radius r (the voxels closer than r to their centre) whose centre
117
+ is at least r from the voxels outside the phase, as in the local thickness of
118
+ Hildebrand & Rüegsegger (1997): a layer of n voxels has thickness n voxels. Each voxel
119
+ gets the largest radius whose opening keeps it, so that the fractions kept decrease
120
+ with the radius (discrete Euclidean balls do not make exact granulometries)."""
121
+ mask = indicator(image, phase)
122
+ h = _spacing(image)
123
+ per = _periodic(image, periodic)
124
+ vol = max(int(mask.sum()), 1)
125
+ hmin = float(h.min())
126
+ pad = 0
127
+ if per: # wrap the image by more than the largest ball (bounded by the plain transform)
128
+ rough = ndimage.distance_transform_edt(mask, sampling=h)
129
+ pad = min(int(np.ceil(rough.max() / hmin)) + 2, max(mask.shape))
130
+ dist = _distance(mask, h, per, pad)
131
+ if radii is None:
132
+ radii = hmin * (1.0 + 0.5 * np.arange(max(0, int(2.0 * (dist.max() / hmin - 1.0))) + 1))
133
+ radii = np.sort(np.asarray(radii, dtype=float))
134
+ radius = np.where(mask, 0.5 * hmin, 0.0) # largest opening radius of every voxel
135
+ for r in radii:
136
+ # balls of radius r centred on voxels at least r from the voxels outside the
137
+ # phase; each covers the voxels closer than r to its centre
138
+ centres = dist >= r
139
+ if not centres.any():
140
+ break
141
+ reach = _distance(~centres, h, per, pad) # distance to the nearest centre
142
+ radius[mask & (reach < r)] = r
143
+ kept = radius[mask]
144
+ fractions = np.array([np.count_nonzero(kept >= r) / vol for r in radii])
145
+ return Granulometry(radii=radii, fractions=fractions, thickness=2.0 * radius)
146
+
147
+
148
+ def local_thickness(image, phase: int = 1, *, periodic=None) -> np.ndarray:
149
+ """Local thickness of every voxel of ``phase`` (0 elsewhere)."""
150
+ return granulometry(image, phase, periodic=periodic).thickness
151
+
152
+
153
+ # -- Euler characteristic ---------------------------------------------------------------------
154
+
155
+
156
+ def euler_characteristic(image, phase: int = 1, *, periodic=None) -> int:
157
+ """Euler characteristic (number of components - tunnels + cavities) of ``phase``,
158
+ 6-connected (its complement 26-connected): vertices - edges + squares - cubes of the
159
+ complex whose vertices are the voxels of the phase, edges their pairs of face
160
+ neighbours, squares and cubes their 2 x 2 and 2 x 2 x 2 blocks (Ohser & Mücklich
161
+ 2000). Periodic images are counted on the torus. Objects closer than a voxel touch on
162
+ the image: the estimate is biased by their contacts (for random objects, about half
163
+ the number of pairs closer than a voxel)."""
164
+ x = indicator(image, phase)
165
+ if not _periodic(image, periodic):
166
+ x = np.pad(x, 1)
167
+
168
+ def nxt(a, axis):
169
+ return np.roll(a, -1, axis=axis)
170
+
171
+ vertices = int(x.sum())
172
+ edges = sum(int((x & nxt(x, a)).sum()) for a in range(3))
173
+ squares = 0
174
+ for a, b in ((0, 1), (0, 2), (1, 2)):
175
+ pair = x & nxt(x, a)
176
+ squares += int((pair & nxt(pair, b)).sum())
177
+ cubes = x & nxt(x, 0)
178
+ cubes = cubes & nxt(cubes, 1)
179
+ cubes = cubes & nxt(cubes, 2)
180
+ return vertices - edges + squares - int(cubes.sum())
181
+
182
+
183
+ @dataclass
184
+ class Minkowski:
185
+ """Densities of the four Minkowski functionals of a phase: ``V_V``, ``S_V``, the
186
+ integral of mean curvature ``M_V`` (``(1/2) int (1/R1 + 1/R2) dS`` per unit volume)
187
+ and the Euler characteristic ``chi_V``."""
188
+
189
+ volume_fraction: float
190
+ specific_surface: float
191
+ euler_density: float # Euler characteristic per unit volume
192
+ mean_curvature: float = float("nan")
193
+
194
+
195
+ def minkowski(image, phase: int = 1, *, periodic=None) -> Minkowski:
196
+ """The Minkowski densities of a phase of an image: its volume fraction, specific surface,
197
+ density of Euler characteristic and density of mean curvature."""
198
+ from morphogen.analysis.surface import specific_surface
199
+ from morphogen.analysis.topology import mean_curvature_density
200
+
201
+ volume = float(np.prod(np.asarray(indicator(image, phase).shape) * _spacing(image)))
202
+ return Minkowski(
203
+ volume_fraction=float(indicator(image, phase).mean()),
204
+ specific_surface=specific_surface(image, phase, periodic=periodic),
205
+ euler_density=euler_characteristic(image, phase, periodic=periodic) / volume,
206
+ mean_curvature=mean_curvature_density(image, phase, periodic=periodic),
207
+ )
208
+
209
+
210
+ # -- geometric tortuosity -----------------------------------------------------------------------
211
+
212
+
213
+ def geodesic_distance(image, phase: int = 1, axis: int = 0) -> np.ndarray:
214
+ """Length of the shortest path inside ``phase`` (26-connected voxels, Euclidean steps
215
+ between voxel centres) from the face ``axis = 0`` of the box to every voxel (inf: not
216
+ reached; NaN outside the phase)."""
217
+ from scipy.sparse import coo_matrix
218
+ from scipy.sparse.csgraph import dijkstra
219
+
220
+ mask = indicator(image, phase)
221
+ h = _spacing(image)
222
+ index = np.full(mask.shape, -1, dtype=np.int64)
223
+ index[mask] = np.arange(int(mask.sum()))
224
+ rows, cols, weights = [], [], []
225
+
226
+ def pair(d, n): # slices of the voxels and of their neighbours at offset d
227
+ return (slice(0, n - d), slice(d, n)) if d >= 0 else (slice(-d, n), slice(0, n + d))
228
+
229
+ for offset in np.ndindex(3, 3, 3):
230
+ d = np.array(offset) - 1
231
+ if tuple(d) <= (0, 0, 0):
232
+ continue # each pair of neighbours once
233
+ sa, sb = zip(*(pair(int(di), n) for di, n in zip(d, mask.shape, strict=True)), strict=True)
234
+ a, b = index[sa], index[sb]
235
+ ok = (a >= 0) & (b >= 0)
236
+ rows.append(a[ok])
237
+ cols.append(b[ok])
238
+ weights.append(np.full(int(ok.sum()), float(np.linalg.norm(d * h))))
239
+ n = int(mask.sum())
240
+ graph = coo_matrix(
241
+ (np.concatenate(weights), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)
242
+ ).tocsr()
243
+ sources = np.take(index, 0, axis=axis)
244
+ sources = sources[sources >= 0]
245
+ out = np.full(mask.shape, np.nan)
246
+ if sources.size == 0:
247
+ out[mask] = np.inf
248
+ return out
249
+ dist = dijkstra(graph, directed=False, indices=sources, min_only=True)
250
+ out[mask] = dist + 0.5 * h[axis] # from the face, not from the first voxel centres
251
+ return out
252
+
253
+
254
+ def geometric_tortuosity(image, phase: int = 1, axis: int = 0) -> float:
255
+ """Mean length of the shortest paths through ``phase`` between the faces normal to
256
+ ``axis``, divided by the edge of the box (inf when the phase does not percolate)."""
257
+ dist = geodesic_distance(image, phase, axis)
258
+ outlet = np.take(dist, -1, axis=axis)
259
+ outlet = outlet[np.isfinite(outlet) | np.isinf(outlet)]
260
+ reached = outlet[np.isfinite(outlet)]
261
+ if reached.size == 0:
262
+ return float("inf")
263
+ h = _spacing(image)[axis]
264
+ length = dist.shape[axis] * h
265
+ return float(np.mean(reached + 0.5 * h) / length)
@@ -0,0 +1,160 @@
1
+ """The particles of a phase in a volume: its connected parts, those that touch split by
2
+ the watershed of their distance map, with their volumes, their centres and their number
3
+ per unit volume — measured in three dimensions, where the stereology of
4
+ :mod:`morphogen.analysis.stereology` recovers them from sections.
5
+
6
+ The distance of each voxel of the phase to the other phase is highest at the heart of
7
+ the particles and low in the necks where two of them touch or overlap. Its maxima of a
8
+ prominence at least ``prominence`` (the descent from a maximum to the saddle towards a
9
+ higher one: a neck, not the roughness of a surface) are the markers of the particles, and
10
+ the watershed of the opposite of the distance (:mod:`morphogen.kernels.watershed`: the
11
+ voxels conquered from the markers in decreasing order of their distance) shares the
12
+ phase between them: two overlapping balls are cut by the plane of their neck. Voxels are
13
+ 26-connected, through the faces of a periodic image.
14
+
15
+ In an image that is not periodic, the particles cut by its frame are known in part only:
16
+ they are left out, and each of the others counts for ``Π n_i / Π (n_i - 1 - w_i)`` over
17
+ the axes (``n_i`` voxels of the image, ``w_i`` voxels of the particle: the inverse of the
18
+ fraction of its positions that keep it whole in the frame, Miles 1974 and Lantuéjoul
19
+ 1980), so that the number per unit volume and the distribution of sizes are not biased
20
+ towards the small particles.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass
26
+
27
+ import numpy as np
28
+ from scipy import ndimage
29
+
30
+ from morphogen.analysis.basic import indicator
31
+ from morphogen.analysis.morphology import _distance, _periodic, _spacing
32
+
33
+
34
+ @dataclass
35
+ class Particles:
36
+ """The particles of a phase: ``labels`` (0 outside the phase, else the number of the
37
+ particle from 1), their ``volumes`` and ``centroids`` (n x 3, in the box), their
38
+ ``weights`` (1; in an image that is not periodic, 0 for a particle cut by the frame
39
+ and the factor of Miles and Lantuéjoul for the others) and the ``volume`` of the
40
+ image."""
41
+
42
+ labels: np.ndarray
43
+ volumes: np.ndarray
44
+ centroids: np.ndarray
45
+ weights: np.ndarray
46
+ volume: float
47
+
48
+ @property
49
+ def count(self) -> int:
50
+ """The number of particles (those cut by the frame included)."""
51
+ return len(self.volumes)
52
+
53
+ @property
54
+ def radii(self) -> np.ndarray:
55
+ """The radii of the balls of the volumes of the particles."""
56
+ return np.cbrt(0.75 * self.volumes / np.pi)
57
+
58
+ def density(self, edges=None):
59
+ """The number of particles per unit volume; in the classes of radii between
60
+ ``edges``, an array."""
61
+ if edges is None:
62
+ return float(self.weights.sum() / self.volume)
63
+ counts, _ = np.histogram(self.radii, bins=edges, weights=self.weights)
64
+ return counts / self.volume
65
+
66
+ def mean_radius(self) -> float:
67
+ """Number mean of the radii of the particles."""
68
+ return float(np.average(self.radii, weights=self.weights))
69
+
70
+ def radius_cv(self) -> float:
71
+ """Coefficient of variation of the radii of the particles."""
72
+ mean = self.mean_radius()
73
+ spread = np.average((self.radii - mean) ** 2, weights=self.weights)
74
+ return float(np.sqrt(spread) / mean)
75
+
76
+
77
+ def _centroids(labels: np.ndarray, count: int, spacing, origin, periodic: bool) -> np.ndarray:
78
+ """The centres of mass of the particles; through the faces of a periodic image, from
79
+ the positions of their voxels nearest their first one."""
80
+ index = np.nonzero(labels)
81
+ which = labels[index] - 1
82
+ position = np.stack(index, axis=1).astype(float)
83
+ if periodic:
84
+ _, first = np.unique(which, return_index=True)
85
+ shape = np.asarray(labels.shape, dtype=float)
86
+ reference = position[first][which]
87
+ position = reference + (position - reference + 0.5 * shape) % shape - 0.5 * shape
88
+ sums = np.stack([np.bincount(which, position[:, a], minlength=count) for a in range(3)], 1)
89
+ centres = sums / np.bincount(which, minlength=count)[:, None]
90
+ if periodic:
91
+ centres %= np.asarray(labels.shape, dtype=float)
92
+ return np.asarray(origin, dtype=float) + (centres + 0.5) * np.asarray(spacing, dtype=float)
93
+
94
+
95
+ def particle_sizes(
96
+ image,
97
+ phase: int = 1,
98
+ *,
99
+ separate: bool = True,
100
+ prominence: float | None = None,
101
+ min_radius: float = 0.0,
102
+ periodic=None,
103
+ ) -> Particles:
104
+ """The particles of ``phase`` in the volume of an image (see the module): its
105
+ 26-connected parts and, with ``separate``, those that touch split by the watershed
106
+ of their distance map from its maxima of prominence at least ``prominence`` (physical
107
+ units; default half a voxel). The particles of equivalent radius below ``min_radius``
108
+ are left out. On periodic images each particle counts once, whole across the faces;
109
+ otherwise those cut by the frame have a zero weight and the others the factor of
110
+ Miles and Lantuéjoul."""
111
+ from morphogen.kernels.watershed import flood_volume, prominent_maxima_volume
112
+
113
+ mask = np.ascontiguousarray(indicator(image, phase).astype(bool))
114
+ h = _spacing(image)
115
+ per = _periodic(image, periodic)
116
+ origin = getattr(image, "origin", (0.0, 0.0, 0.0))
117
+ volume = float(mask.size * np.prod(h))
118
+ empty = Particles(np.zeros(mask.shape, np.int32), np.zeros(0), np.zeros((0, 3)),
119
+ np.zeros(0), volume) # fmt: skip
120
+ if not mask.any():
121
+ return empty
122
+ pad = 0
123
+ if per: # the distance through the faces, beyond the largest inscribed ball
124
+ rough = ndimage.distance_transform_edt(mask, sampling=h)
125
+ pad = min(int(np.ceil(rough.max() / float(h.min()))) + 2, max(mask.shape))
126
+ distance = _distance(mask, h, per, pad)
127
+ if separate:
128
+ prominence = 0.5 * float(h.min()) if prominence is None else float(prominence)
129
+ else:
130
+ prominence = np.inf # the highest point of each connected part alone
131
+ peaks = prominent_maxima_volume(distance, mask, prominence, per)
132
+ labels, count = ndimage.label(peaks, structure=np.ones((3, 3, 3), dtype=bool))
133
+ labels = labels.astype(np.int32)
134
+ labels[~mask] = -1
135
+ flood_volume(-distance, labels, per)
136
+ labels[~mask] = 0
137
+ volumes = np.bincount(labels.ravel(), minlength=count + 1)[1:] * float(np.prod(h))
138
+ keep = np.cbrt(0.75 * volumes / np.pi) >= float(min_radius)
139
+ if not keep.all():
140
+ renumber = np.zeros(count + 1, dtype=np.int32)
141
+ renumber[1:][keep] = np.arange(1, int(keep.sum()) + 1)
142
+ labels, volumes, count = renumber[labels], volumes[keep], int(keep.sum())
143
+ if count == 0:
144
+ return empty
145
+ weights = np.ones(count)
146
+ if not per:
147
+ n = np.asarray(mask.shape)
148
+ for k, box in enumerate(ndimage.find_objects(labels)):
149
+ free = 1.0
150
+ for axis in range(3):
151
+ if n[axis] == 1:
152
+ continue # a planar image: no frame across its plane
153
+ low, high = box[axis].start, box[axis].stop
154
+ if low == 0 or high == n[axis]:
155
+ free = 0.0 # cut by the frame
156
+ break
157
+ free *= (n[axis] - 1 - (high - low)) / n[axis]
158
+ weights[k] = 1.0 / free if free > 0.0 else 0.0
159
+ centroids = _centroids(labels, count, h, origin, per)
160
+ return Particles(labels, volumes, centroids, weights, volume)