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,512 @@
1
+ """Tetrahedral meshes of a box: linear (4-node) or quadratic (10-node) elements.
2
+
3
+ Quadratic elements follow the VTK / Abaqus C3D10 node order: corners 0-3, then the
4
+ mid-edge nodes of edges (0, 1), (1, 2), (0, 2), (0, 3), (1, 3), (2, 3). They are
5
+ isoparametric: a mid-edge node may leave the middle of its straight edge, and the edge
6
+ is then the parabola through its three nodes (:func:`morphogen.mesh.curved.curved_mesh`
7
+ puts the nodes of the interfaces on the implicit surfaces of the phases). An element is
8
+ *straight* when its mid-edge nodes are the middles of its edges, *curved* otherwise
9
+ (:meth:`TetMesh.deviations`, :attr:`TetMesh.curved`).
10
+
11
+ A mesh of the box is bounded by its faces. A mesh of whole periodic cells (``whole``)
12
+ fills the volume of the box without being cut by its faces: its outer boundary is made
13
+ of pairs of translated facets, and every node on it has translates by the periods of the
14
+ box (:meth:`TetMesh.periodic_links`). The faces of the elements on that boundary are
15
+ recorded (``outer``) when the mesh is made, so that they are known in a mesh of some of
16
+ its phases too, where the walls of the pores are free faces as well.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+
23
+ import numpy as np
24
+ from scipy.spatial import cKDTree
25
+
26
+ #: Corner pairs of the six edges of a tetrahedron, in mid-node order.
27
+ TET_EDGES = np.array([[0, 1], [1, 2], [0, 2], [0, 3], [1, 3], [2, 3]])
28
+ #: Corner triples of the four faces (outward normals for positive tetrahedra), and the
29
+ #: mid-edge nodes of each face (indices into the 10-node element).
30
+ TET_FACES = np.array([[0, 2, 1], [0, 1, 3], [1, 2, 3], [0, 3, 2]])
31
+ TET_FACE_MIDS = np.array([[6, 5, 4], [4, 8, 7], [5, 9, 8], [7, 9, 6]])
32
+
33
+
34
+ #: A rule of the tetrahedron exact to degree 3 (barycentric coordinates, weights): the
35
+ #: Jacobian of a 10-node element is a polynomial of that degree
36
+ _CUBIC_RULE = (
37
+ np.array(
38
+ [
39
+ [0.25, 0.25, 0.25, 0.25],
40
+ [0.5, 1 / 6, 1 / 6, 1 / 6],
41
+ [1 / 6, 0.5, 1 / 6, 1 / 6],
42
+ [1 / 6, 1 / 6, 0.5, 1 / 6],
43
+ [1 / 6, 1 / 6, 1 / 6, 0.5],
44
+ ]
45
+ ),
46
+ np.array([-0.8, 0.45, 0.45, 0.45, 0.45]),
47
+ )
48
+ #: Barycentric coordinates of the ten nodes of a quadratic tetrahedron
49
+ TET10_NODES = np.concatenate(
50
+ [np.eye(4), 0.5 * (np.eye(4)[TET_EDGES[:, 0]] + np.eye(4)[TET_EDGES[:, 1]])]
51
+ )
52
+
53
+
54
+ def tet_volumes(nodes: np.ndarray, elements: np.ndarray) -> np.ndarray:
55
+ """Signed volumes of the tetrahedra of corners 0-3 (straight edges)."""
56
+ p = nodes[elements[:, :4]]
57
+ a, b, c = p[:, 1] - p[:, 0], p[:, 2] - p[:, 0], p[:, 3] - p[:, 0]
58
+ return np.einsum("ij,ij->i", a, np.cross(b, c)) / 6.0
59
+
60
+
61
+ def edge_deviations(nodes: np.ndarray, elements: np.ndarray) -> np.ndarray:
62
+ """The departures (elements x 6 x 3) of the mid-edge nodes of 10-node tetrahedra from
63
+ the middles of their straight edges: zero for straight elements."""
64
+ ends = nodes[elements[:, TET_EDGES]] # (n, 6, 2, 3)
65
+ return nodes[elements[:, 4:]] - 0.5 * (ends[:, :, 0] + ends[:, :, 1])
66
+
67
+
68
+ def corner_gradients(nodes: np.ndarray, elements: np.ndarray) -> np.ndarray:
69
+ """Gradients (elements x 4 x 3) of the barycentric coordinates of the straight
70
+ tetrahedra of corners 0-3."""
71
+ p = nodes[elements[:, :4]]
72
+ edges = np.stack([p[:, 1] - p[:, 0], p[:, 2] - p[:, 0], p[:, 3] - p[:, 0]], axis=2)
73
+ inverse = np.linalg.inv(edges) # its rows: the gradients of L1, L2, L3
74
+ return np.concatenate([-inverse.sum(axis=1, keepdims=True), inverse], axis=1)
75
+
76
+
77
+ def jacobian_ratios(gradients: np.ndarray, deviations: np.ndarray, bary) -> np.ndarray:
78
+ """The ratio of the volume element of curved 10-node tetrahedra to that of their
79
+ straight ones at points of barycentric coordinates ``bary`` (points x 4): elements x
80
+ points. The curved element is the straight one moved by ``sum_k N_k(L) d_k``, with
81
+ ``N_k = 4 L_i L_j`` the function of the mid-edge node of the edge (i, j) and ``d_k``
82
+ its departure: the ratio is ``det(I + sum_k d_k (x) grad N_k)``."""
83
+ bary = np.atleast_2d(np.asarray(bary, dtype=float))
84
+ i, j = TET_EDGES[:, 0], TET_EDGES[:, 1]
85
+ # grad N_k = 4 (L_i grad L_j + L_j grad L_i): (elements, points, 6, 3)
86
+ grad = 4.0 * (
87
+ bary[None, :, i, None] * gradients[:, None, j, :]
88
+ + bary[None, :, j, None] * gradients[:, None, i, :]
89
+ )
90
+ f = np.einsum("eka,eqkb->eqab", deviations, grad)
91
+ f += np.eye(3)
92
+ return np.linalg.det(f)
93
+
94
+
95
+ def element_volumes(nodes: np.ndarray, elements: np.ndarray) -> np.ndarray:
96
+ """Signed volumes of the elements: of the tetrahedra of their corners, or, for 10-node
97
+ elements with curved edges, the integral of their Jacobian (a polynomial of degree 3
98
+ in the barycentric coordinates, by a rule exact for it)."""
99
+ volumes = tet_volumes(nodes, elements)
100
+ if elements.shape[1] != 10:
101
+ return volumes
102
+ dev = edge_deviations(nodes, elements)
103
+ scale = np.abs(volumes) ** (1.0 / 3.0)
104
+ curved = np.flatnonzero(np.abs(dev).max(axis=(1, 2)) > 1e-10 * scale)
105
+ if curved.size:
106
+ points, weights = _CUBIC_RULE
107
+ ratios = jacobian_ratios(corner_gradients(nodes, elements[curved]), dev[curved], points)
108
+ volumes[curved] *= ratios @ weights
109
+ return volumes
110
+
111
+
112
+ def tet_quality(nodes: np.ndarray, elements: np.ndarray) -> np.ndarray:
113
+ """Mean-ratio-like quality: 1 for a regular tetrahedron, 0 for a flat one.
114
+
115
+ ``q = 6 sqrt(2) V / l_rms^3`` with ``l_rms`` the root mean square edge length.
116
+ """
117
+ p = nodes[elements[:, :4]]
118
+ l2 = sum(((p[:, b] - p[:, a]) ** 2).sum(axis=1) for a, b in TET_EDGES)
119
+ vol = np.abs(tet_volumes(nodes, elements))
120
+ with np.errstate(divide="ignore", invalid="ignore"):
121
+ q = 6.0 * np.sqrt(2.0) * vol / (l2 / 6.0) ** 1.5
122
+ return np.nan_to_num(q)
123
+
124
+
125
+ @dataclass
126
+ class TetMesh:
127
+ """Tetrahedral mesh of the box ``[lower, upper]`` with a phase per element.
128
+
129
+ ``periodic`` tells whether the meshed microstructure is periodic (periodic boundary
130
+ conditions are then meaningful); the opposite faces need not have matching nodes.
131
+ Meshes of polycrystals also give the cell (grain) of each element, ``cell``, and the
132
+ crystal orientation of each cell, ``orientations`` (Bunge Euler angles in degrees).
133
+ The crack meshes of a morphology (:func:`morphogen.fracture.lefm.crack_mesh`), whose
134
+ phases are those of its materials, give the side of the crack of each element,
135
+ ``side`` (0 or 1).
136
+ """
137
+
138
+ nodes: np.ndarray
139
+ elements: np.ndarray
140
+ phase: np.ndarray
141
+ lower: np.ndarray
142
+ upper: np.ndarray
143
+ periodic: bool = False
144
+ metadata: dict = field(default_factory=dict)
145
+ cell: np.ndarray | None = None
146
+ orientations: np.ndarray | None = None
147
+ whole: bool = False
148
+ #: whole periodic cells: which faces of each element (``TET_FACES`` order) bound the
149
+ #: volume element; by default, the free faces of the mesh (all the cells meshed)
150
+ outer: np.ndarray | None = None
151
+ #: crack meshes of a morphology: the side of the crack of each element (0 or 1)
152
+ side: np.ndarray | None = None
153
+ #: meshes that follow the sharp edges of the phases: these edges (pairs of corner
154
+ #: nodes), and the two pieces of the structure that meet along each
155
+ #: (:meth:`~morphogen.models.base.Microstructure.implicit_pieces`)
156
+ sharp: np.ndarray | None = None
157
+ sharp_pieces: np.ndarray | None = None
158
+ _cache: dict = field(default_factory=dict, init=False, repr=False, compare=False)
159
+
160
+ def __post_init__(self) -> None:
161
+ self.nodes = np.ascontiguousarray(self.nodes, dtype=np.float64)
162
+ self.elements = np.ascontiguousarray(self.elements, dtype=np.int64)
163
+ self.phase = np.ascontiguousarray(self.phase, dtype=np.int64)
164
+ self.lower = np.asarray(self.lower, dtype=np.float64)
165
+ self.upper = np.asarray(self.upper, dtype=np.float64)
166
+ if self.elements.ndim != 2 or self.elements.shape[1] not in (4, 10):
167
+ raise ValueError("tetrahedra need 4 (linear) or 10 (quadratic) nodes")
168
+ if self.phase.shape != (len(self.elements),):
169
+ raise ValueError("one phase per element")
170
+ if self.cell is not None:
171
+ self.cell = np.ascontiguousarray(self.cell, dtype=np.int64)
172
+ if self.cell.shape != (len(self.elements),):
173
+ raise ValueError("one cell label per element")
174
+ if self.orientations is not None:
175
+ self.orientations = np.ascontiguousarray(self.orientations, dtype=np.float64)
176
+ if self.orientations.ndim != 2 or self.orientations.shape[1] != 3:
177
+ raise ValueError("orientations: three Euler angles per cell")
178
+ if (
179
+ self.cell is not None
180
+ and self.cell.size
181
+ and self.cell.max() >= len(self.orientations)
182
+ ):
183
+ raise ValueError("orientations: one row per cell label")
184
+ if self.whole and self.outer is None:
185
+ self.outer = self._free_mask()
186
+ if self.outer is not None:
187
+ self.outer = np.ascontiguousarray(self.outer, dtype=bool)
188
+ if self.outer.shape != (len(self.elements), 4):
189
+ raise ValueError("outer: four flags (faces) per element")
190
+ if self.side is not None:
191
+ self.side = np.ascontiguousarray(self.side, dtype=np.int64)
192
+ if self.side.shape != (len(self.elements),):
193
+ raise ValueError("one side of the crack per element")
194
+ if self.sharp is not None:
195
+ self.sharp = np.ascontiguousarray(self.sharp, dtype=np.int64).reshape(-1, 2)
196
+ if self.sharp_pieces is not None:
197
+ self.sharp_pieces = np.ascontiguousarray(self.sharp_pieces, dtype=np.int64)
198
+ if self.sharp_pieces.shape != self.sharp.shape:
199
+ raise ValueError("sharp_pieces: two pieces per sharp edge")
200
+
201
+ def _derived(self, nodes, elements, keep=None, numbers=None) -> TetMesh:
202
+ """A mesh with new nodes and elements and the same attributes (elements
203
+ ``keep`` of this one; ``numbers``: the new numbers of its nodes, -1 for those
204
+ that are left out)."""
205
+ sel = slice(None) if keep is None else keep
206
+ sharp, sharp_pieces = self.sharp, self.sharp_pieces
207
+ if sharp is not None and numbers is not None:
208
+ moved = numbers[sharp]
209
+ there = (moved >= 0).all(axis=1)
210
+ sharp = moved[there]
211
+ sharp_pieces = None if sharp_pieces is None else sharp_pieces[there]
212
+ return TetMesh(
213
+ nodes=nodes,
214
+ elements=elements,
215
+ phase=self.phase[sel],
216
+ lower=self.lower,
217
+ upper=self.upper,
218
+ periodic=self.periodic,
219
+ metadata=dict(self.metadata),
220
+ cell=None if self.cell is None else self.cell[sel],
221
+ orientations=self.orientations,
222
+ whole=self.whole,
223
+ outer=None if self.outer is None else self.outer[sel],
224
+ side=None if self.side is None else self.side[sel],
225
+ sharp=sharp,
226
+ sharp_pieces=sharp_pieces,
227
+ )
228
+
229
+ @property
230
+ def order(self) -> int:
231
+ return 1 if self.elements.shape[1] == 4 else 2
232
+
233
+ @property
234
+ def n_nodes(self) -> int:
235
+ return len(self.nodes)
236
+
237
+ @property
238
+ def n_elements(self) -> int:
239
+ return len(self.elements)
240
+
241
+ @property
242
+ def size(self) -> np.ndarray:
243
+ return self.upper - self.lower
244
+
245
+ @property
246
+ def box_volume(self) -> float:
247
+ return float(np.prod(self.size))
248
+
249
+ def volumes(self) -> np.ndarray:
250
+ """Signed volumes of the elements (those of curved 10-node elements exactly)."""
251
+ return element_volumes(self.nodes, self.elements)
252
+
253
+ def deviations(self) -> np.ndarray | None:
254
+ """The departures (elements x 6 x 3) of the mid-edge nodes of a 10-node mesh from
255
+ the middles of their straight edges (zero where the elements are straight); None
256
+ for a 4-node mesh."""
257
+ if self.order == 1:
258
+ return None
259
+ return edge_deviations(self.nodes, self.elements)
260
+
261
+ @property
262
+ def curved(self) -> bool:
263
+ """Whether some 10-node elements have curved edges (mid-edge nodes off the
264
+ middles of their edges, beyond the round-off of coordinates read from a file)."""
265
+ if self.order == 1:
266
+ return False
267
+ if "curved" not in self._cache:
268
+ dev = np.abs(self.deviations()).max(axis=(1, 2)) if self.n_elements else np.zeros(0)
269
+ scale = np.abs(tet_volumes(self.nodes, self.elements)) ** (1.0 / 3.0)
270
+ self._cache["curved"] = bool(np.any(dev > 1e-10 * scale))
271
+ return self._cache["curved"]
272
+
273
+ def min_jacobian(self) -> float:
274
+ """The smallest ratio of the volume element of the 10-node elements to that of
275
+ their straight tetrahedra, over their ten nodes and their four integration points
276
+ (1 for a straight mesh; positive for valid elements)."""
277
+ if not self.curved:
278
+ return 1.0
279
+ a, b = 0.5854101966249685, 0.1381966011250105
280
+ gauss = np.full((4, 4), b) + (a - b) * np.eye(4)
281
+ dev = self.deviations()
282
+ bent = np.flatnonzero(np.abs(dev).max(axis=(1, 2)) > 0.0)
283
+ ratios = jacobian_ratios(
284
+ corner_gradients(self.nodes, self.elements[bent]),
285
+ dev[bent],
286
+ np.concatenate([TET10_NODES, gauss]),
287
+ )
288
+ return float(ratios.min())
289
+
290
+ def quality(self) -> np.ndarray:
291
+ return tet_quality(self.nodes, self.elements)
292
+
293
+ def phase_fractions(self) -> dict[int, float]:
294
+ """Volume of each phase over the volume of the box (missing phases: voids)."""
295
+ vol = self.volumes()
296
+ return {
297
+ int(p): float(vol[self.phase == p].sum() / self.box_volume)
298
+ for p in np.unique(self.phase)
299
+ }
300
+
301
+ def tolerance(self) -> float:
302
+ return 1e-9 * float(np.max(self.size))
303
+
304
+ def face_nodes(self, axis: int, side: int) -> np.ndarray:
305
+ """Nodes on the face of the box normal to ``axis`` (``side`` 0: lower, 1: upper)."""
306
+ target = self.lower[axis] if side == 0 else self.upper[axis]
307
+ return np.flatnonzero(np.abs(self.nodes[:, axis] - target) <= self.tolerance())
308
+
309
+ def boundary_nodes(self) -> np.ndarray:
310
+ """Nodes on the boundary of the volume element: the faces of the box, or the
311
+ outer boundary of whole periodic cells."""
312
+ if self.whole:
313
+ return np.unique(self.outer_faces())
314
+ on = np.zeros(self.n_nodes, dtype=bool)
315
+ for axis in range(3):
316
+ for side in (0, 1):
317
+ on[self.face_nodes(axis, side)] = True
318
+ return np.flatnonzero(on)
319
+
320
+ def _free_mask(self) -> np.ndarray:
321
+ """Faces of each element (``TET_FACES`` order) that belong to no other element."""
322
+ key = np.sort(self.elements[:, TET_FACES].reshape(-1, 3), axis=1)
323
+ _, inverse, counts = np.unique(key, axis=0, return_inverse=True, return_counts=True)
324
+ return (counts[inverse.ravel()] == 1).reshape(-1, 4)
325
+
326
+ def _faces(self, mask: np.ndarray) -> np.ndarray:
327
+ """The faces flagged in an (elements, 4) mask: (k, 3) corners or (k, 6) for P2
328
+ (corners then mid-edge nodes), oriented with outward normals."""
329
+ elem, local = np.nonzero(mask)
330
+ faces = self.elements[elem[:, None], TET_FACES[local]]
331
+ if self.order == 2:
332
+ faces = np.concatenate(
333
+ [faces, self.elements[elem[:, None], TET_FACE_MIDS[local]]], axis=1
334
+ )
335
+ return faces
336
+
337
+ def free_faces(self) -> np.ndarray:
338
+ """Element faces belonging to a single element: (k, 3) corners or (k, 6) for P2
339
+ (corners then mid-edge nodes), oriented with outward normals."""
340
+ if "free_faces" not in self._cache:
341
+ self._cache["free_faces"] = self._faces(self._free_mask())
342
+ return self._cache["free_faces"]
343
+
344
+ def _torus(self, candidates: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
345
+ """Classes of translates (by the periods of the box) among nodes, and the shift
346
+ of each node from the first of its class (translates agree to the rounding of
347
+ their coordinates, distinct nodes may be a micrometre apart in a unit box)."""
348
+ from morphogen.mesh.polyhedra import torus_classes
349
+
350
+ return torus_classes(self.nodes[candidates], self.lower, self.size, self.tolerance())
351
+
352
+ def outer_faces(self) -> np.ndarray:
353
+ """Faces bounding the volume element, with outward normals: those on the faces of
354
+ the box, or the ``outer`` faces of whole periodic cells."""
355
+ if not self.whole:
356
+ return np.concatenate([self.boundary_faces(a, s) for a in range(3) for s in (0, 1)])
357
+ if "outer_faces" not in self._cache:
358
+ self._cache["outer_faces"] = self._faces(self.outer)
359
+ return self._cache["outer_faces"]
360
+
361
+ def periodic_links(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
362
+ """Nodes of the boundary that are translates of others by the periods of the box:
363
+ ``(slave, master, shift)`` with ``x_slave = x_master + shift * size`` (shift in
364
+ periods), each slave linked to the first node of its class."""
365
+ if "links" not in self._cache:
366
+ candidates = self.boundary_nodes()
367
+ if candidates.size == 0:
368
+ empty = np.zeros(0, dtype=np.int64)
369
+ return empty, empty, np.zeros((0, 3), dtype=np.int64)
370
+ labels, shift = self._torus(candidates)
371
+ first = np.full(int(labels.max()) + 1, -1)
372
+ first[labels[::-1]] = np.arange(len(labels))[::-1]
373
+ slave = np.flatnonzero(first[labels] != np.arange(len(labels)))
374
+ master = first[labels[slave]]
375
+ self._cache["links"] = (
376
+ candidates[slave],
377
+ candidates[master],
378
+ shift[slave] - shift[master],
379
+ )
380
+ return self._cache["links"]
381
+
382
+ def boundary_faces(self, axis: int, side: int) -> np.ndarray:
383
+ """Element faces lying on a face of the box: (k, 3) corners or (k, 6) for P2
384
+ (corners then mid-edge nodes), oriented with outward normals."""
385
+ target = self.lower[axis] if side == 0 else self.upper[axis]
386
+ tol = self.tolerance()
387
+ on_plane = np.abs(self.nodes[:, axis] - target) <= tol
388
+ out = []
389
+ for f, mids in zip(TET_FACES, TET_FACE_MIDS, strict=True):
390
+ sel = np.all(on_plane[self.elements[:, f]], axis=1)
391
+ if not np.any(sel):
392
+ continue
393
+ faces = (
394
+ self.elements[sel][:, f]
395
+ if self.order == 1
396
+ else np.concatenate([self.elements[sel][:, f], self.elements[sel][:, mids]], axis=1)
397
+ )
398
+ out.append(faces)
399
+ if not out:
400
+ return np.zeros((0, 3 if self.order == 1 else 6), dtype=np.int64)
401
+ return np.concatenate(out)
402
+
403
+ def periodic_pairs(self, axis: int) -> np.ndarray:
404
+ """Pairs (node on the lower face, node on the upper face) at the same position
405
+ across the box along ``axis`` (all face nodes for matching faces)."""
406
+
407
+ lower = self.face_nodes(axis, 0)
408
+ upper = self.face_nodes(axis, 1)
409
+ if lower.size == 0 or upper.size == 0:
410
+ return np.zeros((0, 2), dtype=np.int64)
411
+ others = [d for d in range(3) if d != axis]
412
+ dist, near = cKDTree(self.nodes[lower][:, others]).query(self.nodes[upper][:, others])
413
+ ok = dist <= 1e-7 * float(np.max(self.size))
414
+ return np.stack([lower[near[ok]], upper[ok]], axis=1)
415
+
416
+ def matching_faces(self) -> bool:
417
+ """Whether every node of a face has an image on the opposite face. Whole periodic
418
+ cells: whether the faces bounding them come in translated pairs (in a mesh of
419
+ some of the cells, the faces facing the others have none)."""
420
+ if self.whole:
421
+ faces = self.outer_faces()[:, :3]
422
+ if not len(faces):
423
+ return True
424
+ nodes, local = np.unique(faces, return_inverse=True)
425
+ labels, shift = self._torus(nodes)
426
+ labels, shift = labels[local.reshape(-1, 3)], shift[local.reshape(-1, 3)]
427
+ order = np.argsort(labels, axis=1)
428
+ labels = np.take_along_axis(labels, order, axis=1)
429
+ shift = np.take_along_axis(shift, order[..., None], axis=1)
430
+ # a face and its translate: the same classes, the same shifts between corners
431
+ key = np.concatenate([labels, (shift[:, 1:] - shift[:, :1]).reshape(-1, 6)], axis=1)
432
+ _, counts = np.unique(key, axis=0, return_counts=True)
433
+ return bool(np.all(counts == 2))
434
+ for axis in range(3):
435
+ n_pairs = len(self.periodic_pairs(axis))
436
+ if n_pairs != self.face_nodes(axis, 0).size or n_pairs != self.face_nodes(axis, 1).size:
437
+ return False
438
+ return True
439
+
440
+ def subset(self, phases) -> TetMesh:
441
+ """Mesh of the elements of the given phases (unused nodes removed)."""
442
+ return self.select(np.isin(self.phase, list(phases)))
443
+
444
+ def select(self, keep) -> TetMesh:
445
+ """Mesh of the elements ``keep`` (a mask or indices; unused nodes removed)."""
446
+ elements = self.elements[keep]
447
+ used, inverse = np.unique(elements, return_inverse=True)
448
+ numbers = np.full(self.n_nodes, -1, dtype=np.int64)
449
+ numbers[used] = np.arange(len(used))
450
+ return self._derived(self.nodes[used], inverse.reshape(elements.shape), keep, numbers)
451
+
452
+ def quadratic(self) -> TetMesh:
453
+ """The same mesh with 10-node elements (mid-edge nodes on straight edges)."""
454
+ if self.order == 2:
455
+ return self
456
+ edges = self.elements[:, TET_EDGES].reshape(-1, 2)
457
+ edges.sort(axis=1)
458
+ unique, inverse = np.unique(edges, axis=0, return_inverse=True)
459
+ mids = 0.5 * (self.nodes[unique[:, 0]] + self.nodes[unique[:, 1]])
460
+ # mid-edge nodes on a face of the box must lie exactly on it
461
+ nodes = np.concatenate([self.nodes, mids])
462
+ mid_ids = self.n_nodes + inverse.reshape(-1, 6)
463
+ return self._derived(nodes, np.concatenate([self.elements, mid_ids], axis=1))
464
+
465
+ def straight(self) -> TetMesh:
466
+ """The same 10-node mesh with straight edges (its mid-edge nodes at the middles
467
+ of their edges); the mesh itself if it has no curved edge."""
468
+ if not self.curved:
469
+ return self
470
+ nodes = self.nodes.copy()
471
+ ends = self.elements[:, TET_EDGES] # (n, 6, 2)
472
+ nodes[self.elements[:, 4:]] = 0.5 * (self.nodes[ends[..., 0]] + self.nodes[ends[..., 1]])
473
+ out = self._derived(nodes, self.elements)
474
+ out.metadata.pop("curved", None)
475
+ return out
476
+
477
+ def linear(self) -> TetMesh:
478
+ """The same mesh with 4-node elements (mid-edge nodes dropped)."""
479
+ if self.order == 1:
480
+ return self
481
+ corners = self.elements[:, :4]
482
+ used, inverse = np.unique(corners, return_inverse=True)
483
+ numbers = np.full(self.n_nodes, -1, dtype=np.int64)
484
+ numbers[used] = np.arange(len(used))
485
+ return self._derived(self.nodes[used], inverse.reshape(corners.shape), None, numbers)
486
+
487
+ def components(self) -> tuple[np.ndarray, int]:
488
+ """Connected components of the elements (sharing at least one node)."""
489
+ from scipy.sparse import coo_matrix
490
+ from scipy.sparse.csgraph import connected_components
491
+
492
+ m = self.n_elements
493
+ rows = np.repeat(np.arange(m), self.elements.shape[1])
494
+ incidence = coo_matrix(
495
+ (np.ones(rows.size), (rows, self.elements.ravel())), shape=(m, self.n_nodes)
496
+ ).tocsr()
497
+ n_comp, labels = connected_components(incidence @ incidence.T, directed=False)
498
+ return labels, n_comp
499
+
500
+ def summary(self) -> dict:
501
+ q = self.quality()
502
+ out = {
503
+ "n_nodes": self.n_nodes,
504
+ "n_elements": self.n_elements,
505
+ "order": self.order,
506
+ "quality_min": float(q.min()) if q.size else float("nan"),
507
+ "quality_mean": float(q.mean()) if q.size else float("nan"),
508
+ **{f"mesh_fraction_{p}": v for p, v in self.phase_fractions().items()},
509
+ }
510
+ if self.cell is not None:
511
+ out["n_grains"] = int(np.unique(self.cell).size)
512
+ return out
@@ -0,0 +1,124 @@
1
+ """Hexahedral (voxel) finite-element meshes of voxel images."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ import numpy as np
8
+
9
+ from morphogen.image import VoxelImage
10
+
11
+ #: Corner offsets of a hexahedron in VTK / Abaqus / Gmsh order.
12
+ HEX_CORNERS = np.array(
13
+ [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]]
14
+ )
15
+ #: Local nodes of the hexahedron faces lying on each face of the box (outward normals).
16
+ HEX_FACES = {
17
+ "x0": (0, 4, 7, 3),
18
+ "x1": (1, 2, 6, 5),
19
+ "y0": (0, 1, 5, 4),
20
+ "y1": (3, 7, 6, 2),
21
+ "z0": (0, 3, 2, 1),
22
+ "z1": (4, 5, 6, 7),
23
+ }
24
+ FACE_NAMES = tuple(HEX_FACES)
25
+
26
+
27
+ @dataclass
28
+ class VoxelMesh:
29
+ """One 8-node hexahedron per selected voxel.
30
+
31
+ ``nodes`` are numbered from 0 here; writers shift to 1-based numbering when the
32
+ format requires it. ``node_sets`` holds the nodes on the six faces of the box.
33
+ """
34
+
35
+ nodes: np.ndarray
36
+ elements: np.ndarray
37
+ phase: np.ndarray
38
+ label: np.ndarray | None
39
+ node_ijk: np.ndarray
40
+ element_ijk: np.ndarray
41
+ grid_shape: tuple[int, int, int]
42
+ spacing: tuple[float, float, float]
43
+ node_sets: dict[str, np.ndarray] = field(default_factory=dict)
44
+ metadata: dict = field(default_factory=dict)
45
+
46
+ @property
47
+ def n_nodes(self) -> int:
48
+ return len(self.nodes)
49
+
50
+ @property
51
+ def n_elements(self) -> int:
52
+ return len(self.elements)
53
+
54
+ def volume(self) -> float:
55
+ return float(self.n_elements * np.prod(self.spacing))
56
+
57
+ def element_sets(self) -> dict[str, np.ndarray]:
58
+ """Elements of each phase, named ``phase_<p>``."""
59
+ return {f"phase_{p}": np.flatnonzero(self.phase == p) for p in np.unique(self.phase)}
60
+
61
+ def periodic_pairs(self, axis: int) -> np.ndarray:
62
+ """Pairs (node on the lower face, node on the upper face) facing each other."""
63
+ n = self.grid_shape[axis]
64
+ lo = np.flatnonzero(self.node_ijk[:, axis] == 0)
65
+ hi = np.flatnonzero(self.node_ijk[:, axis] == n)
66
+ others = [a for a in range(3) if a != axis]
67
+ size = self.grid_shape[others[1]] + 1
68
+
69
+ def key(idx):
70
+ ijk = self.node_ijk[idx]
71
+ return ijk[:, others[0]].astype(np.int64) * size + ijk[:, others[1]]
72
+
73
+ _, ia, ib = np.intersect1d(key(lo), key(hi), return_indices=True)
74
+ return np.stack([lo[ia], hi[ib]], axis=1)
75
+
76
+ def boundary_faces(self, face: str) -> np.ndarray:
77
+ """Quadrilaterals (node indices) of the element faces lying on a box face."""
78
+ axis = "xyz".index(face[0])
79
+ at = 0 if face[1] == "0" else self.grid_shape[axis] - 1
80
+ on = self.element_ijk[:, axis] == at
81
+ return self.elements[on][:, list(HEX_FACES[face])]
82
+
83
+
84
+ def voxel_mesh(image: VoxelImage, phases=None, *, labels: VoxelImage | None = None) -> VoxelMesh:
85
+ """Mesh the voxels of ``image`` whose value is in ``phases`` (default: all voxels).
86
+
87
+ ``labels`` (e.g. the cell labels of a tessellation) are attached to the elements.
88
+ """
89
+ data = image.data
90
+ if data.dtype.kind == "f":
91
+ raise ValueError("voxel meshes need a phase or label image, not partial volumes")
92
+ nx, ny, nz = image.shape
93
+ mask = np.ones(data.shape, dtype=bool) if phases is None else np.isin(data, list(phases))
94
+ ijk = np.argwhere(mask)
95
+ if len(ijk) == 0:
96
+ raise ValueError("no voxel to mesh: the selected phases are absent")
97
+ strides = np.array([(ny + 1) * (nz + 1), nz + 1, 1], dtype=np.int64)
98
+ corners = ijk[:, None, :] + HEX_CORNERS[None, :, :]
99
+ full_ids = corners @ strides
100
+ used, elements = np.unique(full_ids, return_inverse=True)
101
+ elements = elements.reshape(full_ids.shape).astype(np.int64)
102
+ node_ijk = np.stack(
103
+ [used // strides[0], (used // strides[1]) % (ny + 1), used % (nz + 1)], axis=1
104
+ )
105
+ nodes = np.asarray(image.origin) + node_ijk * np.asarray(image.spacing)
106
+ node_sets = {}
107
+ for name in FACE_NAMES:
108
+ axis = "xyz".index(name[0])
109
+ target = 0 if name[1] == "0" else image.shape[axis]
110
+ node_sets[name] = np.flatnonzero(node_ijk[:, axis] == target)
111
+ phase = data[mask].astype(np.int64)
112
+ label = labels.data[mask].astype(np.int64) if labels is not None else None
113
+ return VoxelMesh(
114
+ nodes=nodes,
115
+ elements=elements,
116
+ phase=phase,
117
+ label=label,
118
+ node_ijk=node_ijk,
119
+ element_ijk=ijk,
120
+ grid_shape=(nx, ny, nz),
121
+ spacing=tuple(image.spacing),
122
+ node_sets=node_sets,
123
+ metadata=dict(image.metadata),
124
+ )
@@ -0,0 +1,31 @@
1
+ """Micromorphic continua (Eringen, Mindlin; Forest's micromorphic approach) on
2
+ tetrahedral meshes, in small and finite strains (:mod:`morphogen.micromorphic.finite`):
3
+ the mixed finite elements of a displacement and generalized degrees of freedom
4
+ (:mod:`morphogen.micromorphic.space`), the microfoam model of metallic foams
5
+ (:mod:`morphogen.micromorphic.microfoam`), a micromorphic damage model to crack with
6
+ (:mod:`morphogen.micromorphic.damage`) and a micromorphic ductile damage of
7
+ elasto-viscoplastic solids (:mod:`morphogen.micromorphic.ductile`)."""
8
+
9
+ from morphogen.micromorphic.damage import DamageProblem, MicromorphicDamage
10
+ from morphogen.micromorphic.ductile import DuctileProblem, MicromorphicDuctile
11
+ from morphogen.micromorphic.microfoam import (
12
+ CHI,
13
+ Microfoam,
14
+ MicrofoamProblem,
15
+ characteristic_length,
16
+ )
17
+ from morphogen.micromorphic.space import MixedProblem, MixedSpace, PathResult
18
+
19
+ __all__ = [
20
+ "CHI",
21
+ "DamageProblem",
22
+ "DuctileProblem",
23
+ "Microfoam",
24
+ "MicrofoamProblem",
25
+ "MicromorphicDamage",
26
+ "MicromorphicDuctile",
27
+ "MixedProblem",
28
+ "MixedSpace",
29
+ "PathResult",
30
+ "characteristic_length",
31
+ ]