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
morphogen/viz/video.py ADDED
@@ -0,0 +1,904 @@
1
+ """Videos of morphologies and fields: ``.mp4`` through ffmpeg (``ffmpeg`` on the path, the
2
+ ``MORPHOGEN_FFMPEG`` variable or the imageio-ffmpeg package), ``.gif`` through Pillow, or a
3
+ folder of PNG frames.
4
+
5
+ Morphologies: a section sweeping through a voxel image along an axis, the three orthogonal
6
+ sections moving together (as the orthoslices of Avizo), a turntable of the surface of a
7
+ phase or of a mesh. Fields on tetrahedral meshes: a turntable coloured by a field, a
8
+ cross-section sweeping through the mesh, and the deformed mesh with a magnified
9
+ displacement (a mode oscillating, or a load growing), optionally cut by a plane, and its
10
+ history along the steps of a loading path; fields on voxel images, the same section at
11
+ successive times. The 3D views are rendered off screen by VTK; colours come from
12
+ matplotlib colormaps, on a fixed range over the frames, with a colour bar beside them.
13
+ Every video plays once, loops (``repeat`` times) or goes back and forth
14
+ (``mode="bounce"``).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import functools
20
+ import importlib.util
21
+ import os
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+ from morphogen.image import VoxelImage
30
+ from morphogen.viz.png import label_colors
31
+
32
+ MODES = ("once", "loop", "bounce")
33
+
34
+
35
+ def ffmpeg_path() -> str | None:
36
+ """The ffmpeg executable: ``MORPHOGEN_FFMPEG``, the path, or imageio-ffmpeg's."""
37
+ env = os.environ.get("MORPHOGEN_FFMPEG")
38
+ if env and Path(env).exists():
39
+ return env
40
+ found = shutil.which("ffmpeg")
41
+ if found:
42
+ return found
43
+ try:
44
+ import imageio_ffmpeg
45
+
46
+ return imageio_ffmpeg.get_ffmpeg_exe()
47
+ except Exception: # optional
48
+ return None
49
+
50
+
51
+ def sequence(frames, mode: str = "once", repeat: int = 1) -> list[np.ndarray]:
52
+ """The frames played once, ``repeat`` times in a loop, or forth and back."""
53
+ frames = [np.asarray(f) for f in frames]
54
+ if mode not in MODES:
55
+ raise ValueError(f"mode: one of {MODES}")
56
+ if mode == "bounce":
57
+ frames = frames + frames[-2:0:-1]
58
+ return frames * (max(int(repeat), 1) if mode != "once" else 1)
59
+
60
+
61
+ def _even(frame: np.ndarray) -> np.ndarray:
62
+ h, w = frame.shape[:2]
63
+ return np.pad(frame, ((0, h % 2), (0, w % 2), (0, 0)), mode="edge")
64
+
65
+
66
+ def write_video(
67
+ frames, path, *, fps: float = 24.0, mode: str = "once", repeat: int = 1, crf: int = 18
68
+ ) -> Path:
69
+ """Write RGB frames (uint8, all of one size) to ``.mp4`` (H.264 by ffmpeg, quality
70
+ ``crf``), ``.gif`` or a folder of PNG files (a path without suffix)."""
71
+ path = Path(path)
72
+ frames = [
73
+ np.ascontiguousarray(np.asarray(f, dtype=np.uint8)[..., :3])
74
+ for f in sequence(frames, mode, repeat)
75
+ ]
76
+ if not frames:
77
+ raise ValueError("write_video: no frame")
78
+ suffix = path.suffix.lower()
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ if suffix == ".mp4":
81
+ exe = ffmpeg_path()
82
+ if exe is None:
83
+ raise RuntimeError(
84
+ "write_video: ffmpeg is needed for .mp4 (or pip install imageio-ffmpeg)"
85
+ )
86
+ frames = [_even(f) for f in frames]
87
+ h, w = frames[0].shape[:2]
88
+ cmd = [
89
+ exe,
90
+ "-y",
91
+ "-loglevel",
92
+ "error",
93
+ "-f",
94
+ "rawvideo",
95
+ "-pix_fmt",
96
+ "rgb24",
97
+ "-s",
98
+ f"{w}x{h}",
99
+ ]
100
+ cmd += [
101
+ "-r",
102
+ str(fps),
103
+ "-i",
104
+ "-",
105
+ "-c:v",
106
+ "libx264",
107
+ "-pix_fmt",
108
+ "yuv420p",
109
+ "-crf",
110
+ str(int(crf)),
111
+ ]
112
+ cmd += ["-movflags", "+faststart", str(path)]
113
+ done = subprocess.run(cmd, input=b"".join(f.tobytes() for f in frames), capture_output=True)
114
+ if done.returncode:
115
+ raise RuntimeError(f"ffmpeg failed: {done.stderr.decode(errors='replace')[:500]}")
116
+ elif suffix == ".gif":
117
+ from PIL import Image
118
+
119
+ images = [Image.fromarray(f) for f in frames]
120
+ loop = 0 if mode != "once" else 1
121
+ images[0].save(
122
+ path, save_all=True, append_images=images[1:], duration=int(1000 / fps), loop=loop
123
+ )
124
+ elif suffix == "":
125
+ from PIL import Image
126
+
127
+ path.mkdir(parents=True, exist_ok=True)
128
+ for k, f in enumerate(frames):
129
+ Image.fromarray(f).save(path / f"frame_{k:05d}.png")
130
+ else:
131
+ raise ValueError("write_video: .mp4, .gif or a folder")
132
+ return path
133
+
134
+
135
+ # -- colours ---------------------------------------------------------------------------
136
+
137
+
138
+ def _cmap(name):
139
+ import matplotlib
140
+
141
+ return matplotlib.colormaps[name] if isinstance(name, str) else name
142
+
143
+
144
+ def _rgb(plane: np.ndarray, labels: bool, cmap, vmin, vmax) -> np.ndarray:
145
+ if labels:
146
+ return label_colors(plane)
147
+ span = (vmax - vmin) or 1.0
148
+ return (_cmap(cmap)(np.clip((plane - vmin) / span, 0.0, 1.0))[..., :3] * 255).astype(np.uint8)
149
+
150
+
151
+ def _caption(rgb: np.ndarray, text: str) -> np.ndarray:
152
+ from PIL import Image, ImageDraw
153
+
154
+ img = Image.fromarray(rgb)
155
+ draw = ImageDraw.Draw(img)
156
+ draw.rectangle((0, 0, 8 + 6 * len(text), 14), fill=(255, 255, 255))
157
+ draw.text((4, 2), text, fill=(0, 0, 0))
158
+ return np.asarray(img)
159
+
160
+
161
+ def _resize(rgb: np.ndarray, size: int) -> np.ndarray:
162
+ from PIL import Image
163
+
164
+ h, w = rgb.shape[:2]
165
+ scale = size / max(h, w)
166
+ return np.asarray(
167
+ Image.fromarray(rgb).resize((max(int(w * scale), 1), max(int(h * scale), 1)), Image.NEAREST)
168
+ )
169
+
170
+
171
+ #: Width in pixels of the colour bars beside the frames
172
+ BAR = 88
173
+
174
+
175
+ def _font(size: int):
176
+ from PIL import ImageFont
177
+
178
+ try:
179
+ return ImageFont.load_default(size=size)
180
+ except TypeError: # pragma: no cover - Pillow < 10.1: its bitmap font
181
+ return ImageFont.load_default()
182
+
183
+
184
+ def _with_bar(rgb: np.ndarray, colors, lo: float, hi: float, label: str = "", categories=None):
185
+ """The frame with a colour bar on its right (``BAR`` pixels wide), titled ``label``: a
186
+ ramp of ``colors`` (a colormap, or RGB rows in [0, 1] from ``lo`` to ``hi``) with five
187
+ values, or a box per category (``categories``: their names, one row of ``colors``
188
+ each)."""
189
+ from PIL import Image, ImageDraw
190
+
191
+ h, w = rgb.shape[:2]
192
+ canvas = np.full((h, w + BAR, 3), 255, np.uint8)
193
+ canvas[:, :w] = rgb
194
+ top, bottom = int(0.16 * h), max(int(0.86 * h), int(0.16 * h) + 10)
195
+ x0 = w + 8
196
+ if isinstance(colors, np.ndarray):
197
+ table = np.asarray(colors, dtype=float)[:, :3]
198
+ else:
199
+ table = _cmap(colors)(np.linspace(0.0, 1.0, 256))[:, :3]
200
+ table = (np.clip(table, 0.0, 1.0) * 255).astype(np.uint8)
201
+ boxes = []
202
+ if categories is None:
203
+ rows = np.linspace(len(table) - 1, 0, bottom - top).round().astype(int)
204
+ canvas[top:bottom, x0 : x0 + 14] = table[rows][:, None, :]
205
+ else:
206
+ step = max(min(20, (bottom - top) // max(len(categories), 1)), 6)
207
+ for k in range(len(categories)):
208
+ y = top + k * step
209
+ canvas[y : y + step - 3, x0 : x0 + 14] = table[k]
210
+ boxes.append(y + (step - 3) // 2)
211
+ img = Image.fromarray(canvas)
212
+ draw = ImageDraw.Draw(img)
213
+ font = _font(11 if h < 320 else 13)
214
+ if label:
215
+ draw.text((x0 - 2, max(top - 22, 1)), str(label)[:13], fill=(0, 0, 0), font=font)
216
+ if categories is None:
217
+ for k in range(5):
218
+ y = bottom - k * (bottom - top) / 4.0
219
+ draw.line([(x0 + 14, y), (x0 + 18, y)], fill=(0, 0, 0))
220
+ draw.text(
221
+ (x0 + 21, y - 6), f"{lo + k * (hi - lo) / 4.0:.3g}", fill=(0, 0, 0), font=font
222
+ )
223
+ else:
224
+ for name, y in zip(categories, boxes, strict=True):
225
+ draw.text((x0 + 21, y - 6), str(name)[:10], fill=(0, 0, 0), font=font)
226
+ return np.asarray(img)
227
+
228
+
229
+ #: Diverging colormaps: their range is centred on zero for fields of both signs
230
+ DIVERGING = ("coolwarm", "bwr", "seismic", "RdBu", "RdBu_r", "PiYG", "PRGn", "BrBG", "PuOr",
231
+ "RdGy", "RdYlBu", "RdYlGn", "Spectral", "berlin", "managua", "vanimo") # fmt: skip
232
+
233
+
234
+ def _range(data: np.ndarray, vmin, vmax, cmap=None):
235
+ """The colour range of data (``vmin``, ``vmax`` when given); centred on zero for a
236
+ diverging colormap when the data change sign."""
237
+ finite = np.asarray(data, dtype=float)
238
+ finite = finite[np.isfinite(finite)]
239
+ lo = float(finite.min()) if vmin is None and finite.size else (vmin or 0.0)
240
+ hi = float(finite.max()) if vmax is None and finite.size else (vmax or 1.0)
241
+ if vmin is None and abs(lo) < 1e-9 * abs(hi):
242
+ lo = 0.0
243
+ if vmin is None and vmax is None and isinstance(cmap, str) and cmap in DIVERGING:
244
+ if lo < 0.0 < hi:
245
+ lo, hi = -max(-lo, hi), max(-lo, hi)
246
+ return lo, hi
247
+
248
+
249
+ # -- morphologies in sections ----------------------------------------------------------
250
+
251
+
252
+ def section_frames(
253
+ image,
254
+ axis: int = 2,
255
+ *,
256
+ size: int = 480,
257
+ cmap="viridis",
258
+ vmin=None,
259
+ vmax=None,
260
+ labels=None,
261
+ caption=True,
262
+ bar: bool = False,
263
+ label: str = "",
264
+ ):
265
+ """A section sweeping through a voxel image along ``axis``: label colours for phase
266
+ images, a colormap (fixed range) for continuous ones, with a colour bar (``bar``)
267
+ titled ``label``."""
268
+ data = np.asarray(image.data if isinstance(image, VoxelImage) else image)
269
+ labels = data.dtype.kind in "iub" if labels is None else labels
270
+ lo, hi = _range(data, vmin, vmax, cmap) if not labels else (0.0, 1.0)
271
+ frames = []
272
+ for k in range(data.shape[axis]):
273
+ plane = np.take(data, k, axis=axis).T[::-1] # first in-plane axis horizontal
274
+ rgb = _resize(_rgb(plane, labels, cmap, lo, hi), size)
275
+ rgb = _caption(rgb, f"{'xyz'[axis]} = {k}") if caption else rgb
276
+ frames.append(_with_bar(rgb, cmap, lo, hi, label) if bar and not labels else rgb)
277
+ return frames
278
+
279
+
280
+ def time_section_frames(
281
+ images,
282
+ axis: int = 2,
283
+ index: int | None = None,
284
+ *,
285
+ size: int = 480,
286
+ cmap="viridis",
287
+ vmin=None,
288
+ vmax=None,
289
+ captions=None,
290
+ bar: bool = True,
291
+ label: str = "",
292
+ ):
293
+ """The same section (``index`` along ``axis``, by default the middle one) of successive
294
+ fields on a voxel grid (a field at the times of a loading path), on one colour range,
295
+ with a colour bar and a caption per time (e.g. ``"t = 10"``)."""
296
+ datas = [
297
+ np.asarray(im.data if isinstance(im, VoxelImage) else im, dtype=float) for im in images
298
+ ]
299
+ if not datas:
300
+ raise ValueError("time_section_frames: at least one field")
301
+ lo, hi = _range(np.concatenate([d.ravel() for d in datas]), vmin, vmax, cmap)
302
+ k = datas[0].shape[axis] // 2 if index is None else int(index)
303
+ out = []
304
+ for n, d in enumerate(datas):
305
+ plane = np.take(d, k, axis=axis).T[::-1]
306
+ rgb = _resize(_rgb(plane, False, cmap, lo, hi), size)
307
+ if captions is not None:
308
+ rgb = _caption(rgb, str(captions[n]))
309
+ out.append(_with_bar(rgb, cmap, lo, hi, label) if bar else rgb)
310
+ return out
311
+
312
+
313
+ def orthoslice_frames(
314
+ image, *, frames: int = 48, size: int = 300, cmap="viridis", vmin=None, vmax=None, labels=None
315
+ ):
316
+ """The three orthogonal sections moving together through a voxel image, side by side
317
+ (normal to x, y and z)."""
318
+ data = np.asarray(image.data if isinstance(image, VoxelImage) else image)
319
+ labels = data.dtype.kind in "iub" if labels is None else labels
320
+ lo, hi = _range(data, vmin, vmax, cmap) if not labels else (0.0, 1.0)
321
+ out = []
322
+ for t in np.linspace(0.0, 1.0, int(frames)):
323
+ tiles = []
324
+ for axis in range(3):
325
+ k = round(t * (data.shape[axis] - 1))
326
+ plane = np.take(data, k, axis=axis).T[::-1]
327
+ rgb = _resize(_rgb(plane, labels, cmap, lo, hi), size)
328
+ canvas = np.full((size, size, 3), 255, np.uint8)
329
+ canvas[: rgb.shape[0], : rgb.shape[1]] = rgb
330
+ tiles.append(_caption(canvas, f"{'xyz'[axis]} = {k}"))
331
+ out.append(np.concatenate(tiles, axis=1))
332
+ return out
333
+
334
+
335
+ # -- 3D views (VTK) ----------------------------------------------------------------------
336
+
337
+
338
+ def _vtk():
339
+ try:
340
+ import vtk
341
+ from vtk.util import numpy_support
342
+ except ImportError as exc: # pragma: no cover - optional dependency
343
+ raise ImportError("3D views need VTK: pip install vtk") from exc
344
+ return vtk, numpy_support
345
+
346
+
347
+ NO_RENDERING = (
348
+ "VTK cannot render here: it finds no display, EGL or OSMesa (on a headless machine, run "
349
+ "under a virtual display, xvfb-run, or install the OSMesa or EGL library)"
350
+ )
351
+
352
+ _PROBE = """\
353
+ import vtk
354
+ window = vtk.vtkRenderWindow()
355
+ window.SetOffScreenRendering(1)
356
+ window.AddRenderer(vtk.vtkRenderer())
357
+ window.SetSize(8, 8)
358
+ window.Render()
359
+ """
360
+
361
+
362
+ @functools.cache
363
+ def vtk_can_render() -> bool:
364
+ """Whether VTK can render off screen here. Without a display, EGL or OSMesa, VTK aborts
365
+ the process at its first render, so a subprocess renders first; the answer is kept."""
366
+ if importlib.util.find_spec("vtk") is None:
367
+ return False
368
+ try:
369
+ probe = subprocess.run(
370
+ [sys.executable, "-c", _PROBE], capture_output=True, timeout=120, check=False
371
+ )
372
+ except (OSError, subprocess.TimeoutExpired):
373
+ return False
374
+ return probe.returncode == 0
375
+
376
+
377
+ def _lut(vtk, cmap, lo, hi):
378
+ lut = vtk.vtkLookupTable()
379
+ lut.SetNumberOfTableValues(256)
380
+ lut.SetRange(lo, hi)
381
+ colors = _cmap(cmap)(np.linspace(0.0, 1.0, 256))
382
+ for k, c in enumerate(colors):
383
+ lut.SetTableValue(k, *c)
384
+ lut.Build()
385
+ return lut
386
+
387
+
388
+ def _phase_lut(vtk, n: int):
389
+ """A lookup table of the phases ``0 .. n - 1`` in the colours of the sections."""
390
+ n = max(int(n), 2)
391
+ lut = vtk.vtkLookupTable()
392
+ lut.SetNumberOfTableValues(n)
393
+ lut.SetRange(0.0, n - 1.0)
394
+ for k, c in enumerate(label_colors(np.arange(n))):
395
+ lut.SetTableValue(k, *(np.asarray(c, dtype=float) / 255.0), 1.0)
396
+ lut.Build()
397
+ return lut
398
+
399
+
400
+ def _colours(vtk, mesh, field, cmap, clim):
401
+ """Point or cell values of ``field`` on a mesh, their lookup table and the number of
402
+ labels of its colour bar; ``field="phase"``: the phases of the elements, in the
403
+ colours of the sections."""
404
+ if isinstance(field, str):
405
+ if field != "phase":
406
+ raise ValueError("field: 'phase', or values per node or per element")
407
+ phase = np.asarray(mesh.phase, dtype=float)
408
+ n = int(phase.max()) + 1 if phase.size else 1
409
+ return None, phase, _phase_lut(vtk, n), max(n, 2)
410
+ point, cell = _field_values(mesh, field)
411
+ values = point if point is not None else cell
412
+ if values is None:
413
+ return None, None, None, 5
414
+ return point, cell, _lut(vtk, cmap, *(clim or _range(values, None, None, cmap))), 5
415
+
416
+
417
+ def _grid(mesh, point=None, cell=None):
418
+ """A VTK unstructured grid of a tetrahedral mesh with point and cell scalars."""
419
+ vtk, ns = _vtk()
420
+ grid = vtk.vtkUnstructuredGrid()
421
+ points = vtk.vtkPoints()
422
+ points.SetData(ns.numpy_to_vtk(np.ascontiguousarray(mesh.nodes, dtype=float), deep=True))
423
+ grid.SetPoints(points)
424
+ cell_type = vtk.VTK_TETRA if mesh.order == 1 else vtk.VTK_QUADRATIC_TETRA
425
+ nn = mesh.elements.shape[1]
426
+ offsets = np.arange(0, nn * (mesh.n_elements + 1), nn, dtype=np.int64)
427
+ cells = vtk.vtkCellArray()
428
+ cells.SetData(
429
+ ns.numpy_to_vtkIdTypeArray(offsets, deep=True),
430
+ ns.numpy_to_vtkIdTypeArray(
431
+ np.ascontiguousarray(mesh.elements, dtype=np.int64).ravel(), deep=True
432
+ ),
433
+ )
434
+ grid.SetCells(cell_type, cells)
435
+ if point is not None:
436
+ arr = ns.numpy_to_vtk(np.ascontiguousarray(point, dtype=float), deep=True)
437
+ arr.SetName("field")
438
+ grid.GetPointData().SetScalars(arr)
439
+ if cell is not None:
440
+ arr = ns.numpy_to_vtk(np.ascontiguousarray(cell, dtype=float), deep=True)
441
+ arr.SetName("field")
442
+ grid.GetCellData().SetScalars(arr)
443
+ return grid
444
+
445
+
446
+ def _phase_surface(image: VoxelImage, phase: int):
447
+ """The surface of a phase of a voxel image (flying edges on its indicator, padded so
448
+ that the faces of the box close it)."""
449
+ vtk, ns = _vtk()
450
+ data = (np.asarray(image.data) == phase).astype(np.float32)
451
+ data = np.pad(data, 1)
452
+ img = vtk.vtkImageData()
453
+ img.SetDimensions(*data.shape)
454
+ img.SetSpacing(*image.spacing)
455
+ img.SetOrigin(*(np.asarray(image.origin) - 0.5 * np.asarray(image.spacing)))
456
+ img.GetPointData().SetScalars(ns.numpy_to_vtk(data.ravel(order="F"), deep=True))
457
+ edges = vtk.vtkFlyingEdges3D()
458
+ edges.SetInputData(img)
459
+ edges.SetValue(0, 0.5)
460
+ edges.ComputeNormalsOn()
461
+ edges.Update()
462
+ return edges.GetOutput()
463
+
464
+
465
+ class Scene:
466
+ """An off-screen VTK scene: actors, a camera turning about the centre of their
467
+ bounds, and the rendered frames as RGB arrays."""
468
+
469
+ def __init__(self, size=(640, 480), background=(1.0, 1.0, 1.0)):
470
+ vtk, ns = _vtk()
471
+ if not vtk_can_render():
472
+ raise RuntimeError(NO_RENDERING)
473
+ self._vtk, self._ns = vtk, ns
474
+ self.renderer = vtk.vtkRenderer()
475
+ self.renderer.SetBackground(*background)
476
+ self.window = vtk.vtkRenderWindow()
477
+ self.window.SetOffScreenRendering(1)
478
+ self.window.AddRenderer(self.renderer)
479
+ self.size = (int(size[0]), int(size[1]))
480
+ self.window.SetSize(*self.size)
481
+ self._legend = None
482
+
483
+ def add(self, data, *, lut=None, color=(0.8, 0.8, 0.85), edges=False, opacity=1.0):
484
+ vtk = self._vtk
485
+ if data.IsA("vtkUnstructuredGrid"):
486
+ surface = vtk.vtkDataSetSurfaceFilter()
487
+ surface.SetInputData(data)
488
+ surface.Update()
489
+ data = surface.GetOutput()
490
+ mapper = vtk.vtkPolyDataMapper()
491
+ mapper.SetInputData(data)
492
+ if lut is not None:
493
+ mapper.SetLookupTable(lut)
494
+ mapper.SetScalarRange(lut.GetRange())
495
+ mapper.ScalarVisibilityOn()
496
+ else:
497
+ mapper.ScalarVisibilityOff()
498
+ actor = vtk.vtkActor()
499
+ actor.SetMapper(mapper)
500
+ prop = actor.GetProperty()
501
+ prop.SetColor(*color)
502
+ prop.SetOpacity(opacity)
503
+ if edges:
504
+ prop.EdgeVisibilityOn()
505
+ prop.SetEdgeColor(0.2, 0.2, 0.2)
506
+ self.renderer.AddActor(actor)
507
+ return actor
508
+
509
+ def bar(self, lut, title: str = "", labels: int = 5):
510
+ """A colour bar of the lookup table on the right of the frames, which keep their
511
+ size; ``labels`` equal to the number of colours of the table: one box per value
512
+ (phases)."""
513
+ n = lut.GetNumberOfTableValues()
514
+ colors = np.array([lut.GetTableValue(k)[:3] for k in range(n)])
515
+ lo, hi = lut.GetRange()
516
+ categories = [f"{lo + k:g}" for k in range(n)] if int(labels) == n else None
517
+ self._legend = (colors, lo, hi, title, categories)
518
+ self.window.SetSize(max(self.size[0] - BAR, 16), self.size[1])
519
+
520
+ def view(self, elevation: float = 25.0, azimuth: float = 30.0, zoom: float = 1.0):
521
+ camera = self.renderer.GetActiveCamera()
522
+ self.renderer.ResetCamera()
523
+ camera.Elevation(elevation)
524
+ camera.Azimuth(azimuth)
525
+ camera.OrthogonalizeViewUp()
526
+ camera.Zoom(zoom)
527
+ self.renderer.ResetCameraClippingRange()
528
+
529
+ def frame(self) -> np.ndarray:
530
+ self.window.Render()
531
+ grab = self._vtk.vtkWindowToImageFilter()
532
+ grab.SetInput(self.window)
533
+ grab.ReadFrontBufferOff()
534
+ grab.Update()
535
+ img = grab.GetOutput()
536
+ w, h, _ = img.GetDimensions()
537
+ arr = self._ns.vtk_to_numpy(img.GetPointData().GetScalars()).reshape(h, w, -1)
538
+ rgb = np.ascontiguousarray(arr[::-1, :, :3])
539
+ return rgb if self._legend is None else _with_bar(rgb, *self._legend)
540
+
541
+
542
+ def _field_values(mesh, field):
543
+ """Point or cell scalars of a field (vectors by their norm)."""
544
+ if field is None:
545
+ return None, None
546
+ values = np.asarray(field, dtype=float)
547
+ if values.ndim == 2:
548
+ values = np.linalg.norm(values, axis=1)
549
+ if len(values) == mesh.n_nodes:
550
+ return values, None
551
+ if len(values) == mesh.n_elements:
552
+ return None, values
553
+ raise ValueError("field: one value (or vector) per node or per element")
554
+
555
+
556
+ def turntable_frames(
557
+ obj,
558
+ *,
559
+ field=None,
560
+ phase: int = 1,
561
+ frames: int = 72,
562
+ size=(640, 480),
563
+ elevation: float = 25.0,
564
+ azimuth: float = 30.0,
565
+ cmap="viridis",
566
+ clim=None,
567
+ title: str = "",
568
+ edges: bool = False,
569
+ ):
570
+ """A turntable of the surface of a phase of a voxel image, or of a tetrahedral mesh
571
+ coloured by ``field`` (per node or element, vectors by their norm; ``"phase"``: the
572
+ phases of the elements)."""
573
+ scene = Scene(size)
574
+ vtk, _ = _vtk()
575
+ if isinstance(obj, VoxelImage):
576
+ scene.add(_phase_surface(obj, phase), color=(0.75, 0.78, 0.86))
577
+ else:
578
+ point, cell, lut, labels = _colours(vtk, obj, field, cmap, clim)
579
+ if lut is not None:
580
+ scene.bar(lut, title or ("phase" if isinstance(field, str) else ""), labels)
581
+ scene.add(_grid(obj, point, cell), lut=lut, edges=edges)
582
+ scene.view(elevation, azimuth)
583
+ out = []
584
+ for _ in range(int(frames)):
585
+ out.append(scene.frame())
586
+ scene.renderer.GetActiveCamera().Azimuth(360.0 / int(frames))
587
+ return out
588
+
589
+
590
+ def _clipped(grid, origin, normal):
591
+ vtk, _ = _vtk()
592
+ plane = vtk.vtkPlane()
593
+ plane.SetOrigin(*origin)
594
+ plane.SetNormal(*normal)
595
+ clip = vtk.vtkTableBasedClipDataSet()
596
+ clip.SetInputData(grid)
597
+ clip.SetClipFunction(plane)
598
+ clip.Update()
599
+ return clip.GetOutput()
600
+
601
+
602
+ def section_sweep_frames(
603
+ mesh,
604
+ field=None,
605
+ *,
606
+ axis: int = 2,
607
+ frames: int = 48,
608
+ size=(640, 480),
609
+ elevation: float = 25.0,
610
+ azimuth: float = 30.0,
611
+ cmap="viridis",
612
+ clim=None,
613
+ title: str = "",
614
+ ):
615
+ """A cross-section sweeping through a tetrahedral mesh along ``axis``: the part beyond
616
+ the plane, coloured by ``field`` on its outer faces and on the cut (``"phase"``: the
617
+ phases of the elements)."""
618
+ vtk, _ = _vtk()
619
+ point, cell, lut, labels = _colours(vtk, mesh, field, cmap, clim)
620
+ grid = _grid(mesh, point, cell)
621
+ lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
622
+ normal = np.eye(3)[axis]
623
+ scene = Scene(size)
624
+ if lut is not None:
625
+ scene.bar(lut, title or ("phase" if isinstance(field, str) else ""), labels)
626
+ actor = scene.add(grid, lut=lut)
627
+ scene.view(elevation, azimuth)
628
+ out = []
629
+ for t in np.linspace(0.02, 0.98, int(frames)):
630
+ origin = lower + t * (upper - lower)
631
+ cut = _clipped(grid, origin, normal)
632
+ surface = vtk.vtkDataSetSurfaceFilter()
633
+ surface.SetInputData(cut)
634
+ surface.Update()
635
+ actor.GetMapper().SetInputData(surface.GetOutput())
636
+ out.append(scene.frame())
637
+ return out
638
+
639
+
640
+ def field_frames(
641
+ mesh,
642
+ displacement,
643
+ field=None,
644
+ *,
645
+ magnification: float | None = None,
646
+ frames: int = 48,
647
+ wave: str = "sine",
648
+ section=None,
649
+ size=(640, 480),
650
+ elevation: float = 25.0,
651
+ azimuth: float = 30.0,
652
+ cmap="viridis",
653
+ clim=None,
654
+ title: str = "",
655
+ scaling: str | None = None,
656
+ ):
657
+ """The deformed mesh ``x + s(t) m u``: ``wave`` "sine" (a mode oscillating, ``s =
658
+ sin 2πt``) or "ramp" (a load growing, ``s = t``); ``m`` the magnification (by default
659
+ the largest displacement drawn as a tenth of the mesh); coloured by ``field`` (by
660
+ default the norm of the displacement), optionally cut by a plane ``section = (axis,
661
+ fraction)``. The field is that of the full load, which a linear solution scales by
662
+ ``s`` (``scaling`` of :func:`field_scaling`: by default ``"magnitude"`` for the norm of
663
+ the displacement, ``"linear"`` for other values, ``"none"`` for the phases), so that
664
+ the colours follow the load in a range fixed over the frames (``clim``, else that of
665
+ the full load from zero, symmetric when an oscillating load changes the sign)."""
666
+ vtk, ns = _vtk()
667
+ u = np.asarray(displacement, dtype=float).reshape(-1, 3)
668
+ m = _magnification(mesh, [u], magnification)
669
+ values = np.linalg.norm(u, axis=1) if field is None else field
670
+ if scaling is None:
671
+ scaling = "magnitude" if field is None else "linear"
672
+ if isinstance(values, str): # the phases do not follow the load
673
+ scaling = "none"
674
+ if scaling not in SCALINGS:
675
+ raise ValueError(f"scaling: one of {', '.join(SCALINGS)}")
676
+ if clim is None and scaling != "none":
677
+ point, cell = _field_values(mesh, values)
678
+ lo, hi = _range(point if point is not None else cell, None, None, cmap)
679
+ lo, hi = min(lo, 0.0), max(hi, 0.0) # the load grows from zero
680
+ if wave == "sine" and scaling == "linear":
681
+ lo, hi = -max(-lo, hi), max(-lo, hi)
682
+ clim = (lo, hi)
683
+ point, cell, lut, labels = _colours(vtk, mesh, values, cmap, clim)
684
+ grid = _grid(mesh, point, cell)
685
+ scene = Scene(size)
686
+ scene.bar(lut, title or ("u" if field is None else ""), labels)
687
+ actor = scene.add(grid, lut=lut)
688
+ times = np.linspace(0.0, 1.0, int(frames), endpoint=wave == "ramp")
689
+ scales = np.sin(2 * np.pi * times) if wave == "sine" else times
690
+ lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
691
+ first = True
692
+ out = []
693
+ for s in scales:
694
+ moved = mesh.nodes + s * m * u
695
+ grid.GetPoints().SetData(ns.numpy_to_vtk(np.ascontiguousarray(moved), deep=True))
696
+ if scaling != "none":
697
+ factor = {"linear": s, "magnitude": abs(s), "quadratic": s * s}[scaling]
698
+ for data, base in ((grid.GetPointData(), point), (grid.GetCellData(), cell)):
699
+ if base is not None:
700
+ arr = ns.numpy_to_vtk(np.ascontiguousarray(factor * base), deep=True)
701
+ arr.SetName("field")
702
+ data.SetScalars(arr)
703
+ grid.Modified()
704
+ actor.GetMapper().SetInputData(_surface(vtk, grid, section, lower, upper))
705
+ if first:
706
+ scene.view(elevation, azimuth)
707
+ first = False
708
+ out.append(scene.frame())
709
+ return out
710
+
711
+
712
+ #: How the fields of a linear solution follow its load factor ``s`` (:func:`field_scaling`)
713
+ SCALINGS = ("linear", "magnitude", "quadratic", "none")
714
+
715
+
716
+ def field_scaling(name: str | None) -> str:
717
+ """How a field of a linear solution follows its load factor ``s``: ``"linear"`` (``s
718
+ v``: the components of stresses, strains and displacements), ``"magnitude"`` (``|s|
719
+ v``: norms and equivalent values, the von Mises stress, the norm of the displacement,
720
+ ``None``), ``"quadratic"`` (``s² v``: energy densities) or ``"none"`` (the phases)."""
721
+ if name is None:
722
+ return "magnitude"
723
+ name = str(name).lower()
724
+ if name == "phase":
725
+ return "none"
726
+ if "energy" in name:
727
+ return "quadratic"
728
+ if name in ("von_mises", "displacement", "equivalent_strain", "heat_flux") or name.endswith(
729
+ ("_norm", "_magnitude")
730
+ ):
731
+ return "magnitude"
732
+ return "linear"
733
+
734
+
735
+ def _magnification(mesh, displacements, magnification) -> float:
736
+ """The magnification of displacements: by default, the largest one drawn as a tenth
737
+ of the size of the mesh."""
738
+ if magnification is not None:
739
+ return float(magnification)
740
+ size = float(np.ptp(mesh.nodes, axis=0).max())
741
+ peak = max((float(np.linalg.norm(u, axis=1).max()) for u in displacements), default=0.0)
742
+ return 0.1 * size / max(peak, 1e-300)
743
+
744
+
745
+ def _surface(vtk, grid, section, lower, upper):
746
+ """The outer faces of a grid, cut by the plane ``section = (axis, fraction)`` of the
747
+ box ``[lower, upper]`` (the part beyond it)."""
748
+ shown = grid
749
+ if section is not None:
750
+ axis, fraction = section
751
+ origin = lower + float(fraction) * (upper - lower)
752
+ shown = _clipped(grid, origin, np.eye(3)[int(axis)])
753
+ surface = vtk.vtkDataSetSurfaceFilter()
754
+ surface.SetInputData(shown)
755
+ surface.Update()
756
+ return surface.GetOutput()
757
+
758
+
759
+ def deformed_view(
760
+ mesh,
761
+ displacement=None,
762
+ field=None,
763
+ *,
764
+ magnification: float | None = None,
765
+ section=None,
766
+ size=(640, 480),
767
+ elevation: float = 25.0,
768
+ azimuth: float = 30.0,
769
+ cmap="viridis",
770
+ clim=None,
771
+ title: str = "",
772
+ edges: bool = False,
773
+ ) -> np.ndarray:
774
+ """One view (an RGB array) of a tetrahedral mesh coloured by ``field`` (per node or
775
+ element, vectors by their norm; ``"phase"``: the phases of the elements), deformed by
776
+ ``m u`` when a ``displacement`` is given (``m`` as in :func:`field_frames`), cut by
777
+ the plane ``section = (axis, fraction)``."""
778
+ vtk, ns = _vtk()
779
+ point, cell, lut, labels = _colours(vtk, mesh, field, cmap, clim)
780
+ grid = _grid(mesh, point, cell)
781
+ if displacement is not None:
782
+ u = np.asarray(displacement, dtype=float).reshape(-1, 3)
783
+ moved = mesh.nodes + _magnification(mesh, [u], magnification) * u
784
+ grid.GetPoints().SetData(ns.numpy_to_vtk(np.ascontiguousarray(moved), deep=True))
785
+ scene = Scene(size)
786
+ if lut is not None:
787
+ scene.bar(lut, title or ("phase" if isinstance(field, str) else ""), labels)
788
+ lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
789
+ scene.add(_surface(vtk, grid, section, lower, upper), lut=lut, edges=edges)
790
+ scene.view(elevation, azimuth)
791
+ return scene.frame()
792
+
793
+
794
+ def history_frames(
795
+ mesh,
796
+ displacements,
797
+ fields=None,
798
+ *,
799
+ frames: int | None = None,
800
+ magnification: float | None = None,
801
+ section=None,
802
+ size=(640, 480),
803
+ elevation: float = 25.0,
804
+ azimuth: float = 30.0,
805
+ cmap="viridis",
806
+ clim=None,
807
+ title: str = "",
808
+ captions=None,
809
+ ):
810
+ """The mesh deformed by the displacements of successive times (the steps of a loading
811
+ path), ``x + m u_k`` (``m`` as in :func:`field_frames`), coloured by the ``fields`` of
812
+ these times (per node or element; by default the norm of the displacement) on one
813
+ range, cut by the plane ``section = (axis, fraction)``. ``frames``: that many frames
814
+ interpolated linearly between the times (by default one per time); ``captions``: a
815
+ text per time (e.g. ``"t = 10"``), shown on the frames nearest to it."""
816
+ vtk, ns = _vtk()
817
+ us = [np.asarray(u, dtype=float).reshape(-1, 3) for u in displacements]
818
+ if not us:
819
+ raise ValueError("history_frames: at least one time")
820
+ raw = [np.linalg.norm(u, axis=1) for u in us] if fields is None else list(fields)
821
+ if len(raw) != len(us):
822
+ raise ValueError("history_frames: one field per displacement")
823
+ pairs = [_field_values(mesh, f) for f in raw]
824
+ on_points = pairs[0][0] is not None
825
+ values = [p if on_points else c for p, c in pairs]
826
+ lut = _lut(vtk, cmap, *(clim or _range(np.concatenate(values), None, None, cmap)))
827
+ m = _magnification(mesh, us, magnification)
828
+ grid = _grid(mesh, *((values[0], None) if on_points else (None, values[0])))
829
+ scene = Scene(size)
830
+ scene.bar(lut, title or ("u" if fields is None else ""))
831
+ actor = scene.add(grid, lut=lut)
832
+ n = len(us)
833
+ positions = (
834
+ np.arange(n, dtype=float) if frames is None else np.linspace(0.0, n - 1.0, int(frames))
835
+ )
836
+ lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
837
+
838
+ def show(s: float) -> int:
839
+ i = min(int(np.floor(s)), max(n - 2, 0))
840
+ j = min(i + 1, n - 1)
841
+ a = s - i if n > 1 else 0.0
842
+ moved = mesh.nodes + m * ((1.0 - a) * us[i] + a * us[j])
843
+ grid.GetPoints().SetData(ns.numpy_to_vtk(np.ascontiguousarray(moved), deep=True))
844
+ arr = ns.numpy_to_vtk(
845
+ np.ascontiguousarray((1.0 - a) * values[i] + a * values[j]), deep=True
846
+ )
847
+ arr.SetName("field")
848
+ (grid.GetPointData() if on_points else grid.GetCellData()).SetScalars(arr)
849
+ grid.Modified()
850
+ actor.GetMapper().SetInputData(_surface(vtk, grid, section, lower, upper))
851
+ return i if a < 0.5 else j
852
+
853
+ show(positions[-1]) # the camera framing the last (largest) deformation
854
+ scene.view(elevation, azimuth)
855
+ out = []
856
+ for s in positions:
857
+ k = show(float(s))
858
+ rgb = scene.frame()
859
+ out.append(_caption(rgb, str(captions[k])) if captions is not None else rgb)
860
+ return out
861
+
862
+
863
+ def frame_pattern_frames(
864
+ frame,
865
+ mode,
866
+ *,
867
+ magnification: float = 1.0,
868
+ frames: int = 48,
869
+ wave: str = "sine",
870
+ tiles=None,
871
+ size: int = 480,
872
+ ):
873
+ """A pattern of a frame of beams oscillating (``wave="sine"``) or growing (``"ramp"``)
874
+ on ``tiles`` copies of its cell: a plane frame
875
+ (:class:`~morphogen.homogenization.frames.Frame`, 3 x 3 cells by default) or a frame
876
+ of struts in space (:class:`~morphogen.homogenization.frames.SpaceFrame`, one cell
877
+ seen in perspective)."""
878
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
879
+
880
+ from morphogen.viz.figures import _figure
881
+
882
+ space = frame.lattice.shape[0] == 3
883
+ tiles = tiles or ((1, 1, 1) if space else (3, 3))
884
+ times = np.linspace(0.0, 1.0, int(frames), endpoint=wave == "ramp")
885
+ scales = np.sin(2 * np.pi * times) if wave == "sine" else times
886
+ mode = np.asarray(mode, dtype=float)
887
+ fig = _figure(size / 120, size / 120)
888
+ canvas = FigureCanvasAgg(fig)
889
+ ax = fig.add_subplot(projection="3d") if space else fig.subplots()
890
+ frame.plot(ax, mode, scale=magnification, tiles=tiles)
891
+ limits = [ax.get_xlim(), ax.get_ylim()] + ([ax.get_zlim()] if space else [])
892
+ setters = (ax.set_xlim, ax.set_ylim) + ((ax.set_zlim,) if space else ())
893
+ out = []
894
+ for s in scales:
895
+ ax.clear()
896
+ moved = s * mode if abs(s) > 1e-12 else None
897
+ frame.plot(ax, moved, scale=magnification * abs(s), tiles=tiles, lw=0.8)
898
+ for setter, lim in zip(setters, limits, strict=True): # those of the largest motion
899
+ setter(*lim)
900
+ if space:
901
+ ax.set_box_aspect(tuple(max(b - a, 1e-9) for a, b in limits))
902
+ canvas.draw()
903
+ out.append(np.asarray(canvas.buffer_rgba())[..., :3].copy())
904
+ return out