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,1352 @@
1
+ """Triangle surfaces of morphologies and of the fields of simulations, for the 3D view of
2
+ the interface (:mod:`morphogen.gui`), with the volumes that colour the faces of the box
3
+ and the sections of that view.
4
+
5
+ A :class:`Surface` is made of triangles in *groups*, each lying between two *regions*:
6
+ the one behind its triangles (``inside``) and the one in front of them (``outside``, -1
7
+ beyond the box). Its triangles turn counter-clockwise around their normal, which points
8
+ from inside to outside, so that a view of opaque regions draws, on each side of a
9
+ triangle, the region that a ray entering through it meets: the inside seen from the
10
+ front, the outside seen from the back (and the inside again behind the faces of the box,
11
+ whose shell is then seen from within, through a section). Between two regions, the
12
+ inside is the larger of the two. The regions are the phases of a morphology, or its
13
+ cells (grains) with their phases (:attr:`Surface.region_phase`,
14
+ :attr:`Surface.region_label`).
15
+
16
+ What the surfaces are:
17
+
18
+ * morphologies with a level set (two phases): its zero level set by the marching cubes of
19
+ scikit-image (the ``surface`` extra), sampled at the centres of the voxels of
20
+ ``resolution`` cells along the longest edge of the domain (as
21
+ :func:`morphogen.viz.sections.level_set_measures`), padded by one cell on every side
22
+ (periodically, or by its last values) and cut by the faces of the box; without
23
+ scikit-image, the faces of its voxels of phase 1. The level set is the volume of the
24
+ view (:attr:`Surface.volume`), which draws the phases on the faces of the box and on a
25
+ section;
26
+ * tessellations without grain boundaries (Voronoi and Laguerre polycrystals): the exact
27
+ facets of their cells (:meth:`~morphogen.models.tessellation.Tessellation.cell_complex`),
28
+ between cells and on the faces of the box; their voxels give the sections;
29
+ * the other morphologies (cells or grains, several phases, no level set): the faces
30
+ between voxels of different regions, those regions being the volume;
31
+ * simulations on tetrahedral meshes (:func:`vtu_surface`): the faces of the elements on
32
+ the boundary of the mesh and between regions (phases, grains), with the field at their
33
+ vertices (the nodal values, or on each side the mean of the values of the elements of
34
+ that region around the node) and the displacement of their nodes;
35
+ * simulations on voxels (FFT, :func:`vti_surface`): the faces between voxels of
36
+ different regions; the regions and the field of the voxels are volumes.
37
+
38
+ The number of triangles is bounded (``max_triangles``, :data:`MAX_TRIANGLES` by default):
39
+ the grids of morphologies are made coarser, voxel images subsampled, meshes simplified by
40
+ clustering their vertices. :func:`encode` turns a surface into the JSON data of the page,
41
+ its arrays in base64 (little-endian).
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import base64
47
+ import dataclasses
48
+ import math
49
+ from dataclasses import dataclass
50
+ from pathlib import Path
51
+
52
+ import numpy as np
53
+ from numba import njit
54
+
55
+ from morphogen.domain import Grid
56
+ from morphogen.viz.png import PALETTE, label_colors
57
+
58
+ __all__ = [
59
+ "DIRECTIONS",
60
+ "EXTERIOR",
61
+ "MAX_TRIANGLES",
62
+ "MAX_VOLUME",
63
+ "MIN_RESOLUTION",
64
+ "Surface",
65
+ "Volume",
66
+ "encode",
67
+ "magnification",
68
+ "mesh_surface",
69
+ "morphology_surface",
70
+ "voxel_surface",
71
+ "vti_surface",
72
+ "vtu_surface",
73
+ ]
74
+
75
+ #: Largest number of triangles of a surface (the 3D view stays fluid with it)
76
+ MAX_TRIANGLES = 300_000
77
+ #: Largest number of cells along an edge of a volume (and of the voxel faces drawn)
78
+ MAX_VOLUME = 128
79
+ #: Coarsest grid (cells along the longest edge) to which a budget lowers a resolution
80
+ MIN_RESOLUTION = 8
81
+ #: Tessellations of more cells are drawn by their voxels (their exact cells take long)
82
+ MAX_EXACT_CELLS = 500
83
+ #: Region beyond the faces of the box
84
+ EXTERIOR = -1
85
+ #: Arrays of the files of fields that are not fields (phases, grains, orientations...)
86
+ NOT_FIELDS = ("phase", "grain", "cell", "euler", "outer", "fluctuation")
87
+
88
+
89
+ @dataclass
90
+ class Volume:
91
+ """Values on the cells of a regular grid of the box (arrays ``[i, j, k]`` along x, y
92
+ and z, encoded x fastest), which colour the faces of the box (when ``box``) and the
93
+ sections of the 3D view.
94
+
95
+ ``kind``: ``"level_set"`` (negative in phase 1, quantized on 8 bits, ``phi = step (q -
96
+ 128)``, interpolated linearly between the cell centres, across the faces of the box
97
+ when ``periodic``), ``"regions"`` (the region of each cell) or ``"field"`` (values
98
+ quantized on 16 bits over ``range``: ``value = lo + q (hi - lo) / 65535``).
99
+ """
100
+
101
+ kind: str
102
+ data: np.ndarray
103
+ periodic: bool = False
104
+ step: float = 1.0
105
+ range: tuple[float, float] | None = None
106
+ box: bool = True
107
+
108
+
109
+ @dataclass
110
+ class Surface:
111
+ """Triangles in groups between regions (see the module).
112
+
113
+ Attributes
114
+ ----------
115
+ positions, normals
116
+ Vertices (n, 3) and their unit normals, from inside to outside.
117
+ triangles
118
+ Vertex indices (m, 3), counter-clockwise around the normals.
119
+ groups
120
+ One row per group (g, 6): inside and outside regions, first vertex and number of
121
+ vertices, first triangle and number of triangles (vertices and triangles are
122
+ stored group after group; vertices are not shared between groups).
123
+ region_phase, region_label
124
+ Phase of each region, and its cell or grain (None without labels; -1: none).
125
+ lower, upper
126
+ The box.
127
+ method
128
+ How the triangles were made: ``"marching cubes"``, ``"cells"`` (exact facets),
129
+ ``"voxels"`` (voxel faces) or ``"mesh"`` (faces of a tetrahedral mesh).
130
+ resolution
131
+ Cells along the longest edge of the grid used (None for meshes and cells).
132
+ reduced
133
+ Whether the grid was made coarser, or the mesh simplified, to fit the budget.
134
+ volume
135
+ Level set or regions of the cells of the box (:class:`Volume`), or None.
136
+ field, fields
137
+ Field drawn and the fields available (simulations).
138
+ values
139
+ Field at the vertices (n, 2): seen from the inside, from the outside.
140
+ field_volume
141
+ Field of the cells (voxel images), quantized over ``field_range``.
142
+ field_range
143
+ Smallest and largest finite values of the field (all its elements or voxels).
144
+ point_field
145
+ Whether the field is nodal (otherwise of the elements or voxels).
146
+ displacement
147
+ Displacement of the vertices (n, 3), or None.
148
+ lattice
149
+ Voxel faces: the nodes of their grid along each edge, and the node (C order) and
150
+ the direction of the normal (:data:`DIRECTIONS`) of each vertex, which encode
151
+ them compactly; None otherwise.
152
+ """
153
+
154
+ positions: np.ndarray
155
+ normals: np.ndarray
156
+ triangles: np.ndarray
157
+ groups: np.ndarray
158
+ region_phase: np.ndarray
159
+ region_label: np.ndarray | None
160
+ lower: np.ndarray
161
+ upper: np.ndarray
162
+ method: str
163
+ resolution: int | None = None
164
+ reduced: bool = False
165
+ volume: Volume | None = None
166
+ field: str | None = None
167
+ fields: list[str] = dataclasses.field(default_factory=list)
168
+ values: np.ndarray | None = None
169
+ field_volume: Volume | None = None
170
+ field_range: tuple[float, float] | None = None
171
+ point_field: bool = False
172
+ displacement: np.ndarray | None = None
173
+ lattice: tuple | None = None
174
+
175
+ @property
176
+ def n_triangles(self) -> int:
177
+ return len(self.triangles)
178
+
179
+ @property
180
+ def n_vertices(self) -> int:
181
+ return len(self.positions)
182
+
183
+ def group_triangles(self, a: int, b: int) -> np.ndarray:
184
+ """Triangles of the groups between regions ``a`` and ``b`` (either side)."""
185
+ rows = [g for g in self.groups if {int(g[0]), int(g[1])} == {int(a), int(b)}]
186
+ if not rows:
187
+ return np.zeros((0, 3), dtype=np.int64)
188
+ return np.concatenate([self.triangles[g[4] : g[4] + g[5]] for g in rows])
189
+
190
+ def area(self, a: int | None = None, b: int | None = None) -> float:
191
+ """Area of the triangles between regions ``a`` and ``b`` (all of them by
192
+ default)."""
193
+ tri = self.triangles if a is None else self.group_triangles(a, b)
194
+ p = self.positions[tri].astype(np.float64)
195
+ return float(
196
+ 0.5 * np.linalg.norm(np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0]), axis=1).sum()
197
+ )
198
+
199
+
200
+ # -- helpers ------------------------------------------------------------------------------------
201
+
202
+
203
+ def _skimage() -> bool:
204
+ try:
205
+ import skimage.measure # noqa: F401
206
+ except ImportError:
207
+ return False
208
+ return True
209
+
210
+
211
+ def _vertex_normals(positions: np.ndarray, triangles: np.ndarray) -> np.ndarray:
212
+ """Unit normals of the vertices: the sum of the normals of their triangles weighted by
213
+ their areas (z for vertices of no triangle of positive area)."""
214
+ n = len(positions)
215
+ out = np.zeros((n, 3))
216
+ if len(triangles):
217
+ p = positions[triangles].astype(np.float64)
218
+ normal = np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0])
219
+ for c in range(3):
220
+ for k in range(3):
221
+ out[:, c] += np.bincount(triangles[:, k], weights=normal[:, c], minlength=n)
222
+ norm = np.linalg.norm(out, axis=1)
223
+ flat = norm <= 1e-30
224
+ out[flat] = (0.0, 0.0, 1.0)
225
+ norm[flat] = 1.0
226
+ return out / norm[:, None]
227
+
228
+
229
+ def _compact(positions: np.ndarray, triangles: np.ndarray):
230
+ """The vertices used by the triangles, renumbered."""
231
+ used, inverse = np.unique(triangles, return_inverse=True)
232
+ return positions[used], inverse.reshape(-1, 3), used
233
+
234
+
235
+ def _assemble(pair: np.ndarray, local: np.ndarray, size: int):
236
+ """Vertices shared within each group of triangles: ``pair`` (m, 2) the regions of each
237
+ triangle, ``local`` (m, 3) the identities of their corners (below ``size``), merged in
238
+ a group when equal. Returns the triangles (group after group), the identity and the
239
+ group of each vertex, and the table of groups (see :attr:`Surface.groups`)."""
240
+ if not len(pair):
241
+ empty = np.zeros((0, 3), dtype=np.int64)
242
+ return (
243
+ empty,
244
+ np.zeros(0, dtype=np.int64),
245
+ np.zeros(0, dtype=np.int64),
246
+ np.zeros((0, 6), dtype=np.int64),
247
+ )
248
+ pairs, group = np.unique(pair, axis=0, return_inverse=True)
249
+ group = group.ravel()
250
+ order = np.argsort(group, kind="stable")
251
+ group, local = group[order], local[order]
252
+ keys = group[:, None].astype(np.int64) * int(size) + local
253
+ unique, inverse = np.unique(keys.ravel(), return_inverse=True)
254
+ triangles = inverse.reshape(-1, 3)
255
+ vgroup = unique // int(size)
256
+ ids, first_v, count_v = np.unique(vgroup, return_index=True, return_counts=True)
257
+ _, first_t, count_t = np.unique(group, return_index=True, return_counts=True)
258
+ table = np.column_stack([pairs[ids, 0], pairs[ids, 1], first_v, count_v, first_t, count_t])
259
+ return triangles, unique % int(size), vgroup, table.astype(np.int64)
260
+
261
+
262
+ def _canonical(inside: np.ndarray, outside: np.ndarray):
263
+ """Whether each face must be turned so that its inside is the larger region (the
264
+ exterior always outside)."""
265
+ return (outside > inside) & (outside != EXTERIOR) | (inside == EXTERIOR)
266
+
267
+
268
+ def _cell_step(phi: np.ndarray) -> float:
269
+ """Typical change of a level set over a cell at its zero level set: the median of its
270
+ differences between neighbours of opposite signs (1 without any)."""
271
+ neg = phi < 0
272
+ steps = []
273
+ for a in range(phi.ndim):
274
+ if phi.shape[a] < 2:
275
+ continue
276
+ lo = [slice(None)] * phi.ndim
277
+ hi = [slice(None)] * phi.ndim
278
+ lo[a], hi[a] = slice(0, -1), slice(1, None)
279
+ cross = neg[tuple(lo)] != neg[tuple(hi)]
280
+ steps.append(np.abs(phi[tuple(hi)] - phi[tuple(lo)])[cross])
281
+ steps = np.concatenate(steps) if steps else np.zeros(0)
282
+ steps = steps[np.isfinite(steps) & (steps > 0)]
283
+ return float(np.median(steps)) if steps.size else 1.0
284
+
285
+
286
+ def _crossed_cubes(phi: np.ndarray) -> int:
287
+ """Cubes of 2 x 2 x 2 samples whose values change sign (marching cubes puts two
288
+ triangles in each, on average)."""
289
+ neg = phi < 0
290
+ some, every = neg, neg
291
+ for a in range(3):
292
+ if neg.shape[a] < 2:
293
+ return 0
294
+ lo = [slice(None)] * 3
295
+ hi = [slice(None)] * 3
296
+ lo[a], hi[a] = slice(0, -1), slice(1, None)
297
+ some = some[tuple(lo)] | some[tuple(hi)]
298
+ every = every[tuple(lo)] & every[tuple(hi)]
299
+ return int(np.count_nonzero(some & ~every))
300
+
301
+
302
+ def _finest(sample, requested: int, budget: int):
303
+ """The finest grid, of at most ``requested`` cells along the longest edge, whose
304
+ triangles fit ``budget``: ``sample(n)`` gives the data of a grid and its count of
305
+ triangles. From the requested grid, coarser by the square root of the ratio of the
306
+ counts (those of a surface grow as the square of the resolution), then finer again
307
+ while the count leaves room (thin features vanish on coarse grids, which lowers the
308
+ count more than the resolution); six samplings at most. Returns the resolution, its
309
+ data and count, and whether it is coarser than requested."""
310
+ fits = last = None # (resolution, data, count): the finest grid within, the last tried
311
+ above = None # the coarsest grid beyond
312
+ n = int(requested)
313
+ for _ in range(6):
314
+ data, count = sample(n)
315
+ last = (n, data, count)
316
+ if count <= budget or n <= MIN_RESOLUTION:
317
+ if fits is None or n > fits[0]:
318
+ fits = last
319
+ if n == requested or count > 0.75 * budget:
320
+ break
321
+ elif above is None or n < above:
322
+ above = n
323
+ low = fits[0] if fits is not None else MIN_RESOLUTION - 1
324
+ top = int(requested) if above is None else above - 1
325
+ guess = int(n * math.sqrt(budget / max(count, 1)) * 0.97)
326
+ n = min(max(guess, low + 1, MIN_RESOLUTION), top)
327
+ if n <= low:
328
+ break
329
+ n, data, count = fits if fits is not None else last
330
+ return n, data, count, n < int(requested)
331
+
332
+
333
+ def _shape(lengths, n: int) -> tuple[int, int, int]:
334
+ """Cells along each edge for ``n`` along the longest (square cells, as the grids of
335
+ :meth:`morphogen.domain.Grid.for_domain`)."""
336
+ lengths = np.asarray(lengths, dtype=float)
337
+ h = float(lengths.max()) / int(n)
338
+ return tuple(int(k) for k in np.maximum(1, np.rint(lengths / h)))
339
+
340
+
341
+ def _resampled(data: np.ndarray, shape, *, linear: bool, periodic: bool = False) -> np.ndarray:
342
+ """Values of cells at the centres of the cells of a coarser grid of the same box:
343
+ those of the cells containing them, or interpolated linearly."""
344
+ if tuple(shape) == data.shape:
345
+ return data
346
+ coords = np.meshgrid(
347
+ *[(np.arange(m) + 0.5) * (n / m) - 0.5 for n, m in zip(data.shape, shape, strict=True)],
348
+ indexing="ij",
349
+ )
350
+ if not linear:
351
+ idx = [
352
+ np.clip(np.rint(c), 0, n - 1).astype(np.int64)
353
+ for c, n in zip(coords, data.shape, strict=True)
354
+ ]
355
+ return data[tuple(idx)]
356
+ from scipy.ndimage import map_coordinates
357
+
358
+ mode = "grid-wrap" if periodic else "nearest"
359
+ out = map_coordinates(data.astype(np.float32), np.stack(coords), order=1, mode=mode)
360
+ return out.astype(data.dtype, copy=False)
361
+
362
+
363
+ def _level_volume(phi: np.ndarray, periodic: bool) -> Volume:
364
+ """A level set at the cell centres as a :class:`Volume` (8 bits, a sixteenth of the
365
+ change over a cell at the interface per step, at most :data:`MAX_VOLUME` cells along
366
+ an edge)."""
367
+ m = min(max(phi.shape), MAX_VOLUME)
368
+ coarse = _resampled(phi, _shape(phi.shape, m), linear=True, periodic=periodic)
369
+ step = _cell_step(coarse) / 16.0
370
+ q = np.clip(np.floor(128.0 + coarse / step), 0, 255).astype(np.uint8)
371
+ return Volume("level_set", q, periodic=periodic, step=step)
372
+
373
+
374
+ def _region_volume(regions: np.ndarray, box: bool = True) -> Volume:
375
+ """Regions of cells as a :class:`Volume` (at most :data:`MAX_VOLUME` cells along an
376
+ edge, the region of the cell holding each centre)."""
377
+ m = min(max(regions.shape), MAX_VOLUME)
378
+ coarse = _resampled(regions, _shape(regions.shape, m), linear=False)
379
+ top = int(coarse.max()) if coarse.size else 0
380
+ return Volume("regions", np.ascontiguousarray(coarse, dtype=_index_type(top)), box=box)
381
+
382
+
383
+ def _field_volume(values: np.ndarray, shape, value_range) -> Volume:
384
+ """Values of cells as a :class:`Volume` (16 bits over their range; 0 for the values
385
+ that are not finite)."""
386
+ coarse = _resampled(values, shape, linear=False).astype(np.float64)
387
+ lo, hi = value_range
388
+ span = hi - lo if hi > lo else 1.0
389
+ q = np.clip(np.rint((coarse - lo) / span * 65535.0), 0, 65535)
390
+ q[~np.isfinite(coarse)] = 0
391
+ return Volume("field", q.astype(np.uint16), range=(float(lo), float(hi)))
392
+
393
+
394
+ def _finite_range(values: np.ndarray) -> tuple[float, float]:
395
+ v = np.asarray(values, dtype=np.float64)
396
+ v = v[np.isfinite(v)]
397
+ return (float(v.min()), float(v.max())) if v.size else (0.0, 1.0)
398
+
399
+
400
+ def _scalars(values: np.ndarray) -> np.ndarray:
401
+ """One value per row: the values, or the norms of vectors."""
402
+ v = np.asarray(values, dtype=np.float64)
403
+ return np.linalg.norm(v.reshape(len(v), -1), axis=1) if v.ndim > 1 else v
404
+
405
+
406
+ # -- morphologies: marching cubes of the level set ---------------------------------------------
407
+
408
+
409
+ def _level_set(micro, grid: Grid) -> np.ndarray:
410
+ """The level set at the cell centres of ``grid``, made finite (its placeholders of no
411
+ interface at the size of the domain, as for its measures)."""
412
+ phi = np.asarray(micro.level_set(grid=grid).data, dtype=np.float32)
413
+ far = np.float32(micro.domain.diagonal)
414
+ return np.clip(np.nan_to_num(phi, nan=far, posinf=far, neginf=-far), -far, far)
415
+
416
+
417
+ def _clip(positions: np.ndarray, triangles: np.ndarray, axis: int, value: float, above: bool):
418
+ """The triangles cut by the plane ``x_axis = value``: their parts on the side kept
419
+ (``above`` or below), with a new vertex on each edge crossing it (the vertex of the
420
+ edge lying on the plane, if any). The triangles left with a repeated corner are
421
+ dropped: the surface stays closed wherever it was."""
422
+ d = positions[:, axis] - value
423
+ if not above:
424
+ d = -d
425
+ inside = d >= 0.0
426
+ if inside.all() or not len(triangles):
427
+ return positions, triangles
428
+ flags = inside[triangles]
429
+ count = flags.sum(axis=1)
430
+ one, two = triangles[count == 1], triangles[count == 2]
431
+ turn = np.arange(3)
432
+ one = np.take_along_axis(one, (np.argmax(flags[count == 1], axis=1)[:, None] + turn) % 3, 1)
433
+ two = np.take_along_axis(two, (np.argmin(flags[count == 2], axis=1)[:, None] + turn) % 3, 1)
434
+ edges = np.concatenate([one[:, [0, 1]], one[:, [0, 2]], two[:, [0, 1]], two[:, [0, 2]]])
435
+ edges.sort(axis=1)
436
+ n = len(positions)
437
+ unique, inverse = np.unique(edges[:, 0] * n + edges[:, 1], return_inverse=True)
438
+ i, j = unique // n, unique % n
439
+ t = d[i] / (d[i] - d[j])
440
+ fresh = (t > 0.0) & (t < 1.0) # otherwise an end of the edge lies on the plane
441
+ points = positions[i[fresh]] + t[fresh, None] * (positions[j[fresh]] - positions[i[fresh]])
442
+ points[:, axis] = value
443
+ vertex = np.where(t <= 0.0, i, j)
444
+ vertex[fresh] = n + np.arange(int(fresh.sum()))
445
+ ids = vertex[inverse.ravel()]
446
+ a, b = len(one), len(two)
447
+ ab1, ac1, ab2, ac2 = np.split(ids, [a, 2 * a, 2 * a + b])
448
+ out = np.concatenate(
449
+ [
450
+ triangles[count == 3],
451
+ np.stack([one[:, 0], ab1, ac1], axis=1),
452
+ np.stack([ab2, two[:, 1], two[:, 2]], axis=1),
453
+ np.stack([ab2, two[:, 2], ac2], axis=1),
454
+ ]
455
+ )
456
+ repeated = (out[:, 0] == out[:, 1]) | (out[:, 1] == out[:, 2]) | (out[:, 0] == out[:, 2])
457
+ return np.concatenate([positions, points]), out[~repeated]
458
+
459
+
460
+ def _outward(positions, triangles, phi, origin, spacing) -> np.ndarray:
461
+ """The triangles turned, if needed, so that their normals point to the increasing
462
+ values of ``phi`` (samples at ``origin + index * spacing``): out of phase 1."""
463
+ from scipy.ndimage import map_coordinates
464
+
465
+ if not len(triangles):
466
+ return triangles
467
+ sample = triangles[:: max(1, len(triangles) // 4000)]
468
+ p = positions[sample]
469
+ normal = np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0])
470
+ norm = np.linalg.norm(normal, axis=1)
471
+ ok = norm > 0
472
+ normal = normal[ok] / norm[ok, None]
473
+ centre = p[ok].mean(axis=1)
474
+ delta = 0.25 * float(np.min(spacing))
475
+
476
+ def at(x):
477
+ return map_coordinates(phi, ((x - origin) / spacing).T, order=1, mode="nearest")
478
+
479
+ rise = at(centre + delta * normal) - at(centre - delta * normal)
480
+ return triangles if np.sum(rise > 0) >= np.sum(rise < 0) else triangles[:, ::-1].copy()
481
+
482
+
483
+ def _marching_cubes_surface(micro, resolution: int, max_triangles: int) -> Surface:
484
+ """The zero level set of a two-phase morphology by marching cubes (see the module)."""
485
+ from skimage.measure import marching_cubes
486
+
487
+ domain = micro.domain
488
+ lower, upper = domain.lower.astype(float), domain.upper.astype(float)
489
+ per_cube = 2.0 # triangles per cube crossed by the surface, on average
490
+
491
+ def sample(n):
492
+ grid = Grid.for_domain(domain, shape=n)
493
+ phi = _level_set(micro, grid)
494
+ padded = np.pad(phi, 1, mode="wrap" if domain.periodic else "edge")
495
+ zero = padded == 0 # values at the level: vertices on samples, pushed outside
496
+ if zero.any():
497
+ padded = np.where(zero, np.float32(1e-3 * _cell_step(padded)), padded)
498
+ crossed = _crossed_cubes(padded)
499
+ return (grid, phi, padded, crossed), int(per_cube * crossed)
500
+
501
+ requested, reduced = int(resolution), False
502
+ for _ in range(3): # beyond the budget, coarser again with the count of this structure
503
+ n, (grid, phi, padded, crossed), _, coarser = _finest(sample, requested, max_triangles)
504
+ reduced = reduced or coarser
505
+ spacing = grid.spacing.astype(float)
506
+ origin = lower - 0.5 * spacing # the sample 0 of the padded grid, a cell outside
507
+ positions, triangles = np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64)
508
+ if not crossed:
509
+ break
510
+ verts, faces, _, _ = marching_cubes(
511
+ padded, 0.0, spacing=tuple(spacing), allow_degenerate=False
512
+ )
513
+ positions = verts.astype(np.float64) + origin
514
+ triangles = _outward(positions, faces.astype(np.int64), padded, origin, spacing)
515
+ for axis in range(3):
516
+ positions, triangles = _clip(positions, triangles, axis, lower[axis], True)
517
+ positions, triangles = _clip(positions, triangles, axis, upper[axis], False)
518
+ positions, triangles, _ = _compact(positions, triangles)
519
+ if len(triangles) <= max_triangles or n <= MIN_RESOLUTION:
520
+ break
521
+ per_cube = max(per_cube, 1.02 * len(triangles) / crossed) # thin struts make more
522
+ requested, reduced = n - 1, True
523
+ m, k = len(triangles), len(positions)
524
+ groups = np.array([[1, 0, 0, k, 0, m]], dtype=np.int64) if m else np.zeros((0, 6), np.int64)
525
+ surface = Surface(
526
+ positions=positions,
527
+ normals=_vertex_normals(positions, triangles),
528
+ triangles=triangles,
529
+ groups=groups,
530
+ region_phase=np.array([0, 1]),
531
+ region_label=None,
532
+ lower=lower,
533
+ upper=upper,
534
+ method="marching cubes",
535
+ resolution=n,
536
+ reduced=reduced,
537
+ volume=_level_volume(phi, domain.periodic),
538
+ )
539
+ return _within(surface, max_triangles)
540
+
541
+
542
+ # -- morphologies: exact cells of tessellations -----------------------------------------------
543
+
544
+
545
+ def _exact_cells(micro) -> bool:
546
+ from morphogen.models.tessellation import Tessellation
547
+
548
+ return (
549
+ isinstance(micro, Tessellation)
550
+ and micro.boundary_thickness == 0
551
+ and 0 < micro.n_cells <= MAX_EXACT_CELLS
552
+ )
553
+
554
+
555
+ def _cells_surface(micro, resolution: int) -> Surface:
556
+ """The facets of the exact cells of a tessellation, between cells and on the faces of
557
+ the box (flat, their vertices their own); its labels give the sections."""
558
+ cx = micro.cell_complex()
559
+ vectors, _ = cx.facet_vectors()
560
+ pieces = cx.facet_pieces
561
+ cells = cx.piece_cell
562
+ rows = []
563
+ for f, loop in enumerate(cx.facets):
564
+ if len(loop) < 3:
565
+ continue
566
+ a, b = int(pieces[f, 0]), int(pieces[f, 1])
567
+ inside = int(cells[a])
568
+ outside = int(cells[b]) if b >= 0 else EXTERIOR
569
+ if inside == outside:
570
+ continue
571
+ normal = vectors[f]
572
+ norm = float(np.linalg.norm(normal))
573
+ if norm <= 0:
574
+ continue
575
+ loop = np.asarray(loop, dtype=np.int64)
576
+ if _canonical(np.array([inside]), np.array([outside]))[0]:
577
+ inside, outside, loop, normal = outside, inside, loop[::-1], -normal
578
+ rows.append((inside, outside, loop, normal / norm))
579
+ rows.sort(key=lambda r: (r[0], r[1]))
580
+ positions, normals, triangles, groups = [], [], [], []
581
+ nv = nt = 0
582
+ for inside, outside, loop, normal in rows:
583
+ k = len(loop)
584
+ fan = np.stack([np.zeros(k - 2, np.int64), np.arange(1, k - 1), np.arange(2, k)], axis=1)
585
+ if groups and groups[-1][0] == inside and groups[-1][1] == outside:
586
+ groups[-1][3] += k
587
+ groups[-1][5] += k - 2
588
+ else:
589
+ groups.append([inside, outside, nv, k, nt, k - 2])
590
+ positions.append(cx.vertices[loop])
591
+ normals.append(np.repeat(normal[None], k, axis=0))
592
+ triangles.append(fan + nv)
593
+ nv += k
594
+ nt += k - 2
595
+ domain = micro.domain
596
+ n = min(int(resolution), MAX_VOLUME)
597
+ labels = micro.labels(grid=Grid.for_domain(domain, shape=n)).data
598
+ return Surface(
599
+ positions=np.concatenate(positions) if positions else np.zeros((0, 3)),
600
+ normals=np.concatenate(normals) if normals else np.zeros((0, 3)),
601
+ triangles=np.concatenate(triangles) if triangles else np.zeros((0, 3), np.int64),
602
+ groups=np.array(groups, dtype=np.int64).reshape(-1, 6),
603
+ region_phase=np.asarray(micro.cell_phases, dtype=np.int64),
604
+ region_label=np.arange(micro.n_cells),
605
+ lower=domain.lower.astype(float),
606
+ upper=domain.upper.astype(float),
607
+ method="cells",
608
+ resolution=None,
609
+ volume=_region_volume(np.asarray(labels, dtype=np.int64), box=False),
610
+ )
611
+
612
+
613
+ # -- voxel faces ---------------------------------------------------------------------------------
614
+
615
+
616
+ #: Directions of the normals of voxel faces: +x, -x, +y, -y, +z, -z
617
+ DIRECTIONS = np.array(
618
+ [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], dtype=float
619
+ )
620
+
621
+
622
+ def _voxel_faces(regions: np.ndarray):
623
+ """The faces between voxels of different regions, two triangles each: their regions
624
+ (m, 2, the larger inside) and the identities of their corners (m, 3), a node of the
625
+ grid (C order) and the direction of the normal (:data:`DIRECTIONS`), ``node * 6 +
626
+ direction``."""
627
+ shape = np.array(regions.shape)
628
+ nodes = shape + 1
629
+ strides = np.array([nodes[1] * nodes[2], nodes[2], 1], dtype=np.int64)
630
+ pairs, corners = [], []
631
+ for a in range(3):
632
+ if shape[a] < 2:
633
+ continue
634
+ lo = [slice(None)] * 3
635
+ hi = [slice(None)] * 3
636
+ lo[a], hi[a] = slice(0, -1), slice(1, None)
637
+ first, second = regions[tuple(lo)], regions[tuple(hi)]
638
+ where = np.nonzero(first != second)
639
+ inside, outside = first[where].astype(np.int64), second[where].astype(np.int64)
640
+ base = np.stack(where, axis=1).astype(np.int64)
641
+ base[:, a] += 1 # the plane of nodes between the two voxels
642
+ u, v = np.eye(3, dtype=np.int64)[(a + 1) % 3], np.eye(3, dtype=np.int64)[(a + 2) % 3]
643
+ quad = np.stack([base, base + u, base + u + v, base + v], axis=1) @ strides # around +a
644
+ turn = _canonical(inside, outside)
645
+ inside, outside = np.where(turn, outside, inside), np.where(turn, inside, outside)
646
+ quad[turn] = quad[turn][:, ::-1]
647
+ direction = np.where(turn, 2 * a + 1, 2 * a)
648
+ ids = quad * 6 + direction[:, None]
649
+ corners += [ids[:, [0, 1, 2]], ids[:, [0, 2, 3]]]
650
+ pair = np.stack([inside, outside], axis=1)
651
+ pairs += [pair, pair]
652
+ if not pairs:
653
+ return np.zeros((0, 2), np.int64), np.zeros((0, 3), np.int64)
654
+ return np.concatenate(pairs), np.concatenate(corners)
655
+
656
+
657
+ def _count_faces(regions: np.ndarray) -> int:
658
+ """Faces between voxels of different regions."""
659
+ total = 0
660
+ for a in range(3):
661
+ if regions.shape[a] >= 2:
662
+ total += int(np.count_nonzero(np.diff(regions, axis=a) != 0))
663
+ return total
664
+
665
+
666
+ def voxel_surface(
667
+ regions: np.ndarray,
668
+ region_phase,
669
+ region_label=None,
670
+ lower=(0.0, 0.0, 0.0),
671
+ upper=(1.0, 1.0, 1.0),
672
+ *,
673
+ values: np.ndarray | None = None,
674
+ field: str | None = None,
675
+ fields=(),
676
+ max_triangles: int = MAX_TRIANGLES,
677
+ method: str = "voxels",
678
+ ) -> Surface:
679
+ """The faces between voxels of different regions of an image of regions (cells of
680
+ the box ``[lower, upper]``), subsampled when its faces exceed ``max_triangles`` or its
681
+ edges :data:`MAX_VOLUME` cells; the regions and the ``values`` of a field of the
682
+ voxels are its volumes (the field: :attr:`Surface.field_volume`)."""
683
+ regions = np.asarray(regions, dtype=np.int64)
684
+ lower = np.asarray(lower, dtype=float)
685
+ upper = np.asarray(upper, dtype=float)
686
+ full = regions.shape
687
+
688
+ def sample(m):
689
+ coarse = _resampled(regions, _shape(full, m), linear=False)
690
+ return coarse, 2 * _count_faces(coarse)
691
+
692
+ requested = min(max(full), MAX_VOLUME)
693
+ _, coarse, _, reduced = _finest(sample, requested, max_triangles)
694
+ reduced = reduced or requested < max(full)
695
+ nodes = np.array(coarse.shape) + 1
696
+ pair, corners = _voxel_faces(coarse)
697
+ triangles, local, _, groups = _assemble(pair, corners, int(np.prod(nodes)) * 6)
698
+ node, direction = local // 6, local % 6
699
+ index = np.stack(np.unravel_index(node, tuple(nodes)), axis=1)
700
+ surface = Surface(
701
+ positions=lower + index * ((upper - lower) / (nodes - 1)),
702
+ normals=DIRECTIONS[direction],
703
+ triangles=triangles,
704
+ groups=groups,
705
+ region_phase=np.asarray(region_phase, dtype=np.int64),
706
+ region_label=None if region_label is None else np.asarray(region_label, dtype=np.int64),
707
+ lower=lower,
708
+ upper=upper,
709
+ method=method,
710
+ resolution=int(max(coarse.shape)),
711
+ reduced=reduced,
712
+ volume=_region_volume(coarse),
713
+ field=field,
714
+ fields=list(fields),
715
+ lattice=(nodes, node, direction),
716
+ )
717
+ if values is not None:
718
+ value_range = _finite_range(values)
719
+ surface.field_range = value_range
720
+ surface.field_volume = _field_volume(np.asarray(values), coarse.shape, value_range)
721
+ return surface
722
+
723
+
724
+ def _regions_of(micro, grid: Grid):
725
+ """Regions of the voxels of a morphology: its phases, or its (cell, phase) pairs
726
+ when it has cells or grains; with the phase and the label of each region."""
727
+ phase = np.asarray(micro.voxelize(grid=grid).data, dtype=np.int64)
728
+ if not micro.has_labels:
729
+ return phase, np.arange(int(phase.max()) + 1 if phase.size else 1), None
730
+ labels = np.asarray(micro.labels(grid=grid).data, dtype=np.int64)
731
+ span = int(phase.max()) + 1 if phase.size else 1
732
+ unique, inverse = np.unique((labels + 1) * span + phase, return_inverse=True)
733
+ return inverse.reshape(phase.shape), unique % span, unique // span - 1
734
+
735
+
736
+ def _voxels_of_morphology(micro, resolution: int, max_triangles: int) -> Surface:
737
+ """The voxel faces of a morphology between its regions (see the module)."""
738
+ domain = micro.domain
739
+
740
+ def sample(n):
741
+ regions, phase, label = _regions_of(micro, Grid.for_domain(domain, shape=n))
742
+ return (regions, phase, label), 2 * _count_faces(regions)
743
+
744
+ requested = min(int(resolution), MAX_VOLUME)
745
+ _, (regions, phase, label), _, reduced = _finest(sample, requested, max_triangles)
746
+ reduced = reduced or requested < int(resolution)
747
+ surface = voxel_surface(
748
+ regions, phase, label, domain.lower, domain.upper, max_triangles=max_triangles
749
+ )
750
+ surface.reduced = surface.reduced or reduced
751
+ return surface
752
+
753
+
754
+ def morphology_surface(
755
+ micro, resolution: int = 96, *, max_triangles: int = MAX_TRIANGLES, method: str = "auto"
756
+ ) -> Surface:
757
+ """The surface of a morphology between its regions, on a grid of ``resolution`` cells
758
+ along the longest edge of its domain (coarser if it exceeds ``max_triangles``).
759
+
760
+ ``method``: ``"marching cubes"`` of the level set (two phases), ``"cells"`` (exact
761
+ facets of tessellations), ``"voxels"`` (faces between voxels of different regions),
762
+ or ``"auto"``: the cells of tessellations without grain boundaries, the voxels of
763
+ morphologies with cells or grains, several phases or no level set, the marching cubes
764
+ of the others (their voxels without scikit-image). See the module.
765
+ """
766
+ resolution = int(resolution)
767
+ if resolution < MIN_RESOLUTION:
768
+ raise ValueError(f"resolution: at least {MIN_RESOLUTION} cells per edge")
769
+ if method == "auto":
770
+ from morphogen.viz.sections import has_level_set
771
+
772
+ if _exact_cells(micro):
773
+ method = "cells"
774
+ elif has_level_set(micro) and not micro.has_labels and _skimage():
775
+ method = "marching cubes"
776
+ else:
777
+ method = "voxels"
778
+ if method == "cells":
779
+ if not _exact_cells(micro):
780
+ raise ValueError("method cells: tessellations without grain boundaries")
781
+ surface = _cells_surface(micro, resolution)
782
+ if surface.n_triangles <= max_triangles:
783
+ return surface
784
+ method = "voxels"
785
+ if method == "marching cubes":
786
+ try:
787
+ return _marching_cubes_surface(micro, resolution, max_triangles)
788
+ except NotImplementedError: # no level set after all: its voxels
789
+ method = "voxels"
790
+ if method != "voxels":
791
+ raise ValueError("method: auto, marching cubes, cells or voxels")
792
+ return _voxels_of_morphology(micro, resolution, max_triangles)
793
+
794
+
795
+ # -- simulations on tetrahedral meshes -------------------------------------------------------------
796
+
797
+
798
+ def _tet_faces(nodes: np.ndarray, tets: np.ndarray, regions: np.ndarray):
799
+ """The faces of the elements on the boundary of a mesh and between regions, turned
800
+ outwards from their inside (the larger region; the exterior outside): corners (m, 3),
801
+ regions (m, 2)."""
802
+ from morphogen.mesh.tetra import TET_FACES, tet_volumes
803
+
804
+ tets = tets.copy()
805
+ flip = tet_volumes(nodes, tets) < 0
806
+ tets[flip] = tets[flip][:, [0, 2, 1, 3]]
807
+ faces = tets[:, TET_FACES].reshape(-1, 3)
808
+ element = np.repeat(np.arange(len(tets)), 4)
809
+ s = np.sort(faces, axis=1)
810
+ n = len(nodes)
811
+ if n < 2**21:
812
+ key = (s[:, 0] * n + s[:, 1]) * n + s[:, 2]
813
+ _, inverse, counts = np.unique(key, return_inverse=True, return_counts=True)
814
+ else: # pragma: no cover - meshes of millions of nodes
815
+ _, inverse, counts = np.unique(s, axis=0, return_inverse=True, return_counts=True)
816
+ inverse = inverse.ravel()
817
+ times = counts[inverse]
818
+ single = np.flatnonzero(times == 1)
819
+ shared = np.flatnonzero(times == 2)
820
+ shared = shared[np.argsort(inverse[shared], kind="stable")]
821
+ f1, f2 = shared[0::2], shared[1::2]
822
+ r1, r2 = regions[element[f1]], regions[element[f2]]
823
+ differ = r1 != r2
824
+ f1, f2, r1, r2 = f1[differ], f2[differ], r1[differ], r2[differ]
825
+ keep = np.where(r1 > r2, f1, f2) # the face of the element of the larger region
826
+ corners = np.concatenate([faces[single], faces[keep]])
827
+ pair = np.concatenate(
828
+ [
829
+ np.stack([regions[element[single]], np.full(len(single), EXTERIOR)], axis=1),
830
+ np.stack([np.maximum(r1, r2), np.minimum(r1, r2)], axis=1),
831
+ ]
832
+ )
833
+ return corners, pair.astype(np.int64)
834
+
835
+
836
+ def _node_region_means(tets: np.ndarray, regions: np.ndarray, values: np.ndarray):
837
+ """Mean of the finite values of the elements of each region around each node: the
838
+ sorted keys ``node * R + region`` and their means."""
839
+ span = int(regions.max()) + 1 if regions.size else 1
840
+ node = tets.ravel().astype(np.int64)
841
+ region = np.repeat(regions, tets.shape[1])
842
+ value = np.repeat(np.asarray(values, dtype=np.float64), tets.shape[1])
843
+ finite = np.isfinite(value)
844
+ keys, inverse = np.unique(node * span + region, return_inverse=True)
845
+ sums = np.bincount(inverse, weights=np.where(finite, value, 0.0), minlength=len(keys))
846
+ counts = np.bincount(inverse, weights=finite.astype(float), minlength=len(keys))
847
+ with np.errstate(invalid="ignore", divide="ignore"):
848
+ means = sums / counts
849
+ return keys, means, span
850
+
851
+
852
+ def _lookup(keys, means, span, node, region) -> np.ndarray:
853
+ want = node * span + region
854
+ i = np.minimum(np.searchsorted(keys, want), len(keys) - 1)
855
+ return np.where(keys[i] == want, means[i], np.nan)
856
+
857
+
858
+ @njit(cache=True)
859
+ def _raster_tets(nodes, tets, lower, spacing, out): # pragma: no cover - compiled
860
+ """The element containing the centre of each cell of a grid (``out``, -1 where none,
861
+ the last one found on shared faces)."""
862
+ nx, ny, nz = out.shape
863
+ size = (nx, ny, nz)
864
+ first = np.empty(3, np.int64)
865
+ last = np.empty(3, np.int64)
866
+ m = np.empty((3, 3))
867
+ for e in range(tets.shape[0]):
868
+ p0 = nodes[tets[e, 0]]
869
+ lo = p0.copy()
870
+ hi = p0.copy()
871
+ for c in range(1, 4):
872
+ q = nodes[tets[e, c]]
873
+ for a in range(3):
874
+ lo[a] = min(lo[a], q[a])
875
+ hi[a] = max(hi[a], q[a])
876
+ for a in range(3):
877
+ first[a] = max(0, math.ceil((lo[a] - lower[a]) / spacing[a] - 0.5))
878
+ last[a] = min(size[a] - 1, math.floor((hi[a] - lower[a]) / spacing[a] - 0.5))
879
+ if first[0] > last[0] or first[1] > last[1] or first[2] > last[2]:
880
+ continue
881
+ for c in range(3): # columns: the edges from the first corner
882
+ q = nodes[tets[e, c + 1]]
883
+ for a in range(3):
884
+ m[a, c] = q[a] - p0[a]
885
+ det = (
886
+ m[0, 0] * (m[1, 1] * m[2, 2] - m[1, 2] * m[2, 1])
887
+ - m[0, 1] * (m[1, 0] * m[2, 2] - m[1, 2] * m[2, 0])
888
+ + m[0, 2] * (m[1, 0] * m[2, 1] - m[1, 1] * m[2, 0])
889
+ )
890
+ if det == 0.0:
891
+ continue
892
+ inv = np.linalg.inv(m)
893
+ tol = 1e-9
894
+ for i in range(first[0], last[0] + 1):
895
+ x = lower[0] + (i + 0.5) * spacing[0] - p0[0]
896
+ for j in range(first[1], last[1] + 1):
897
+ y = lower[1] + (j + 0.5) * spacing[1] - p0[1]
898
+ for k in range(first[2], last[2] + 1):
899
+ z = lower[2] + (k + 0.5) * spacing[2] - p0[2]
900
+ l1 = inv[0, 0] * x + inv[0, 1] * y + inv[0, 2] * z
901
+ l2 = inv[1, 0] * x + inv[1, 1] * y + inv[1, 2] * z
902
+ l3 = inv[2, 0] * x + inv[2, 1] * y + inv[2, 2] * z
903
+ if l1 >= -tol and l2 >= -tol and l3 >= -tol and l1 + l2 + l3 <= 1.0 + tol:
904
+ out[i, j, k] = e
905
+
906
+
907
+ def _index_type(top: int):
908
+ """The smallest unsigned integers holding ``top``."""
909
+ return np.uint8 if top < 256 else (np.uint16 if top < 65536 else np.uint32)
910
+
911
+
912
+ def _mesh_volumes(nodes, tets, regions, n_regions, lower, upper, resolution, values=None):
913
+ """The regions of the cells of a grid of the box (``resolution`` cells along its
914
+ longest edge) from the elements containing their centres (``n_regions`` where none:
915
+ the pores left out of the mesh), and the field there: the value of the element, or
916
+ the nodal values interpolated linearly."""
917
+ shape = _shape(upper - lower, min(int(resolution), MAX_VOLUME))
918
+ spacing = (upper - lower) / np.array(shape)
919
+ element = np.full(shape, -1, dtype=np.int64)
920
+ _raster_tets(nodes, tets, lower, spacing, element)
921
+ inside = element >= 0
922
+ cells = np.where(inside, regions[np.maximum(element, 0)], n_regions)
923
+ volume = Volume("regions", np.ascontiguousarray(cells, dtype=_index_type(n_regions)), box=False)
924
+ if values is None:
925
+ return volume, None
926
+ field = np.full(shape, np.nan)
927
+ if len(values) == len(tets):
928
+ field[inside] = values[element[inside]]
929
+ else: # nodal values, by the barycentric coordinates of the centres
930
+ index = np.argwhere(inside)
931
+ for start in range(0, len(index), 1 << 18):
932
+ chunk = index[start : start + (1 << 18)]
933
+ e = element[tuple(chunk.T)]
934
+ x = nodes[tets[e]]
935
+ local = np.linalg.solve(
936
+ np.stack([x[:, 1] - x[:, 0], x[:, 2] - x[:, 0], x[:, 3] - x[:, 0]], axis=2),
937
+ (lower + (chunk + 0.5) * spacing - x[:, 0])[..., None],
938
+ )[..., 0]
939
+ weights = np.concatenate([1.0 - local.sum(axis=1, keepdims=True), local], axis=1)
940
+ field[tuple(chunk.T)] = np.einsum("ij,ij->i", weights, values[tets[e]])
941
+ return volume, _field_volume(field, shape, _finite_range(values))
942
+
943
+
944
+ def mesh_surface(
945
+ nodes,
946
+ elements,
947
+ regions,
948
+ region_phase,
949
+ region_label=None,
950
+ lower=None,
951
+ upper=None,
952
+ *,
953
+ values=None,
954
+ field: str | None = None,
955
+ fields=(),
956
+ displacement=None,
957
+ resolution: int | None = 96,
958
+ max_triangles: int = MAX_TRIANGLES,
959
+ ) -> Surface:
960
+ """The faces of a tetrahedral mesh (corners of ``elements``) on its boundary and
961
+ between ``regions`` of elements, with a field (``values``: one per node, or one per
962
+ element, averaged at the nodes in each region) and the ``displacement`` of the nodes.
963
+
964
+ Vertices are shared by the faces of a group on the same face of the box (or inside
965
+ it), whose normals they average. The volumes of the sections are the regions and the
966
+ field of the cells of a grid of ``resolution`` cells along the longest edge (None:
967
+ none), from the elements containing their centres. A surface beyond
968
+ ``max_triangles`` is simplified by clustering its vertices (:func:`_clustered`).
969
+ """
970
+ nodes = np.asarray(nodes, dtype=np.float64)
971
+ tets = np.asarray(elements, dtype=np.int64)[:, :4]
972
+ regions = np.asarray(regions, dtype=np.int64)
973
+ lower = nodes.min(axis=0) if lower is None else np.asarray(lower, dtype=float)
974
+ upper = nodes.max(axis=0) if upper is None else np.asarray(upper, dtype=float)
975
+ corners, pair = _tet_faces(nodes, tets, regions)
976
+ # the face of the box of each boundary face (1-6; 7 inside: walls of pores), 0 between
977
+ # regions: vertices are shared only within a group on the same plane
978
+ tol = 1e-7 * float(np.max(upper - lower))
979
+ plane = np.zeros(len(corners), dtype=np.int64)
980
+ boundary = pair[:, 1] == EXTERIOR
981
+ plane[boundary] = 7
982
+ for a in range(3):
983
+ for side, value in enumerate((lower[a], upper[a])):
984
+ on = np.abs(nodes[:, a] - value) <= tol
985
+ plane[boundary & np.all(on[corners], axis=1)] = 1 + 2 * a + side
986
+ local = corners * 8 + plane[:, None]
987
+ triangles, ids, vgroup, groups = _assemble(pair, local, len(nodes) * 8)
988
+ node = ids // 8
989
+ positions = nodes[node]
990
+ surface = Surface(
991
+ positions=positions,
992
+ normals=_vertex_normals(positions, triangles),
993
+ triangles=triangles,
994
+ groups=groups,
995
+ region_phase=np.asarray(region_phase, dtype=np.int64),
996
+ region_label=None if region_label is None else np.asarray(region_label, dtype=np.int64),
997
+ lower=lower,
998
+ upper=upper,
999
+ method="mesh",
1000
+ field=field,
1001
+ fields=list(fields),
1002
+ )
1003
+ if values is not None:
1004
+ values = _scalars(values)
1005
+ if resolution is not None:
1006
+ surface.volume, surface.field_volume = _mesh_volumes(
1007
+ nodes, tets, regions, len(surface.region_phase), lower, upper, resolution, values
1008
+ )
1009
+ if values is not None:
1010
+ surface.field_range = _finite_range(values)
1011
+ inside, outside = groups[vgroup, 0], groups[vgroup, 1] # every group has vertices
1012
+ if len(values) == len(nodes):
1013
+ front = back = values[node]
1014
+ surface.point_field = True
1015
+ elif len(values) == len(tets):
1016
+ keys, means, span = _node_region_means(tets, regions, values)
1017
+ front = _lookup(keys, means, span, node, inside)
1018
+ back = _lookup(keys, means, span, node, np.maximum(outside, 0))
1019
+ back = np.where(outside >= 0, back, front)
1020
+ else:
1021
+ raise ValueError("values: one per node or one per element")
1022
+ surface.values = np.stack([front, back], axis=1)
1023
+ if displacement is not None:
1024
+ u = np.asarray(displacement, dtype=np.float64).reshape(len(nodes), -1)[:, :3]
1025
+ surface.displacement = u[node]
1026
+ return _within(surface, max_triangles)
1027
+
1028
+
1029
+ def vtu_surface(
1030
+ path,
1031
+ field: str | None = None,
1032
+ *,
1033
+ resolution: int | None = 96,
1034
+ max_triangles: int = MAX_TRIANGLES,
1035
+ ) -> Surface:
1036
+ """The surface of the fields of a simulation on a tetrahedral mesh (a ``.vtu`` file of
1037
+ :func:`morphogen.io.write_vtu_tet`): its faces between its phases (and grains, the
1038
+ ``cell`` array of polycrystals), ``field`` at their vertices (by default the von Mises
1039
+ stress, else its first field; ``"displacement"``: its norm) and the displacement of
1040
+ their nodes; its volumes for the sections (:func:`mesh_surface`)."""
1041
+ from morphogen.io.vtk import read_vtu
1042
+
1043
+ data = read_vtu(path)
1044
+ nodes, cells = data["points"], data["cells"]
1045
+ if cells.ndim != 2 or cells.shape[1] not in (4, 10):
1046
+ raise ValueError(f"{Path(path).name}: not a mesh of tetrahedra")
1047
+ cell_data, point_data = data["cell_data"], data["point_data"]
1048
+ phase = np.asarray(cell_data.get("phase", np.zeros(len(cells))), dtype=np.int64)
1049
+ grain = cell_data.get("cell", cell_data.get("grain"))
1050
+ if grain is None:
1051
+ regions, region_phase, region_label = phase, np.arange(int(phase.max(initial=0)) + 1), None
1052
+ else:
1053
+ grain = np.asarray(grain, dtype=np.int64)
1054
+ span = int(phase.max(initial=0)) + 1
1055
+ unique, inverse = np.unique((grain + 1) * span + phase, return_inverse=True)
1056
+ regions, region_phase, region_label = inverse.ravel(), unique % span, unique // span - 1
1057
+ names = [n for n in dict.fromkeys([*point_data, *cell_data]) if n not in NOT_FIELDS]
1058
+ field = field or _default_field(names)
1059
+ values = None
1060
+ if field is not None:
1061
+ if field not in names:
1062
+ raise ValueError(f"field: one of {', '.join(names) or 'none here'}")
1063
+ values = point_data[field] if field in point_data else cell_data[field]
1064
+ boxes = data.get("field_data", {})
1065
+ lower = boxes.get("box_lower")
1066
+ upper = boxes.get("box_upper")
1067
+ return mesh_surface(
1068
+ nodes,
1069
+ cells,
1070
+ regions,
1071
+ region_phase,
1072
+ region_label,
1073
+ None if lower is None else np.asarray(lower, dtype=float).reshape(3),
1074
+ None if upper is None else np.asarray(upper, dtype=float).reshape(3),
1075
+ values=values,
1076
+ field=field,
1077
+ fields=names,
1078
+ displacement=point_data.get("displacement"),
1079
+ resolution=resolution,
1080
+ max_triangles=max_triangles,
1081
+ )
1082
+
1083
+
1084
+ def _default_field(names: list[str]) -> str | None:
1085
+ """The field drawn first: the von Mises stress, else the first field."""
1086
+ return "von_mises" if "von_mises" in names else (names[0] if names else None)
1087
+
1088
+
1089
+ def vti_surface(
1090
+ path,
1091
+ field: str | None = None,
1092
+ *,
1093
+ phases=None,
1094
+ morphology=None,
1095
+ max_triangles: int = MAX_TRIANGLES,
1096
+ ) -> Surface:
1097
+ """The surface of the fields of a simulation on voxels (a ``.vti`` file of fields):
1098
+ the faces between its phases and grains (``grain``) and ``field`` of the voxels as a
1099
+ volume (by default the von Mises stress, else its first field). The phases are the
1100
+ ``phase`` array of the file, else ``phases`` (an image of the same shape), else those
1101
+ of ``morphology`` voxelized on the grid of the file, else a single phase. Only the
1102
+ arrays needed are read."""
1103
+ from morphogen.domain import Domain
1104
+ from morphogen.io.vtk import read_vti, vti_names
1105
+
1106
+ names = [n for n in vti_names(path) if n not in NOT_FIELDS]
1107
+ field = field or _default_field(names)
1108
+ if field is not None and field not in names:
1109
+ raise ValueError(f"field: one of {', '.join(names) or 'none here'}")
1110
+ wanted = {"phase", "grain"} | ({field} if field else set())
1111
+ images = {img.name: img for img in read_vti(path, names=wanted)}
1112
+ if not images:
1113
+ raise ValueError(f"{Path(path).name}: no fields of voxels")
1114
+ first = next(iter(images.values()))
1115
+ shape = first.data.shape
1116
+ lower = np.asarray(first.origin, dtype=float)
1117
+ upper = lower + np.asarray(first.spacing, dtype=float) * np.array(shape)
1118
+ if "phase" in images:
1119
+ phase = images["phase"].data
1120
+ elif phases is not None and np.shape(phases) == shape:
1121
+ phase = phases
1122
+ elif morphology is not None:
1123
+ grid = Grid(Domain(size=tuple(upper - lower), origin=tuple(lower)), shape)
1124
+ phase = morphology.voxelize(grid=grid).data
1125
+ else:
1126
+ phase = np.zeros(shape, dtype=np.int64)
1127
+ phase = np.asarray(phase, dtype=np.int64)
1128
+ if "grain" in images:
1129
+ grain = np.asarray(images["grain"].data, dtype=np.int64)
1130
+ span = int(phase.max(initial=0)) + 1
1131
+ unique, inverse = np.unique((grain + 1) * span + phase, return_inverse=True)
1132
+ regions, region_phase = inverse.reshape(shape), unique % span
1133
+ region_label = unique // span - 1
1134
+ else:
1135
+ regions, region_phase, region_label = phase, np.arange(int(phase.max(initial=0)) + 1), None
1136
+ values = None if field is None else np.asarray(images[field].data, dtype=np.float64)
1137
+ return voxel_surface(
1138
+ regions,
1139
+ region_phase,
1140
+ region_label,
1141
+ lower,
1142
+ upper,
1143
+ values=values,
1144
+ field=field,
1145
+ fields=names,
1146
+ max_triangles=max_triangles,
1147
+ )
1148
+
1149
+
1150
+ # -- budget ------------------------------------------------------------------------------------
1151
+
1152
+
1153
+ def _within(surface: Surface, max_triangles: int) -> Surface:
1154
+ """The surface, simplified by :func:`_clustered` when it exceeds ``max_triangles``."""
1155
+ if surface.n_triangles <= max_triangles:
1156
+ return surface
1157
+ return _clustered(surface, max_triangles)
1158
+
1159
+
1160
+ def _clustered(surface: Surface, max_triangles: int) -> Surface:
1161
+ """A coarser surface by clustering of vertices: those of a group in the same cell of
1162
+ a grid merge (their attributes averaged), and the triangles that lose a corner, or
1163
+ repeat another, are dropped; the cells grow until the triangles fit the budget."""
1164
+ area = max(surface.area(), 1e-300)
1165
+ size = math.sqrt(2.0 * area / max(int(max_triangles), 1))
1166
+ span = surface.upper - surface.lower
1167
+ group_of = np.repeat(np.arange(len(surface.groups)), surface.groups[:, 3])
1168
+ for _ in range(40):
1169
+ cells = np.floor((surface.positions - surface.lower) / size).astype(np.int64)
1170
+ dims = np.maximum(np.ceil(span / size).astype(np.int64) + 2, 1)
1171
+ cell = ((cells[:, 0] + 1) * dims[1] + cells[:, 1] + 1) * dims[2] + cells[:, 2] + 1
1172
+ key = group_of * int(np.prod(dims)) + cell
1173
+ unique, inverse = np.unique(key, return_inverse=True)
1174
+ tri = inverse.ravel()[surface.triangles]
1175
+ ok = (tri[:, 0] != tri[:, 1]) & (tri[:, 1] != tri[:, 2]) & (tri[:, 0] != tri[:, 2])
1176
+ tri = tri[ok]
1177
+ _, first = np.unique(np.sort(tri, axis=1), axis=0, return_index=True)
1178
+ tri = tri[np.sort(first)]
1179
+ if len(tri) <= max_triangles:
1180
+ break
1181
+ size *= 1.25
1182
+ counts = np.bincount(inverse.ravel(), minlength=len(unique)).astype(float)
1183
+
1184
+ def mean(a):
1185
+ out = np.zeros((len(unique), a.shape[1]))
1186
+ for c in range(a.shape[1]):
1187
+ out[:, c] = np.bincount(inverse.ravel(), weights=a[:, c], minlength=len(unique))
1188
+ return out / counts[:, None]
1189
+
1190
+ positions = mean(surface.positions)
1191
+ vgroup = unique // int(np.prod(dims))
1192
+ # triangles in the order of their groups (vertices are, by their keys)
1193
+ tri = tri[np.argsort(vgroup[tri[:, 0]], kind="stable")]
1194
+ ids, first_v, count_v = np.unique(vgroup, return_index=True, return_counts=True)
1195
+ tgroup = vgroup[tri[:, 0]]
1196
+ t_ids, first_t, count_t = np.unique(tgroup, return_index=True, return_counts=True)
1197
+ start = np.zeros(len(ids), dtype=np.int64)
1198
+ number = np.zeros(len(ids), dtype=np.int64)
1199
+ where = np.searchsorted(ids, t_ids)
1200
+ start[where], number[where] = first_t, count_t
1201
+ groups = np.column_stack(
1202
+ [surface.groups[ids, 0], surface.groups[ids, 1], first_v, count_v, start, number]
1203
+ )
1204
+ out = Surface(
1205
+ positions=positions,
1206
+ normals=_vertex_normals(positions, tri),
1207
+ triangles=tri,
1208
+ groups=groups.astype(np.int64),
1209
+ region_phase=surface.region_phase,
1210
+ region_label=surface.region_label,
1211
+ lower=surface.lower,
1212
+ upper=surface.upper,
1213
+ method=surface.method,
1214
+ resolution=surface.resolution,
1215
+ reduced=True,
1216
+ volume=surface.volume,
1217
+ field=surface.field,
1218
+ fields=surface.fields,
1219
+ field_volume=surface.field_volume,
1220
+ field_range=surface.field_range,
1221
+ point_field=surface.point_field,
1222
+ )
1223
+ if surface.values is not None:
1224
+ out.values = mean(np.nan_to_num(surface.values, nan=0.0))
1225
+ if surface.displacement is not None:
1226
+ out.displacement = mean(surface.displacement)
1227
+ return out
1228
+
1229
+
1230
+ # -- encoding ----------------------------------------------------------------------------------
1231
+
1232
+
1233
+ def _b64(array: np.ndarray, dtype: str, order: str = "C") -> str:
1234
+ data = np.asarray(array).astype(dtype, copy=False)
1235
+ return base64.b64encode(data.tobytes(order=order)).decode("ascii")
1236
+
1237
+
1238
+ def _hex(rgb) -> str:
1239
+ return "#{:02x}{:02x}{:02x}".format(*(int(c) for c in rgb))
1240
+
1241
+
1242
+ def _volume(volume: Volume | None) -> dict | None:
1243
+ if volume is None:
1244
+ return None
1245
+ dtype = {"uint8": "<u1", "uint16": "<u2", "uint32": "<u4"}[volume.data.dtype.name]
1246
+ out = {
1247
+ "kind": volume.kind,
1248
+ "shape": [int(k) for k in volume.data.shape],
1249
+ "dtype": volume.data.dtype.name,
1250
+ "data": _b64(volume.data, dtype, order="F"), # x fastest, as 3D textures
1251
+ "box": bool(volume.box),
1252
+ }
1253
+ if volume.kind == "level_set":
1254
+ out.update(periodic=bool(volume.periodic), step=float(volume.step))
1255
+ if volume.range is not None:
1256
+ out["range"] = [float(volume.range[0]), float(volume.range[1])]
1257
+ return out
1258
+
1259
+
1260
+ #: The share of the values of a field left beyond each end of its default colour scale
1261
+ SHOWN_TAIL = 0.01
1262
+
1263
+
1264
+ def _shown_range(values, lo: float, hi: float) -> list[float]:
1265
+ """The default colour scale of a field on the vertices: from the first to the last
1266
+ percentile of its values, so that the peak of a singular field (the tip of a crack,
1267
+ a poor element) does not darken all the others; the whole range when that would leave
1268
+ too little (the phases of a field of few values)."""
1269
+ if values is None:
1270
+ return [float(lo), float(hi)]
1271
+ finite = np.asarray(values, dtype=float)
1272
+ finite = finite[np.isfinite(finite)]
1273
+ if finite.size == 0:
1274
+ return [float(lo), float(hi)]
1275
+ a, b = np.quantile(finite, [SHOWN_TAIL, 1.0 - SHOWN_TAIL])
1276
+ if not b > a or (b - a) < 1e-6 * max(abs(hi - lo), 1e-300):
1277
+ return [float(lo), float(hi)]
1278
+ return [float(a), float(b)]
1279
+
1280
+
1281
+ def magnification(surface: Surface) -> float | None:
1282
+ """The magnification of the displacement drawing the largest one as a tenth of the
1283
+ box (as the videos of :mod:`morphogen.viz.video`), None without displacement."""
1284
+ if surface.displacement is None or not len(surface.displacement):
1285
+ return None
1286
+ peak = float(np.max(np.linalg.norm(surface.displacement, axis=1)))
1287
+ size = float(np.max(surface.upper - surface.lower))
1288
+ return 0.1 * size / peak if peak > 0 else 0.0
1289
+
1290
+
1291
+ def encode(surface: Surface) -> dict:
1292
+ """JSON data of a surface for the page: its arrays in base64, little-endian
1293
+ (``positions``, ``normals``, field ``values`` and ``displacement`` in float32,
1294
+ ``indices`` in uint32, the volumes in unsigned integers, x fastest; voxel faces give
1295
+ the node and the direction of each vertex instead of its position and normal,
1296
+ ``lattice``), its groups, the phase, label and colours of its regions (those of the
1297
+ sections, :data:`morphogen.viz.png.PALETTE`, and of their cells)."""
1298
+ phase = np.asarray(surface.region_phase, dtype=np.int64)
1299
+ colors = [_hex(PALETTE[min(max(int(p), 0), len(PALETTE) - 1)]) for p in phase]
1300
+ regions: dict = {"phase": phase.tolist(), "color": colors, "label": None, "label_color": None}
1301
+ if surface.region_label is not None:
1302
+ label = np.asarray(surface.region_label, dtype=np.int64)
1303
+ regions["label"] = label.tolist()
1304
+ regions["label_color"] = [
1305
+ _hex(c) if k >= 0 else colors[i]
1306
+ for i, (k, c) in enumerate(zip(label, label_colors(label), strict=True))
1307
+ ]
1308
+ out = {
1309
+ "method": surface.method,
1310
+ "resolution": surface.resolution,
1311
+ "reduced": bool(surface.reduced),
1312
+ "lower": [float(v) for v in surface.lower],
1313
+ "upper": [float(v) for v in surface.upper],
1314
+ "vertices": surface.n_vertices,
1315
+ "triangles": surface.n_triangles,
1316
+ "positions": None,
1317
+ "normals": None,
1318
+ "lattice": None,
1319
+ "indices": _b64(surface.triangles, "<u4"),
1320
+ "groups": surface.groups.astype(np.int64).tolist(),
1321
+ "regions": regions,
1322
+ "volume": _volume(surface.volume),
1323
+ "field": None,
1324
+ "displacement": None,
1325
+ "magnification": None,
1326
+ }
1327
+ if surface.lattice is None:
1328
+ out["positions"] = _b64(surface.positions, "<f4")
1329
+ out["normals"] = _b64(surface.normals, "<f4")
1330
+ else: # voxel faces: the nodes and directions of the vertices
1331
+ nodes, node, direction = surface.lattice
1332
+ out["lattice"] = {
1333
+ "nodes": [int(k) for k in nodes],
1334
+ "node": _b64(node, "<u4"),
1335
+ "direction": _b64(direction, "<u1"),
1336
+ }
1337
+ if surface.field is not None:
1338
+ lo, hi = surface.field_range or (0.0, 1.0)
1339
+ values = surface.values
1340
+ out["field"] = {
1341
+ "name": surface.field,
1342
+ "names": list(surface.fields),
1343
+ "range": [float(lo), float(hi)],
1344
+ "shown": _shown_range(values, lo, hi),
1345
+ "point": bool(surface.point_field),
1346
+ "values": None if values is None else _b64(np.nan_to_num(values, nan=lo), "<f4"),
1347
+ "volume": _volume(surface.field_volume),
1348
+ }
1349
+ if surface.displacement is not None:
1350
+ out["displacement"] = _b64(surface.displacement, "<f4")
1351
+ out["magnification"] = magnification(surface)
1352
+ return out