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,1046 @@
1
+ """Apparent properties of a volume element (Kanit et al. 2003; Dirrenberger et al. 2014).
2
+
3
+ Scalar properties follow Dirrenberger et al. (2014), sections 3.5 and 4:
4
+
5
+ ``bulk_modulus``
6
+ hydrostatic strain ``E = 1`` (eq. 63): ``k = tr(Sigma) / 9`` (eq. 70); the energy
7
+ estimate is ``<sigma : eps> / 9`` (eq. 64). Under SUBC, ``Sigma = 1`` is imposed and
8
+ ``k = 1 / tr(E)``.
9
+ ``shear_modulus``
10
+ simple shear ``E_12 = E_21 = 1/2`` (eq. 65): ``mu = Sigma_12`` (eq. 71); the energy
11
+ estimate is ``<sigma : eps>`` (eq. 66). Under SUBC, ``Sigma_12 = 1`` and
12
+ ``mu = 1 / (2 E_12)``.
13
+ ``conductivity``
14
+ gradient ``G = e_1`` (eq. 60): ``k = -Q_1`` with ``q = -k grad T`` (eq. 68); the
15
+ energy estimate is ``<k grad T . grad T>`` (eq. 61). Under UHF (``subc``), ``Q = -e_1``
16
+ and ``k = 1 / G_1``.
17
+ ``electrical_conductivity``, ``permittivity``, ``permeability``, ``diffusivity``
18
+ the same problem for the other transport phenomena of a scalar potential
19
+ (:data:`TRANSPORT_PROPERTIES`): Ohm's law, electrostatics, magnetostatics and Fick's
20
+ law, each with the coefficient of the materials for it
21
+ (:data:`~morphogen.homogenization.materials.TRANSPORT`).
22
+
23
+ With voids, averages are taken over the whole box with zero stress and flux in the
24
+ voids (eqs. 24 and 29). Each result also carries the isotropy criterion of the
25
+ realization (eqs. 72-74), computed on its macroscopic response.
26
+
27
+ Tensors: the stiffness (six loadings), the conductivity tensor (three; that of each
28
+ transport phenomenon, ``<property>_tensor``), and the thermal
29
+ expansion ``A`` of ``E = S : Sigma + A dT``: the macroscopic strain of a unit change of
30
+ temperature without macroscopic stress (a stress-controlled loading, see
31
+ :func:`morphogen.homogenization.core.superpose`).
32
+
33
+ Loading paths (:class:`~morphogen.homogenization.paths.LoadingPath`) follow the
34
+ nonlinear behaviours of the phases in time: by finite elements with periodic or
35
+ kinematic conditions (:mod:`morphogen.homogenization.nonlinear`), or by the FFT solver of
36
+ voxel images with periodic conditions (:mod:`morphogen.homogenization.fft_nonlinear`).
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ from dataclasses import dataclass
43
+
44
+ import numpy as np
45
+
46
+ from morphogen.homogenization.core import VOIGT_NAMES, Loading, Solution, boundary_condition
47
+ from morphogen.homogenization.coupled import COUPLINGS, coupled_tensors
48
+ from morphogen.homogenization.elements import VOIGT, tensor_to_voigt
49
+ from morphogen.homogenization.fe import FEElasticProblem, FEThermalProblem, integration_of
50
+ from morphogen.homogenization.fft import FFTElasticProblem, FFTThermalProblem
51
+ from morphogen.homogenization.fft_nonlinear import NonlinearFFTProblem
52
+ from morphogen.homogenization.materials import TRANSPORT, Material, transport_physics
53
+ from morphogen.homogenization.nonlinear import NonlinearFEProblem
54
+ from morphogen.homogenization.paths import LoadingPath, PathResult
55
+ from morphogen.homogenization.postprocess import anisotropy, compliance, engineering_constants
56
+ from morphogen.homogenization.xfem import (
57
+ LevelSetSample,
58
+ NonlinearXFEMProblem,
59
+ XFEMElasticProblem,
60
+ XFEMThermalProblem,
61
+ )
62
+ from morphogen.image import VoxelImage
63
+ from morphogen.mesh.tetra import TetMesh
64
+ from morphogen.stopping import checkpoint
65
+
66
+ log = logging.getLogger("morphogen")
67
+
68
+ #: The apparent scalar property and tensor of each transport phenomenon (the coefficient
69
+ #: of the materials for it: :data:`~morphogen.homogenization.materials.TRANSPORT`)
70
+ TRANSPORT_PROPERTIES = {physics: (name, f"{name}_tensor") for physics, name in TRANSPORT.items()}
71
+ _OTHERS = [names for physics, names in TRANSPORT_PROPERTIES.items() if physics != "thermal"]
72
+ #: The scalar properties: one value per realization and boundary condition
73
+ PROPERTIES = ("bulk_modulus", "shear_modulus", "conductivity", *(s for s, _ in _OTHERS))
74
+ #: The tensors (``swelling``: that of the strains of an absorbed species; ``poroelastic``:
75
+ #: the drained stiffness, the tensor and the modulus of Biot of a porous sample:
76
+ #: :mod:`morphogen.homogenization.poroelastic`)
77
+ TENSORS = (
78
+ "stiffness",
79
+ "conductivity_tensor",
80
+ "thermal_expansion",
81
+ *(t for _, t in _OTHERS),
82
+ "swelling",
83
+ "poroelastic",
84
+ )
85
+ #: The strong couplings (:mod:`morphogen.homogenization.coupled`): each gives the tensors of
86
+ #: its coupled law (``piezoelectric``: the stiffness, the piezoelectric matrix and the
87
+ #: permittivity, with the constants derived from them)
88
+ COUPLED = tuple(COUPLINGS)
89
+ #: The properties of a harmonic regime (:mod:`morphogen.homogenization.harmonic`): the
90
+ #: complex stiffness of viscoelastic phases and the complex conductivity of leaky
91
+ #: dielectrics at the ``frequencies`` of :func:`homogenize`, the effective refractive
92
+ #: index at its ``wavelengths``
93
+ HARMONIC = ("dynamic_stiffness", "complex_conductivity", "refractive_index")
94
+ #: The properties of the flow of a fluid through the pores (the void phases) of a voxel
95
+ #: image: ``hydraulic_permeability``, the tensor of Darcy's law
96
+ #: (:mod:`morphogen.homogenization.flow`), and ``acoustic``, the parameters of the
97
+ #: equivalent fluid of a rigid porous frame (:mod:`morphogen.homogenization.acoustics`)
98
+ FLOW = ("hydraulic_permeability", "acoustic")
99
+ #: The physics of the problem that gives each property (``"coupled"``: the fields of a
100
+ #: strong coupling solved together; ``"harmonic"``: a complex law at each frequency)
101
+ PHYSICS = {
102
+ "bulk_modulus": "elastic",
103
+ "shear_modulus": "elastic",
104
+ "stiffness": "elastic",
105
+ "thermal_expansion": "elastic",
106
+ "swelling": "elastic",
107
+ "poroelastic": "elastic",
108
+ **{name: physics for physics, names in TRANSPORT_PROPERTIES.items() for name in names},
109
+ **dict.fromkeys(COUPLED, "coupled"),
110
+ **dict.fromkeys(HARMONIC, "harmonic"),
111
+ **dict.fromkeys(FLOW, "flow"),
112
+ }
113
+
114
+
115
+ def bulk_isotropy(tensor) -> float:
116
+ """sqrt(T:K:T / T:J:T) (eq. 73): zero for a purely spherical response."""
117
+ t = np.asarray(tensor, dtype=float)
118
+ tr = np.trace(t)
119
+ dev = t - tr / 3.0 * np.eye(3)
120
+ sph = tr * tr / 3.0
121
+ return float(np.sqrt(np.sum(dev * dev) / sph)) if sph > 0 else float("nan")
122
+
123
+
124
+ def shear_isotropy(tensor) -> float:
125
+ """sqrt(T:J:T / T:K:T) (eq. 74): zero for a purely deviatoric response."""
126
+ t = np.asarray(tensor, dtype=float)
127
+ tr = np.trace(t)
128
+ dev = t - tr / 3.0 * np.eye(3)
129
+ dd = float(np.sum(dev * dev))
130
+ return float(np.sqrt(tr * tr / 3.0 / dd)) if dd > 0 else float("nan")
131
+
132
+
133
+ def thermal_isotropy(vector, axis: int = 0) -> float:
134
+ """``(|Q_2| + |Q_3|) / |Q_1|`` for a loading along ``axis`` (eq. 72)."""
135
+ v = np.abs(np.asarray(vector, dtype=float))
136
+ return float((v.sum() - v[axis]) / v[axis]) if v[axis] > 0 else float("nan")
137
+
138
+
139
+ @dataclass
140
+ class Apparent:
141
+ """Apparent property of one volume element for one boundary condition."""
142
+
143
+ property: str
144
+ bc: str
145
+ value: float
146
+ energy: float
147
+ isotropy: float
148
+ response: np.ndarray
149
+ solution: Solution
150
+
151
+ def row(self) -> dict:
152
+ """Flat record (long format) with the response components and solver data."""
153
+ out = {
154
+ "property": self.property,
155
+ "bc": self.bc,
156
+ "value": self.value,
157
+ "energy_value": self.energy,
158
+ "isotropy": self.isotropy,
159
+ "material_fraction": self.solution.material_fraction,
160
+ }
161
+ r = np.asarray(self.response)
162
+ if r.shape == (3, 3):
163
+ for (a, b), name in zip(VOIGT, ("11", "22", "33", "23", "31", "12"), strict=True):
164
+ out[f"R{name}"] = float(r[a, b])
165
+ else:
166
+ for d in range(3):
167
+ out[f"R{d + 1}"] = float(r[d])
168
+ out.update(self.solution.info.to_dict())
169
+ return out
170
+
171
+
172
+ @dataclass
173
+ class Response:
174
+ """Macroscopic response of a volume element to a named loading for one boundary
175
+ condition: the macroscopic strain and stress (gradient and flux), prescribed or
176
+ solved for."""
177
+
178
+ name: str
179
+ bc: str
180
+ solution: Solution
181
+
182
+ def components(self) -> dict[str, float]:
183
+ """``E11 ... E12`` (engineering shears) and ``S11 ... S12``, or ``G1 ... G3``
184
+ and ``Q1 ... Q3``, and the energy."""
185
+ sol = self.solution
186
+ if sol.physics == "elastic":
187
+ e = tensor_to_voigt(sol.strain, strain=True)
188
+ s = tensor_to_voigt(sol.stress, strain=False)
189
+ out = {f"E{n}": float(v) for n, v in zip(VOIGT_NAMES, e, strict=True)}
190
+ out.update({f"S{n}": float(v) for n, v in zip(VOIGT_NAMES, s, strict=True)})
191
+ else:
192
+ out = {f"G{d + 1}": float(sol.strain[d]) for d in range(3)}
193
+ out.update({f"Q{d + 1}": float(sol.stress[d]) for d in range(3)})
194
+ out["energy"] = float(sol.energy)
195
+ return out
196
+
197
+ def row(self) -> dict:
198
+ """Flat record (long format) with the components and solver data."""
199
+ out = {"property": self.name, "bc": self.bc, **self.components()}
200
+ out["material_fraction"] = self.solution.material_fraction
201
+ out.update(self.solution.info.to_dict())
202
+ return out
203
+
204
+
205
+ def _shear_planes(plane) -> tuple[int, int]:
206
+ a, b = sorted(int(x) for x in plane)
207
+ if a == b or not (0 <= a < 3 and 0 <= b < 3):
208
+ raise ValueError(f"shear plane: two different axes in 0..2, got {plane!r}")
209
+ return a, b
210
+
211
+
212
+ def apparent_bulk_modulus(problem, *, fields: bool = False) -> Apparent:
213
+ """The apparent bulk modulus of a problem under its boundary conditions (:class:`Apparent`):
214
+ under a hydrostatic strain, or a hydrostatic stress with static uniform conditions
215
+ (``subc``); the fields of the solution with ``fields``."""
216
+ if problem.bc == "subc":
217
+ sol = problem.solve(Loading.stress(np.eye(3)), fields=fields)
218
+ tr = float(np.trace(sol.strain))
219
+ return Apparent(
220
+ "bulk_modulus",
221
+ problem.bc,
222
+ 1.0 / tr,
223
+ 1.0 / sol.energy,
224
+ bulk_isotropy(sol.strain),
225
+ sol.strain,
226
+ sol,
227
+ )
228
+ sol = problem.solve(Loading.strain(np.eye(3)), fields=fields)
229
+ return Apparent(
230
+ "bulk_modulus",
231
+ problem.bc,
232
+ float(np.trace(sol.stress) / 9.0),
233
+ sol.energy / 9.0,
234
+ bulk_isotropy(sol.stress),
235
+ sol.stress,
236
+ sol,
237
+ )
238
+
239
+
240
+ def apparent_shear_modulus(problem, plane=(0, 1), *, fields: bool = False) -> Apparent:
241
+ """The apparent shear modulus of a problem in a plane (its two axes; :class:`Apparent`): under a
242
+ shear strain in it, or a shear stress with static uniform conditions (``subc``); the fields
243
+ of the solution with ``fields``."""
244
+ a, b = _shear_planes(plane)
245
+ t = np.zeros((3, 3))
246
+ if problem.bc == "subc":
247
+ t[a, b] = t[b, a] = 1.0
248
+ sol = problem.solve(Loading.stress(t), fields=fields)
249
+ return Apparent(
250
+ "shear_modulus",
251
+ problem.bc,
252
+ float(1.0 / (2.0 * sol.strain[a, b])),
253
+ 1.0 / sol.energy,
254
+ shear_isotropy(sol.strain),
255
+ sol.strain,
256
+ sol,
257
+ )
258
+ t[a, b] = t[b, a] = 0.5
259
+ sol = problem.solve(Loading.strain(t), fields=fields)
260
+ return Apparent(
261
+ "shear_modulus",
262
+ problem.bc,
263
+ float(sol.stress[a, b]),
264
+ sol.energy,
265
+ shear_isotropy(sol.stress),
266
+ sol.stress,
267
+ sol,
268
+ )
269
+
270
+
271
+ def apparent_conductivity(problem, axis: int = 0, *, fields: bool = False) -> Apparent:
272
+ """The apparent conductivity of a problem along an axis (:class:`Apparent`): under a gradient
273
+ along it, or a flux with static uniform conditions (``subc``); the fields of the solution
274
+ with ``fields``. The problem of another transport phenomenon gives its property
275
+ (:data:`TRANSPORT_PROPERTIES`: the apparent electrical conductivity, permittivity,
276
+ permeability or diffusivity)."""
277
+ e = np.zeros(3)
278
+ e[axis] = 1.0
279
+ name = TRANSPORT_PROPERTIES[problem.physics][0]
280
+ if problem.bc == "subc":
281
+ sol = problem.solve(Loading.flux(-e, physics=problem.physics), fields=fields)
282
+ return Apparent(
283
+ name,
284
+ problem.bc,
285
+ float(1.0 / sol.strain[axis]),
286
+ 1.0 / sol.energy,
287
+ thermal_isotropy(sol.strain, axis),
288
+ sol.strain,
289
+ sol,
290
+ )
291
+ sol = problem.solve(Loading.gradient(e, physics=problem.physics), fields=fields)
292
+ return Apparent(
293
+ name,
294
+ problem.bc,
295
+ float(-sol.stress[axis]) + 0.0,
296
+ sol.energy,
297
+ thermal_isotropy(sol.stress, axis),
298
+ sol.stress,
299
+ sol,
300
+ )
301
+
302
+
303
+ def stiffness_tensor(problem) -> tuple[np.ndarray, list[Solution]]:
304
+ """Apparent stiffness (6 x 6, Voigt order 11 22 33 23 31 12) from six loadings.
305
+
306
+ KUBC and periodic conditions impose the six unit strains (Dirrenberger et al. 2014,
307
+ appendix A); SUBC impose the six unit stresses and the compliance is inverted.
308
+ """
309
+ if problem.bc == "mixed":
310
+ raise ValueError("the full stiffness tensor is defined for kubc, periodic or subc")
311
+ c = np.zeros((6, 6))
312
+ sols = []
313
+ for j in range(6):
314
+ unit = np.zeros(6)
315
+ unit[j] = 1.0
316
+ if problem.bc == "subc":
317
+ sol = problem.solve(Loading.stress(unit))
318
+ c[:, j] = tensor_to_voigt(sol.strain, strain=True)
319
+ else:
320
+ sol = problem.solve(Loading.strain(unit))
321
+ c[:, j] = tensor_to_voigt(sol.stress, strain=False)
322
+ sols.append(sol)
323
+ if problem.bc == "subc":
324
+ c = np.linalg.inv(c)
325
+ return 0.5 * (c + c.T), sols
326
+
327
+
328
+ def thermal_expansion(problem) -> tuple[np.ndarray, Solution]:
329
+ """Apparent thermal expansion tensor (3 x 3): the macroscopic strain of a unit change
330
+ of temperature under zero macroscopic stress (``E = S : Sigma + A dT``)."""
331
+ if problem.bc == "mixed":
332
+ raise ValueError("the thermal expansion is defined for kubc, periodic or subc")
333
+ sol = problem.solve(Loading.stress(np.zeros(6), temperature=1.0))
334
+ return 0.5 * (sol.strain + sol.strain.T), sol
335
+
336
+
337
+ def conductivity_tensor(problem) -> tuple[np.ndarray, list[Solution]]:
338
+ """Apparent conductivity tensor (3 x 3) from three gradient (or flux) loadings; that
339
+ of the transport phenomenon of the problem (:data:`TRANSPORT_PROPERTIES`)."""
340
+ if problem.bc == "mixed":
341
+ raise ValueError("the conductivity tensor is defined for kubc, periodic or subc")
342
+ k = np.zeros((3, 3))
343
+ sols = []
344
+ for d in range(3):
345
+ e = np.zeros(3)
346
+ e[d] = 1.0
347
+ if problem.bc == "subc":
348
+ sol = problem.solve(Loading.flux(-e, physics=problem.physics))
349
+ k[:, d] = sol.strain
350
+ else:
351
+ sol = problem.solve(Loading.gradient(e, physics=problem.physics))
352
+ k[:, d] = -sol.stress
353
+ sols.append(sol)
354
+ if problem.bc == "subc":
355
+ k = np.linalg.inv(k)
356
+ return 0.5 * (k + k.T), sols
357
+
358
+
359
+ def isotropic_projection(stiffness) -> tuple[float, float]:
360
+ """Bulk and shear moduli of the isotropic part of a Voigt stiffness matrix."""
361
+ c = np.asarray(stiffness, dtype=float)
362
+ d = c[0, 0] + c[1, 1] + c[2, 2]
363
+ o = c[0, 1] + c[0, 2] + c[1, 2]
364
+ s = c[3, 3] + c[4, 4] + c[5, 5]
365
+ return (d + 2.0 * o) / 9.0, (d - o + 3.0 * s) / 15.0
366
+
367
+
368
+ def isotropy_errors(stiffness) -> dict[str, float]:
369
+ """Relative deviations from isotropy of a Voigt stiffness (Dirrenberger 2014, 5.1.4).
370
+
371
+ ``normal``: spread of C11, C22, C33; ``coupling``: of C12, C13, C23; ``shear``: of
372
+ C44, C55, C66; ``cauchy``: ``|C44 - (C11 - C12)/2| / C44`` with mean values; ``other``:
373
+ largest remaining component relative to the mean of C11, C22, C33.
374
+ """
375
+ c = np.asarray(stiffness, dtype=float)
376
+
377
+ def spread(values):
378
+ v = np.asarray(values)
379
+ m = v.mean()
380
+ return float(np.max(np.abs(v - m)) / abs(m)) if m != 0 else float("nan")
381
+
382
+ diag = [c[0, 0], c[1, 1], c[2, 2]]
383
+ coup = [c[0, 1], c[0, 2], c[1, 2]]
384
+ shear = [c[3, 3], c[4, 4], c[5, 5]]
385
+ mask = np.ones((6, 6), dtype=bool)
386
+ mask[:3, :3] = False
387
+ mask[[3, 4, 5], [3, 4, 5]] = False
388
+ return {
389
+ "normal": spread(diag),
390
+ "coupling": spread(coup),
391
+ "shear": spread(shear),
392
+ "cauchy": float(abs(np.mean(shear) - (np.mean(diag) - np.mean(coup)) / 2) / np.mean(shear)),
393
+ "other": float(np.max(np.abs(c[mask])) / np.mean(diag)),
394
+ }
395
+
396
+
397
+ def _cpu_only(device: str) -> None:
398
+ """Finite elements run on the CPU: ``device`` may be ``"cpu"`` or ``"auto"``."""
399
+ if device not in ("cpu", "auto"):
400
+ raise ValueError(
401
+ f"device {device!r}: the GPU runs the FFT solvers of voxel images; finite "
402
+ "elements run on the CPU"
403
+ )
404
+
405
+
406
+ def make_problem(
407
+ sample,
408
+ materials: dict[int, Material],
409
+ physics: str,
410
+ bc: str = "periodic",
411
+ *,
412
+ solver: str = "auto",
413
+ tol: float = 1e-8,
414
+ maxiter: int | None = None,
415
+ grains=None,
416
+ orientations=None,
417
+ device: str = "cpu",
418
+ integration: str | None = None,
419
+ ):
420
+ """Boundary-value problem of a sample for ``physics`` 'elastic', 'thermal' or another
421
+ transport phenomenon of a scalar potential (:data:`~morphogen.homogenization.materials.
422
+ TRANSPORT`: 'electrical', 'dielectric', 'magnetic', 'diffusion'), which the thermal
423
+ problems solve with the coefficient of the materials for it.
424
+
425
+ A :class:`~morphogen.mesh.tetra.TetMesh` (conforming mesh) is solved by finite
426
+ elements, with any boundary condition; a :class:`~morphogen.image.VoxelImage` by
427
+ the FFT solver, with periodic conditions; a :class:`~morphogen.homogenization.xfem.
428
+ LevelSetSample` (the level set of a morphology on a regular grid) by extended finite
429
+ elements, with periodic conditions. ``solver`` is the linear solver of the
430
+ finite element problems (see :mod:`morphogen.homogenization.solvers`), or ``"fenicsx"``
431
+ to assemble and solve them by FEniCSx (:mod:`morphogen.homogenization.fenicsx`); ``device``
432
+ that of the FFT solver (``"cpu"``, ``"gpu"`` or ``"auto"``, see :mod:`morphogen.gpu`).
433
+ ``integration`` (elastic problems on a mesh of 10-node tetrahedra): ``"full"``, or
434
+ ``"bbar"``, the volume change of each element as its mean, for nearly incompressible
435
+ phases (:mod:`morphogen.homogenization.dilatation`).
436
+
437
+ Crystals (anisotropic materials) are turned by the orientation of their grain: the
438
+ grains and orientations of a polycrystal mesh (``mesh.cell``, ``mesh.orientations``),
439
+ or, for a voxel image, ``grains`` (image or array of grain labels, e.g.
440
+ ``tessellation.labels(...)``) and ``orientations`` (Bunge angles of each grain).
441
+ """
442
+ elastic = not transport_physics(physics)
443
+ if isinstance(sample, LevelSetSample):
444
+ if grains is not None or orientations is not None:
445
+ raise ValueError("XFEM: two phases without grains (no orientations)")
446
+ _cpu_only(device)
447
+ if solver == "fenicsx":
448
+ raise ValueError("solver 'fenicsx' solves conforming tetrahedral meshes")
449
+ cls = XFEMElasticProblem if elastic else XFEMThermalProblem
450
+ return cls(sample, materials, bc, solver=solver, tol=tol, maxiter=maxiter, physics=physics)
451
+ if isinstance(sample, TetMesh):
452
+ if grains is not None or orientations is not None:
453
+ raise ValueError("a mesh carries its own grains and orientations (mesh.cell)")
454
+ _cpu_only(device)
455
+ if solver == "fenicsx":
456
+ from morphogen.homogenization.fenicsx import (
457
+ FenicsxElasticProblem,
458
+ FenicsxThermalProblem,
459
+ )
460
+
461
+ cls = FenicsxElasticProblem if elastic else FenicsxThermalProblem
462
+ if integration_of(integration) != "full":
463
+ raise ValueError("integration 'bbar': the solvers of morphoGen, not 'fenicsx'")
464
+ else:
465
+ cls = FEElasticProblem if elastic else FEThermalProblem
466
+ options = {"integration": integration_of(integration)} if elastic else {}
467
+ if solver == "fenicsx":
468
+ options = {}
469
+ return cls(
470
+ sample, materials, bc, solver=solver, tol=tol, maxiter=maxiter, physics=physics,
471
+ **options,
472
+ ) # fmt: skip
473
+ if isinstance(sample, VoxelImage):
474
+ if solver == "fenicsx":
475
+ raise ValueError(
476
+ "solver 'fenicsx' solves tetrahedral meshes: mesh the image "
477
+ "(morphogen.mesh.conforming) or solve it by FFT"
478
+ )
479
+ cls = FFTElasticProblem if elastic else FFTThermalProblem
480
+ return cls(
481
+ sample,
482
+ materials,
483
+ bc,
484
+ tol=tol,
485
+ maxiter=maxiter,
486
+ grains=grains,
487
+ orientations=orientations,
488
+ device=device,
489
+ physics=physics,
490
+ )
491
+ raise TypeError(
492
+ "homogenization needs a TetMesh (finite elements, see morphogen.mesh.conforming), a "
493
+ "VoxelImage (FFT solver) or a LevelSetSample (extended finite elements), got "
494
+ f"{type(sample).__name__}"
495
+ )
496
+
497
+
498
+ def homogenize(
499
+ sample,
500
+ materials: dict[int, Material],
501
+ *,
502
+ bcs=("periodic",),
503
+ properties=("bulk_modulus", "shear_modulus"),
504
+ solver: str = "auto",
505
+ tol: float = 1e-8,
506
+ maxiter: int | None = None,
507
+ fields: bool = False,
508
+ grains=None,
509
+ orientations=None,
510
+ loadings: dict | None = None,
511
+ paths: dict | None = None,
512
+ nonlinear: dict | None = None,
513
+ device: str = "cpu",
514
+ ntfa: dict | None = None,
515
+ mean_temperature: float = 300.0,
516
+ frequencies=None,
517
+ wavelengths=None,
518
+ fracture=None,
519
+ fluid_bulk_modulus: float | None = None,
520
+ integration: str | None = None,
521
+ ) -> dict[str, Apparent | Response | PathResult | dict]:
522
+ """Apparent properties of ``sample`` for every pair (property, boundary condition).
523
+
524
+ ``sample`` is a conforming tetrahedral mesh (finite elements: ``kubc``, ``mixed``,
525
+ ``periodic`` and ``subc`` conditions), a voxel image (FFT solver: ``periodic``
526
+ only) or the level set of a morphology on a regular grid (:class:`~morphogen.
527
+ homogenization.xfem.LevelSetSample`: extended finite elements, ``periodic`` only, whose
528
+ interfaces cut the elements). Returns a mapping ``"<property>.<bc>"`` ->
529
+ :class:`Apparent` (:data:`PROPERTIES`:
530
+ the bulk and shear moduli, and the property of each transport phenomenon:
531
+ ``conductivity``, ``electrical_conductivity``, ``permittivity``, ``permeability``,
532
+ ``diffusivity``); the tensors (:data:`TENSORS`: ``stiffness``, ``thermal_expansion``,
533
+ ``conductivity_tensor`` and the ``<property>_tensor`` of the other transports) map to
534
+ ``{"tensor": array, ...}``, the stiffness with its ``compliance`` (``S = C^-1``, in the same
535
+ notation: Voigt order 11 22 33 23 31 12 with engineering shears,
536
+ :data:`morphogen.homogenization.postprocess.NOTATION`), its engineering constants and
537
+ anisotropy indices. ``loadings`` (name -> :class:`Loading`, or a mapping for
538
+ :meth:`Loading.from_spec`) are solved too: ``"<name>.<bc>"`` -> :class:`Response`.
539
+ Problems sharing a boundary condition reuse the assembled system and the unit
540
+ solutions. With ``fields``, the solutions keep the element fields (strain/stress or
541
+ gradient/flux). ``grains`` and ``orientations``: crystal orientations of a voxel
542
+ image (see :func:`make_problem`); ``device``: that of the FFT solver of an image
543
+ (``"cpu"``, ``"gpu"`` or ``"auto"``, see :mod:`morphogen.gpu`).
544
+
545
+ ``paths`` (name -> :class:`LoadingPath`, or a mapping for
546
+ :meth:`LoadingPath.from_spec`) are followed in time with the nonlinear behaviours of
547
+ the materials, under periodic and kinematic conditions (finite elements) or periodic
548
+ ones (FFT): ``"<name>.<bc>"`` -> :class:`PathResult`; ``nonlinear``: options of
549
+ :class:`NonlinearFEProblem` and :class:`NonlinearFFTProblem` (``newton_tol``,
550
+ ``max_newton``, ``max_cuts``, ``kinematics``: ``"small"`` or ``"finite"`` strains;
551
+ ``integration``: ``"bbar"`` or ``"full"``; ``tangent``: ``"auto"``,
552
+ ``"symmetric"`` or ``"full"``, the consistent tangents of the points symmetrized for
553
+ the conjugate gradients or kept whole for GMRES; ``contact``: True, or a mapping of
554
+ the options ``friction``, ``stiffness``, ``tangential``, ``depth``, ``augmentations``
555
+ and ``tolerance`` of :class:`~morphogen.contact.periodic.ContactCell`: on the mesh
556
+ of the solid of a porous sample, the walls of the pores that close along a path
557
+ press on each other, and on their images across the faces of a periodic cell, with
558
+ Coulomb's friction — in finite strains unless ``kinematics`` says otherwise, the
559
+ tangent factorized; the curves of the paths get the columns ``contact_area``,
560
+ ``contact_pressure``, ``contact_penetration`` and ``contact_dissipation``;
561
+ ``interfaces``: a mapping of the law of the interfaces of the phases of a mesh
562
+ (:func:`~morphogen.fracture.periodic.interface_law`: ``law``, ``normal_strength``,
563
+ ``mode_I``, ``friction``...), of the ``faces`` that are interfaces (``"phases"``,
564
+ ``"grains"`` or pairs of phases), of the ``viscosity`` of their regularization and
565
+ of the elastic ``slip`` of their friction; ``laws`` in the place of a law: one for
566
+ each pair of phases, ``{"0-1": {...}, "0-2": {...}}``:
567
+ :class:`~morphogen.fracture.periodic.CohesiveCell`, whose interfaces open, break,
568
+ close again and rub along a path, the tangent factorized; the curves get the columns
569
+ ``debonded_area``, ``interface_damage``, ``interface_opening`` and
570
+ ``interface_dissipation``; ``microdamage``: a mapping of the options of the
571
+ alternate scheme of the microdamage of regularized cleavage planes, its
572
+ ``tolerance``, the most ``passes`` of a step and its ``acceleration``
573
+ (:meth:`~morphogen.homogenization.nonlinear._PathSolver.microdamage_options`)).
574
+
575
+ ``integration``: ``"full"`` integrates the strain energy at every point of the
576
+ elements; ``"bbar"`` (also ``"reduced"``) takes the volume change of each element as
577
+ its mean — selective reduced integration, ``B``-bar in small strains and ``F``-bar in
578
+ finite strains (:mod:`morphogen.homogenization.dilatation`) —, which keeps the
579
+ elements from locking when a phase is nearly incompressible (elastomers: Poisson's
580
+ ratio near 1/2) or flows plastically. On a mesh of 10-node tetrahedra it applies to
581
+ the elastic problems and to the loading paths (default ``"full"``); on a voxel image,
582
+ to the loading paths (default ``"bbar"``: the linear FFT solver integrates its voxels
583
+ at every point).
584
+ With ``fields``, their element (voxel) fields are kept at the end of each segment
585
+ (``fields="steps"``: of each step, the other solutions keeping their fields).
586
+
587
+ The strong couplings (:data:`COUPLED`: ``piezoelectric``, ``piezomagnetic``,
588
+ ``magnetoelectroelastic``, ``magnetoelectric``, ``thermoelectric``) are properties too:
589
+ the fields of each are solved together on a voxel image, under periodic conditions
590
+ (:mod:`morphogen.homogenization.coupled`), with the coupling coefficients of the
591
+ materials (``Material(coupling=...)``), and ``"<coupling>.periodic"`` maps to the
592
+ tensors of the effective coupled law and the constants derived from them
593
+ (:func:`~morphogen.homogenization.coupled.split_law`); ``mean_temperature``: the mean
594
+ absolute temperature of the thermoelectric law (K).
595
+
596
+ The properties of a harmonic regime (:data:`HARMONIC`, voxel images;
597
+ :mod:`morphogen.homogenization.harmonic`): ``dynamic_stiffness``, the complex stiffness
598
+ of viscoelastic phases, and ``complex_conductivity``, that of leaky dielectrics
599
+ (``sigma + i omega eps``), at the angular ``frequencies``; ``refractive_index``, the
600
+ effective index of the ``refractive_index`` of the materials at the ``wavelengths``
601
+ (the long-wavelength limit of optics). ``"<property>.periodic"`` maps to the storage
602
+ and loss parts of the tensors at each frequency and their scalar entries
603
+ (:meth:`~morphogen.homogenization.harmonic.HarmonicResponse.to_dict`).
604
+
605
+ ``fracture`` (voxel images; a :class:`~morphogen.fracture.phasefield.PhaseField`, or
606
+ a mapping of its parameters with the options ``staggered_tol`` and ``max_staggered``
607
+ of its solver): the ``paths`` are followed by the phase-field method of brittle
608
+ fracture (:mod:`morphogen.fracture.phasefield`), the phases elastic, and
609
+ ``"<name>.periodic"`` maps to a :class:`~morphogen.fracture.phasefield.
610
+ PhaseFieldResult`, whose quantities ``strength`` and ``work`` are those of the
611
+ statistics of representative volumes.
612
+
613
+ The flow of a fluid through the pores (:data:`FLOW`; voxel images of cubic voxels,
614
+ the pores their void phases): ``hydraulic_permeability``, the permeability tensor of
615
+ Darcy's law by the lattice Boltzmann method (:mod:`morphogen.homogenization.flow`),
616
+ and ``acoustic``, the parameters of the equivalent fluid of the rigid porous frame
617
+ (porosity, permeability, tortuosity, viscous and thermal characteristic lengths,
618
+ thermal permeability: :mod:`morphogen.homogenization.acoustics`, whose
619
+ ``equivalent_fluid`` and ``absorption`` give the sound absorption of a layer).
620
+
621
+ The weak couplings of :mod:`morphogen.homogenization.poroelastic` are properties of
622
+ the elastic solvers: ``swelling``, the tensor of the strains of a unit content of an
623
+ absorbed species (``Material(swelling=...)``; as ``thermal_expansion``), and
624
+ ``poroelastic``, the law of a porous sample whose pores (the voids) hold a fluid under
625
+ pressure, under periodic or kinematic uniform conditions: its drained stiffness, the
626
+ tensor and the modulus of Biot and, with the bulk modulus of the fluid
627
+ ``fluid_bulk_modulus``, its undrained response (Gassmann, Skempton).
628
+
629
+ ``ntfa`` (voxel images): the ``paths`` are followed by a reduced model instead
630
+ (:mod:`morphogen.homogenization.ntfa`), trained on the paths of ``ntfa["training"]``
631
+ with ``ntfa["modes"]`` modes per plastic phase (default 6): ``"<name>.ntfa"`` ->
632
+ :class:`PathResult`; ``ntfa["save"]``: a file for the model; ``ntfa["full_field"]``:
633
+ the full-field paths too, for comparison.
634
+ """
635
+ props = list(properties)
636
+ path_fields, fields = fields, bool(fields)
637
+ named = {str(k): Loading.from_spec(v) for k, v in (loadings or {}).items()}
638
+ named_paths = {str(k): LoadingPath.from_spec(v) for k, v in (paths or {}).items()}
639
+ unknown = [p for p in props if p not in PHYSICS]
640
+ if unknown:
641
+ raise ValueError(f"unknown properties {unknown}; available: {list(PHYSICS)}")
642
+ bc_names = [boundary_condition(b) for b in bcs]
643
+ if isinstance(sample, (VoxelImage, LevelSetSample)):
644
+ other = [b for b in bc_names if b != "periodic"]
645
+ if other:
646
+ raise ValueError(
647
+ f"boundary conditions {other} need a conforming mesh (finite elements): the "
648
+ "FFT solver of voxel images and the extended finite elements of level sets "
649
+ "are periodic"
650
+ )
651
+ out: dict = {}
652
+ options = {"solver": solver, "tol": tol, "maxiter": maxiter}
653
+ if grains is not None or orientations is not None:
654
+ options.update(grains=grains, orientations=orientations)
655
+ if isinstance(sample, VoxelImage):
656
+ options["device"] = device
657
+ else:
658
+ _cpu_only(device)
659
+ nonlinear = dict(nonlinear or {})
660
+ # the options of the microdamage of regularized cleavage planes (the loading paths)
661
+ microdamage = nonlinear.pop("microdamage", None)
662
+ contact = _contact_options(nonlinear.pop("contact", None), sample, solver)
663
+ interfaces = _interface_options(nonlinear.pop("interfaces", None), sample, solver)
664
+ if contact is not None and interfaces is not None:
665
+ raise ValueError(
666
+ "nonlinear: 'contact' (the walls of the pores) or 'interfaces' (those of the "
667
+ "phases, whose lips touch and rub once broken), not both"
668
+ )
669
+ if integration is not None:
670
+ if isinstance(sample, LevelSetSample):
671
+ raise ValueError(
672
+ "integration: an option of the finite elements of a mesh and of the voxels "
673
+ "of the loading paths, not of the extended finite elements"
674
+ )
675
+ if fracture is None: # the phase field has its own elements
676
+ nonlinear.setdefault("integration", integration_of(integration))
677
+ elif "integration" in nonlinear and isinstance(sample, TetMesh):
678
+ integration = nonlinear["integration"] = integration_of(nonlinear["integration"])
679
+ for bc in bc_names:
680
+ elastic = [p for p in props if PHYSICS[p] == "elastic"]
681
+ # the properties of each physics, and the problems of those in use
682
+ wanted = {"elastic": elastic}
683
+ wanted.update({ph: [p for p in props if PHYSICS[p] == ph] for ph in TRANSPORT_PROPERTIES})
684
+ problems = {}
685
+ for physics, mine in wanted.items():
686
+ if physics == "elastic": # the weak couplings solve problems of their own
687
+ mine = [p for p in mine if p not in ("swelling", "poroelastic")]
688
+ if mine or any(lo.physics == physics for lo in named.values()):
689
+ extra = {}
690
+ if physics == "elastic" and isinstance(sample, TetMesh):
691
+ extra["integration"] = integration
692
+ problems[physics] = make_problem(sample, materials, physics, bc, **options, **extra)
693
+ for prop in (p for p in props if PHYSICS[p] == "coupled"):
694
+ checkpoint()
695
+ if not isinstance(sample, VoxelImage):
696
+ raise ValueError(
697
+ f"{prop}: the coupled problems are solved on voxel images (the FFT "
698
+ "solver, periodic conditions), not on meshes"
699
+ )
700
+ out[f"{prop}.{bc}"] = coupled_tensors(
701
+ sample, materials, prop, grains=grains, orientations=orientations,
702
+ temperature=mean_temperature, tol=tol, maxiter=maxiter,
703
+ ) # fmt: skip
704
+ for prop in (p for p in props if PHYSICS[p] == "harmonic"):
705
+ checkpoint()
706
+ out[f"{prop}.{bc}"] = _harmonic(
707
+ sample,
708
+ materials,
709
+ prop,
710
+ frequencies,
711
+ wavelengths,
712
+ grains,
713
+ orientations,
714
+ tol,
715
+ maxiter,
716
+ )
717
+ flows = [p for p in props if PHYSICS[p] == "flow"]
718
+ if flows:
719
+ checkpoint()
720
+ for prop, res in _flow(sample, materials, flows, tol).items():
721
+ out[f"{prop}.{bc}"] = res
722
+ for name, loading in named.items():
723
+ checkpoint()
724
+ if bc == "mixed" and not loading.strain_controlled.all():
725
+ log.info("loading %s skipped for mixed boundary conditions", name)
726
+ continue
727
+ sol = problems[loading.physics].solve(loading, fields=fields)
728
+ out[f"{name}.{bc}"] = Response(name, bc, sol)
729
+ if elastic:
730
+ problem = problems.get("elastic")
731
+ for prop in elastic:
732
+ checkpoint() # each property a stop of morphogen.stopping
733
+ if prop in ("swelling", "poroelastic"):
734
+ if bc == "mixed" or (prop == "poroelastic" and bc == "subc"):
735
+ log.info("%s skipped for %s boundary conditions", prop, bc)
736
+ continue
737
+ out[f"{prop}.{bc}"] = _weak_coupling(
738
+ sample, materials, prop, bc, fluid_bulk_modulus, options
739
+ )
740
+ elif prop == "bulk_modulus":
741
+ out[f"{prop}.{bc}"] = apparent_bulk_modulus(problem, fields=fields)
742
+ elif prop == "shear_modulus":
743
+ out[f"{prop}.{bc}"] = apparent_shear_modulus(problem, fields=fields)
744
+ elif bc == "mixed":
745
+ log.info("%s skipped for mixed boundary conditions", prop)
746
+ elif prop == "stiffness":
747
+ tensor, _ = stiffness_tensor(problem)
748
+ k, mu = isotropic_projection(tensor)
749
+ out[f"{prop}.{bc}"] = {
750
+ "tensor": tensor,
751
+ "compliance": compliance(tensor),
752
+ "bulk_modulus": k,
753
+ "shear_modulus": mu,
754
+ "isotropy_errors": isotropy_errors(tensor),
755
+ **engineering_constants(tensor),
756
+ **anisotropy(tensor),
757
+ }
758
+ else:
759
+ tensor, _ = thermal_expansion(problem)
760
+ out[f"{prop}.{bc}"] = {
761
+ "tensor": tensor,
762
+ **{
763
+ f"A{name}": float(tensor[a, b])
764
+ for (a, b), name in zip(VOIGT, VOIGT_NAMES, strict=True)
765
+ },
766
+ "mean": float(np.trace(tensor) / 3.0),
767
+ }
768
+ for physics, (scalar, _) in TRANSPORT_PROPERTIES.items():
769
+ for prop in wanted[physics]:
770
+ problem = problems[physics]
771
+ checkpoint()
772
+ if prop == scalar:
773
+ out[f"{prop}.{bc}"] = apparent_conductivity(problem, fields=fields)
774
+ else:
775
+ if bc == "mixed":
776
+ log.info("%s skipped for mixed boundary conditions", prop)
777
+ continue
778
+ tensor, _ = conductivity_tensor(problem)
779
+ out[f"{prop}.{bc}"] = {"tensor": tensor, "mean": float(np.trace(tensor) / 3)}
780
+ if named_paths and (not ntfa or ntfa.get("full_field")):
781
+ if bc not in ("periodic", "kubc"):
782
+ log.info("loading paths skipped for %s conditions", bc)
783
+ continue
784
+ if fracture is not None:
785
+ problem = _fracture_problem(
786
+ sample, materials, fracture, grains, orientations, nonlinear
787
+ )
788
+ elif isinstance(sample, VoxelImage):
789
+ problem = NonlinearFFTProblem(
790
+ sample, materials, bc, tol=tol, maxiter=maxiter, grains=grains,
791
+ orientations=orientations, device=device, **(nonlinear or {}),
792
+ ) # fmt: skip
793
+ elif isinstance(sample, LevelSetSample):
794
+ if "integration" in (nonlinear or {}):
795
+ raise ValueError(
796
+ "nonlinear: 'integration' is an option of the voxels of the FFT solver"
797
+ )
798
+ problem = NonlinearXFEMProblem(
799
+ sample, materials, bc, solver=solver, tol=tol, maxiter=maxiter,
800
+ **(nonlinear or {}),
801
+ ) # fmt: skip
802
+ elif contact is not None:
803
+ from morphogen.contact.periodic import ContactCell
804
+
805
+ problem = ContactCell(
806
+ sample, materials, bc, tol=tol, maxiter=maxiter, **contact, **nonlinear
807
+ )
808
+ elif interfaces is not None:
809
+ from morphogen.fracture.periodic import CohesiveCell
810
+
811
+ law, cell = interfaces
812
+ problem = CohesiveCell(
813
+ sample, materials, law, bc, tol=tol, maxiter=maxiter, **cell, **nonlinear
814
+ )
815
+ else:
816
+ problem = NonlinearFEProblem(
817
+ sample, materials, bc, solver=solver, tol=tol, maxiter=maxiter,
818
+ **(nonlinear or {}),
819
+ ) # fmt: skip
820
+ if microdamage and hasattr(problem, "microdamage_options"):
821
+ problem.microdamage_options(**microdamage)
822
+ for name, path in named_paths.items():
823
+ out[f"{name}.{bc}"] = problem.run(path, name=name, fields=path_fields)
824
+ if ntfa:
825
+ out.update(_ntfa_paths(sample, materials, named_paths, ntfa, tol, nonlinear))
826
+ return out
827
+
828
+
829
+ #: The options of the contact of the walls of the pores along the loading paths
830
+ #: (``nonlinear["contact"]``): those of morphogen.contact.periodic.ContactCell
831
+ CONTACT_OPTIONS = ("friction", "stiffness", "tangential", "depth", "points", "augmentations",
832
+ "tolerance") # fmt: skip
833
+
834
+
835
+ def _contact_options(contact, sample, solver: str) -> dict | None:
836
+ """The options of the cell whose walls may touch (``nonlinear["contact"]``: True or a
837
+ mapping of :data:`CONTACT_OPTIONS`), or None without contact."""
838
+ if contact is None or contact is False:
839
+ return None
840
+ if not isinstance(sample, TetMesh):
841
+ raise ValueError(
842
+ "nonlinear: 'contact' is that of the walls of the pores of a mesh (finite "
843
+ "elements on the conforming mesh of the solid), not of a voxel image or a level set"
844
+ )
845
+ if solver not in ("auto", "direct"):
846
+ raise ValueError(
847
+ f"nonlinear: with 'contact' the tangent is factorized (solver 'direct', not {solver!r})"
848
+ )
849
+ if contact is True:
850
+ return {}
851
+ if not isinstance(contact, dict):
852
+ raise ValueError("nonlinear: 'contact' is True or a mapping of its options")
853
+ unknown = sorted(set(contact) - set(CONTACT_OPTIONS))
854
+ if unknown:
855
+ raise ValueError(
856
+ f"nonlinear: unknown options {unknown} of 'contact'; use {list(CONTACT_OPTIONS)}"
857
+ )
858
+ return dict(contact)
859
+
860
+
861
+ #: The options of the interfaces of the phases along the loading paths
862
+ #: (``nonlinear["interfaces"]``): their law and its parameters
863
+ #: (morphogen.fracture.periodic.interface_law), and those of
864
+ #: morphogen.fracture.periodic.CohesiveCell
865
+ INTERFACE_OPTIONS = (
866
+ "law",
867
+ "stiffness",
868
+ "normal_strength",
869
+ "shear_strength",
870
+ "mode_I",
871
+ "mode_II",
872
+ "eta",
873
+ "strength",
874
+ "energy",
875
+ "beta",
876
+ "penalty",
877
+ "tangential",
878
+ "friction",
879
+ "faces",
880
+ "viscosity",
881
+ "slip",
882
+ "laws",
883
+ )
884
+
885
+
886
+ def _interface_options(interfaces, sample, solver: str) -> tuple[dict, dict] | None:
887
+ """The law of the interfaces and the options of their cell (``nonlinear["interfaces"]``:
888
+ a mapping of :data:`INTERFACE_OPTIONS`), or None without interfaces."""
889
+ if interfaces is None or interfaces is False:
890
+ return None
891
+ if not isinstance(sample, TetMesh):
892
+ raise ValueError(
893
+ "nonlinear: 'interfaces' are those of the phases of a mesh (finite elements on "
894
+ "a conforming mesh of the phases), not of a voxel image or a level set"
895
+ )
896
+ if solver not in ("auto", "direct"):
897
+ raise ValueError(
898
+ "nonlinear: with 'interfaces' the tangent is factorized (solver 'direct', not "
899
+ f"{solver!r})"
900
+ )
901
+ if not isinstance(interfaces, dict):
902
+ raise ValueError("nonlinear: 'interfaces' is a mapping of their law and options")
903
+ unknown = sorted(set(interfaces) - set(INTERFACE_OPTIONS))
904
+ if unknown:
905
+ raise ValueError(
906
+ f"nonlinear: unknown options {unknown} of 'interfaces'; use {list(INTERFACE_OPTIONS)}"
907
+ )
908
+ cell = {k: interfaces[k] for k in ("faces", "viscosity", "slip") if k in interfaces}
909
+ law = {k: v for k, v in interfaces.items() if k not in cell}
910
+ if "laws" in law: # a law per pair of phases: "0-1", or the two phases
911
+ laws = law.pop("laws")
912
+ if law or not isinstance(laws, dict) or not laws:
913
+ raise ValueError(
914
+ "nonlinear: 'interfaces' with 'laws' (a mapping of pairs of phases to "
915
+ f"their laws) takes no law of its own: {sorted(law)}"
916
+ )
917
+ try:
918
+ law = {
919
+ tuple(sorted(int(p) for p in (key.split("-") if isinstance(key, str) else key))):
920
+ spec
921
+ for key, spec in laws.items()
922
+ } # fmt: skip
923
+ except (TypeError, ValueError):
924
+ raise ValueError(
925
+ "nonlinear: the 'laws' of the interfaces are those of pairs of phases "
926
+ f"('0-1'), got {list(laws)}"
927
+ ) from None
928
+ return law, cell
929
+
930
+
931
+ def _flow(sample, materials, props, tol) -> dict:
932
+ """The permeability tensor and the acoustic parameters (those of ``props``) of the
933
+ pores of a voxel image (:mod:`morphogen.homogenization.flow`,
934
+ :mod:`morphogen.homogenization.acoustics`); the flows are solved once for both."""
935
+ from morphogen.homogenization.acoustics import acoustic_parameters
936
+ from morphogen.homogenization.flow import ENTRIES, permeability_tensor
937
+
938
+ if not isinstance(sample, VoxelImage):
939
+ raise ValueError(
940
+ f"{props[0]}: the flow through the pores is solved on voxel images (the lattice "
941
+ "Boltzmann method, periodic conditions), not on meshes"
942
+ )
943
+ lattice = min(max(tol, 1e-6), 1e-3) # of the mean velocity of the flows
944
+ out = {}
945
+ if "acoustic" in props:
946
+ out["acoustic"] = acoustic_parameters(sample, materials, tol=lattice)
947
+ if "hydraulic_permeability" in props:
948
+ if "acoustic" in out:
949
+ res = out["acoustic"]
950
+ flow = {"tensor": res["permeability_tensor"], "mean": res["permeability"]}
951
+ flow.update({k: res[k] for k in (*ENTRIES[1:], "steps", "error")})
952
+ out["hydraulic_permeability"] = flow
953
+ else:
954
+ out["hydraulic_permeability"] = permeability_tensor(sample, materials, tol=lattice)
955
+ return {p: out[p] for p in props}
956
+
957
+
958
+ def _weak_coupling(sample, materials, prop, bc, fluid_bulk, options) -> dict:
959
+ """The swelling tensor or the poroelastic law of a sample
960
+ (:mod:`morphogen.homogenization.poroelastic`)."""
961
+ from morphogen.homogenization.poroelastic import poroelastic_tensors, swelling_tensor
962
+
963
+ if prop == "poroelastic":
964
+ return poroelastic_tensors(sample, materials, bc, fluid_bulk=fluid_bulk, **options)
965
+ tensor, _ = swelling_tensor(sample, materials, bc, **options)
966
+ names = zip(VOIGT, VOIGT_NAMES, strict=True)
967
+ return {
968
+ "tensor": tensor,
969
+ **{f"B{name}": float(tensor[a, b]) for (a, b), name in names},
970
+ "mean": float(np.trace(tensor) / 3.0),
971
+ }
972
+
973
+
974
+ def _fracture_problem(sample, materials, fracture, grains, orientations, nonlinear=None):
975
+ """The phase-field problem of the loading paths of a voxel image that breaks: in small
976
+ strains, or in finite strains with ``nonlinear: {kinematics: finite}`` (and the other
977
+ options of the nonlinear FFT solver)."""
978
+ from morphogen.fracture.phasefield import PhaseField, PhaseFieldProblem
979
+
980
+ if not isinstance(sample, VoxelImage):
981
+ raise ValueError(
982
+ "fracture: the phase-field method runs on voxel images (the FFT solver, periodic "
983
+ "conditions), not on meshes"
984
+ )
985
+ options = {}
986
+ if isinstance(fracture, dict):
987
+ fracture = dict(fracture)
988
+ options = {k: fracture.pop(k) for k in ("staggered_tol", "max_staggered", "tol")
989
+ if k in fracture} # fmt: skip
990
+ nonlinear = dict(nonlinear or {})
991
+ if nonlinear.pop("kinematics", "small") == "finite":
992
+ from morphogen.fracture.phasefield_finite import FinitePhaseFieldProblem
993
+
994
+ if grains is not None or orientations is not None:
995
+ raise ValueError("fracture in finite strains: isotropic phases (no crystals)")
996
+ return FinitePhaseFieldProblem(
997
+ sample, materials, PhaseField.from_config(fracture), **options, **nonlinear
998
+ )
999
+ return PhaseFieldProblem(sample, materials, PhaseField.from_config(fracture), grains=grains,
1000
+ orientations=orientations, **options) # fmt: skip
1001
+
1002
+
1003
+ def _harmonic(sample, materials, prop, frequencies, wavelengths, grains, orientations, tol,
1004
+ maxiter) -> dict: # fmt: skip
1005
+ """A property of a harmonic regime (:data:`HARMONIC`) of a voxel image."""
1006
+ from morphogen.homogenization import harmonic
1007
+
1008
+ if not isinstance(sample, VoxelImage):
1009
+ raise ValueError(
1010
+ f"{prop}: the harmonic problems are solved on voxel images (the FFT solver, "
1011
+ "periodic conditions), not on meshes"
1012
+ )
1013
+ if prop == "refractive_index":
1014
+ if wavelengths is None:
1015
+ raise ValueError("refractive_index: give the wavelengths")
1016
+ return harmonic.effective_index(
1017
+ sample, materials, wavelengths, tol=tol, maxiter=maxiter
1018
+ ).to_dict()
1019
+ if frequencies is None:
1020
+ raise ValueError(f"{prop}: give the angular frequencies")
1021
+ solve = (
1022
+ harmonic.dynamic_stiffness if prop == "dynamic_stiffness" else harmonic.complex_conductivity
1023
+ )
1024
+ return solve(sample, materials, frequencies, grains=grains, orientations=orientations,
1025
+ tol=tol, maxiter=maxiter).to_dict() # fmt: skip
1026
+
1027
+
1028
+ def _ntfa_paths(sample, materials, named_paths, spec: dict, tol: float, nonlinear) -> dict:
1029
+ """The loading paths followed by an NTFA model trained on the sample."""
1030
+ from morphogen.homogenization.ntfa import train_ntfa
1031
+
1032
+ if not isinstance(sample, VoxelImage):
1033
+ raise ValueError("ntfa: a periodic voxel image (the reduced model is trained by FFT)")
1034
+ unknown = set(spec) - {"training", "modes", "save", "full_field"}
1035
+ if unknown:
1036
+ raise ValueError(f"ntfa: unknown options {sorted(unknown)}")
1037
+ training = [LoadingPath.from_spec(p) for p in dict(spec.get("training") or {}).values()]
1038
+ if not training:
1039
+ raise ValueError("ntfa: give the training paths ('training')")
1040
+ newton = (nonlinear or {}).get("newton_tol", 1e-6)
1041
+ model = train_ntfa(
1042
+ sample, materials, training, modes=spec.get("modes", 6), tol=tol, newton_tol=newton
1043
+ )
1044
+ if spec.get("save"):
1045
+ model.save(spec["save"])
1046
+ return {f"{name}.ntfa": model.run(path, name=name) for name, path in named_paths.items()}