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/io/meshes.py ADDED
@@ -0,0 +1,844 @@
1
+ """Mesh files: Abaqus/CalculiX (.inp), Gmsh 2.2 (.msh), VTK (.vtu), Medit (.mesh), STL,
2
+ and meshio.
3
+
4
+ Voxel meshes (8-node hexahedra) and conforming tetrahedral meshes (4- or 10-node
5
+ tetrahedra) are written with their phases (element sets, physical groups or cell data)
6
+ and the nodes or element faces lying on the six faces of the box, or, for meshes of
7
+ whole periodic cells, on the boundary of the cells (``outer``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+ from typing import NamedTuple
14
+
15
+ import numpy as np
16
+
17
+ from morphogen._version import __version__
18
+ from morphogen.io import medit
19
+ from morphogen.io.vtk import write_vtu
20
+ from morphogen.mesh.surface import SurfaceMesh
21
+ from morphogen.mesh.tetra import TetMesh
22
+ from morphogen.mesh.voxel import FACE_NAMES, VoxelMesh
23
+
24
+ #: Physical tags of the box faces in Gmsh files (``outer``: boundary of whole cells).
25
+ FACE_TAGS = {**{name: 101 + i for i, name in enumerate(FACE_NAMES)}, "outer": 107}
26
+
27
+
28
+ def _write_rows(f, rows: np.ndarray, fmt: str) -> None:
29
+ np.savetxt(f, rows, fmt=fmt)
30
+
31
+
32
+ def _write_id_list(f, ids: np.ndarray, per_line: int = 16) -> None:
33
+ ids = np.asarray(ids, dtype=np.int64)
34
+ for start in range(0, len(ids), per_line):
35
+ f.write(", ".join(str(int(i)) for i in ids[start : start + per_line]) + "\n")
36
+
37
+
38
+ def write_inp(
39
+ path,
40
+ mesh: VoxelMesh,
41
+ *,
42
+ element_type: str = "C3D8",
43
+ label_sets: bool = False,
44
+ materials: dict | None = None,
45
+ orientations=None,
46
+ kinematics: str = "small",
47
+ ):
48
+ """Abaqus / CalculiX input file: nodes, elements by phase, face node sets.
49
+
50
+ Element sets ``PHASE_<p>`` (and ``CELL_<id>`` with ``label_sets``), node sets
51
+ ``X0, X1, Y0, Y1, Z0, Z1``. ``orientations`` (Bunge angles of each label) adds the
52
+ sets of the cells and their orientations ``ORI_<id>``; ``materials`` the materials
53
+ and the solid sections, as :func:`write_inp_tet` (one per cell, with its orientation,
54
+ when orientations are given; one per phase otherwise), in small or finite strains
55
+ (``kinematics``).
56
+ """
57
+ path = Path(path)
58
+ if orientations is not None and mesh.label is None:
59
+ raise ValueError("orientations: the elements need the labels of their cells")
60
+ mats = _abaqus_materials(path, _present(materials, mesh.phase), kinematics)
61
+ with open(path, "w", encoding="ascii", newline="\n") as f:
62
+ f.write("*HEADING\n")
63
+ f.write(f"morphoGen {__version__} voxel mesh: {mesh.n_elements} elements\n")
64
+ _mfront_header(f, mats.sources, finite=kinematics == "finite", axes=bool(mats.axes))
65
+ f.write("*NODE\n")
66
+ ids = np.arange(1, mesh.n_nodes + 1)
67
+ _write_rows(f, np.column_stack([ids, mesh.nodes]), "%d, %.12g, %.12g, %.12g")
68
+ eid = 1
69
+ for p in np.unique(mesh.phase):
70
+ sel = np.flatnonzero(mesh.phase == p)
71
+ f.write(f"*ELEMENT, TYPE={element_type}, ELSET=PHASE_{p}\n")
72
+ rows = np.column_stack([np.arange(eid, eid + len(sel)), mesh.elements[sel] + 1])
73
+ _write_rows(f, rows, ", ".join(["%d"] * 9))
74
+ eid += len(sel)
75
+ cells = label_sets or orientations is not None
76
+ _write_cells(f, mesh.phase, mesh.label if cells else None, orientations, mats,
77
+ per_cell=orientations is not None) # fmt: skip
78
+ for name in FACE_NAMES:
79
+ nodes = mesh.node_sets.get(name)
80
+ if nodes is not None and len(nodes):
81
+ f.write(f"*NSET, NSET={name.upper()}\n")
82
+ _write_id_list(f, nodes + 1)
83
+ _initial_temperature(f, mesh.n_nodes, mats)
84
+ return path
85
+
86
+
87
+ def write_msh(path, mesh: VoxelMesh, *, boundary: bool = True):
88
+ """Gmsh 2.2 ASCII file: hexahedra tagged by phase, optional boundary quadrangles.
89
+
90
+ Physical volumes ``phase_<p>`` have tag p + 1; the elementary tag is the cell label
91
+ + 1 when labels are attached. Physical surfaces ``x0 ... z1`` (tags 101-106) hold the
92
+ element faces lying on the box faces.
93
+ """
94
+ path = Path(path)
95
+ quads = {name: mesh.boundary_faces(name) for name in FACE_NAMES} if boundary else {}
96
+ quads = {k: v for k, v in quads.items() if len(v)}
97
+ phases = np.unique(mesh.phase)
98
+ with open(path, "w", encoding="ascii", newline="\n") as f:
99
+ f.write("$MeshFormat\n2.2 0 8\n$EndMeshFormat\n")
100
+ f.write("$PhysicalNames\n")
101
+ f.write(f"{len(phases) + len(quads)}\n")
102
+ for p in phases:
103
+ f.write(f'3 {p + 1} "phase_{p}"\n')
104
+ for name in quads:
105
+ f.write(f'2 {FACE_TAGS[name]} "{name}"\n')
106
+ f.write("$EndPhysicalNames\n$Nodes\n")
107
+ f.write(f"{mesh.n_nodes}\n")
108
+ _write_rows(
109
+ f, np.column_stack([np.arange(1, mesh.n_nodes + 1), mesh.nodes]), "%d %.12g %.12g %.12g"
110
+ )
111
+ f.write("$EndNodes\n$Elements\n")
112
+ n_quads = sum(len(q) for q in quads.values())
113
+ f.write(f"{mesh.n_elements + n_quads}\n")
114
+ eid = 1
115
+ for name, q in quads.items():
116
+ tag = FACE_TAGS[name]
117
+ rows = np.column_stack(
118
+ [np.arange(eid, eid + len(q)), np.full((len(q), 4), [3, 2, tag, tag]), q + 1]
119
+ )
120
+ _write_rows(f, rows, " ".join(["%d"] * 9))
121
+ eid += len(q)
122
+ geom = (mesh.label if mesh.label is not None else mesh.phase) + 1
123
+ rows = np.column_stack(
124
+ [
125
+ np.arange(eid, eid + mesh.n_elements),
126
+ np.full(mesh.n_elements, 5),
127
+ np.full(mesh.n_elements, 2),
128
+ mesh.phase + 1,
129
+ geom,
130
+ mesh.elements + 1,
131
+ ]
132
+ )
133
+ _write_rows(f, rows, " ".join(["%d"] * 13))
134
+ f.write("$EndElements\n")
135
+ return path
136
+
137
+
138
+ def read_msh(path) -> dict:
139
+ """Minimal reader of Gmsh 2.2 ASCII files (nodes and elements by type)."""
140
+ lines = Path(path).read_text(encoding="ascii").splitlines()
141
+ out = {"nodes": None, "elements": {}}
142
+ i = 0
143
+ while i < len(lines):
144
+ if lines[i] == "$Nodes":
145
+ n = int(lines[i + 1])
146
+ arr = np.array([lines[i + 2 + k].split() for k in range(n)], dtype=float)
147
+ out["nodes"] = arr[:, 1:]
148
+ i += n + 2
149
+ elif lines[i] == "$Elements":
150
+ n = int(lines[i + 1])
151
+ for k in range(n):
152
+ vals = [int(v) for v in lines[i + 2 + k].split()]
153
+ etype, ntags = vals[1], vals[2]
154
+ out["elements"].setdefault(etype, []).append(
155
+ vals[3 : 3 + ntags] + vals[3 + ntags :]
156
+ )
157
+ i += n + 2
158
+ else:
159
+ i += 1
160
+ out["elements"] = {k: np.array(v) for k, v in out["elements"].items()}
161
+ return out
162
+
163
+
164
+ def write_vtu_mesh(path, mesh: VoxelMesh, *, compress: bool = True):
165
+ """A voxel mesh written as a VTK unstructured grid (.vtu) of hexahedra, with the phase of each
166
+ element (and its cell, if labelled)."""
167
+ data = {"phase": mesh.phase.astype(np.int32)}
168
+ if mesh.label is not None:
169
+ data["cell"] = mesh.label.astype(np.int32)
170
+ return write_vtu(path, mesh.nodes, mesh.elements, 12, data, compress=compress)
171
+
172
+
173
+ def write_periodic_pairs(path, mesh: VoxelMesh | TetMesh) -> Path:
174
+ """CSV of facing nodes on opposite faces (1-based ids, as in .inp and .msh files).
175
+ Meshes of whole periodic cells: each node of their boundary that is a translate of
176
+ another, that node and the periods between them (``x_node = x_image + shift * edges``).
177
+ """
178
+ path = Path(path)
179
+ if isinstance(mesh, TetMesh) and mesh.whole:
180
+ slave, master, shift = mesh.periodic_links()
181
+ rows = np.column_stack([slave + 1, master + 1, shift])
182
+ with open(path, "w", encoding="ascii", newline="\n") as f:
183
+ f.write("node,image,shift_x,shift_y,shift_z\n")
184
+ _write_rows(f, rows, "%d,%d,%d,%d,%d")
185
+ return path
186
+ with open(path, "w", encoding="ascii", newline="\n") as f:
187
+ f.write("axis,node_lower,node_upper\n")
188
+ for axis, name in enumerate("xyz"):
189
+ pairs = mesh.periodic_pairs(axis) + 1
190
+ for a, b in pairs:
191
+ f.write(f"{name},{a},{b}\n")
192
+ return path
193
+
194
+
195
+ #: Gmsh and VTK numbers of the 10-node tetrahedron: Gmsh swaps the last two mid-edge nodes.
196
+ _GMSH_TET10 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 9, 8])
197
+
198
+
199
+ def _tet_face_nodes(mesh: TetMesh) -> dict[str, np.ndarray]:
200
+ if mesh.whole:
201
+ return {"outer": mesh.boundary_nodes()}
202
+ return {
203
+ f"{'xyz'[axis]}{side}": mesh.face_nodes(axis, side) for axis in range(3) for side in (0, 1)
204
+ }
205
+
206
+
207
+ def _tet_face_elements(mesh: TetMesh) -> dict[str, np.ndarray]:
208
+ if mesh.whole:
209
+ return {"outer": mesh.outer_faces()}
210
+ return {
211
+ f"{'xyz'[axis]}{side}": mesh.boundary_faces(axis, side)
212
+ for axis in range(3)
213
+ for side in (0, 1)
214
+ }
215
+
216
+
217
+ #: morphoGen's Voigt index of each of Abaqus's components (11, 22, 33, 12, 13, 23)
218
+ _ABAQUS = np.array([0, 1, 2, 5, 4, 3])
219
+
220
+
221
+ def abaqus_anisotropic(stiffness) -> list[float]:
222
+ """The 21 constants of Abaqus's ``*ELASTIC, TYPE=ANISOTROPIC``: D1111, D1122, D2222,
223
+ D1133, D2233, D3333, D1112, D2212, D3312, D1212, D1113, D2213, D3313, D1213, D1313,
224
+ D1123, D2223, D3323, D1223, D1323, D2323 (Abaqus's components 11, 22, 33, 12, 13, 23,
225
+ engineering shear strains), of a stiffness in morphoGen's Voigt order (11, 22, 33,
226
+ 23, 31, 12)."""
227
+ d = np.asarray(stiffness, dtype=float)[np.ix_(_ABAQUS, _ABAQUS)]
228
+ return [float(d[i, j]) for j in range(6) for i in range(j + 1)]
229
+
230
+
231
+ def _numbers(values, per_line: int = 8) -> str:
232
+ """Data lines of at most ``per_line`` numbers, as Abaqus reads them."""
233
+ text = [f"{float(v):.15g}" for v in values]
234
+ return "".join(", ".join(text[k : k + per_line]) + "\n" for k in range(0, len(text), per_line))
235
+
236
+
237
+ class _AbaqusMaterials(NamedTuple):
238
+ """The materials of an Abaqus input (:func:`_abaqus_materials`)."""
239
+
240
+ names: dict # the material of each phase
241
+ lines: list # the lines of their definitions
242
+ sources: list # the MFront sources of their laws
243
+ axes: set # the phases whose laws read the axes of their crystals in their state
244
+ unoriented: set # the phases whose sections take no orientation (MFront's finite strains)
245
+ depvar: int # the largest number of state variables of the laws
246
+ expanding: set # the phases whose materials expand (from the initial temperature)
247
+
248
+
249
+ def _abaqus_materials(path: Path, materials: dict, kinematics: str = "small") -> _AbaqusMaterials:
250
+ """The material of each phase (a name, or a :class:`Material` defined here), the
251
+ lines of the definitions, the MFront sources of the nonlinear materials, and in
252
+ finite strains of all of them (in ``<stem>_mfront`` next to the input; the
253
+ parameters of the user's laws in ``<behaviour>-parameters.txt``, next to it too),
254
+ the phases whose laws read the axes of their crystals in their first six state
255
+ variables, those whose sections take no orientation (the laws of finite strains:
256
+ MFront's abaqus interface takes no ``*ORIENTATION`` there), and the largest number of
257
+ state variables of the laws."""
258
+ import shutil
259
+
260
+ from morphogen.io.mfront import (
261
+ ABAQUS_AXES,
262
+ identifier,
263
+ mfront_brick,
264
+ mfront_state_size,
265
+ mfront_symmetry,
266
+ user_behaviour,
267
+ write_mfront,
268
+ write_parameters,
269
+ )
270
+
271
+ if kinematics not in ("small", "finite"):
272
+ raise ValueError("kinematics: 'small' or 'finite'")
273
+ finite = kinematics == "finite"
274
+ names: dict[int, str] = {}
275
+ lines: list[str] = []
276
+ sources: list[Path] = []
277
+ parameters: dict[str, tuple] = {}
278
+ axes: set[int] = set()
279
+ unoriented: set[int] = set()
280
+ expanding: set[int] = set()
281
+ depvar = 0
282
+ folder = path.parent / f"{path.stem}_mfront"
283
+ for p, m in sorted(materials.items()):
284
+ p = int(p)
285
+ if isinstance(m, str):
286
+ names[p] = m
287
+ continue
288
+ if m.void:
289
+ lines.append(f"** phase {p}: void, no material and no section\n")
290
+ continue
291
+ n_state = 0
292
+ if m.nonlinear and m.mfront is not None:
293
+ # the user's law, with its material properties as constants (one at least for
294
+ # the interface); the dispatcher of MFront takes ABAQUSBEHAVIOUR_<behaviour>_3D
295
+ # and ignores what follows (a material per phase)
296
+ user = user_behaviour(m, kinematics)
297
+ if "_" in user.name:
298
+ raise ValueError(
299
+ f"phase {p}: the dispatcher of MFront in Abaqus splits the names of the "
300
+ f"materials at '_'; rename the behaviour {user.name}"
301
+ )
302
+ if finite and user.orthotropic and not user.abaqus_axes:
303
+ raise ValueError(
304
+ f"phase {p}: MFront's abaqus interface takes orthotropic laws of finite "
305
+ f"strains with the axes in their state variables: add {ABAQUS_AXES} to "
306
+ f"the source of {user.name}"
307
+ )
308
+ target = folder / user.source.name
309
+ if target not in sources:
310
+ folder.mkdir(parents=True, exist_ok=True)
311
+ shutil.copyfile(user.source, target)
312
+ sources.append(target)
313
+ if parameters.setdefault(user.name, m.mfront.parameters) != m.mfront.parameters:
314
+ raise ValueError(f"phase {p}: the parameters of {user.name} are global")
315
+ write_parameters(path.parent, user.name, m.mfront.parameters)
316
+ name = f"ABAQUSBEHAVIOUR_{user.name.upper()}_3D_PHASE{p}"
317
+ values = dict(m.mfront.material_properties)
318
+ constants = [values[k] for k in user.properties] or [0.0]
319
+ n_state = user.internal_variables + (6 if user.abaqus_axes else 0)
320
+ if user.abaqus_axes:
321
+ axes.add(p)
322
+ if user.abaqus_axes or finite:
323
+ unoriented.add(p)
324
+ lines.append(f"*MATERIAL, NAME={name}\n")
325
+ if n_state:
326
+ lines += ["*DEPVAR\n", f"{n_state},\n"]
327
+ lines += [f"*USER MATERIAL, CONSTANTS={len(constants)}, UNSYMM\n",
328
+ _numbers(constants)] # fmt: skip
329
+ elif m.nonlinear or finite:
330
+ if finite and m.expands and mfront_brick(m, kinematics):
331
+ raise ValueError(
332
+ f"phase {p}: MFront's abaqus interface computes no thermal expansion "
333
+ "of the laws of finite strains of its brick (von Mises, Hill's "
334
+ "criterion, GTN's porous plasticity): it has no stress-free expansion in "
335
+ "finite strains"
336
+ )
337
+ # the dispatcher of MFront splits ABAQUSBEHAVIOUR_<behaviour>_3D at its '_'
338
+ behaviour = f"{identifier(path.stem)[:40]}Phase{p}"
339
+ sources.append(write_mfront(m, folder / f"{behaviour}.mfront", name=behaviour,
340
+ kinematics=kinematics)) # fmt: skip
341
+ name = f"ABAQUSBEHAVIOUR_{behaviour.upper()}_3D"
342
+ # in finite strains, the axes of the orthotropic laws are their first six state
343
+ # variables; the abaqus interface of MFront asks one constant of the laws
344
+ # without material properties (whose values are in their sources)
345
+ oriented = finite and mfront_symmetry(m, kinematics) == "orthotropic"
346
+ n_state = mfront_state_size(m, kinematics) + (6 if oriented else 0)
347
+ if oriented:
348
+ axes.add(p)
349
+ # in finite strains the axes are state variables; a learned law in the axes of
350
+ # the sample (not oriented) is not turned by the grains, as morphoGen runs it
351
+ if finite or (m.learned is not None and not m.learned.oriented):
352
+ unoriented.add(p)
353
+ lines.append(f"*MATERIAL, NAME={name}\n")
354
+ if n_state:
355
+ lines += ["*DEPVAR\n", f"{n_state},\n"]
356
+ lines += ["*USER MATERIAL, CONSTANTS=1, UNSYMM\n", "0.\n"]
357
+ else:
358
+ if not m.elastic:
359
+ raise ValueError(f"phase {p}: the material has no elastic parameters")
360
+ name = f"PHASE_{p}"
361
+ lines.append(f"*MATERIAL, NAME={name}\n")
362
+ if m.stiffness is None:
363
+ lines += ["*ELASTIC\n", _numbers((m.young, m.poisson))]
364
+ else: # in the axes of the crystal (the orientation of its section)
365
+ lines += ["*ELASTIC, TYPE=ANISOTROPIC\n", _numbers(abaqus_anisotropic(m.stiffness))]
366
+ if m.expands:
367
+ if not isinstance(m.expansion, tuple):
368
+ lines += ["*EXPANSION\n", _numbers([m.expansion])]
369
+ else:
370
+ a = np.asarray(m.expansion, dtype=float)
371
+ if np.abs(a - np.diag(np.diag(a))).max() > 1e-12 * np.abs(a).max():
372
+ raise ValueError(
373
+ f"phase {p}: an expansion tensor with shear components in the "
374
+ "axes of the crystal (Abaqus's orthotropic expansion)"
375
+ )
376
+ lines += ["*EXPANSION, TYPE=ORTHO\n", _numbers(np.diag(a))]
377
+ if m.density:
378
+ lines += ["*DENSITY\n", _numbers([m.density])]
379
+ if m.expands and m.mfront is None: # *EXPANSION, or the MFront law of the phase
380
+ expanding.add(p)
381
+ names[p] = name
382
+ depvar = max(depvar, n_state)
383
+ return _AbaqusMaterials(names, lines, sources, axes, unoriented, depvar, expanding)
384
+
385
+
386
+ def _present(materials: dict | None, phases) -> dict:
387
+ """The materials of the phases of a mesh."""
388
+ present = {int(p) for p in phases}
389
+ return {p: m for p, m in (materials or {}).items() if int(p) in present}
390
+
391
+
392
+ def _mfront_header(f, sources: list[Path], *, finite: bool = False, axes: bool = False) -> None:
393
+ """The comments of an Abaqus input on its MFront laws: compilation and run."""
394
+ if sources:
395
+ folder = sources[0].parent.name
396
+ what = "the materials" if finite else "the nonlinear materials"
397
+ f.write(
398
+ f"** {what} are MFront laws ({folder}/), compiled by\n"
399
+ f"** cd {folder} && mfront --obuild --interface=abaqus "
400
+ f"{' '.join(s.name for s in sources)}\n"
401
+ "** and run with the umat of MFront (share/doc/mfront/abaqus/umat.cpp of TFEL)\n"
402
+ f"** and {folder}/src (libABAQUSBEHAVIOUR.so) on LD_LIBRARY_PATH, from this\n"
403
+ "** directory (the <behaviour>-parameters.txt of the laws are read there)\n"
404
+ )
405
+ if finite:
406
+ f.write("** the laws are of finite strains: their steps need NLGEOM=YES\n")
407
+ if axes:
408
+ f.write(
409
+ "** the orthotropic laws read the axes of their crystals in their first six\n"
410
+ "** state variables (*INITIAL CONDITIONS, TYPE=SOLUTION), not *ORIENTATION\n"
411
+ )
412
+
413
+
414
+ def _initial_axes(f, entries: list, depvar: int) -> None:
415
+ """``*INITIAL CONDITIONS, TYPE=SOLUTION``: the axes [100] and [010] of the crystal of
416
+ each element set in its first six state variables, then zeros, ``depvar`` values for
417
+ each (Abaqus reads the same number of values for every element: seven on the line of
418
+ the set, eight on each following line)."""
419
+ if not entries:
420
+ return
421
+ f.write("*INITIAL CONDITIONS, TYPE=SOLUTION\n")
422
+ for label, rot in entries:
423
+ values = [f"{v:.12g}" for v in (*rot[0], *rot[1])] + ["0."] * (depvar - 6)
424
+ f.write(", ".join([label, *values[:7]]) + "\n")
425
+ for k in range(7, len(values), 8):
426
+ f.write(", ".join(values[k : k + 8]) + "\n")
427
+
428
+
429
+ def _initial_temperature(f, n_nodes: int, materials: _AbaqusMaterials) -> None:
430
+ """``*INITIAL CONDITIONS, TYPE=TEMPERATURE``: the nodes at 293.15 K when a material
431
+ expands. It is the natural temperature of morphoGen's MFront laws, from which they count
432
+ their thermal expansion (MFront's reference temperatures), and ``*EXPANSION`` counts it
433
+ from the initial temperature: the steps then give absolute temperatures, 293.15 K plus
434
+ morphoGen's change of temperature (Abaqus's nodes start at 0 otherwise)."""
435
+ if not materials.expanding:
436
+ return
437
+ f.write(
438
+ "** the expanding materials count their expansion from the initial temperature of\n"
439
+ "** the nodes, 293.15 K (the natural temperature of morphoGen's MFront laws): the\n"
440
+ "** steps give absolute temperatures, 293.15 K plus morphoGen's change of temperature\n"
441
+ "*NSET, NSET=ALL_NODES, GENERATE\n"
442
+ f"1, {n_nodes}, 1\n"
443
+ "*INITIAL CONDITIONS, TYPE=TEMPERATURE\n"
444
+ "ALL_NODES, 293.15\n"
445
+ )
446
+
447
+
448
+ def _write_cells(f, phase, cell, orientations, materials: _AbaqusMaterials | None = None, *,
449
+ per_cell: bool = True) -> None: # fmt: skip
450
+ """The element sets of the cells (grains) ``CELL_<c>`` and the orientation of each,
451
+ ``ORI_<c>`` (rectangular: the axes [100] and [010] of the crystal in the axes of the
452
+ box), the materials, and the solid sections: one per cell (``per_cell``) when the
453
+ elements have cells, with its orientation (each cell of one phase), one per phase
454
+ otherwise. The sections of the laws of finite strains have no orientation; those
455
+ whose laws read the axes of their crystals in their first six state variables get
456
+ them from the initial conditions (:func:`_initial_axes`). The elements are numbered
457
+ phase after phase."""
458
+ from morphogen.orientations import euler_to_matrix
459
+
460
+ if materials is None:
461
+ materials = _AbaqusMaterials({}, [], [], set(), set(), 0, set())
462
+ names, axes, unoriented = materials.names, materials.axes, materials.unoriented
463
+ phase = np.asarray(phase)
464
+ phases = np.unique(phase)
465
+ cells = np.unique(cell) if cell is not None else np.zeros(0, dtype=np.int64)
466
+ if cells.size:
467
+ order = np.concatenate([np.flatnonzero(phase == p) for p in phases])
468
+ numbers = np.empty(phase.size, dtype=np.int64)
469
+ numbers[order] = np.arange(1, phase.size + 1)
470
+ for c in cells:
471
+ f.write(f"*ELSET, ELSET=CELL_{c}\n")
472
+ _write_id_list(f, np.sort(numbers[cell == c]))
473
+ oriented = cells.size > 0 and orientations is not None
474
+ rotations = {}
475
+ if oriented:
476
+ g = euler_to_matrix(np.asarray(orientations, dtype=float)[cells])
477
+ for c, rot in zip(cells, g.reshape(-1, 3, 3), strict=True):
478
+ rotations[int(c)] = rot
479
+ if not set(np.unique(phase[cell == c]).tolist()) <= unoriented:
480
+ f.write(f"*ORIENTATION, NAME=ORI_{c}, SYSTEM=RECTANGULAR\n")
481
+ f.write(", ".join(f"{v:.12g}" for v in (*rot[0], *rot[1])) + "\n")
482
+ f.writelines(materials.lines)
483
+ if not names:
484
+ return
485
+ initial = [] # the element sets whose laws read their axes in their state variables
486
+ if cells.size and per_cell:
487
+ for c in cells:
488
+ own = np.unique(phase[cell == c])
489
+ if own.size > 1:
490
+ raise ValueError(
491
+ f"cell {c} spans the phases {own.tolist()}: a section has one material"
492
+ )
493
+ name = names.get(int(own[0]))
494
+ if name is None:
495
+ continue
496
+ if int(own[0]) in axes:
497
+ initial.append((f"CELL_{c}", rotations.get(int(c), np.eye(3))))
498
+ extra = f", ORIENTATION=ORI_{c}" if oriented and int(own[0]) not in unoriented else ""
499
+ f.write(f"*SOLID SECTION, ELSET=CELL_{c}, MATERIAL={name}{extra}\n")
500
+ else:
501
+ for p in phases:
502
+ if names.get(int(p)) is not None:
503
+ f.write(f"*SOLID SECTION, ELSET=PHASE_{p}, MATERIAL={names[int(p)]}\n")
504
+ if int(p) in axes:
505
+ initial.append((f"PHASE_{p}", np.eye(3)))
506
+ _initial_axes(f, initial, materials.depvar)
507
+
508
+
509
+ def write_inp_tet(path, mesh: TetMesh, *, materials: dict | None = None,
510
+ kinematics: str = "small") -> Path: # fmt: skip
511
+ """Abaqus / CalculiX input file of a tetrahedral mesh (C3D4 or C3D10 elements).
512
+
513
+ Element sets ``PHASE_<p>``, node sets ``X0, X1, Y0, Y1, Z0, Z1`` (``OUTER``, the
514
+ boundary of whole periodic cells). Meshes of
515
+ polycrystals add one element set per grain, ``CELL_<id>``, and the orientation of its
516
+ crystal axes, ``ORI_<id>`` (rectangular system: the axes [100] and [010] of the crystal
517
+ in the axes of the box). ``materials`` writes the solid sections, one per grain with
518
+ its orientation for polycrystals: phase -> the name of a material defined elsewhere,
519
+ or phase -> :class:`~morphogen.homogenization.Material`, defined in the file:
520
+ ``*ELASTIC`` (isotropic, or the 21 constants of ``TYPE=ANISOTROPIC`` in the axes of
521
+ the crystal: see :func:`abaqus_anisotropic`), ``*EXPANSION``, ``*DENSITY``, and the
522
+ nonlinear materials as the MFront laws of the abaqus interface
523
+ (:mod:`morphogen.io.mfront`, their sources in ``<stem>_mfront``): the material
524
+ ``ABAQUSBEHAVIOUR_<behaviour>_3D``, its ``*DEPVAR`` and ``*USER MATERIAL`` (one
525
+ constant, zero, which the interface asks of laws without material properties). Voids
526
+ have no section. In finite strains (``kinematics``), every material is an MFront law
527
+ (Hencky's elasticity for the elastic ones; steps with ``NLGEOM=YES``), and the
528
+ orthotropic laws read the axes of their crystals in their first six state variables,
529
+ which ``*INITIAL CONDITIONS, TYPE=SOLUTION`` gives (MFront's abaqus interface takes no
530
+ ``*ORIENTATION`` in finite strains). When a material expands, the nodes start at
531
+ 293.15 K (``*INITIAL CONDITIONS, TYPE=TEMPERATURE``), from which the MFront laws
532
+ count their expansion: the steps give absolute temperatures.
533
+ """
534
+ path = Path(path)
535
+ etype = "C3D4" if mesh.order == 1 else "C3D10"
536
+ nn = mesh.elements.shape[1]
537
+ phases = np.unique(mesh.phase)
538
+ mats = _abaqus_materials(path, _present(materials, phases), kinematics)
539
+ with open(path, "w", encoding="ascii", newline="\n") as f:
540
+ f.write("*HEADING\n")
541
+ f.write(f"morphoGen {__version__} conforming mesh: {mesh.n_elements} {etype} elements\n")
542
+ _mfront_header(f, mats.sources, finite=kinematics == "finite", axes=bool(mats.axes))
543
+ f.write("*NODE\n")
544
+ ids = np.arange(1, mesh.n_nodes + 1)
545
+ _write_rows(f, np.column_stack([ids, mesh.nodes]), "%d, %.12g, %.12g, %.12g")
546
+ eid = 1
547
+ for p in phases:
548
+ sel = np.flatnonzero(mesh.phase == p)
549
+ f.write(f"*ELEMENT, TYPE={etype}, ELSET=PHASE_{p}\n")
550
+ rows = np.column_stack([np.arange(eid, eid + len(sel)), mesh.elements[sel] + 1])
551
+ if nn <= 15:
552
+ _write_rows(f, rows, ", ".join(["%d"] * (nn + 1)))
553
+ else: # pragma: no cover - only 4- and 10-node elements exist
554
+ raise ValueError("unsupported element")
555
+ eid += len(sel)
556
+ _write_cells(f, mesh.phase, mesh.cell, mesh.orientations, mats)
557
+ for name, nodes in _tet_face_nodes(mesh).items():
558
+ if len(nodes):
559
+ f.write(f"*NSET, NSET={name.upper()}\n")
560
+ _write_id_list(f, nodes + 1)
561
+ _initial_temperature(f, mesh.n_nodes, mats)
562
+ return path
563
+
564
+
565
+ def write_msh_tet(path, mesh: TetMesh, *, boundary: bool = True) -> Path:
566
+ """Gmsh 2.2 ASCII file of a tetrahedral mesh (element types 4 and 11).
567
+
568
+ Physical volumes ``phase_<p>`` have tag p + 1; the elementary tag is the grain + 1 for
569
+ polycrystals; physical surfaces ``x0 ... z1`` (tags 101-106) hold the element faces
570
+ (3- or 6-node triangles) lying on the box faces, ``outer`` (tag 107) those bounding
571
+ whole periodic cells.
572
+ """
573
+ path = Path(path)
574
+ order = mesh.order
575
+ tet_type, tri_type = (4, 2) if order == 1 else (11, 9)
576
+ elements = mesh.elements if order == 1 else mesh.elements[:, _GMSH_TET10]
577
+ faces = _tet_face_elements(mesh) if boundary else {}
578
+ faces = {k: v for k, v in faces.items() if len(v)}
579
+ phases = np.unique(mesh.phase)
580
+ with open(path, "w", encoding="ascii", newline="\n") as f:
581
+ f.write("$MeshFormat\n2.2 0 8\n$EndMeshFormat\n")
582
+ f.write("$PhysicalNames\n")
583
+ f.write(f"{len(phases) + len(faces)}\n")
584
+ for p in phases:
585
+ f.write(f'3 {p + 1} "phase_{p}"\n')
586
+ for name in faces:
587
+ f.write(f'2 {FACE_TAGS[name]} "{name}"\n')
588
+ f.write("$EndPhysicalNames\n$Nodes\n")
589
+ f.write(f"{mesh.n_nodes}\n")
590
+ _write_rows(
591
+ f, np.column_stack([np.arange(1, mesh.n_nodes + 1), mesh.nodes]), "%d %.12g %.12g %.12g"
592
+ )
593
+ f.write("$EndNodes\n$Elements\n")
594
+ f.write(f"{mesh.n_elements + sum(len(v) for v in faces.values())}\n")
595
+ eid = 1
596
+ for name, tri in faces.items():
597
+ tag = FACE_TAGS[name]
598
+ rows = np.column_stack(
599
+ [
600
+ np.arange(eid, eid + len(tri)),
601
+ np.full((len(tri), 4), [tri_type, 2, tag, tag]),
602
+ tri + 1,
603
+ ]
604
+ )
605
+ _write_rows(f, rows, " ".join(["%d"] * rows.shape[1]))
606
+ eid += len(tri)
607
+ geom = (mesh.cell if mesh.cell is not None else mesh.phase) + 1
608
+ rows = np.column_stack(
609
+ [
610
+ np.arange(eid, eid + mesh.n_elements),
611
+ np.full(mesh.n_elements, tet_type),
612
+ np.full(mesh.n_elements, 2),
613
+ mesh.phase + 1,
614
+ geom,
615
+ elements + 1,
616
+ ]
617
+ )
618
+ _write_rows(f, rows, " ".join(["%d"] * rows.shape[1]))
619
+ f.write("$EndElements\n")
620
+ return path
621
+
622
+
623
+ def write_vtu_tet(
624
+ path,
625
+ mesh: TetMesh,
626
+ cell_data: dict | None = None,
627
+ point_data: dict | None = None,
628
+ *,
629
+ compress: bool = True,
630
+ ) -> Path:
631
+ """VTK unstructured grid of a tetrahedral mesh (cell types 10 and 24) with its phases,
632
+ the grains of polycrystals (``cell``) and their orientations (``euler``: Bunge angles
633
+ in degrees), and optional fields."""
634
+ data = {"phase": mesh.phase.astype(np.int32)}
635
+ if mesh.cell is not None:
636
+ data["cell"] = mesh.cell.astype(np.int32)
637
+ if mesh.orientations is not None:
638
+ data["euler"] = mesh.orientations[mesh.cell]
639
+ if mesh.whole:
640
+ data["outer"] = _outer_bits(mesh)
641
+ data.update(cell_data or {})
642
+ cell_type = 10 if mesh.order == 1 else 24
643
+ return write_vtu(
644
+ path,
645
+ mesh.nodes,
646
+ mesh.elements,
647
+ cell_type,
648
+ data,
649
+ point_data=point_data,
650
+ field_data=_box_fields(mesh),
651
+ compress=compress,
652
+ )
653
+
654
+
655
+ def _outer_bits(mesh: TetMesh) -> np.ndarray:
656
+ """The faces of each element bounding whole periodic cells, as bits 0-3."""
657
+ return (mesh.outer.astype(np.int32) << np.arange(4, dtype=np.int32)).sum(axis=1)
658
+
659
+
660
+ def _box_fields(mesh: TetMesh) -> dict:
661
+ return {
662
+ "box_lower": mesh.lower,
663
+ "box_upper": mesh.upper,
664
+ "periodic": np.array([int(mesh.periodic)], dtype=np.int32),
665
+ "whole": np.array([int(mesh.whole)], dtype=np.int32),
666
+ }
667
+
668
+
669
+ def _box_comment(mesh: TetMesh) -> str:
670
+ box = " ".join(f"{v:.17g}" for v in (*mesh.lower, *mesh.upper))
671
+ return f"morphogen box {box} periodic {int(mesh.periodic)} whole {int(mesh.whole)}"
672
+
673
+
674
+ def write_medit_tet(path, mesh: TetMesh) -> Path:
675
+ """Medit file (MMG): tetrahedra with reference phase + 1, or grain + 1 for
676
+ polycrystals (the phase of each grain is then given in a comment), corners only for
677
+ 10-node meshes; boundary triangles with references 1-6 (faces x0, x1, ..., z1), or
678
+ 1 for the faces bounding whole periodic cells."""
679
+ lin = mesh.linear()
680
+ tri, refs = [], []
681
+ if lin.whole:
682
+ tri.append(lin.outer_faces())
683
+ refs.append(np.ones(len(tri[0]), dtype=np.int64))
684
+ else:
685
+ for axis in range(3):
686
+ for side in (0, 1):
687
+ faces = lin.boundary_faces(axis, side)
688
+ tri.append(faces)
689
+ refs.append(np.full(len(faces), 1 + 2 * axis + side))
690
+ comments = [_box_comment(mesh)]
691
+ if lin.cell is not None:
692
+ cell_phase = np.full(int(lin.cell.max(initial=-1)) + 1, -1, dtype=np.int64)
693
+ cell_phase[lin.cell] = lin.phase
694
+ comments.append("morphogen references cell phases " + " ".join(map(str, cell_phase)))
695
+ return medit.write_mesh(
696
+ path,
697
+ lin.nodes,
698
+ lin.elements,
699
+ np.concatenate(tri),
700
+ tet_refs=(lin.cell if lin.cell is not None else lin.phase) + 1,
701
+ tri_refs=np.concatenate(refs),
702
+ comments=comments,
703
+ )
704
+
705
+
706
+ def read_tet_mesh(path, *, box=None, periodic: bool | None = None) -> TetMesh:
707
+ """Tetrahedral mesh written by morphoGen: ``.vtu`` (cell types 10 or 24 and a
708
+ ``phase`` cell array; ``cell`` and ``euler`` for polycrystals) or Medit ``.mesh``
709
+ (tetrahedra references = phase + 1, or grain + 1 for polycrystals).
710
+
711
+ The box (``(lower, upper)``) and the periodicity are read from the file when it
712
+ records them (files written by morphoGen do); otherwise the box is the bounding box
713
+ of the nodes, which is wrong when the meshed phases do not touch every face. Meshes
714
+ of whole periodic cells keep the faces bounding them.
715
+ """
716
+ from morphogen.io.vtk import read_vtu
717
+ from morphogen.mesh.tetra import TET_FACES
718
+
719
+ path = Path(path)
720
+ ext = path.suffix.lower()
721
+ stored_box, stored_periodic, whole = None, False, False
722
+ cell = orientations = outer = None
723
+ if ext == ".vtu":
724
+ data = read_vtu(path)
725
+ types = np.unique(data["types"])
726
+ if not set(types.tolist()) <= {10, 24} or len(types) != 1:
727
+ raise ValueError(f"{path}: expected only 4-node or only 10-node tetrahedra")
728
+ nodes, elements = data["points"], data["cells"]
729
+ phase = data["cell_data"].get("phase", np.zeros(len(elements)))
730
+ if "cell" in data["cell_data"]:
731
+ cell = np.asarray(data["cell_data"]["cell"], dtype=np.int64)
732
+ euler = data["cell_data"].get("euler")
733
+ if euler is not None and cell.size:
734
+ orientations = np.zeros((int(cell.max()) + 1, 3))
735
+ orientations[cell] = np.asarray(euler, dtype=float).reshape(-1, 3)
736
+ fields = data.get("field_data", {})
737
+ if "box_lower" in fields and "box_upper" in fields:
738
+ stored_box = (fields["box_lower"], fields["box_upper"])
739
+ stored_periodic = bool(fields.get("periodic", [0])[0])
740
+ whole = bool(fields.get("whole", [0])[0])
741
+ if whole and "outer" in data["cell_data"]:
742
+ bits = np.asarray(data["cell_data"]["outer"], dtype=np.int64)
743
+ outer = (bits[:, None] >> np.arange(4)) & 1
744
+ elif ext == ".mesh":
745
+ data = medit.read_mesh(path)
746
+ if "Tetrahedra" not in data:
747
+ raise ValueError(f"{path}: no tetrahedra")
748
+ nodes, elements = data["Vertices"], data["Tetrahedra"]
749
+ phase = data["Tetrahedra_refs"] - 1
750
+ for line in data.get("comments", []):
751
+ words = line.split()
752
+ if words[:2] == ["morphogen", "box"] and len(words) >= 8:
753
+ values = [float(w) for w in words[2:8]]
754
+ stored_box = (values[:3], values[3:])
755
+ if len(words) >= 10 and words[8] == "periodic":
756
+ stored_periodic = bool(int(words[9]))
757
+ if len(words) >= 12 and words[10] == "whole":
758
+ whole = bool(int(words[11]))
759
+ elif words[:4] == ["morphogen", "references", "cell", "phases"]:
760
+ cell_phase = np.array([int(w) for w in words[4:]], dtype=np.int64)
761
+ cell = phase
762
+ phase = cell_phase[cell]
763
+ if whole and len(data.get("Triangles", [])): # the faces of the elements
764
+ corners = np.sort(elements[:, TET_FACES].reshape(-1, 3), axis=1)
765
+ tri = np.sort(data["Triangles"], axis=1)
766
+ both, inverse = np.unique(np.concatenate([tri, corners]), axis=0, return_inverse=True)
767
+ on = np.zeros(len(both), dtype=bool)
768
+ on[inverse.ravel()[: len(tri)]] = True
769
+ outer = on[inverse.ravel()[len(tri) :]].reshape(-1, 4)
770
+ else:
771
+ raise ValueError(f"{path}: tetrahedral meshes are read from .vtu or .mesh files")
772
+ used, inverse = np.unique(elements, return_inverse=True)
773
+ nodes = np.asarray(nodes, dtype=float)[used]
774
+ if box is None:
775
+ box = stored_box if stored_box is not None else (nodes.min(axis=0), nodes.max(axis=0))
776
+ return TetMesh(
777
+ nodes=nodes,
778
+ elements=inverse.reshape(elements.shape),
779
+ phase=np.asarray(phase, dtype=np.int64),
780
+ lower=np.asarray(box[0], dtype=float),
781
+ upper=np.asarray(box[1], dtype=float),
782
+ periodic=stored_periodic if periodic is None else bool(periodic),
783
+ metadata={"source": str(path)},
784
+ cell=cell,
785
+ orientations=orientations,
786
+ whole=whole,
787
+ outer=outer,
788
+ )
789
+
790
+
791
+ def write_stl(path, surface: SurfaceMesh, *, name: str = "morphogen") -> Path:
792
+ """Binary STL."""
793
+ path = Path(path)
794
+ tri = surface.vertices[surface.faces].astype(np.float32)
795
+ normals = surface.face_normals().astype(np.float32)
796
+ record = np.dtype([("n", "<f4", 3), ("v", "<f4", (3, 3)), ("attr", "<u2")])
797
+ data = np.zeros(len(tri), dtype=record)
798
+ data["n"] = normals
799
+ data["v"] = tri
800
+ header = f"{name} (morphoGen {__version__})".encode("ascii", "replace")[:80].ljust(80, b" ")
801
+ with open(path, "wb") as f:
802
+ f.write(header)
803
+ f.write(np.uint32(len(tri)).tobytes())
804
+ f.write(data.tobytes())
805
+ return path
806
+
807
+
808
+ def read_stl(path) -> SurfaceMesh:
809
+ """Binary STL reader (vertices are not merged)."""
810
+ raw = Path(path).read_bytes()
811
+ n = int(np.frombuffer(raw, dtype="<u4", count=1, offset=80)[0])
812
+ record = np.dtype([("n", "<f4", 3), ("v", "<f4", (3, 3)), ("attr", "<u2")])
813
+ data = np.frombuffer(raw, dtype=record, count=n, offset=84)
814
+ verts = data["v"].reshape(-1, 3).astype(float)
815
+ return SurfaceMesh(verts, np.arange(3 * n).reshape(n, 3))
816
+
817
+
818
+ def write_meshio(path, mesh: VoxelMesh | TetMesh | SurfaceMesh) -> Path:
819
+ """Any other format supported by the optional ``meshio`` package."""
820
+ try:
821
+ import meshio
822
+ except ImportError: # pragma: no cover - depends on the environment
823
+ raise ImportError(
824
+ f"format of {path} needs the optional 'meshio' package: pip install 'morphogen[io]'"
825
+ ) from None
826
+ if isinstance(mesh, SurfaceMesh):
827
+ m = meshio.Mesh(mesh.vertices, [("triangle", mesh.faces)])
828
+ elif isinstance(mesh, TetMesh):
829
+ kind = "tetra" if mesh.order == 1 else "tetra10"
830
+ data = {"phase": [mesh.phase]}
831
+ if mesh.cell is not None:
832
+ data["cell"] = [mesh.cell]
833
+ if mesh.orientations is not None:
834
+ data["euler"] = [mesh.orientations[mesh.cell]]
835
+ if mesh.whole:
836
+ data["outer"] = [_outer_bits(mesh)]
837
+ m = meshio.Mesh(mesh.nodes, [(kind, mesh.elements)], cell_data=data)
838
+ else:
839
+ data = {"phase": [mesh.phase]}
840
+ if mesh.label is not None:
841
+ data["cell"] = [mesh.label]
842
+ m = meshio.Mesh(mesh.nodes, [("hexahedron", mesh.elements)], cell_data=data)
843
+ meshio.write(str(path), m)
844
+ return Path(path)