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,1080 @@
1
+ """Materials of the phases: linear (thermo-)elasticity and the transport phenomena of one
2
+ scalar potential (heat conduction, electrical conduction, dielectric and magnetic
3
+ polarization, diffusion), isotropic or anisotropic (crystals), and voids.
4
+
5
+ Every transport phenomenon is a flux proportional to the gradient of a potential,
6
+ ``flux = -K grad(potential)`` without sources (:data:`TRANSPORT`): Fourier's law (``q = -k
7
+ grad T``, the ``conductivity``), Ohm's law (``j = -sigma grad V``, the
8
+ ``electrical_conductivity``), electrostatics (``D = -eps grad V``, the ``permittivity``),
9
+ magnetostatics without currents (``B = -mu grad psi``, the ``permeability``) and Fick's law
10
+ (``J = -D grad c``, the ``diffusivity``). They share their solvers, their boundary
11
+ conditions and their bounds; a phase whose coefficient is zero is inert for that physics
12
+ (an insulator), as a void is for all.
13
+
14
+ Thermal expansion makes the stress ``sigma = D (eps - alpha dT)`` for a change of
15
+ temperature ``dT`` from the stress-free state; a crystal's expansion tensor turns with it.
16
+
17
+ An isotropic elastic material may also yield: von Mises elasto-(visco)plasticity with
18
+ isotropic and kinematic hardening (:class:`~morphogen.homogenization.behaviours.Plasticity`,
19
+ for the loading paths of :mod:`morphogen.homogenization.nonlinear`), or porous
20
+ elasto-(visco)plasticity (Gurson-Tvergaard-Needleman, Rousselier, the elliptic criterion
21
+ of compaction: :class:`~morphogen.homogenization.porous.PorousPlasticity`); the linear
22
+ properties use its elasticity. A crystal may slip on its slip systems: the crystal
23
+ plasticity of Méric and Cailletaud (:class:`~morphogen.homogenization.crystal.
24
+ CrystalPlasticity`), which turns with the orientation of each grain.
25
+
26
+ Elasticity matrices use the Voigt order ``(11, 22, 33, 23, 31, 12)`` with engineering
27
+ shear strains, so that ``sigma = D eps`` (:mod:`morphogen.homogenization.elements`). The
28
+ matrices of a crystal are given in its own axes; a crystal orientation (Bunge Euler
29
+ angles ``(phi1, Phi, phi2)`` in degrees, :mod:`morphogen.orientations`) turns them into
30
+ the axes of the sample: ``C_ijkl = g_pi g_qj g_rk g_sl C'_pqrs`` with ``crystal = g @
31
+ sample``.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import logging
37
+ import math
38
+ from dataclasses import dataclass
39
+
40
+ import numpy as np
41
+
42
+ from morphogen.homogenization.behaviours import Plasticity
43
+ from morphogen.homogenization.crystal import CrystalPlasticity
44
+ from morphogen.homogenization.porous import PorousPlasticity
45
+
46
+ log = logging.getLogger("morphogen")
47
+
48
+ #: The transport phenomena of one scalar potential, ``flux = -K grad(potential)``: the
49
+ #: name of each physics and the parameter of :class:`Material` that holds its ``K``
50
+ #: (``thermal``: the ``conductivity``, or the tensor ``conductivities`` of a crystal)
51
+ TRANSPORT = {
52
+ "thermal": "conductivity",
53
+ "electrical": "electrical_conductivity",
54
+ "dielectric": "permittivity",
55
+ "magnetic": "permeability",
56
+ "diffusion": "diffusivity",
57
+ }
58
+ #: The potential, the flux and the law of each transport phenomenon (for the messages and
59
+ #: the documentation)
60
+ TRANSPORT_LAWS = {
61
+ "thermal": ("temperature", "heat flux", "Fourier's law q = -k grad T"),
62
+ "electrical": ("electric potential", "current density", "Ohm's law j = -sigma grad V"),
63
+ "dielectric": ("electric potential", "electric displacement", "D = -eps grad V"),
64
+ "magnetic": ("magnetic scalar potential", "magnetic induction", "B = -mu grad psi"),
65
+ "diffusion": ("concentration", "mass flux", "Fick's law J = -D grad c"),
66
+ }
67
+ #: The physics of the linear problems: elasticity and the transport phenomena
68
+ PHYSICS = ("elastic", *TRANSPORT)
69
+ #: The behaviours of :mod:`morphogen.homogenization.laws` of a material
70
+ _ANALYTIC = ("viscoelasticity", "hyperelasticity", "damage")
71
+
72
+
73
+ def transport_physics(physics: str) -> bool:
74
+ """Whether ``physics`` is a transport phenomenon of :data:`TRANSPORT` (a scalar
75
+ potential), not elasticity; an unknown name is an error."""
76
+ if physics not in PHYSICS:
77
+ raise ValueError(f"physics: one of {PHYSICS}, got {physics!r}")
78
+ return physics != "elastic"
79
+
80
+
81
+ #: Voigt index of each pair of tensor indices
82
+ _VOIGT_PAIRS = ((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1))
83
+ _VOIGT_INDEX = np.empty((3, 3), dtype=np.int64)
84
+ for _k, (_i, _j) in enumerate(_VOIGT_PAIRS):
85
+ _VOIGT_INDEX[_i, _j] = _VOIGT_INDEX[_j, _i] = _k
86
+ _I0 = np.array([i for i, _ in _VOIGT_PAIRS])
87
+ _I1 = np.array([j for _, j in _VOIGT_PAIRS])
88
+
89
+
90
+ def voigt_to_tensor4(d) -> np.ndarray:
91
+ """Fourth-order tensor(s) ``C_ijkl`` of Voigt matrices (..., 6, 6)."""
92
+ d = np.asarray(d, dtype=float)
93
+ return d[..., _VOIGT_INDEX[:, :, None, None], _VOIGT_INDEX[None, None, :, :]]
94
+
95
+
96
+ def tensor4_to_voigt(c) -> np.ndarray:
97
+ """Voigt matrices (..., 6, 6) of fourth-order tensors with the minor symmetries."""
98
+ c = np.asarray(c, dtype=float)
99
+ return c[..., _I0[:, None], _I1[:, None], _I0[None, :], _I1[None, :]]
100
+
101
+
102
+ def rotate_stiffness(d, euler) -> np.ndarray:
103
+ """Elasticity matrix of a crystal (crystal axes) in the sample axes, for one
104
+ orientation (shape (6, 6)) or several (shape (n, 6, 6))."""
105
+ from morphogen.orientations import euler_to_matrix
106
+
107
+ g = euler_to_matrix(euler)
108
+ c = np.einsum("npi,nqj,nrk,nsl,pqrs->nijkl", g, g, g, g, voigt_to_tensor4(d), optimize=True)
109
+ out = tensor4_to_voigt(c)
110
+ out = 0.5 * (out + np.swapaxes(out, -1, -2))
111
+ return out[0] if np.ndim(euler) == 1 else out
112
+
113
+
114
+ def rotate_conductivity(k, euler) -> np.ndarray:
115
+ """Conductivity tensor of a crystal in the sample axes (``g^T K g``)."""
116
+ from morphogen.orientations import euler_to_matrix
117
+
118
+ g = euler_to_matrix(euler)
119
+ out = np.einsum("npi,pq,nqj->nij", g, np.asarray(k, dtype=float), g)
120
+ out = 0.5 * (out + np.swapaxes(out, -1, -2))
121
+ return out[0] if np.ndim(euler) == 1 else out
122
+
123
+
124
+ def isotropic_matrix(lam: float, mu: float) -> np.ndarray:
125
+ """Elasticity matrix (6 x 6) of an isotropic material."""
126
+ d = np.zeros((6, 6))
127
+ d[:3, :3] = lam
128
+ d[[0, 1, 2], [0, 1, 2]] += 2.0 * mu
129
+ d[[3, 4, 5], [3, 4, 5]] = mu
130
+ return d
131
+
132
+
133
+ def voigt_average(d) -> tuple[float, float]:
134
+ """Bulk and shear moduli of the Voigt average over uniform orientations."""
135
+ d = np.asarray(d, dtype=float)
136
+ a = d[0, 0] + d[1, 1] + d[2, 2]
137
+ b = d[1, 2] + d[2, 0] + d[0, 1]
138
+ c = d[3, 3] + d[4, 4] + d[5, 5]
139
+ return float((a + 2.0 * b) / 9.0), float((a - b + 3.0 * c) / 15.0)
140
+
141
+
142
+ def reuss_average(d) -> tuple[float, float]:
143
+ """Bulk and shear moduli of the Reuss average over uniform orientations."""
144
+ s = np.linalg.inv(np.asarray(d, dtype=float))
145
+ a = s[0, 0] + s[1, 1] + s[2, 2]
146
+ b = s[1, 2] + s[2, 0] + s[0, 1]
147
+ c = s[3, 3] + s[4, 4] + s[5, 5]
148
+ return float(1.0 / (a + 2.0 * b)), float(15.0 / (4.0 * a - 4.0 * b + 3.0 * c))
149
+
150
+
151
+ def _expansion(value, name: str = "expansion"):
152
+ """Thermal expansion (or the swelling ``name``) as one coefficient (isotropic) or a
153
+ 3 x 3 tensor (tuple)."""
154
+ a = np.asarray(value, dtype=float)
155
+ if not np.all(np.isfinite(a)):
156
+ raise ValueError(f"{name}: finite coefficients")
157
+ if a.ndim == 0:
158
+ return float(a)
159
+ if a.shape == (3,):
160
+ a = np.diag(a)
161
+ if a.shape != (3, 3) or not np.allclose(a, a.T, atol=1e-12 * max(np.abs(a).max(), 1e-300)):
162
+ raise ValueError(f"{name}: one coefficient, three principal values or a 3 x 3 tensor")
163
+ if np.allclose(a, a[0, 0] * np.eye(3), rtol=0, atol=1e-15 * abs(a[0, 0])):
164
+ return float(a[0, 0])
165
+ return tuple(tuple(float(v) for v in row) for row in 0.5 * (a + a.T))
166
+
167
+
168
+ def _matrix(value, shape, name) -> tuple:
169
+ m = np.asarray(value, dtype=float)
170
+ if m.shape != shape or not np.all(np.isfinite(m)):
171
+ raise ValueError(f"{name}: expected a finite {shape[0]} x {shape[1]} matrix")
172
+ if not np.allclose(m, m.T, rtol=1e-10, atol=1e-12 * float(np.abs(m).max())):
173
+ raise ValueError(f"{name}: the matrix must be symmetric")
174
+ if np.linalg.eigvalsh(0.5 * (m + m.T)).min() <= 0:
175
+ raise ValueError(f"{name}: the matrix must be positive definite")
176
+ return tuple(tuple(float(v) for v in row) for row in 0.5 * (m + m.T))
177
+
178
+
179
+ def _transport(value, name: str):
180
+ """A transport coefficient: one value (isotropic; zero: a phase inert for that
181
+ physics, an insulator), or a symmetric positive definite 3 x 3 tensor in the axes of
182
+ the crystal (three principal values, or the tensor), kept as a tuple."""
183
+ k = np.asarray(value, dtype=float)
184
+ if k.shape == (3,):
185
+ k = k[0] if np.allclose(k, k[0], rtol=1e-12, atol=0.0) else np.diag(k)
186
+ if np.ndim(k) == 0:
187
+ if not (math.isfinite(k) and k >= 0):
188
+ raise ValueError(f"{name}: must be non-negative, got {value!r}")
189
+ return float(k)
190
+ return _matrix(k, (3, 3), name)
191
+
192
+
193
+ def _index(value):
194
+ """A complex refractive index ``n + i k``: a number, a pair ``(n, k)`` (the form of
195
+ the configurations), or one of them per wavelength; kept as a complex number or a
196
+ tuple of them."""
197
+ a = np.asarray(value)
198
+ if a.dtype.kind not in "iufc":
199
+ raise ValueError("refractive_index: n, (n, k), or a list of them per wavelength")
200
+ if not np.iscomplexobj(a):
201
+ if a.ndim == 2 and a.shape[1] == 2: # pairs (n, k) per wavelength
202
+ a = a[:, 0] + 1j * a[:, 1]
203
+ elif a.shape == (2,): # one pair
204
+ a = a[0] + 1j * a[1]
205
+ a = np.asarray(a, dtype=complex)
206
+ transparent = np.all(a.imag == 0)
207
+ if a.ndim > 1 or not np.all(np.isfinite(a)) or (transparent and np.any(a.real <= 0)):
208
+ raise ValueError(
209
+ "refractive_index: n, (n, k), or a list of pairs (n, k) per wavelength (finite, "
210
+ "n positive for a transparent phase)"
211
+ )
212
+ return complex(a) if a.ndim == 0 else tuple(complex(v) for v in a)
213
+
214
+
215
+ def lame(young: float, poisson: float) -> tuple[float, float]:
216
+ """Lame coefficients (lambda, mu) from Young's modulus and Poisson's ratio."""
217
+ mu = young / (2.0 * (1.0 + poisson))
218
+ lam = young * poisson / ((1.0 + poisson) * (1.0 - 2.0 * poisson))
219
+ return lam, mu
220
+
221
+
222
+ def bulk_shear(young: float, poisson: float) -> tuple[float, float]:
223
+ """Bulk and shear moduli (k, mu) from Young's modulus and Poisson's ratio."""
224
+ return young / (3.0 * (1.0 - 2.0 * poisson)), young / (2.0 * (1.0 + poisson))
225
+
226
+
227
+ def young_poisson(bulk: float, shear: float) -> tuple[float, float]:
228
+ """Young's modulus and Poisson's ratio from the bulk and shear moduli."""
229
+ young = 9.0 * bulk * shear / (3.0 * bulk + shear)
230
+ poisson = (3.0 * bulk - 2.0 * shear) / (2.0 * (3.0 * bulk + shear))
231
+ return young, poisson
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class Material:
236
+ """Linear material of a phase, or a void.
237
+
238
+ Isotropic materials: ``young`` and ``poisson`` define the elastic behaviour,
239
+ ``conductivity`` the thermal one; a material may define either or both. Crystals:
240
+ ``stiffness``, the 6 x 6 elasticity matrix in the axes of the crystal (see
241
+ :meth:`cubic`, :meth:`hexagonal`, :meth:`anisotropic`), and ``conductivities``, the
242
+ 3 x 3 conductivity tensor in the same axes (or ``conductivity`` when it is isotropic).
243
+ ``expansion`` is the thermal expansion: one coefficient, or (crystals) principal
244
+ values or a 3 x 3 tensor in the axes of the crystal. In a polycrystal, each grain
245
+ turns them by its orientation. ``swelling`` is likewise the strain of a unit content
246
+ of a species the phase absorbs (moisture, a solvent, lithium: the hygroscopic or
247
+ chemical expansion), for the effective swelling of
248
+ :mod:`morphogen.homogenization.poroelastic`. ``density`` (optional) gives the
249
+ effective density and specific properties. The other transport phenomena
250
+ (:data:`TRANSPORT`) each have their coefficient: ``electrical_conductivity`` (Ohm),
251
+ ``permittivity`` (dielectrics), ``permeability`` (magnetostatics) and ``diffusivity``
252
+ (Fick), one value or, in the
253
+ axes of the crystal, three principal values or a 3 x 3 tensor; zero makes the phase
254
+ inert for that physics (an insulator in a conducting composite), as a void is for
255
+ all. ``refractive_index``: the complex refractive index ``n + i k`` of the phase at
256
+ optical frequencies (a number, a pair ``(n, k)``, or one pair per wavelength), for the
257
+ effective index of :mod:`morphogen.homogenization.harmonic`. ``coupling`` holds the
258
+ coefficients of the strong couplings between these physics
259
+ (:class:`~morphogen.homogenization.coupled.Coupling`: piezoelectric, piezomagnetic,
260
+ magnetoelectric, Seebeck and pyroelectric coefficients; a mapping of them), for the
261
+ coupled problems of :mod:`morphogen.homogenization.coupled`. ``viscoelasticity``
262
+ (a generalized Maxwell model), ``hyperelasticity`` (a strain energy, in finite strains)
263
+ and ``damage`` (the isotropic damage of quasi-brittle solids, Mazars' law of
264
+ concrete) give an isotropic
265
+ material one of the behaviours of :mod:`morphogen.homogenization.laws` along loading
266
+ paths (a viscoelasticity and a hyperelasticity together: finite viscoelasticity; a
267
+ ``damage`` of Lemaitre or of Kachanov goes with a ``plasticity``, whose effective
268
+ stress it degrades).
269
+ ``plasticity`` (isotropic materials) makes it yield along
270
+ loading paths, ``porous_plasticity`` (isotropic materials) makes it a porous plastic
271
+ material, ``crystal_plasticity`` makes it slip on the systems of its lattice,
272
+ ``mfront`` gives it an MFront behaviour along them
273
+ (:class:`~morphogen.homogenization.mfront.MFrontBehaviour`; its elastic parameters
274
+ remain those of the linear problems and of the reference media) and ``learned`` a law
275
+ learned from data (:class:`~morphogen.learning.behaviour.LearnedBehaviour`; likewise).
276
+ A void carries neither stress nor flux.
277
+ """
278
+
279
+ young: float | None = None
280
+ poisson: float | None = None
281
+ conductivity: float | None = None
282
+ void: bool = False
283
+ stiffness: tuple | None = None
284
+ conductivities: tuple | None = None
285
+ symmetry: str = "isotropic"
286
+ expansion: float | tuple | None = None
287
+ density: float | None = None
288
+ plasticity: Plasticity | None = None
289
+ crystal_plasticity: CrystalPlasticity | None = None
290
+ mfront: object | None = None
291
+ porous_plasticity: PorousPlasticity | None = None
292
+ learned: object | None = None
293
+ electrical_conductivity: float | tuple | None = None
294
+ permittivity: float | tuple | None = None
295
+ permeability: float | tuple | None = None
296
+ diffusivity: float | tuple | None = None
297
+ refractive_index: complex | tuple | None = None
298
+ coupling: object | None = None
299
+ viscoelasticity: object | None = None
300
+ hyperelasticity: object | None = None
301
+ damage: object | None = None
302
+ swelling: float | tuple | None = None
303
+
304
+ def __post_init__(self) -> None:
305
+ if self.hyperelasticity is not None and self.young is None and not self.void:
306
+ self._elasticity_of_the_law()
307
+ others = [name for name in TRANSPORT.values() if name != "conductivity"]
308
+ params = (self.young, self.poisson, self.conductivity, self.stiffness,
309
+ self.conductivities, self.refractive_index,
310
+ *(getattr(self, name) for name in others)) # fmt: skip
311
+ if self.density is not None:
312
+ if not (math.isfinite(self.density) and self.density >= 0):
313
+ raise ValueError(f"density: must be non-negative, got {self.density!r}")
314
+ object.__setattr__(self, "density", float(self.density))
315
+ if self.void:
316
+ if any(v is not None for v in params) or self.expansion is not None:
317
+ raise ValueError("a void has no elastic or thermal parameters")
318
+ if self.swelling is not None:
319
+ raise ValueError("a void does not swell")
320
+ if (
321
+ self.plasticity is not None
322
+ or self.crystal_plasticity is not None
323
+ or self.porous_plasticity is not None
324
+ ):
325
+ raise ValueError("a void has no plasticity")
326
+ if self.mfront is not None:
327
+ raise ValueError("a void has no MFront behaviour")
328
+ if self.learned is not None:
329
+ raise ValueError("a void has no learned law")
330
+ if self.coupling is not None:
331
+ raise ValueError("a void has no coupling coefficients")
332
+ if any(getattr(self, name) is not None for name in _ANALYTIC):
333
+ raise ValueError("a void has no behaviour")
334
+ if self.density:
335
+ raise ValueError("a void has no density")
336
+ return
337
+ if self.expansion is not None:
338
+ if not (self.young is not None or self.stiffness is not None):
339
+ raise ValueError("expansion: a material with elastic parameters")
340
+ object.__setattr__(self, "expansion", _expansion(self.expansion))
341
+ if self.swelling is not None:
342
+ if not (self.young is not None or self.stiffness is not None):
343
+ raise ValueError("swelling: a material with elastic parameters")
344
+ object.__setattr__(self, "swelling", _expansion(self.swelling, "swelling"))
345
+ if (self.young is None) != (self.poisson is None):
346
+ raise ValueError("give both 'young' and 'poisson' (or neither)")
347
+ if self.young is not None and self.stiffness is not None:
348
+ raise ValueError("give young/poisson (isotropic) or a stiffness matrix, not both")
349
+ if self.conductivity is not None and self.conductivities is not None:
350
+ raise ValueError("give a conductivity or a conductivity tensor, not both")
351
+ if all(v is None for v in params):
352
+ raise ValueError(
353
+ "a material needs elastic parameters, a transport coefficient (conductivity, "
354
+ f"{', '.join(others)}), or several of them"
355
+ )
356
+ for name in others:
357
+ if getattr(self, name) is not None:
358
+ object.__setattr__(self, name, _transport(getattr(self, name), name))
359
+ if self.refractive_index is not None:
360
+ object.__setattr__(self, "refractive_index", _index(self.refractive_index))
361
+ if self.young is not None:
362
+ if not (math.isfinite(self.young) and self.young > 0):
363
+ raise ValueError(f"young: must be positive, got {self.young!r}")
364
+ if not -1.0 < self.poisson < 0.5:
365
+ raise ValueError(f"poisson: must lie in (-1, 0.5), got {self.poisson!r}")
366
+ if self.conductivity is not None and not (
367
+ math.isfinite(self.conductivity) and self.conductivity > 0
368
+ ):
369
+ raise ValueError(f"conductivity: must be positive, got {self.conductivity!r}")
370
+ if self.stiffness is not None:
371
+ object.__setattr__(self, "stiffness", _matrix(self.stiffness, (6, 6), "stiffness"))
372
+ if self.conductivities is not None:
373
+ object.__setattr__(
374
+ self, "conductivities", _matrix(self.conductivities, (3, 3), "conductivities")
375
+ )
376
+ if self.plasticity is not None:
377
+ object.__setattr__(self, "plasticity", Plasticity.from_config(self.plasticity))
378
+ if self.young is None:
379
+ raise ValueError(
380
+ "plasticity: an isotropic elastic material (young and poisson, or bulk and "
381
+ "shear)"
382
+ )
383
+ if self.crystal_plasticity is not None:
384
+ if self.plasticity is not None:
385
+ raise ValueError("give plasticity (von Mises) or crystal_plasticity, not both")
386
+ cp = CrystalPlasticity.from_config(self.crystal_plasticity)
387
+ object.__setattr__(self, "crystal_plasticity", cp)
388
+ if self.young is None and self.stiffness is None:
389
+ raise ValueError("crystal_plasticity: a material with elastic parameters")
390
+ cp.check_softening(self.matrix("elastic")) # of its cleavage planes
391
+ if self.mfront is not None:
392
+ from morphogen.homogenization.mfront import MFrontBehaviour
393
+
394
+ if self.plasticity is not None or self.crystal_plasticity is not None:
395
+ raise ValueError("give plasticity, crystal_plasticity or mfront, one of them")
396
+ if self.young is None and self.stiffness is None:
397
+ raise ValueError(
398
+ "mfront: a material with elastic parameters (the linear problems and "
399
+ "the reference media)"
400
+ )
401
+ object.__setattr__(self, "mfront", MFrontBehaviour.from_config(self.mfront))
402
+ if self.porous_plasticity is not None:
403
+ if (
404
+ self.plasticity is not None
405
+ or self.crystal_plasticity is not None
406
+ or (self.mfront is not None)
407
+ ):
408
+ raise ValueError(
409
+ "give plasticity, porous_plasticity, crystal_plasticity or mfront, one of them"
410
+ )
411
+ pp = PorousPlasticity.from_config(self.porous_plasticity)
412
+ object.__setattr__(self, "porous_plasticity", pp)
413
+ if self.young is None:
414
+ raise ValueError(
415
+ "porous_plasticity: an isotropic elastic material (young and poisson)"
416
+ )
417
+ if self.learned is not None:
418
+ from morphogen.learning.behaviour import LearnedBehaviour
419
+
420
+ behaviours = (self.plasticity, self.crystal_plasticity, self.mfront,
421
+ self.porous_plasticity) # fmt: skip
422
+ if any(b is not None for b in behaviours):
423
+ raise ValueError(
424
+ "give plasticity, porous_plasticity, crystal_plasticity, mfront or learned, "
425
+ "one of them"
426
+ )
427
+ if self.young is None and self.stiffness is None:
428
+ raise ValueError(
429
+ "learned: a material with elastic parameters (the linear problems and the "
430
+ "reference media; morphogen.learning.learned_material takes those of the "
431
+ "model)"
432
+ )
433
+ object.__setattr__(self, "learned", LearnedBehaviour.from_config(self.learned))
434
+ if self.coupling is not None:
435
+ from morphogen.homogenization.coupled import Coupling
436
+
437
+ object.__setattr__(self, "coupling", Coupling.from_config(self.coupling))
438
+ self._analytic_laws()
439
+ tensors = [self.stiffness, self.conductivities]
440
+ tensors += [v for v in (getattr(self, name) for name in others) if isinstance(v, tuple)]
441
+ if all(t is None for t in tensors):
442
+ object.__setattr__(self, "symmetry", "isotropic")
443
+ elif self.symmetry == "isotropic":
444
+ object.__setattr__(self, "symmetry", "anisotropic")
445
+
446
+ def _elasticity_of_the_law(self) -> None:
447
+ """Young's modulus and Poisson's ratio of a hyperelastic material given by its
448
+ law alone: those of its bulk and shear moduli at the natural state."""
449
+ from morphogen.homogenization.laws import Hyperelasticity
450
+
451
+ law = Hyperelasticity.from_config(self.hyperelasticity)
452
+ bulk, shear = law.initial_moduli()
453
+ if bulk is None or shear is None:
454
+ raise ValueError(
455
+ "hyperelasticity: give young and poisson, or the bulk modulus and the "
456
+ "parameters of the law that set its shear modulus"
457
+ )
458
+ young, poisson = young_poisson(bulk, shear)
459
+ object.__setattr__(self, "young", young)
460
+ object.__setattr__(self, "poisson", poisson)
461
+
462
+ def _analytic_laws(self) -> None:
463
+ """The behaviours of :mod:`morphogen.homogenization.laws` of the material,
464
+ checked against its elasticity and its other behaviours."""
465
+ given = [name for name in _ANALYTIC if getattr(self, name) is not None]
466
+ if not given:
467
+ return
468
+ from morphogen.homogenization import laws
469
+
470
+ read = {"viscoelasticity": laws.Viscoelasticity.from_config,
471
+ "hyperelasticity": laws.Hyperelasticity.from_config,
472
+ "damage": laws.damage_from_config} # fmt: skip
473
+ for name in given:
474
+ object.__setattr__(self, name, read[name](getattr(self, name)))
475
+ # a damage of Lemaitre or of Kachanov is that of the plasticity of the material
476
+ coupled = isinstance(self.damage, laws.DuctileDamage)
477
+ others = (None if coupled else self.plasticity, self.crystal_plasticity, self.mfront,
478
+ self.porous_plasticity, self.learned) # fmt: skip
479
+ if any(b is not None for b in others) or ("damage" in given and len(given) > 1):
480
+ raise ValueError(
481
+ "give one behaviour: plasticity, porous_plasticity, crystal_plasticity, "
482
+ "mfront, learned, damage, or viscoelasticity and hyperelasticity (alone or "
483
+ "together); a damage of Lemaitre or of Kachanov (damage.law) goes with a "
484
+ "plasticity"
485
+ )
486
+ if self.young is None:
487
+ raise ValueError(f"{given[0]}: an isotropic elastic material (young and poisson)")
488
+ if self.hyperelasticity is not None:
489
+ bulk, shear = self.hyperelasticity.initial_moduli()
490
+ k0, g0 = bulk_shear(self.young, self.poisson)
491
+ for name, own, mine in (("bulk", bulk, k0), ("shear", shear, g0)):
492
+ if own is not None and not math.isclose(own, mine, rel_tol=1e-6):
493
+ raise ValueError(
494
+ f"hyperelasticity: its {name} modulus at the natural state, {own:.6g}, "
495
+ f"is not that of young and poisson, {mine:.6g} (the linear problems); "
496
+ "leave young and poisson out, or the parameter of the law"
497
+ )
498
+ if coupled: # its plasticity: von Mises' (and Norton's flow for Kachanov's law)
499
+ laws._PlasticDamage(self.plasticity, self.damage, self.young, self.poisson)
500
+ elif self.damage is not None:
501
+ self.damage.strains(self.young)
502
+
503
+ # -- constructors ----------------------------------------------------------------
504
+
505
+ @classmethod
506
+ def from_moduli(
507
+ cls, bulk: float, shear: float, conductivity: float | None = None, *, expansion=None
508
+ ):
509
+ young, poisson = young_poisson(bulk, shear)
510
+ return cls(young=young, poisson=poisson, conductivity=conductivity, expansion=expansion)
511
+
512
+ @classmethod
513
+ def cubic(
514
+ cls,
515
+ c11: float,
516
+ c12: float,
517
+ c44: float,
518
+ *,
519
+ conductivity: float | None = None,
520
+ expansion: float | None = None,
521
+ ):
522
+ """Cubic crystal (stiffness constants in its axes); its conductivity and thermal
523
+ expansion are isotropic."""
524
+ d = np.zeros((6, 6))
525
+ d[:3, :3] = c12
526
+ d[[0, 1, 2], [0, 1, 2]] = c11
527
+ d[[3, 4, 5], [3, 4, 5]] = c44
528
+ return cls(stiffness=d, conductivity=conductivity, symmetry="cubic", expansion=expansion)
529
+
530
+ @classmethod
531
+ def hexagonal(
532
+ cls,
533
+ c11: float,
534
+ c12: float,
535
+ c13: float,
536
+ c33: float,
537
+ c44: float,
538
+ *,
539
+ conductivity=None,
540
+ expansion=None,
541
+ ):
542
+ """Hexagonal (transversely isotropic) crystal, axis c along the third crystal
543
+ axis; ``conductivity`` and ``expansion``: one value, or (basal plane, axis c)."""
544
+ d = np.zeros((6, 6))
545
+ d[0, 0] = d[1, 1] = c11
546
+ d[2, 2] = c33
547
+ d[0, 1] = d[1, 0] = c12
548
+ d[0, 2] = d[2, 0] = d[1, 2] = d[2, 1] = c13
549
+ d[3, 3] = d[4, 4] = c44
550
+ d[5, 5] = 0.5 * (c11 - c12)
551
+ k, kt = _thermal(conductivity, uniaxial=True)
552
+ if expansion is not None and np.shape(expansion) == (2,):
553
+ expansion = (expansion[0], expansion[0], expansion[1])
554
+ return cls(
555
+ stiffness=d,
556
+ conductivity=k,
557
+ conductivities=kt,
558
+ symmetry="hexagonal",
559
+ expansion=expansion,
560
+ )
561
+
562
+ @classmethod
563
+ def anisotropic(cls, stiffness=None, *, conductivity=None, expansion=None):
564
+ """Crystal of any symmetry: 6 x 6 elasticity matrix (Voigt order 11, 22, 33, 23,
565
+ 31, 12, engineering shear strains), conductivity and thermal expansion (one value,
566
+ three principal values along the crystal axes, or a 3 x 3 tensor), in the axes of
567
+ the crystal."""
568
+ k, kt = _thermal(conductivity, uniaxial=False)
569
+ return cls(stiffness=stiffness, conductivity=k, conductivities=kt, expansion=expansion)
570
+
571
+ # -- properties ------------------------------------------------------------------
572
+
573
+ @property
574
+ def elastic(self) -> bool:
575
+ return self.young is not None or self.stiffness is not None
576
+
577
+ @property
578
+ def thermal(self) -> bool:
579
+ return self.conductivity is not None or self.conductivities is not None
580
+
581
+ def has(self, physics: str) -> bool:
582
+ """Whether the material has the parameters of ``physics`` (:data:`PHYSICS`):
583
+ elastic ones, or the coefficient of a transport phenomenon."""
584
+ if not transport_physics(physics):
585
+ return self.elastic
586
+ if physics == "thermal":
587
+ return self.thermal
588
+ return getattr(self, TRANSPORT[physics]) is not None
589
+
590
+ def inert(self, physics: str) -> bool:
591
+ """Whether the material carries nothing for ``physics``: a void, or a phase whose
592
+ transport coefficient is zero (an insulator), left out of that problem as a pore."""
593
+ if self.void:
594
+ return True
595
+ if physics in ("elastic", "thermal"):
596
+ return False
597
+ value = getattr(self, TRANSPORT[physics])
598
+ return value is not None and not isinstance(value, tuple) and value == 0.0
599
+
600
+ @property
601
+ def isotropic(self) -> bool:
602
+ return self.symmetry == "isotropic"
603
+
604
+ @property
605
+ def plastic(self) -> bool:
606
+ """Whether the material yields (von Mises; nonlinear loading paths)."""
607
+ return self.plasticity is not None
608
+
609
+ @property
610
+ def crystal_plastic(self) -> bool:
611
+ """Whether the material slips on its slip systems (crystal plasticity)."""
612
+ return self.crystal_plasticity is not None
613
+
614
+ @property
615
+ def porous(self) -> bool:
616
+ """Whether the material is porous plastic (Gurson, Rousselier, elliptic)."""
617
+ return self.porous_plasticity is not None
618
+
619
+ @property
620
+ def analytic(self) -> bool:
621
+ """Whether the material has a behaviour of :mod:`morphogen.homogenization.laws`
622
+ (viscoelasticity, hyperelasticity, damage)."""
623
+ return any(getattr(self, name) is not None for name in _ANALYTIC)
624
+
625
+ @property
626
+ def nonlinear(self) -> bool:
627
+ """Whether the behaviour of the material is nonlinear (loading paths)."""
628
+ external = self.mfront is not None or self.learned is not None or self.analytic
629
+ return self.plastic or self.crystal_plastic or self.porous or external
630
+
631
+ @property
632
+ def expands(self) -> bool:
633
+ """Whether the material has a (nonzero) thermal expansion."""
634
+ return self.expansion is not None and bool(np.any(np.asarray(self.expansion) != 0))
635
+
636
+ def oriented(self, physics: str) -> bool:
637
+ """Whether the behaviour for ``physics`` depends on the orientation (a learned law
638
+ runs in the axes of its material, unless it is not oriented)."""
639
+ if not transport_physics(physics):
640
+ return (
641
+ self.stiffness is not None
642
+ or isinstance(self.expansion, tuple)
643
+ or isinstance(self.swelling, tuple)
644
+ or self.crystal_plasticity is not None
645
+ or (self.learned is not None and self.learned.oriented)
646
+ )
647
+ if physics == "thermal":
648
+ return self.conductivities is not None
649
+ return isinstance(getattr(self, TRANSPORT[physics]), tuple)
650
+
651
+ def expansion_tensor(self, euler=None) -> np.ndarray:
652
+ """Thermal expansion tensor (3 x 3, zero without expansion) in the axes of the
653
+ sample: for the orientation ``euler`` (shape (3,) or (n, 3)), or of the crystal."""
654
+ a = self.expansion if self.expansion is not None else 0.0
655
+ if not isinstance(a, tuple):
656
+ base = float(a) * np.eye(3)
657
+ if euler is not None and np.ndim(euler) == 2:
658
+ return np.repeat(base[None], len(euler), axis=0)
659
+ return base
660
+ if euler is None:
661
+ return np.array(a)
662
+ return rotate_conductivity(np.array(a), euler) # a symmetric second-order tensor
663
+
664
+ @property
665
+ def lame(self) -> tuple[float, float]:
666
+ self._need_elastic()
667
+ if self.stiffness is not None:
668
+ raise ValueError("Lame coefficients: isotropic materials only")
669
+ return lame(self.young, self.poisson)
670
+
671
+ @property
672
+ def bulk(self) -> float:
673
+ """Bulk modulus (isotropic), or of the Voigt average of a crystal."""
674
+ return self.moduli("voigt")[0]
675
+
676
+ @property
677
+ def shear(self) -> float:
678
+ """Shear modulus (isotropic), or of the Voigt average of a crystal."""
679
+ return self.moduli("voigt")[1]
680
+
681
+ def moduli(self, average: str = "voigt") -> tuple[float, float]:
682
+ """Bulk and shear moduli: exact for isotropic materials; for crystals, the
683
+ ``"voigt"``, ``"reuss"`` or ``"hill"`` average over uniform orientations."""
684
+ self._need_elastic()
685
+ if self.stiffness is None:
686
+ return bulk_shear(self.young, self.poisson)
687
+ if average == "voigt":
688
+ return voigt_average(self.stiffness)
689
+ if average == "reuss":
690
+ return reuss_average(self.stiffness)
691
+ if average == "hill":
692
+ (kv, gv), (kr, gr) = voigt_average(self.stiffness), reuss_average(self.stiffness)
693
+ return 0.5 * (kv + kr), 0.5 * (gv + gr)
694
+ raise ValueError("average: 'voigt', 'reuss' or 'hill'")
695
+
696
+ def mean_conductivity(self, average: str = "voigt", physics: str = "thermal") -> float:
697
+ """Conductivity (isotropic), or the arithmetic (``"voigt"``) or harmonic
698
+ (``"reuss"``) mean of the principal conductivities of a crystal; likewise the
699
+ coefficient of another transport ``physics`` (:data:`TRANSPORT`)."""
700
+ k = np.linalg.eigvalsh(self.matrix(physics))
701
+ if np.all(k == k[0]):
702
+ return float(k[0])
703
+ return float(k.mean() if average == "voigt" else 1.0 / np.mean(1.0 / k))
704
+
705
+ def matrix(self, physics: str, euler=None) -> np.ndarray:
706
+ """Elasticity matrix (6 x 6), or conductivity tensor (3 x 3; that of any transport
707
+ ``physics`` of :data:`TRANSPORT`) in the axes of the sample: for the orientation
708
+ ``euler`` (Bunge angles in degrees; shape (3,) or (n, 3) for n orientations), or in
709
+ the axes of the crystal."""
710
+ if physics == "elastic":
711
+ self._need_elastic()
712
+ base = (
713
+ isotropic_matrix(*lame(self.young, self.poisson))
714
+ if self.stiffness is None
715
+ else np.array(self.stiffness)
716
+ )
717
+ rotate = rotate_stiffness
718
+ elif physics == "thermal":
719
+ self._need_thermal()
720
+ base = (
721
+ self.conductivity * np.eye(3)
722
+ if self.conductivities is None
723
+ else np.array(self.conductivities)
724
+ )
725
+ rotate = rotate_conductivity
726
+ elif physics in TRANSPORT:
727
+ value = getattr(self, TRANSPORT[physics])
728
+ if value is None:
729
+ raise ValueError(f"this material has no {TRANSPORT[physics]}")
730
+ base = np.array(value) if isinstance(value, tuple) else value * np.eye(3)
731
+ rotate = rotate_conductivity
732
+ else:
733
+ raise ValueError(f"physics: one of {PHYSICS}, got {physics!r}")
734
+ if euler is None or not self.oriented(physics):
735
+ if euler is not None and np.ndim(euler) == 2:
736
+ return np.repeat(base[None], len(euler), axis=0)
737
+ return base
738
+ return rotate(base, euler)
739
+
740
+ def _need_elastic(self) -> None:
741
+ if not self.elastic:
742
+ raise ValueError("this material has no elastic parameters")
743
+
744
+ def _need_thermal(self) -> None:
745
+ if not self.thermal:
746
+ raise ValueError("this material has no conductivity")
747
+
748
+ # -- configuration ---------------------------------------------------------------
749
+
750
+ def to_config(self):
751
+ if self.void:
752
+ return "void"
753
+ out = {}
754
+ if self.stiffness is not None:
755
+ d = np.array(self.stiffness)
756
+ if self.symmetry == "cubic":
757
+ out["cubic"] = [float(d[0, 0]), float(d[0, 1]), float(d[3, 3])]
758
+ elif self.symmetry == "hexagonal":
759
+ out["hexagonal"] = [
760
+ float(d[i, j]) for i, j in ((0, 0), (0, 1), (0, 2), (2, 2), (3, 3))
761
+ ]
762
+ else:
763
+ out["stiffness"] = d.tolist()
764
+ for key in ("young", "poisson", "conductivity"):
765
+ if getattr(self, key) is not None:
766
+ out[key] = getattr(self, key)
767
+ if self.conductivities is not None:
768
+ out["conductivity"] = np.array(self.conductivities).tolist()
769
+ if self.expansion is not None:
770
+ out["expansion"] = np.array(self.expansion).tolist()
771
+ if self.swelling is not None:
772
+ out["swelling"] = np.array(self.swelling).tolist()
773
+ if self.density is not None:
774
+ out["density"] = self.density
775
+ if self.plasticity is not None:
776
+ out["plasticity"] = self.plasticity.to_config()
777
+ if self.crystal_plasticity is not None:
778
+ out["crystal_plasticity"] = self.crystal_plasticity.to_config()
779
+ if self.mfront is not None:
780
+ out["mfront"] = self.mfront.to_config()
781
+ if self.porous_plasticity is not None:
782
+ out["porous_plasticity"] = self.porous_plasticity.to_config()
783
+ if self.learned is not None:
784
+ out["learned"] = self.learned.to_config()
785
+ for name in TRANSPORT.values():
786
+ value = getattr(self, name)
787
+ if name != "conductivity" and value is not None:
788
+ out[name] = np.array(value).tolist()
789
+ if self.refractive_index is not None:
790
+ n = np.atleast_1d(self.refractive_index)
791
+ pairs = [[float(v.real), float(v.imag)] for v in n]
792
+ out["refractive_index"] = pairs[0] if np.ndim(self.refractive_index) == 0 else pairs
793
+ if self.coupling is not None:
794
+ out["coupling"] = self.coupling.to_config()
795
+ for name in _ANALYTIC:
796
+ if getattr(self, name) is not None:
797
+ out[name] = getattr(self, name).to_config()
798
+ return out
799
+
800
+ @classmethod
801
+ def from_config(cls, spec) -> Material:
802
+ """``"void"``, or a mapping with young/poisson or bulk/shear (isotropic), or
803
+ ``cubic: [c11, c12, c44]``, ``hexagonal: [c11, c12, c13, c33, c44]`` or
804
+ ``stiffness: 6 x 6`` (crystals); and/or ``conductivity`` (one value, three
805
+ principal values or a 3 x 3 tensor, in the axes of the crystal); and
806
+ ``expansion``, the thermal expansion (likewise), ``swelling``, the strain of a unit
807
+ content of an absorbed species (likewise), ``density``, ``plasticity``
808
+ (:meth:`~morphogen.homogenization.behaviours.Plasticity.from_config`),
809
+ ``porous_plasticity`` (:meth:`~morphogen.homogenization.porous.PorousPlasticity.
810
+ from_config`), ``crystal_plasticity`` (:meth:`~morphogen.homogenization.crystal.
811
+ CrystalPlasticity.from_config`), ``mfront`` (:meth:`~morphogen.homogenization.mfront.
812
+ MFrontBehaviour.from_config`) and ``learned`` (the file of a learned model,
813
+ :meth:`~morphogen.learning.behaviour.LearnedBehaviour.from_config`); or ``zmat``, a
814
+ material file of Z-mat (its path, or a
815
+ mapping ``file``, ``behaviour``, ``name``, ``native``, ``porosity``:
816
+ :func:`~morphogen.homogenization.zmat.zmat_material`), with a ``conductivity`` and a
817
+ ``density``."""
818
+ if isinstance(spec, Material):
819
+ return spec
820
+ if isinstance(spec, dict) and "zmat" in spec:
821
+ import dataclasses
822
+
823
+ from morphogen.homogenization.zmat import zmat_material
824
+
825
+ extra = sorted(set(spec) - {"zmat", "conductivity", "density"})
826
+ if extra:
827
+ raise ValueError(
828
+ f"zmat: the other keys of the material are {extra}; allowed "
829
+ "beside it: conductivity, density"
830
+ )
831
+ options = spec["zmat"]
832
+ options = {"file": options} if isinstance(options, str) else dict(options)
833
+ known = {"file", "behaviour", "name", "native", "directory", "porosity"}
834
+ unknown = sorted(set(options) - known)
835
+ if unknown or "file" not in options:
836
+ raise ValueError("zmat: a path, or {file, behaviour, name, native, porosity}")
837
+ base = zmat_material(options.pop("file"), **options)
838
+ values = {k: float(spec[k]) for k in ("conductivity", "density") if k in spec}
839
+ return dataclasses.replace(base, **values) if values else base
840
+ late = (
841
+ "expansion",
842
+ "swelling",
843
+ "density",
844
+ "plasticity",
845
+ "crystal_plasticity",
846
+ "mfront",
847
+ "learned",
848
+ "porous_plasticity",
849
+ "coupling",
850
+ "refractive_index",
851
+ *_ANALYTIC,
852
+ *(name for name in TRANSPORT.values() if name != "conductivity"),
853
+ )
854
+ if isinstance(spec, dict) and (set(late) & set(spec)):
855
+ import dataclasses
856
+
857
+ extra = {k: spec[k] for k in late if k in spec}
858
+ rest = {k: v for k, v in spec.items() if k not in extra}
859
+ if not rest: # a material of transport coefficients only
860
+ return cls(**extra)
861
+ base = cls.from_config(rest)
862
+ return dataclasses.replace(base, **extra)
863
+ if isinstance(spec, str):
864
+ if spec.strip().lower() in ("void", "pore", "pores", "empty"):
865
+ return VOID
866
+ raise ValueError(f"unknown material {spec!r}; use 'void' or a mapping of parameters")
867
+ if not isinstance(spec, dict):
868
+ raise ValueError(f"a material is 'void' or a mapping, got {spec!r}")
869
+ allowed = {
870
+ "young",
871
+ "poisson",
872
+ "bulk",
873
+ "shear",
874
+ "conductivity",
875
+ "expansion",
876
+ "swelling",
877
+ "density",
878
+ "plasticity",
879
+ "crystal_plasticity",
880
+ "mfront",
881
+ "learned",
882
+ "porous_plasticity",
883
+ "coupling",
884
+ "refractive_index",
885
+ *_ANALYTIC,
886
+ *TRANSPORT.values(),
887
+ }
888
+ crystal = {"cubic", "hexagonal", "stiffness"}
889
+ unknown = sorted(set(spec) - allowed - crystal)
890
+ if unknown:
891
+ raise ValueError(
892
+ f"material: unknown keys {unknown}; allowed: {sorted(allowed | crystal)}"
893
+ )
894
+ conductivity = spec.get("conductivity")
895
+ kinds = [k for k in crystal if k in spec]
896
+ if kinds:
897
+ if len(kinds) > 1 or set(spec) & {"young", "poisson", "bulk", "shear"}:
898
+ raise ValueError(
899
+ "material: give one of cubic, hexagonal, stiffness, young/poisson, bulk/shear"
900
+ )
901
+ values = spec[kinds[0]]
902
+ if kinds[0] == "cubic":
903
+ if len(values) != 3:
904
+ raise ValueError("cubic: [c11, c12, c44]")
905
+ return cls.cubic(*map(float, values), conductivity=conductivity)
906
+ if kinds[0] == "hexagonal":
907
+ if len(values) != 5:
908
+ raise ValueError("hexagonal: [c11, c12, c13, c33, c44]")
909
+ return cls.hexagonal(*map(float, values), conductivity=conductivity)
910
+ return cls.anisotropic(values, conductivity=conductivity)
911
+ if conductivity is not None and np.ndim(conductivity) > 0:
912
+ k, kt = _thermal(conductivity, uniaxial=False)
913
+ iso = {k2: float(v) for k2, v in spec.items() if k2 != "conductivity"}
914
+ if iso:
915
+ raise ValueError("material: an anisotropic conductivity needs a crystal stiffness")
916
+ return cls(conductivity=k, conductivities=kt)
917
+ values = {k: float(v) for k, v in spec.items()}
918
+ if "bulk" in values or "shear" in values:
919
+ if "young" in values or "poisson" in values:
920
+ raise ValueError("material: give young/poisson or bulk/shear, not both")
921
+ if not ("bulk" in values and "shear" in values):
922
+ raise ValueError("material: give both 'bulk' and 'shear'")
923
+ return cls.from_moduli(values["bulk"], values["shear"], values.get("conductivity"))
924
+ return cls(
925
+ young=values.get("young"),
926
+ poisson=values.get("poisson"),
927
+ conductivity=values.get("conductivity"),
928
+ )
929
+
930
+
931
+ def _thermal(conductivity, *, uniaxial: bool):
932
+ """(isotropic value, tensor) of a conductivity given as one value, principal values
933
+ (two for a uniaxial crystal: basal plane and axis), or a 3 x 3 tensor."""
934
+ if conductivity is None:
935
+ return None, None
936
+ c = np.asarray(conductivity, dtype=float)
937
+ if c.ndim == 0:
938
+ return float(c), None
939
+ if uniaxial and c.shape == (2,):
940
+ c = np.array([c[0], c[0], c[1]])
941
+ if c.shape == (3,):
942
+ if np.allclose(c, c[0]):
943
+ return float(c[0]), None
944
+ return None, np.diag(c)
945
+ if c.shape == (3, 3):
946
+ return None, c
947
+ raise ValueError("conductivity: one value, principal values or a 3 x 3 tensor")
948
+
949
+
950
+ VOID = Material(void=True)
951
+
952
+
953
+ def any_oriented(materials: dict[int, Material]) -> bool:
954
+ """Whether some material depends on the orientation of its grain (anisotropic
955
+ elasticity, conductivity or expansion, or slip systems): the grains and their
956
+ orientations are then needed."""
957
+ return any(not m.void and any(m.oriented(p) for p in PHYSICS) for m in materials.values())
958
+
959
+
960
+ def materials_from_config(spec) -> dict[int, Material]:
961
+ """Phase -> material mapping from a configuration mapping (keys may be strings)."""
962
+ if not isinstance(spec, dict) or not spec:
963
+ raise ValueError("materials: expected a mapping phase -> material")
964
+ out = {}
965
+ for key, value in spec.items():
966
+ try:
967
+ phase = int(key)
968
+ except (TypeError, ValueError):
969
+ raise ValueError(f"materials: phase keys must be integers, got {key!r}") from None
970
+ try:
971
+ out[phase] = Material.from_config(value)
972
+ except ValueError as exc:
973
+ raise ValueError(f"materials[{phase}]: {exc}") from None
974
+ return out
975
+
976
+
977
+ @dataclass(frozen=True)
978
+ class MaterialTable:
979
+ """Material of every element (voxel or tetrahedron) of a sample, for one physics.
980
+
981
+ ``mat[e]`` indexes ``matrices`` (-1 for voids): elasticity matrices (n, 6, 6) or
982
+ conductivity tensors (n, 3, 3) in the axes of the sample; one per phase, or one per
983
+ grain for the oriented phases of a polycrystal. ``stat[e]`` indexes ``phases``.
984
+ ``eigen`` (elasticity) holds the thermal strain of each material for a unit change of
985
+ temperature (Voigt order, engineering shears), ``rotations`` the orientation of each
986
+ material (``crystal = g @ sample``; the identity for the materials of the phases that
987
+ are not oriented).
988
+ """
989
+
990
+ mat: np.ndarray
991
+ stat: np.ndarray
992
+ matrices: np.ndarray
993
+ phases: tuple[int, ...]
994
+ isotropic: bool
995
+ eigen: np.ndarray | None = None
996
+ rotations: np.ndarray | None = None
997
+
998
+ @property
999
+ def active(self) -> np.ndarray:
1000
+ return self.mat >= 0
1001
+
1002
+
1003
+ def material_table(
1004
+ phase, materials: dict[int, Material], physics: str, *, grains=None, orientations=None
1005
+ ) -> MaterialTable:
1006
+ """Materials of the elements of phases ``phase`` for ``physics`` (:data:`PHYSICS`:
1007
+ 'elastic', or a transport phenomenon such as 'thermal' or 'electrical'). Crystals are
1008
+ turned by the orientation of their grain (``grains``: grain of each element,
1009
+ ``orientations``: Bunge angles of each grain); without them, their axes are those of
1010
+ the sample. The phases inert for the physics (voids, insulators:
1011
+ :meth:`Material.inert`) have no material (``mat`` -1)."""
1012
+ from morphogen.orientations import euler_to_matrix
1013
+
1014
+ transport = transport_physics(physics)
1015
+ phase = np.asarray(phase)
1016
+ if phase.dtype.kind not in "iub":
1017
+ raise ValueError("homogenization needs an integer phase image, not partial volumes")
1018
+ phase = phase.ravel().astype(np.int64)
1019
+ present = [int(v) for v in np.unique(phase)]
1020
+ missing = [p for p in present if p not in materials]
1021
+ if missing:
1022
+ raise ValueError(f"no material for phase(s) {missing}; phases present: {present}")
1023
+ phases = tuple(present)
1024
+ lookup = np.full(max(phases, default=0) + 1, -1, dtype=np.int64)
1025
+ lookup[list(phases)] = np.arange(len(phases))
1026
+ stat = lookup[phase]
1027
+ mat = np.full(phase.size, -1, dtype=np.int64)
1028
+ blocks, eigen, rotations, count, isotropic = [], [], [], 0, True
1029
+ oriented = grains is not None and orientations is not None
1030
+ for p in phases:
1031
+ m = materials[p]
1032
+ if m.inert(physics):
1033
+ continue
1034
+ if not transport and not m.elastic:
1035
+ raise ValueError(f"phase {p}: the material has no elastic parameters")
1036
+ if transport and not m.has(physics):
1037
+ raise ValueError(f"phase {p}: the material has no {TRANSPORT[physics]}")
1038
+ sel = np.flatnonzero(phase == p)
1039
+ # an MFront behaviour may be orthotropic (a crystal) whatever the elastic parameters
1040
+ # of its material: its grains keep their rotations (unused by isotropic behaviours)
1041
+ mfront = physics == "elastic" and m.mfront is not None
1042
+ if m.oriented(physics) or mfront:
1043
+ if m.oriented(physics):
1044
+ isotropic = False
1045
+ if oriented:
1046
+ ids, inverse = np.unique(np.asarray(grains).ravel()[sel], return_inverse=True)
1047
+ euler = np.asarray(orientations, dtype=float)[ids]
1048
+ blocks.append(m.matrix(physics, euler))
1049
+ eigen.append(m.expansion_tensor(euler))
1050
+ rotations.append(euler_to_matrix(euler).reshape(-1, 3, 3))
1051
+ mat[sel] = count + inverse
1052
+ count += len(ids)
1053
+ continue
1054
+ if m.oriented(physics):
1055
+ log.info("phase %d: crystal axes along the axes of the sample (no orientations)",
1056
+ p) # fmt: skip
1057
+ blocks.append(m.matrix(physics)[None])
1058
+ eigen.append(m.expansion_tensor()[None])
1059
+ rotations.append(np.eye(3)[None])
1060
+ mat[sel] = count
1061
+ count += 1
1062
+ d = 3 if transport else 6
1063
+ matrices = np.concatenate(blocks) if blocks else np.zeros((0, d, d))
1064
+ strains = None
1065
+ if not transport:
1066
+ from morphogen.homogenization.elements import tensor_to_voigt
1067
+
1068
+ a = np.concatenate(eigen) if eigen else np.zeros((0, 3, 3))
1069
+ strains = np.array([tensor_to_voigt(t, strain=True) for t in a]).reshape(-1, 6)
1070
+ return MaterialTable(
1071
+ mat=mat,
1072
+ stat=stat,
1073
+ matrices=np.ascontiguousarray(matrices),
1074
+ phases=phases,
1075
+ isotropic=isotropic,
1076
+ eigen=None if strains is None else np.ascontiguousarray(strains),
1077
+ rotations=np.ascontiguousarray(
1078
+ np.concatenate(rotations) if rotations else np.zeros((0, 3, 3))
1079
+ ),
1080
+ )