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,2612 @@
1
+ """Nonlinear homogenization along loading paths: the periodic element.
2
+
3
+ The unknowns of a step are the fluctuation ``w`` of the displacement ``u = E x + w``
4
+ (periodic, or zero on the boundary for kinematic conditions) and the components of the
5
+ macroscopic strain ``E`` that are not prescribed: the macroscopic degrees of freedom of
6
+ the periodic element of Z-set. Their equations are
7
+
8
+ * equilibrium, ``R_w = int B^T sigma dV = 0`` on the reduced unknowns of ``w``;
9
+ * the macroscopic stress, ``R_E = int sigma dV - V Sigma = 0`` on the components of
10
+ ``E`` prescribed as stresses (``V``: the volume of the box, voids included). The
11
+ reactions of the other components of ``E`` are ``V Sigma``.
12
+
13
+ The stresses come from the behaviours of the phases (von Mises elasto-viscoplasticity,
14
+ :mod:`morphogen.homogenization.behaviours`; crystal plasticity,
15
+ :mod:`morphogen.homogenization.crystal`), integrated implicitly over each step. Newton's
16
+ method solves the equations with the consistent tangent:
17
+
18
+ [ K_ww K_wE ] [dw] [R_w]
19
+ [ K_Ew K_EE ] [dE] = - [R_E], K_ww = int B^T C B, K_wE = int B^T C, K_EE = int C
20
+
21
+ whose macroscopic block is condensed: ``K_ww Y = K_wE`` (one solve per unknown
22
+ component of ``E``, from the solutions of the previous iteration) gives the 6 x 6 (at
23
+ most) system ``(K_EE - K_Ew Y) dE = -R_E + K_Ew K_ww^-1 R_w``. The linear solvers are
24
+ those of the linear problems (sparse LU, or conjugate gradients with algebraic
25
+ multigrid, whose hierarchy is built once per step). The consistent tangents of the
26
+ points are symmetrized for them when the laws of all the phases have symmetric ones;
27
+ otherwise (``tangent``, :data:`TANGENTS`) they are kept whole, ``K_Ew`` is no longer
28
+ ``K_wE^T`` and the tangent is solved by LU or by GMRES (with the multigrid of its
29
+ symmetric part), the Krylov solvers symmetrizing them again at the linearizations where
30
+ their measured asymmetry is below :data:`ASYMMETRY`. A step that does not converge, whose
31
+ local integration fails, or whose corrections by GMRES stagnate at :data:`_STALLED`
32
+ Newton iterations in a row, is divided by two (at most ``max_cuts`` times), and the step
33
+ grows back after two converged steps.
34
+
35
+ In finite strains (``kinematics="finite"``, :mod:`morphogen.homogenization.finite`) the
36
+ equations are written on the reference configuration with the first Piola-Kirchhoff
37
+ stress ``P`` and its tangent ``dP/dF``; the macroscopic gradient ``F = I + E`` is upper
38
+ triangular, its components ``E`` (nominal strains and simple shears) conjugate to those
39
+ of the mean of ``P`` (nominal stresses). The outputs add the Cauchy stress and the
40
+ logarithmic strain.
41
+
42
+ For linear behaviours in small strains the solutions are those of the condensation of
43
+ :func:`morphogen.homogenization.core.superpose`.
44
+
45
+ The time stepping and the Newton iterations (:class:`_PathSolver`) are shared with the
46
+ FFT solver of voxel images (:mod:`morphogen.homogenization.fft_nonlinear`), which gives
47
+ its own discretization and linear solver.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import logging
53
+ import math
54
+ import time
55
+ from collections import deque
56
+ from dataclasses import dataclass, field
57
+ from functools import partial
58
+
59
+ import numpy as np
60
+ import scipy.sparse as sp
61
+ from numba import njit, prange
62
+
63
+ from morphogen.homogenization import dilatation
64
+ from morphogen.homogenization import finite as fin
65
+ from morphogen.homogenization.behaviours import (
66
+ CRYSTAL,
67
+ ELASTIC,
68
+ HILL,
69
+ MFRONT,
70
+ N_PARAMS,
71
+ PLASTIC,
72
+ POROUS,
73
+ STATE_P,
74
+ mises,
75
+ update_points,
76
+ )
77
+ from morphogen.homogenization.behaviours import state_width as j2_width
78
+ from morphogen.homogenization.crystal import (
79
+ _BROKEN,
80
+ CP_ALPHA,
81
+ CP_KIND,
82
+ CP_WIDTH,
83
+ OPENING,
84
+ SLIP,
85
+ CrystalPlasticity,
86
+ turn_twins,
87
+ )
88
+ from morphogen.homogenization.crystal import state_width as cp_width
89
+ from morphogen.homogenization.elements import voigt_to_tensor
90
+ from morphogen.homogenization.fe import (
91
+ CHUNKS,
92
+ GAUSS,
93
+ FEElasticProblem,
94
+ Reduction,
95
+ _expand_columns,
96
+ _geometry,
97
+ _point_gradients,
98
+ _strain_of,
99
+ chunk_slots,
100
+ element_colours,
101
+ node_pattern,
102
+ )
103
+ from morphogen.homogenization.materials import Material, MaterialTable, material_table
104
+ from morphogen.homogenization.paths import LoadingPath, PathResult
105
+ from morphogen.homogenization.porous import P_F0, STATE_FN, porosity
106
+ from morphogen.homogenization.porous import state_width as porous_width
107
+ from morphogen.homogenization.solvers import choose_method, dot, norm, times
108
+ from morphogen.homogenization.tensors import symmetrize
109
+ from morphogen.settings import without_blas_threads
110
+
111
+ log = logging.getLogger("morphogen")
112
+
113
+ #: Kinematics of the nonlinear problems
114
+ KINEMATICS = ("small", "finite")
115
+ #: Consistent tangents of the points in the Newton iterations of the volume elements:
116
+ #: symmetrized and solved by conjugate gradients, or full and solved by GMRES (sparse LU
117
+ #: by finite elements); ``auto`` symmetrizes them when the laws of all the phases have
118
+ #: symmetric tangents, and otherwise, for the Krylov solvers, where their measured
119
+ #: asymmetry is below :data:`ASYMMETRY`
120
+ TANGENTS = ("auto", "symmetric", "full")
121
+ #: With ``tangent="auto"`` and laws whose tangents are not all symmetric, the volume
122
+ #: elements solved by Krylov methods (voxels; finite elements with multigrid) measure the
123
+ #: asymmetry of the consistent tangents of the points of each phase at each linearization
124
+ #: (:func:`asymmetry`) and symmetrize them where the largest is below this value
125
+ #: (conjugate gradients, MINRES); above it they solve the full tangents by GMRES
126
+ ASYMMETRY = 2e-2
127
+ #: Engineering strains of the tensor components of the outputs
128
+ _HALF_SHEAR = np.array([1.0, 1.0, 1.0, 0.5, 0.5, 0.5])
129
+ #: Relative residual of the solutions of the macroscopic coupling ``K_ww Y = K_wE``, and
130
+ #: largest one of the corrections of an inexact Newton iteration (the residual of the
131
+ #: equilibrium decides the convergence)
132
+ _MACRO_TOL = 1e-4
133
+ _MAX_FORCING = 1e-2
134
+ #: The macroscopic coupling is computed again at this Newton iteration of a step, and at
135
+ #: the start of the next step when it took more iterations
136
+ _REFRESH_AFTER = 3
137
+ #: A step is predicted at the second order (:func:`_predicted`) where, on the last step,
138
+ #: the error of that prediction was below this share of the error of the first-order one,
139
+ #: itself below this share of the increments of the step (a response that does not turn)
140
+ _SECOND = 0.5
141
+ #: The condensed block of the macroscopic unknowns kept from an earlier linearization is
142
+ #: updated by the secant of a correction (:func:`_secant`) that has brought the merit
143
+ #: below this share of what it was (a tenth of the residuals: a correction of the
144
+ #: converging iteration, whose step the linearization describes)
145
+ _TRUSTED = 1e-2
146
+ #: Powell's damping of that update: the curvature of the secant along the step between
147
+ #: this share of the curvature of the block and its inverse
148
+ _DAMPING = 0.2
149
+ #: A step whose corrections by GMRES (full tangents) stop above their tolerance at this
150
+ #: many Newton iterations in a row is divided: its tangents are too far from definite for
151
+ #: the Krylov solvers (the softening voxels of a step too large), and its iterations make
152
+ #: little progress
153
+ _STALLED = 3
154
+ #: Gradient (9 components) of each macroscopic strain component (6, engineering shears)
155
+ _MACRO = fin.gradient_of(np.eye(6)).T
156
+ #: The round-off of the stresses of a material point relative to its stiffness times its
157
+ #: strain: the residual it reaches at zero stress (a thousand times the machine epsilon)
158
+ _ROUND_OFF = 1e3 * float(np.finfo(float).eps)
159
+ #: In finite strains, the round-off of the stresses of a gradient ``I + H`` relative to
160
+ #: the stiffness, which does not vanish with ``H``: what is left of the stress of a point
161
+ #: brought back to no strain after a plastic history (ten times the machine epsilon)
162
+ _ROUND_OFF_UNIT = 10.0 * float(np.finfo(float).eps)
163
+ #: The share of the largest scales of the residuals reached along a path that the scales
164
+ #: of a state keep: an unloaded state (an elastic cell brought back to zero strain) has no
165
+ #: force of its own with which to compare its residuals
166
+ _UNLOADED = 1e-6
167
+
168
+
169
+ def kinematics_of(value) -> bool:
170
+ """Whether the kinematics ``"small"`` or ``"finite"`` is finite."""
171
+ if value not in KINEMATICS:
172
+ raise ValueError(f"kinematics: one of {KINEMATICS}, got {value!r}")
173
+ return value == "finite"
174
+
175
+
176
+ # -- kernels ------------------------------------------------------------------------------
177
+
178
+
179
+ @njit(parallel=True, cache=True)
180
+ def _point_strains(nodes, elements, order, u, gp, gw, eps, wts):
181
+ """Strains (engineering) and weights of the integration points of every element."""
182
+ n_el, nn = elements.shape
183
+ ng = gp.shape[0]
184
+ for e in prange(n_el):
185
+ x = np.empty((4, 3))
186
+ gl = np.empty((4, 3))
187
+ dev = np.empty((6, 3))
188
+ grad = np.empty((nn, 3))
189
+ tmp = np.empty(6)
190
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
191
+ for g in range(ng):
192
+ wts[e * ng + g] = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
193
+ _strain_of(grad, elements, e, u, tmp)
194
+ for r in range(6):
195
+ eps[e * ng + g, r] = tmp[r]
196
+
197
+
198
+ @njit(parallel=True, cache=True)
199
+ def _internal_forces(nodes, elements, order, gp, sigma, wts, by_colour, colours, forces):
200
+ """Nodal forces ``int B^T sigma`` (into ``forces``), the integral of the stress, and
201
+ the norm of the contributions of the integration points (before they cancel); the
202
+ elements of a colour in parallel (``by_colour``, ``colours``:
203
+ :func:`~morphogen.homogenization.fe.element_colours`), the sums over all the elements
204
+ chunk by chunk, in the same order for any number of threads."""
205
+ nn = elements.shape[1]
206
+ ng = gp.shape[0]
207
+ for i in prange(forces.size):
208
+ forces[i] = 0.0
209
+ n_colours = colours.size - 1
210
+ # the sums of each chunk (rows wide enough for two chunks not to share a cache line)
211
+ slots = chunk_slots(colours)
212
+ sums = np.zeros((slots[n_colours], 16))
213
+ xs = np.empty((CHUNKS, 4, 3))
214
+ gls = np.empty((CHUNKS, 4, 3))
215
+ devs = np.empty((CHUNKS, 6, 3))
216
+ grads = np.empty((CHUNKS, nn, 3))
217
+ for colour in range(n_colours):
218
+ first = colours[colour]
219
+ count = colours[colour + 1] - first
220
+ chunks = min(count, CHUNKS)
221
+ for chunk in prange(chunks):
222
+ x = xs[chunk]
223
+ gl = gls[chunk]
224
+ dev = devs[chunk]
225
+ grad = grads[chunk]
226
+ part = sums[slots[colour] + chunk]
227
+ for q in range(first + chunk * count // chunks, first + (chunk + 1) * count // chunks):
228
+ e = by_colour[q]
229
+ _, curved = _geometry(nodes, elements, e, x, gl, dev)
230
+ for g in range(ng):
231
+ _point_gradients(order, curved, gl, dev, gp[g], grad)
232
+ i = e * ng + g
233
+ w = wts[i]
234
+ s = sigma[i]
235
+ for r in range(6):
236
+ part[r] += w * s[r]
237
+ for b in range(nn):
238
+ k = elements[e, b]
239
+ gx, gy, gz = grad[b, 0], grad[b, 1], grad[b, 2]
240
+ fx = w * (gx * s[0] + gz * s[4] + gy * s[5])
241
+ fy = w * (gy * s[1] + gz * s[3] + gx * s[5])
242
+ fz = w * (gz * s[2] + gy * s[3] + gx * s[4])
243
+ forces[3 * k] += fx
244
+ forces[3 * k + 1] += fy
245
+ forces[3 * k + 2] += fz
246
+ part[6] += fx * fx + fy * fy + fz * fz
247
+ total = np.zeros(6)
248
+ norm2 = 0.0
249
+ for k in range(sums.shape[0]):
250
+ for r in range(6):
251
+ total[r] += sums[k, r]
252
+ norm2 += sums[k, 6]
253
+ return total, math.sqrt(norm2)
254
+
255
+
256
+ @njit(parallel=True, cache=True)
257
+ def _fill_tangent(nodes, elements, order, gp, tangent, wts, indptr_n, indices_n, by_colour,
258
+ colours, data): # fmt: skip
259
+ """CSR values of ``sum_e int B^T C B`` with the tangent ``C`` of every integration
260
+ point (node-level pattern ``indptr_n``, ``indices_n``), the elements of a colour in
261
+ parallel (``by_colour``, ``colours``:
262
+ :func:`~morphogen.homogenization.fe.element_colours`)."""
263
+ nn = elements.shape[1]
264
+ ng = gp.shape[0]
265
+ for i in prange(data.size):
266
+ data[i] = 0.0
267
+ xs = np.empty((CHUNKS, 4, 3))
268
+ gls = np.empty((CHUNKS, 4, 3))
269
+ devs = np.empty((CHUNKS, 6, 3))
270
+ grads = np.empty((CHUNKS, nn, 3))
271
+ dbs = np.empty((CHUNKS, nn, 6, 3))
272
+ kes = np.empty((CHUNKS, nn * 3, nn * 3))
273
+ places = np.empty((CHUNKS, nn, nn), dtype=np.int64)
274
+ for colour in range(colours.size - 1):
275
+ first = colours[colour]
276
+ count = colours[colour + 1] - first
277
+ chunks = min(count, CHUNKS)
278
+ for chunk in prange(chunks):
279
+ x = xs[chunk]
280
+ gl = gls[chunk]
281
+ dev = devs[chunk]
282
+ grad = grads[chunk]
283
+ db = dbs[chunk]
284
+ ke = kes[chunk]
285
+ pos = places[chunk]
286
+ for q in range(first + chunk * count // chunks, first + (chunk + 1) * count // chunks):
287
+ e = by_colour[q]
288
+ _, curved = _geometry(nodes, elements, e, x, gl, dev)
289
+ ke[:, :] = 0.0
290
+ for g in range(ng):
291
+ _point_gradients(order, curved, gl, dev, gp[g], grad)
292
+ i = e * ng + g
293
+ w = wts[i]
294
+ d = tangent[i]
295
+ for b in range(nn):
296
+ gx, gy, gz = grad[b, 0], grad[b, 1], grad[b, 2]
297
+ for r in range(6):
298
+ db[b, r, 0] = d[r, 0] * gx + d[r, 4] * gz + d[r, 5] * gy
299
+ db[b, r, 1] = d[r, 1] * gy + d[r, 3] * gz + d[r, 5] * gx
300
+ db[b, r, 2] = d[r, 2] * gz + d[r, 3] * gy + d[r, 4] * gx
301
+ for a in range(nn):
302
+ gx, gy, gz = grad[a, 0], grad[a, 1], grad[a, 2]
303
+ for b in range(nn):
304
+ for c2 in range(3):
305
+ ke[3 * a, 3 * b + c2] += w * (
306
+ gx * db[b, 0, c2] + gz * db[b, 4, c2] + gy * db[b, 5, c2]
307
+ )
308
+ ke[3 * a + 1, 3 * b + c2] += w * (
309
+ gy * db[b, 1, c2] + gz * db[b, 3, c2] + gx * db[b, 5, c2]
310
+ )
311
+ ke[3 * a + 2, 3 * b + c2] += w * (
312
+ gz * db[b, 2, c2] + gy * db[b, 3, c2] + gx * db[b, 4, c2]
313
+ )
314
+ for a in range(nn):
315
+ na = elements[e, a]
316
+ lo = indptr_n[na]
317
+ hi = indptr_n[na + 1]
318
+ for b in range(nn):
319
+ nb = elements[e, b]
320
+ left, right = lo, hi
321
+ while left < right:
322
+ mid = (left + right) // 2
323
+ if indices_n[mid] < nb:
324
+ left = mid + 1
325
+ else:
326
+ right = mid
327
+ pos[a, b] = left - lo
328
+ for a in range(nn):
329
+ na = elements[e, a]
330
+ length = indptr_n[na + 1] - indptr_n[na]
331
+ for c in range(3):
332
+ start = 9 * indptr_n[na] + c * 3 * length
333
+ for b in range(nn):
334
+ p = pos[a, b]
335
+ for c2 in range(3):
336
+ data[start + p * 3 + c2] += ke[3 * a + c, 3 * b + c2]
337
+
338
+
339
+ @njit(parallel=True, cache=True)
340
+ def _coupling(nodes, elements, order, gp, tangent, wts, by_colour, colours, out, kee):
341
+ """``int B^T C`` (nodal forces of the six unit macroscopic strains, into ``out``,
342
+ n_dofs x 6) and ``int C`` (into ``kee``); the elements of a colour in parallel, as
343
+ :func:`_internal_forces`."""
344
+ nn = elements.shape[1]
345
+ ng = gp.shape[0]
346
+ for i in prange(out.shape[0]):
347
+ for j in range(6):
348
+ out[i, j] = 0.0
349
+ n_colours = colours.size - 1
350
+ slots = chunk_slots(colours)
351
+ sums = np.zeros((slots[n_colours], 48)) # (36 values: the rows of two chunks apart)
352
+ xs = np.empty((CHUNKS, 4, 3))
353
+ gls = np.empty((CHUNKS, 4, 3))
354
+ devs = np.empty((CHUNKS, 6, 3))
355
+ grads = np.empty((CHUNKS, nn, 3))
356
+ for colour in range(n_colours):
357
+ first = colours[colour]
358
+ count = colours[colour + 1] - first
359
+ chunks = min(count, CHUNKS)
360
+ for chunk in prange(chunks):
361
+ x = xs[chunk]
362
+ gl = gls[chunk]
363
+ dev = devs[chunk]
364
+ grad = grads[chunk]
365
+ part = sums[slots[colour] + chunk]
366
+ for q in range(first + chunk * count // chunks, first + (chunk + 1) * count // chunks):
367
+ e = by_colour[q]
368
+ _, curved = _geometry(nodes, elements, e, x, gl, dev)
369
+ for g in range(ng):
370
+ _point_gradients(order, curved, gl, dev, gp[g], grad)
371
+ i = e * ng + g
372
+ w = wts[i]
373
+ d = tangent[i]
374
+ for r in range(6):
375
+ for c in range(6):
376
+ part[6 * r + c] += w * d[r, c]
377
+ for b in range(nn):
378
+ k = elements[e, b]
379
+ gx, gy, gz = grad[b, 0], grad[b, 1], grad[b, 2]
380
+ for j in range(6):
381
+ out[3 * k, j] += w * (gx * d[0, j] + gz * d[4, j] + gy * d[5, j])
382
+ out[3 * k + 1, j] += w * (gy * d[1, j] + gz * d[3, j] + gx * d[5, j])
383
+ out[3 * k + 2, j] += w * (gz * d[2, j] + gy * d[3, j] + gx * d[4, j])
384
+ kee[:, :] = 0.0
385
+ for k in range(sums.shape[0]):
386
+ for r in range(6):
387
+ for c in range(6):
388
+ kee[r, c] += sums[k, 6 * r + c]
389
+
390
+
391
+ @njit(parallel=True, cache=True)
392
+ def _group_sums(group, n_groups, wts, sigma, eps, p):
393
+ """Integrals over each group of the stress, the strain (engineering), the cumulated
394
+ plastic strain ``p`` and the volume."""
395
+ n = wts.shape[0]
396
+ n_chunks = min(max(n, 1), 256)
397
+ partial = np.zeros((n_chunks, n_groups, 14))
398
+ for ch in prange(n_chunks):
399
+ for i in range(ch * n // n_chunks, (ch + 1) * n // n_chunks):
400
+ acc = partial[ch, group[i]]
401
+ w = wts[i]
402
+ for r in range(6):
403
+ acc[r] += w * sigma[i, r]
404
+ acc[6 + r] += w * eps[i, r]
405
+ acc[12] += w * p[i]
406
+ acc[13] += w
407
+ return partial.sum(axis=0)
408
+
409
+
410
+ # -- behaviours of the elements -------------------------------------------------------------
411
+
412
+
413
+ @dataclass
414
+ class Behaviours:
415
+ """Behaviours of the elements of phases: the kind of each element (elastic, von Mises,
416
+ crystal, MFront), its row of parameters (``pmat``: of :attr:`params`, of the crystal
417
+ arrays or of :attr:`mfront`; -1 for elastic elements), the data of the integration
418
+ kernels (see :func:`morphogen.homogenization.behaviours.update_points`), the number of
419
+ internal variables of a point, the crystal plasticity of each crystal row and the laws
420
+ of the points integrated outside the kernels (:attr:`mfront`: the MFront behaviours
421
+ loaded by MGIS, :class:`~morphogen.homogenization.mfront.MFrontLaw`, and the learned
422
+ laws, :class:`~morphogen.learning.behaviour.LearnedLaw`). :attr:`symmetric`: whether
423
+ the consistent tangents of all the laws are symmetric (see :func:`behaviour_table`)."""
424
+
425
+ kind: np.ndarray
426
+ pmat: np.ndarray
427
+ data: tuple
428
+ width: int
429
+ crystals: list = field(default_factory=list)
430
+ mfront: list = field(default_factory=list)
431
+ symmetric: bool = True
432
+
433
+ @property
434
+ def nonlinear(self) -> bool:
435
+ return bool(np.any(self.kind != ELASTIC))
436
+
437
+
438
+ def behaviour_table(
439
+ phase, materials: dict[int, Material], table: MaterialTable, *, finite: bool = False
440
+ ) -> Behaviours:
441
+ """Behaviours of the elements of phases ``phase`` with their materials ``table``
442
+ (:func:`morphogen.homogenization.materials.material_table`): the slip systems of the
443
+ crystals turn with the orientation of their material.
444
+
445
+ The consistent tangents are symmetric (:attr:`Behaviours.symmetric`) for elasticity,
446
+ for von Mises and Hill plasticity without Armstrong-Frederick terms (``D = 0``), for
447
+ crystal plasticity in small strains without isotropic hardening (``Q b = 0``), for the
448
+ learned potentials and standard models and for the MFront behaviours that declare it;
449
+ not for the Armstrong-Frederick hardening (the backstresses turn the direction of
450
+ flow), the isotropic hardening of the slip systems and the multiplicative crystal
451
+ plasticity of finite strains, porous plasticity (the growth of the porosity), the
452
+ learned perceptrons and recurrent networks, and the other MFront behaviours."""
453
+ phase = np.asarray(phase).ravel().astype(np.int64)
454
+ kind = np.full(phase.size, ELASTIC, dtype=np.int64)
455
+ pmat = np.full(phase.size, -1, dtype=np.int64)
456
+ rows, n_kin, porous_kin = [], 0, -1
457
+ symmetric = True
458
+ crystals: list[CrystalPlasticity] = []
459
+ laws = []
460
+ for p in np.unique(phase):
461
+ m = materials[int(p)]
462
+ sel = phase == p
463
+ if m.void:
464
+ continue
465
+ if m.mfront is not None:
466
+ from morphogen.homogenization.mfront import load_behaviour
467
+
468
+ kind[sel] = MFRONT
469
+ pmat[sel] = len(laws)
470
+ laws.append(load_behaviour(m.mfront, finite=finite))
471
+ elif m.learned is not None: # integrated outside the kernels too, by its model
472
+ from morphogen.learning.behaviour import learned_law
473
+
474
+ kind[sel] = MFRONT
475
+ pmat[sel] = len(laws)
476
+ heat = m.expansion_tensor() if m.expands else None # in the axes of the material
477
+ laws.append(learned_law(m.learned, finite=finite, expansion=heat))
478
+ elif m.analytic: # viscoelasticity, hyperelasticity, damage: likewise, in closed form
479
+ from morphogen.homogenization.laws import analytic_law
480
+
481
+ kind[sel] = MFRONT
482
+ pmat[sel] = len(laws)
483
+ heat = m.expansion_tensor() if m.expands else None
484
+ laws.append(analytic_law(m, finite=finite, expansion=heat))
485
+ elif m.plastic:
486
+ kind[sel] = PLASTIC if m.plasticity.hill is None else HILL
487
+ pmat[sel] = len(rows)
488
+ rows.append(m.plasticity.params(*m.lame))
489
+ n_kin = max(n_kin, len(m.plasticity.kinematic))
490
+ symmetric &= all(c == 0.0 or d == 0.0 for c, d in m.plasticity.kinematic)
491
+ elif m.porous:
492
+ kind[sel] = POROUS
493
+ pmat[sel] = len(rows)
494
+ rows.append(m.porous_plasticity.params(*m.lame))
495
+ porous_kin = max(porous_kin, len(m.porous_plasticity.kinematic))
496
+ symmetric = False
497
+ elif m.crystal_plastic:
498
+ kind[sel] = CRYSTAL
499
+ pmat[sel] = len(crystals)
500
+ crystals.append(m.crystal_plasticity)
501
+ par = m.crystal_plasticity.params_array()
502
+ symmetric &= not finite and bool(np.all((par[:, 1] == 0.0) | (par[:, 2] == 0.0)))
503
+ # the twins slow each other and the systems of a cleavage plane soften together
504
+ symmetric &= not m.crystal_plasticity.extended
505
+ # the rows of the porous and Hill points are longer (the GPU pads them all to ROW_WIDTH)
506
+ n_par = max([N_PARAMS] + [len(r) for r in rows])
507
+ params = (
508
+ np.array([np.pad(r, (0, n_par - len(r))) for r in rows])
509
+ if rows
510
+ else np.zeros((1, N_PARAMS))
511
+ )
512
+ n_max = max((c.n_systems for c in crystals), default=1)
513
+ n_cp = max(len(crystals), 1)
514
+ # the kinds of the systems after their parameters, for the crystals that twin or cleave
515
+ cp_par = np.zeros((n_cp, n_max, CP_WIDTH if any(c.extended for c in crystals) else CP_KIND))
516
+ cp_h = np.zeros((n_cp, n_max, n_max))
517
+ cp_n = np.zeros(n_cp, dtype=np.int64)
518
+ for c, cp in enumerate(crystals):
519
+ ns = cp.n_systems
520
+ cp_par[c, :ns, :CP_KIND] = cp.params_array()
521
+ if cp_par.shape[2] > CP_KIND:
522
+ cp_par[c, :ns, CP_KIND:] = cp.kinds_array()
523
+ cp_h[c, :ns, :ns] = cp.interaction_matrix()
524
+ cp_n[c] = ns
525
+ n_mats = table.matrices.shape[0]
526
+ systems = np.zeros((max(n_mats, 1), n_max, 6))
527
+ for c, cp in enumerate(crystals):
528
+ normals, directions = cp.systems()
529
+ mats = np.unique(table.mat[(kind == CRYSTAL) & (pmat == c)])
530
+ for m in mats[mats >= 0]:
531
+ g = table.rotations[m]
532
+ # vectors of the crystal in the axes of the sample: g^T v
533
+ systems[m, : cp.n_systems, :3] = directions @ g
534
+ systems[m, : cp.n_systems, 3:] = normals @ g
535
+ width = max([j2_width(n_kin)]
536
+ + [cp_width(c.n_systems, finite, c.reorients, c.micro_width) for c in crystals]
537
+ + [law.width for law in laws]
538
+ + ([porous_width(porous_kin)] if porous_kin >= 0 else [])) # fmt: skip
539
+ data = (
540
+ np.ascontiguousarray(table.matrices),
541
+ np.ascontiguousarray(table.eigen),
542
+ np.ascontiguousarray(params),
543
+ int(n_kin),
544
+ np.ascontiguousarray(systems),
545
+ cp_par,
546
+ cp_h,
547
+ cp_n,
548
+ )
549
+ symmetric = bool(symmetric and all(law.symmetric for law in laws))
550
+ return Behaviours(kind=kind, pmat=pmat, data=data, width=int(width), crystals=crystals,
551
+ mfront=laws, symmetric=symmetric) # fmt: skip
552
+
553
+
554
+ def _lattice_turns(crystal, finite: bool, grads, state) -> np.ndarray:
555
+ """The rotations (points x 3 x 3) that the lattices of crystal points have turned by:
556
+ ``R_e`` of the polar decomposition of ``F_e`` in finite strains (none in small
557
+ strains), after that of the twin that turned the lattice, ``R_e R_t``. The lattice
558
+ of orientation ``g`` is then ``g (R_e R_t)^T``."""
559
+ if finite:
560
+ off = CP_ALPHA + 2 * crystal.n_systems
561
+ turns = fin.lattice_rotations(grads, state[:, off : off + 9] + np.eye(3).ravel())
562
+ else:
563
+ turns = np.broadcast_to(np.eye(3), (len(state), 3, 3))
564
+ if crystal.reorients:
565
+ first = cp_width(crystal.n_systems, finite)
566
+ turns = turns @ (state[:, first : first + 9].reshape(-1, 3, 3) + np.eye(3))
567
+ return turns
568
+
569
+
570
+ def _majority(lattices) -> np.ndarray:
571
+ """The points of each element that have the lattice of most of its points (1, the
572
+ others 0): ``lattices``, the rotations of their twins less the identity (elements x
573
+ points x 9; the same numbers for the points that the same twin turned). The lattice
574
+ of the grain unless more than half of the points are turned; then that of the twin
575
+ of most of them (the first of the twins of as many points)."""
576
+ moved = np.any(lattices != 0.0, axis=-1)
577
+ turned = 2 * moved.sum(axis=1) > lattices.shape[1]
578
+ same = np.all(lattices[:, :, None, :] == lattices[:, None, :, :], axis=-1)
579
+ # the points that have the lattice of each point, among those turned (or not) as most
580
+ count = np.where(moved == turned[:, None], same.sum(axis=2), 0)
581
+ chosen = np.argmax(count, axis=1)
582
+ return same[np.arange(len(lattices)), chosen].astype(float)
583
+
584
+
585
+ def _mfront_points(solver):
586
+ """The points of the MFront behaviours of a solver of paths, integrated by MGIS
587
+ (:class:`~morphogen.homogenization.mfront.MFrontPoints`, built at the first call; their
588
+ tangents symmetrized as the solver's), or None without them."""
589
+ beh = solver.behaviours
590
+ if not beh.mfront:
591
+ return None
592
+ points = solver.__dict__.get("_mfront_points")
593
+ if points is None:
594
+ points = external_points(beh.mfront, solver.kind, solver.pmat, solver.point_mat,
595
+ solver.table.rotations, solver.finite,
596
+ symmetric=solver.symmetrize) # fmt: skip
597
+ solver.__dict__["_mfront_points"] = points
598
+ return points
599
+
600
+
601
+ def external_points(laws, kind, pmat, point_mat, rotations, finite: bool, *,
602
+ symmetric: bool = True): # fmt: skip
603
+ """The points of the behaviours integrated outside the kernels (of the kind
604
+ ``MFRONT``, of the ``laws`` ``pmat``): those of the MFront behaviours by MGIS
605
+ (:class:`~morphogen.homogenization.mfront.MFrontPoints`), those of the learned laws by
606
+ their models (:class:`~morphogen.learning.behaviour.LearnedPoints`), together, their
607
+ tangents symmetrized with ``symmetric`` (for the conjugate gradients); None without
608
+ them."""
609
+ if not laws:
610
+ return None
611
+ from morphogen.learning.behaviour import LearnedLaw, LearnedPoints
612
+
613
+ kind, pmat = np.asarray(kind), np.asarray(pmat)
614
+ external = kind == MFRONT
615
+ learned = np.array([isinstance(law, LearnedLaw) for law in laws])
616
+ parts = []
617
+ for flag in (False, True):
618
+ own = np.flatnonzero(learned == flag)
619
+ if own.size == 0:
620
+ continue
621
+ index = np.full(len(laws), -1)
622
+ index[own] = np.arange(own.size)
623
+ row = index[np.where(external, pmat, 0)]
624
+ mine = external & (row >= 0)
625
+ args = ([laws[i] for i in own], np.where(mine, MFRONT, ELASTIC),
626
+ np.where(mine, row, -1), point_mat, rotations, finite) # fmt: skip
627
+ if flag:
628
+ parts.append(LearnedPoints(*args, symmetric=symmetric))
629
+ else:
630
+ from morphogen.homogenization.mfront import MFrontPoints
631
+
632
+ parts.append(MFrontPoints(*args, symmetric=symmetric))
633
+ return parts[0] if len(parts) == 1 else _ExternalPoints(parts)
634
+
635
+
636
+ class _ExternalPoints:
637
+ """The points of MFront behaviours and of learned laws of one solver together."""
638
+
639
+ def __init__(self, parts):
640
+ self.parts = parts
641
+ self.points = np.sort(np.concatenate([part.points for part in parts]))
642
+
643
+ def integrate(self, grads, dtemp, dt, old, new, stress, tangent) -> int:
644
+ return sum(p.integrate(grads, dtemp, dt, old, new, stress, tangent) for p in self.parts)
645
+
646
+ def integrate_compact(self, grads, dtemp, dt, old, new, stress, tangent) -> int:
647
+ failed = 0
648
+ for part in self.parts:
649
+ pos = np.searchsorted(self.points, part.points)
650
+ out = [new[pos], stress[pos], tangent[pos]]
651
+ failed += part.integrate_compact(grads[pos], dtemp, dt, old[pos], *out)
652
+ new[pos], stress[pos], tangent[pos] = out
653
+ return failed
654
+
655
+
656
+ def _update(finite, beh_kind, mat, pmat, data, grads, dtemp, dt, old, new, stress, tangent, guess,
657
+ ratio, symmetric: bool = True) -> int: # fmt: skip
658
+ """Integration of the behaviours of the points in small or finite strains, their
659
+ tangents symmetrized with ``symmetric``."""
660
+ update = fin.update_points_finite if finite else update_points
661
+ return update(beh_kind, mat, pmat, data, grads, dtemp, dt, old, new, stress, tangent,
662
+ int(guess), float(ratio), bool(symmetric)) # fmt: skip
663
+
664
+
665
+ @njit(parallel=True, cache=True)
666
+ def _tangent_norms(tangent, out):
667
+ """``out[p] = (|C_p - C_p^T|^2, |C_p|^2)``: the squared Frobenius norms of twice the
668
+ skew part of the tangent ``C_p`` of each point and of the tangent."""
669
+ nc = tangent.shape[1]
670
+ for p in prange(tangent.shape[0]):
671
+ s = 0.0
672
+ c = 0.0
673
+ for i in range(nc):
674
+ for j in range(nc):
675
+ a = tangent[p, i, j]
676
+ d = a - tangent[p, j, i]
677
+ c += a * a
678
+ s += d * d
679
+ out[p, 0] = s
680
+ out[p, 1] = c
681
+
682
+
683
+ @njit(parallel=True, cache=True)
684
+ def _symmetrize_points(tangent):
685
+ for p in prange(tangent.shape[0]):
686
+ symmetrize(tangent[p])
687
+
688
+
689
+ def asymmetry(tangent, wts, groups=None) -> float:
690
+ """The asymmetry of the consistent tangents ``C_p`` of the points (points x nc x nc,
691
+ weights ``wts``) that decides ``tangent="auto"`` (:data:`ASYMMETRY`): ``|C - C^T| /
692
+ |C|`` for the block-diagonal operator ``C`` of the points, ``sqrt(sum_p w_p |C_p -
693
+ C_p^T|^2 / sum_p w_p |C_p|^2)`` (Frobenius norms), the stiffer points weighing more;
694
+ with ``groups`` (the phase of each point), the largest of those of the phases, so that
695
+ a small phase whose tangents are far from symmetric is not diluted by the others (a
696
+ learned law at 0.6 % of the voxels: 1.3e-2 for the whole volume element, 0.2 for its
697
+ phase). Point by point, ``|C_p - C_p^T| / |C_p|`` reaches 0.1 to 0.2 at a few points of
698
+ morphoGen's own laws (porous points near their softening, crystals whose slip systems
699
+ harden each other strongly) whose tangents are soft, where the operator stays nearly
700
+ symmetric."""
701
+ norms = np.empty((tangent.shape[0], 2))
702
+ _tangent_norms(np.ascontiguousarray(tangent), norms)
703
+ w = np.abs(np.asarray(wts, dtype=float))
704
+ if groups is None:
705
+ return _asymmetry_of(dot(w, norms[:, 0]), dot(w, norms[:, 1]))
706
+ groups = np.asarray(groups)
707
+ largest = 0.0
708
+ for g in np.unique(groups):
709
+ points = np.flatnonzero(groups == g)
710
+ wg = w[points]
711
+ largest = max(largest, _asymmetry_of(dot(wg, norms[points, 0]),
712
+ dot(wg, norms[points, 1]))) # fmt: skip
713
+ return largest
714
+
715
+
716
+ def _asymmetry_of(skew: float, full: float) -> float:
717
+ """The asymmetry of :func:`asymmetry` from the sums of the squared norms of the ``C_p -
718
+ C_p^T`` and of the ``C_p`` (weighted alike)."""
719
+ return math.sqrt(skew / full) if full > 0.0 else 0.0
720
+
721
+
722
+ class _PointArrays:
723
+ """The arrays of the integration points of a discretization of the loading paths (see
724
+ :class:`_PathSolver`) in the memory of the CPU, and the integration of their behaviours
725
+ there (:func:`_update`); :class:`morphogen.homogenization.gpu.VoxelPaths` keeps them on
726
+ the GPU instead. ``problem``: the solver of the paths."""
727
+
728
+ problem: _PathSolver
729
+
730
+ def arrays(self, n_pts: int, nc: int, width: int) -> tuple:
731
+ """Measures of strain, weights, stresses, tangents and two sets of internal
732
+ variables of ``n_pts`` points (measures and stresses of ``nc`` components,
733
+ ``width`` internal variables)."""
734
+ return (np.zeros((n_pts, nc)), np.zeros(n_pts), np.zeros((n_pts, nc)),
735
+ np.zeros((n_pts, nc, nc)), np.zeros((n_pts, width)),
736
+ np.zeros((n_pts, width))) # fmt: skip
737
+
738
+ def integrate(self, grads, dtemp, dt, old, new, stress, tangent, guess, ratio) -> int:
739
+ """Integration of the behaviours of the points over a step (see :func:`_update`;
740
+ MGIS integrates the points of MFront behaviours), their tangents symmetrized as
741
+ the problem says (:attr:`_PathSolver.symmetrize`): the number of points whose
742
+ integration failed."""
743
+ p = self.problem
744
+ failed = _update(p.finite, p.kind, p.point_mat, p.pmat, p.behaviours.data, grads,
745
+ dtemp, dt, old, new, stress, tangent, guess, ratio,
746
+ p.symmetrize) # fmt: skip
747
+ points = _mfront_points(p)
748
+ if points is not None:
749
+ failed += points.integrate(grads, dtemp, dt, old, new, stress, tangent)
750
+ return failed
751
+
752
+ def stress_scale(self, sigma, wts) -> float:
753
+ """Integral of the norm of the stresses of the points: the scale of the residuals of
754
+ the macroscopic unknowns."""
755
+ return float(np.sum(np.abs(wts) * np.sqrt(np.einsum("ij,ij->i", sigma, sigma))))
756
+
757
+ def asymmetry(self, tangent, wts) -> float:
758
+ """The largest asymmetry of the tangents of the points of the phases
759
+ (:func:`asymmetry`)."""
760
+ return asymmetry(tangent, wts, self.problem.point_group)
761
+
762
+ def symmetrize(self, tangent) -> None:
763
+ """The tangents of the points replaced by their symmetric parts, in place (to the
764
+ bit those of the kernels that symmetrize them)."""
765
+ _symmetrize_points(tangent)
766
+
767
+ def host(self, *arrays) -> tuple:
768
+ """The arrays in the memory of the CPU (for the outputs)."""
769
+ return arrays
770
+
771
+
772
+ #: The number of iterates whose largest residual bounds the line search of Newton's
773
+ #: corrections where cleavage planes are regularized by their microdamage
774
+ _MICRO_WINDOW = 4
775
+ #: The share of the largest scales of the residuals reached along a path that the scales
776
+ #: of a state keep where cleavage planes are regularized by their microdamage, in place of
777
+ #: :data:`_UNLOADED`: a cell that a crack cuts through keeps no stress with which to
778
+ #: compare its residuals, and the local iterations of the planes resolve their stresses
779
+ #: to 1e-10 of their strength, no further
780
+ _CUT = 1e-3
781
+ #: The equilibria of a step between two updates of the microdamage are solved to this
782
+ #: share of the last change of the microdamage (over the damage that breaks a plane), no
783
+ #: looser than :data:`_LOOSE` and no tighter than the tolerance of Newton's iteration,
784
+ #: to which the last one is solved: the damage of an equilibrium is known to about the
785
+ #: error of its residual, which the next update takes over
786
+ _SHARE = 0.1
787
+ _LOOSE = 1e-2
788
+ #: The loosest relative residual of the solutions of the macroscopic coupling between the
789
+ #: updates of a microdamage (ten times the tolerance of the equilibria, at most this)
790
+ _COARSE = 1e-2
791
+ #: The acceleration of the alternate scheme of the microdamage (after Storvik et al.
792
+ #: 2021): the relaxation of its updates once their residual has grown over this many
793
+ #: passes in a row, and how far an extrapolated update may go past the plain one, in
794
+ #: units of the residual of each element
795
+ _RELAXATION = 1.6
796
+ _GROWING = 3
797
+ _REACH = 10.0
798
+ #: The share of the merit of the last iterate above which a correction was a poor one:
799
+ #: the condensation of the macroscopic unknowns is then computed again (with regularized
800
+ #: cleavage planes: where one breaks, the tangents of the cell are no longer those of
801
+ #: the condensation that the iterations keep)
802
+ _POOR = 0.25
803
+
804
+
805
+ @dataclass
806
+ class _Planes:
807
+ """The cleavage planes of a crystal that their microdamage regularizes, at the points
808
+ of its ``elements``: the columns of the cumulated slips of the systems of each plane
809
+ (``members``: their sum is its damage) and of the slip systems (``slips``), that of
810
+ the microdamage (``slot``; the marks of the planes follow it), the rate of the
811
+ softening and the strength of each plane, the micromorphic modulus, the rate at which
812
+ the slip lowers the strength, and the damage that breaks a plane."""
813
+
814
+ elements: np.ndarray
815
+ points: np.ndarray
816
+ members: list
817
+ slips: np.ndarray
818
+ slot: int
819
+ softening: np.ndarray
820
+ strength: np.ndarray
821
+ modulus: float
822
+ coupling: float
823
+ broken: float
824
+
825
+
826
+ class _Microdamage:
827
+ """The microdamage of the crystals whose cleavage planes it regularizes (Aslan &
828
+ Forest 2009; :attr:`~morphogen.homogenization.crystal.CrystalPlasticity.regularized`):
829
+ a field ``chi_d`` that follows the damage ``d`` of the planes of the points over a
830
+ length, ``chi_d - ell^2 lap chi_d = d``, and that their thresholds take off the damage
831
+ (an internal variable of their points). The equilibrium of a step is solved for a
832
+ given microdamage, which is then that of the damage reached, and again until it
833
+ settles (a fixed point, as the alternate minimization of a phase field): the points
834
+ harden at a fixed microdamage and soften as it follows them.
835
+
836
+ A plane whose strength the microdamage has brought to nothing is broken through
837
+ (:meth:`_break`): it is marked in its point, keeps no strength, and what it opens
838
+ since is the opening of a crack, not a damage — the microdamage keeps the damage that
839
+ the plane had, and does not spread from a crack that opens.
840
+
841
+ ``solver``: the solver of the paths, whose ``_smooth(elements, values, length)``
842
+ solves the equation of the microdamage for the damage ``values`` of its ``elements``
843
+ (the means of their points)."""
844
+
845
+ def __init__(self, solver):
846
+ beh = solver.behaviours
847
+ self.solver, self.ng = solver, solver.ng
848
+ self.tol, self.most = float(solver.microdamage_tol), int(solver.microdamage_passes)
849
+ self.parts: list[_Planes] = []
850
+ #: the crystals of each length: they share a microdamage, that of the damage of
851
+ #: them all (a crack goes from the one to the other)
852
+ self.fields: dict[float, list[int]] = {}
853
+ for c, cp in enumerate(beh.crystals):
854
+ if not cp.regularized:
855
+ continue
856
+ elements = np.flatnonzero((beh.kind == CRYSTAL) & (beh.pmat == c))
857
+ if elements.size == 0:
858
+ continue
859
+ n = cp.n_systems
860
+ kinds, par = cp.kinds_array(), cp.params_array()
861
+ first = CP_ALPHA + n # the cumulated slips of the systems
862
+ planes = range(cp.n_planes)
863
+ opening = [
864
+ int(np.flatnonzero((kinds[:, 3] == p) & (kinds[:, 0] == OPENING))[0])
865
+ for p in planes
866
+ ]
867
+ modulus, length = cp.cleavage_regularization
868
+ self.fields.setdefault(float(length), []).append(len(self.parts))
869
+ self.parts.append(
870
+ _Planes(
871
+ elements=elements,
872
+ points=(elements[:, None] * self.ng + np.arange(self.ng)).ravel(),
873
+ members=[first + np.flatnonzero(kinds[:, 3] == p) for p in planes],
874
+ slips=first + np.flatnonzero(kinds[:, 0] == SLIP),
875
+ slot=cp_width(n, solver.finite, cp.reorients),
876
+ softening=kinds[opening, 1],
877
+ strength=par[opening, 0],
878
+ modulus=float(modulus),
879
+ coupling=float(cp.cleavage_coupling),
880
+ broken=float(1.0 / kinds[opening, 1].max()),
881
+ )
882
+ )
883
+ if self.parts and type(solver)._smooth is _PathSolver._smooth:
884
+ solver._smooth(np.zeros(0, dtype=np.int64), np.zeros(0), 1.0) # (refuses them)
885
+ self.kept: list = []
886
+ #: the equilibria solved, and the steps kept before the microdamage had settled
887
+ self.passes = 0
888
+ self.unsettled = 0
889
+ self.accelerated = bool(solver.microdamage_acceleration)
890
+ self._restart()
891
+
892
+ def _restart(self) -> None:
893
+ """The acceleration starts again, from the plain updates: no earlier pass (a new
894
+ step, or planes broken through: another fixed point)."""
895
+ self._last = None # the microdamage of the last equilibrium and its residual
896
+ self._norms: list[float] = [] # of the residuals of the passes
897
+ self._growing = 0 # the passes in a row over which the residual has grown
898
+ #: how far the microdamage of the equilibrium was extrapolated past its plain
899
+ #: update, at the points of each part
900
+ self._excess = [0.0] * len(self.parts)
901
+
902
+ def __bool__(self) -> bool:
903
+ return bool(self.parts)
904
+
905
+ @staticmethod
906
+ def _block(part: _Planes) -> slice:
907
+ """The microdamage of the points of a part and the marks of their planes."""
908
+ return slice(part.slot, part.slot + 1 + len(part.members))
909
+
910
+ def begin(self, old) -> None:
911
+ """The microdamage and the marks of the last converged step (those of the points
912
+ ``old``), kept for the steps that are divided."""
913
+ self.kept = [old[part.points, self._block(part)].copy() for part in self.parts]
914
+ self._restart()
915
+
916
+ def rollback(self, old) -> None:
917
+ for part, kept in zip(self.parts, self.kept, strict=True):
918
+ old[part.points, self._block(part)] = kept
919
+ self._restart()
920
+
921
+ @staticmethod
922
+ def _damage(part: _Planes, state):
923
+ """The damage of each plane of the points of a part in ``state`` (points x
924
+ planes), and what the point gives to the microdamage: the damage of its planes,
925
+ that which they had for those broken through."""
926
+ block = state[part.points]
927
+ own = np.stack([block[:, columns].sum(axis=1) for columns in part.members], axis=1)
928
+ marks = block[:, part.slot + 1 : part.slot + 1 + len(part.members)]
929
+ return own, np.where(marks > 0.5, marks - 1.0, own).sum(axis=1)
930
+
931
+ def _strength(self, part: _Planes, state, source, micro):
932
+ """The share of its strength that each plane of the points of a part keeps
933
+ (points x planes) for the damage ``d`` of the planes of the points (``source``:
934
+ what they give to the microdamage) and the microdamage ``micro``: ``fall - w d +
935
+ chi_H (d - chi_d) / Y_0`` (``fall``: of the cumulated slip of ``state``)."""
936
+ fall = 1.0
937
+ if part.coupling > 0.0:
938
+ slipped = state[part.points][:, part.slips].sum(axis=1)
939
+ fall = np.exp(-part.coupling * slipped)[:, None]
940
+ ahead = (part.modulus / part.strength) * (source - micro)[:, None]
941
+ return fall - part.softening * source[:, None] + ahead
942
+
943
+ def _break(self, part: _Planes, old, new, micro, excess=0.0) -> bool:
944
+ """The planes that an equilibrium breaks through. Those that end it without
945
+ strength, ``Y_0 (fall - w d) + chi_H (d - chi_d) <= 0`` at the damage reached
946
+ (``new``) — for the microdamage of the equilibrium (that of ``old``: a plane that
947
+ has softened to nothing, or one that a crack nearby has unloaded and left free
948
+ to open) or for the one that follows it (``micro``: the microdamage takes what
949
+ was left of its strength); nothing: what the tolerance of the microdamage
950
+ resolves of a strength, ``chi_H tol / w``. And those that have opened with a
951
+ damage further ahead of the microdamage than anywhere in the band that breaks,
952
+ ``d - chi_d > (Y_0 / chi_H) / sqrt(1 - w Y_0 / chi_H)`` (the centre of the band
953
+ as its stress comes to nothing): planes that a crack forces open beside those
954
+ that it has broken — in the next element —, and which would harden against it,
955
+ since the microdamage does not follow one element. No plane is broken through
956
+ where the microdamage of the equilibrium had been extrapolated (``excess``: past
957
+ its plain update) beyond that of the damage reached: it was ahead of the damage.
958
+
959
+ These planes are marked in the points, for good, with the damage that they had
960
+ then: that of the start of the step for a plane that had no strength from the
961
+ start of the equilibrium to its end (what it has opened is the opening of a
962
+ crack), that reached otherwise (less what it has opened beyond the bound)."""
963
+ marks = slice(part.slot + 1, part.slot + 1 + len(part.members))
964
+ own, source = self._damage(part, new)
965
+ before, given = self._damage(part, old)
966
+ last = old[part.points, part.slot] # the microdamage of the equilibrium
967
+ ended = self._strength(part, new, source, last)
968
+ ratio = part.softening * part.strength / part.modulus
969
+ lost = np.maximum(self.tol * part.modulus / (part.softening * part.strength), _BROKEN)
970
+ breaks = np.minimum(ended, self._strength(part, new, source, micro)) <= lost
971
+ beyond = (source - micro)[:, None] - part.strength / (part.modulus * np.sqrt(1.0 - ratio))
972
+ forced = (beyond > 0.0) & (own > before)
973
+ breaks = (breaks | forced) & (old[part.points, marks] < 0.5)
974
+ slack = self.tol * part.broken
975
+ ahead = (np.asarray(excess) > slack) & (last - micro > slack)
976
+ breaks &= ~np.broadcast_to(ahead, last.shape)[:, None]
977
+ if not breaks.any():
978
+ return False
979
+ started = self._strength(part, old, given, last)
980
+ kept = np.where(forced, np.maximum(own - beyond, before), own)
981
+ kept = np.where((started <= _BROKEN) & (ended <= lost), before, kept)
982
+ marked = np.where(breaks, 1.0 + kept, old[part.points, marks])
983
+ old[part.points, marks] = marked
984
+ new[part.points, marks] = marked
985
+ return True
986
+
987
+ def _accelerate(self, current, target, weight):
988
+ """The microdamage of the next equilibrium from that of the last one
989
+ (``current``) and that of the damage that it reached (``target``, the plain
990
+ update), for the elements of all the parts (``weight``: their volumes). After
991
+ the scheme of Storvik et al. (2021) for the alternate minimization of a phase
992
+ field, by the residual ``target - current`` of the fixed point: where it has
993
+ decreased over two passes, Anderson's acceleration of depth one — the secant
994
+ extrapolation of the last two updates, within :data:`_REACH` residuals of the
995
+ plain one —, that of a fixed point close by; where it has grown over
996
+ :data:`_GROWING` passes (a crack that starts to run: no fixed point close by), a
997
+ relaxation of the update, :data:`_RELAXATION`; the plain update otherwise."""
998
+ residual = target - current
999
+ norm = math.sqrt(dot(weight, residual * residual))
1000
+ last, self._last = self._last, (current, residual)
1001
+ norms = self._norms
1002
+ norms.append(norm)
1003
+ if last is None or len(norms) < 2:
1004
+ return target
1005
+ if norm > norms[-2]: # the residual grows
1006
+ self._growing += 1
1007
+ if self._growing >= _GROWING:
1008
+ return current + _RELAXATION * residual
1009
+ return target
1010
+ self._growing = 0
1011
+ if len(norms) < 3 or norms[-2] > norms[-3]:
1012
+ return target
1013
+ change = residual - last[1]
1014
+ scale = dot(weight, change * change)
1015
+ if scale <= 0.0:
1016
+ return target
1017
+ gamma = dot(weight, change * residual) / scale
1018
+ step = -gamma * (current - last[0] + change) # past the plain update
1019
+ reach = _REACH * np.abs(residual)
1020
+ return target + np.clip(step, -reach, reach)
1021
+
1022
+ def settle(self, old, new, wts, last: bool = False) -> float:
1023
+ """The microdamage of the damage reached (``new``), given to the points of the
1024
+ step (``old``, which the kernels read, and ``new``): its largest change, over the
1025
+ damage that breaks a plane (more than any tolerance where it breaks planes: the
1026
+ step is then solved again). Unless the microdamage has settled, or the pass is
1027
+ the ``last`` one of the step, the points are given an accelerated update
1028
+ (:meth:`_accelerate`)."""
1029
+ change = 0.0
1030
+ ng = self.ng
1031
+ broke = False
1032
+ found = [None] * len(self.parts) # the microdamage of the damage reached (elements)
1033
+ for length, members in self.fields.items():
1034
+ means = []
1035
+ for k in members:
1036
+ part = self.parts[k]
1037
+ shape = (part.elements.size, ng)
1038
+ source = self._damage(part, new)[1].reshape(shape)
1039
+ weights = np.abs(np.asarray(wts)[part.points]).reshape(shape)
1040
+ means.append((weights * source).sum(axis=1) / weights.sum(axis=1))
1041
+ elements = np.concatenate([self.parts[k].elements for k in members])
1042
+ smooth = self.solver._smooth(elements, np.concatenate(means), length)
1043
+ start = 0
1044
+ for k in members:
1045
+ part = self.parts[k]
1046
+ found[k] = smooth[start : start + part.elements.size]
1047
+ start += part.elements.size
1048
+ micro = np.repeat(found[k], ng)
1049
+ moved = float(np.abs(micro - old[part.points, part.slot]).max())
1050
+ change = max(change, moved / part.broken)
1051
+ broke |= self._break(part, old, new, micro, self._excess[k])
1052
+ self.passes += 1
1053
+ update = found
1054
+ self._excess = [0.0] * len(self.parts)
1055
+ if broke: # another fixed point: the step again, from the plain update
1056
+ change = max(change, 1.0)
1057
+ self._restart()
1058
+ elif self.accelerated and not last and change > self.tol:
1059
+ sizes = np.cumsum([part.elements.size for part in self.parts])[:-1]
1060
+ current = np.concatenate([old[p.points, p.slot][::ng] for p in self.parts])
1061
+ volumes = np.concatenate(
1062
+ [np.abs(np.asarray(wts)[p.points]).reshape(-1, ng).sum(axis=1) for p in self.parts]
1063
+ )
1064
+ update = np.split(self._accelerate(current, np.concatenate(found), volumes), sizes)
1065
+ self._excess = [np.repeat(u - f, ng) for u, f in zip(update, found, strict=True)]
1066
+ for part, values in zip(self.parts, update, strict=True):
1067
+ micro = np.repeat(values, ng)
1068
+ old[part.points, part.slot] = micro
1069
+ new[part.points, part.slot] = micro
1070
+ return change
1071
+
1072
+
1073
+ # -- driver ------------------------------------------------------------------------------
1074
+
1075
+
1076
+ class _Steps:
1077
+ """Time stepping along a path: the planned steps, divided by two after a failure
1078
+ (``level`` divisions) and grown back after two converged steps."""
1079
+
1080
+ def __init__(self, path: LoadingPath, max_cuts: int):
1081
+ self.ends = path.schedule()
1082
+ self.start = float(path.times[0])
1083
+ self.segment_ends = np.asarray(path.times[1:])
1084
+ self.max_cuts = int(max_cuts)
1085
+ self.k = 0
1086
+ self.t = self.start
1087
+ self.level = 0
1088
+ self.successes = 0
1089
+ self.cuts = 0
1090
+
1091
+ @property
1092
+ def done(self) -> bool:
1093
+ return self.k >= len(self.ends)
1094
+
1095
+ def _planned(self) -> float:
1096
+ """Length of the current planned step."""
1097
+ start = self.ends[self.k - 1] if self.k else self.start
1098
+ return float(self.ends[self.k] - start)
1099
+
1100
+ def next(self) -> float:
1101
+ """End of the next attempted step (the end of the planned step, rather than a
1102
+ sliver before it)."""
1103
+ end = float(self.ends[self.k])
1104
+ dt = self._planned() / 2.0**self.level
1105
+ t_try = self.t + dt
1106
+ return end if t_try >= end - 1e-9 * dt else t_try
1107
+
1108
+ def accept(self, t_new: float) -> None:
1109
+ self.t = t_new
1110
+ if t_new == self.ends[self.k]:
1111
+ self.k += 1
1112
+ self.successes += 1
1113
+ if self.successes >= 2 and self.level > 0:
1114
+ self.level -= 1
1115
+ self.successes = 0
1116
+
1117
+ def reject(self) -> None:
1118
+ self.level += 1
1119
+ self.successes = 0
1120
+ self.cuts += 1
1121
+ if self.level > self.max_cuts:
1122
+ raise RuntimeError(
1123
+ f"nonlinear solution: no convergence at time {self.t:.6g} after dividing the "
1124
+ f"step {self.max_cuts} times"
1125
+ )
1126
+
1127
+ def segment(self, t: float) -> int:
1128
+ return int(np.searchsorted(self.segment_ends, t - 1e-12 * max(1.0, abs(t))))
1129
+
1130
+
1131
+ #: Halvings of the Newton corrections in the line search
1132
+ _MAX_HALVINGS = 6
1133
+
1134
+
1135
+ def _line_search(evaluate, x, unknown, dx, merit0: float, merit):
1136
+ """Backtracking line search along the Newton correction ``dx`` of the components
1137
+ ``unknown`` of ``x``: the first of the steps 1, 1/2, ... that decreases the merit
1138
+ (Armijo), or the shortest one if it decreases it at all. Returns the new point and its
1139
+ evaluation (None when the evaluation fails or the merit does not decrease).
1140
+
1141
+ ``merit0`` is the merit at ``x``, or, for a nonmonotone search (Grippo, Lampariello &
1142
+ Lucidi 1986), the largest merit of the last iterates: the merit may then rise from
1143
+ ``x``, below that largest value. The residual of unilateral contacts is not smooth:
1144
+ where the contacts change along the correction, it rises along a direction that is
1145
+ the right one — that of the solution of the contacts as they are —, and the next
1146
+ linearization, with the contacts as they have become, corrects it (an active-set
1147
+ iteration, which the short steps that decrease the residual would let change its set
1148
+ only little by little); the bound keeps the iteration from cycling."""
1149
+ t = 1.0
1150
+ for k in range(_MAX_HALVINGS + 1):
1151
+ x_t = x.copy()
1152
+ x_t[unknown] += t * dx
1153
+ out = evaluate(x_t)
1154
+ if out is not None:
1155
+ m = merit(out)
1156
+ if m <= (1.0 - 1e-4 * t) * merit0 or (k == _MAX_HALVINGS and m < merit0):
1157
+ return x_t, out
1158
+ t *= 0.5
1159
+ return x, None
1160
+
1161
+
1162
+ def _point_merit(out) -> float:
1163
+ return dot(out[2], out[2])
1164
+
1165
+
1166
+ def _fe_merit(out) -> float:
1167
+ """Merit of the residuals of a trial state: the equilibrium relative to the nodal
1168
+ forces, the macroscopic stress relative to the stresses."""
1169
+ r_q, r_e, fscale, escale = out
1170
+ # squares bounded below, not the scales: (1e-300)^2 underflows to zero
1171
+ return dot(r_q, r_q) / max(fscale * fscale, 1e-300) + dot(r_e, r_e) / max(
1172
+ escale * escale, 1e-300
1173
+ )
1174
+
1175
+
1176
+ def _split(evaluate, n_q, temp, dt, values, x):
1177
+ """Evaluation of a trial state ``x = (q, E)`` (the slips from the current iterate)."""
1178
+ return evaluate(x[:n_q], x[n_q:], temp, dt, values, 1, 1.0)
1179
+
1180
+
1181
+ def _predicted(dt: float, last, before=None):
1182
+ """Increments of the unknowns ``(q, E)`` over a step ``dt``, predicted from the last
1183
+ converged step ``last = (segment, dt, dq, dE)``: its rate (first order); with the
1184
+ step ``before`` it, of the same segment, its rate and the change of the rates of the
1185
+ two steps, which are those of their middles (second order: the unknowns extrapolated
1186
+ as a parabola through the ends of the two steps)."""
1187
+ ratio = dt / last[1]
1188
+ dq, de = ratio * last[2], ratio * last[3]
1189
+ if before is not None and before[0] == last[0]:
1190
+ c = dt * (dt + last[1]) / (last[1] + before[1])
1191
+ dq = dq + c * (last[2] / last[1] - before[2] / before[1])
1192
+ de = de + c * (last[3] / last[1] - before[3] / before[1])
1193
+ return dq, de
1194
+
1195
+
1196
+ def _second_order(step, last, before) -> bool:
1197
+ """Whether the next step is predicted at the second order: where the second-order
1198
+ prediction (:func:`_predicted`) of the converged ``step`` from the two steps before
1199
+ it was clearly closer to it than the first-order one (:data:`_SECOND`: half its
1200
+ error, the errors of the fluctuation and of the macroscopic unknowns each relative
1201
+ to its increment), and the first-order one was not far from it (the same share of
1202
+ the increments). A response that turns (a yield, a crack that starts, a contact
1203
+ that closes, twins that start) is predicted at the first order: the second one
1204
+ would overshoot, and the step be divided."""
1205
+ if last is None or before is None or not (step[0] == last[0] == before[0]):
1206
+ return False
1207
+
1208
+ def error(prediction) -> float:
1209
+ total = 0.0
1210
+ for found, guess in zip(step[2:], prediction, strict=True):
1211
+ scale = norm(found)
1212
+ if scale > 0.0:
1213
+ total += norm(found - guess) / scale
1214
+ return total
1215
+
1216
+ first = error(_predicted(step[1], last))
1217
+ return first < _SECOND and error(_predicted(step[1], last, before)) < _SECOND * first
1218
+
1219
+
1220
+ def _secant(schur, step, before, after, symmetric: bool):
1221
+ """The condensed block of the macroscopic unknowns of an earlier linearization (their
1222
+ Schur complement, kept from a correction to the next), updated by the secant of a
1223
+ correction: their ``step`` and their condensed residuals ``before`` and ``after``
1224
+ it. The BFGS update of a symmetric block with Powell's damping (1978): the curvature
1225
+ of the secant along the step is kept between a fifth of and five times that of the
1226
+ block (:data:`_DAMPING`), so that the block stays positive definite and one update
1227
+ changes it by a bounded factor. Broyden's update otherwise, its change bounded by
1228
+ the image of the step likewise."""
1229
+ change = after - before
1230
+ image = schur @ step
1231
+ if symmetric:
1232
+ energy = float(step @ image)
1233
+ if energy <= 0.0:
1234
+ return schur
1235
+ curvature = float(change @ step)
1236
+ low, high = _DAMPING * energy, energy / _DAMPING
1237
+ if not low <= curvature <= high: # (the secant mixed with the image of the block)
1238
+ bound = low if curvature < low else high
1239
+ share = (bound - energy) / (curvature - energy)
1240
+ change = share * change + (1.0 - share) * image
1241
+ curvature = bound
1242
+ return schur - np.outer(image, image) / energy + np.outer(change, change) / curvature
1243
+ length = float(step @ step)
1244
+ if length == 0.0:
1245
+ return schur
1246
+ defect = change - image
1247
+ size, most = float(np.linalg.norm(defect)), float(np.linalg.norm(image)) / _DAMPING
1248
+ if size > most > 0.0:
1249
+ defect = defect * (most / size)
1250
+ return schur + np.outer(defect, step) / length
1251
+
1252
+
1253
+ @dataclass
1254
+ class StepState:
1255
+ """A converged step of a loading path, given to the ``monitor`` of
1256
+ :meth:`_PathSolver.run`: its time, the macroscopic strain (6), the unknowns of the
1257
+ fluctuation, the indices of the macroscopic components solved for, and the
1258
+ discretization with the arrays of its integration points (measures of strain,
1259
+ weights, stresses and consistent tangents at the end of the step)."""
1260
+
1261
+ time: float
1262
+ strain: np.ndarray
1263
+ q: np.ndarray
1264
+ unknown: np.ndarray
1265
+ disc: object
1266
+ grads: np.ndarray
1267
+ wts: np.ndarray
1268
+ sigma: np.ndarray
1269
+ tangent: np.ndarray
1270
+
1271
+
1272
+ def _macro_stress(finite: bool, stress, tangent):
1273
+ """Macroscopic stress (6) of a point and its tangent with respect to the macroscopic
1274
+ strain (6 x 6): the nominal stress in finite strains."""
1275
+ if not finite:
1276
+ return stress, tangent
1277
+ return fin.macro_part(stress), _MACRO.T @ tangent @ _MACRO
1278
+
1279
+
1280
+ def simulate_point(
1281
+ material: Material,
1282
+ path,
1283
+ *,
1284
+ name: str = "point",
1285
+ orientation=None,
1286
+ kinematics: str = "small",
1287
+ tol: float = 1e-10,
1288
+ max_newton: int = 30,
1289
+ max_cuts: int = 12,
1290
+ tangent: str = "auto",
1291
+ ) -> PathResult:
1292
+ """Response of one material point (homogeneous strain and stress) to a loading
1293
+ path: the components prescribed as stresses are solved for by Newton's method with
1294
+ the consistent tangent (a material point simulator, as ``Zsim``). ``orientation``:
1295
+ Bunge angles (degrees) of a crystal; ``kinematics``: ``"small"`` or ``"finite"``
1296
+ strains (the strain then holds the components of the upper triangular displacement
1297
+ gradient, the stress those of the first Piola-Kirchhoff stress). In finite strains,
1298
+ and where its twins turn it, the result has the ``orientation`` of the lattice of a
1299
+ crystal at each step: its Bunge angles ``g R_e^T``, with the rotation ``R_e`` of the
1300
+ polar decomposition of ``F_e`` (the material lines along the first axis stay along
1301
+ it, and the planes normal to the third stay normal to it: the grips of a tension
1302
+ along the first axis, the platens of a compression along the third). ``tangent``
1303
+ (:data:`TANGENTS`): Newton's method solves a dense system, with by default
1304
+ (``"auto"``) the exact tangents of the laws that are not symmetric (those of the learned
1305
+ laws and of the MFront behaviours too) and the symmetrized ones of the others (which
1306
+ only lose their round-off); ``"symmetric"`` symmetrizes them all, ``"full"`` keeps them
1307
+ all exact."""
1308
+ if tangent not in TANGENTS:
1309
+ raise ValueError(f"tangent: one of {TANGENTS}, got {tangent!r}")
1310
+ path = LoadingPath.from_spec(path)
1311
+ finite = kinematics_of(kinematics)
1312
+ if material.void:
1313
+ raise ValueError("simulate_point: the material is a void")
1314
+ mats = {0: material}
1315
+ if orientation is None:
1316
+ table = material_table([0], mats, "elastic")
1317
+ else:
1318
+ euler = np.asarray(orientation, dtype=float).reshape(1, 3)
1319
+ table = material_table([0], mats, "elastic", grains=[0], orientations=euler)
1320
+ beh = behaviour_table([0], mats, table, finite=finite)
1321
+ symmetric = tangent == "symmetric" or (tangent == "auto" and beh.symmetric)
1322
+ points = external_points(beh.mfront, beh.kind, beh.pmat, table.mat, table.rotations, finite,
1323
+ symmetric=tangent == "symmetric") # fmt: skip
1324
+ nc = 9 if finite else 6
1325
+ old, new = np.zeros((1, beh.width)), np.zeros((1, beh.width))
1326
+ stress, tangents = np.zeros((1, nc)), np.zeros((1, nc, nc))
1327
+ unknown = np.flatnonzero(~path.strain_controlled)
1328
+ controls = path.strain_controlled
1329
+ strain = np.zeros(6)
1330
+ rec = {"t": [path.times[0]], "e": [strain.copy()], "s": [np.zeros(6)], "T": [0.0], "p": [0.0]}
1331
+ rec.update({"cauchy": [np.zeros(6)], "full": [np.zeros(nc)]})
1332
+ porous = bool(beh.kind[0] == POROUS)
1333
+ rec["f"] = [float(beh.data[2][beh.pmat[0], P_F0])] if porous else []
1334
+ # the twins and the cleavage planes of a crystal: the curves of their fields
1335
+ crystal = beh.crystals[0] if beh.crystals and beh.crystals[0].extended else None
1336
+ if crystal is not None:
1337
+ rec["crystal"] = {name: [0.0] for name in crystal.field_names}
1338
+ if crystal.regularized:
1339
+ # a point alone has no gradient: its microdamage is its damage (a negative
1340
+ # value tells its kernel), and it softens with it, as fast as it may
1341
+ crystal.check_softening(material.matrix("elastic"), force=True)
1342
+ slot = cp_width(crystal.n_systems, finite, crystal.reorients)
1343
+ old[0, slot] = new[0, slot] = -1.0
1344
+ # the lattice of a crystal, where it turns: its rotation in finite strains, its twins
1345
+ lattice = beh.crystals[beh.pmat[0]] if beh.kind[0] == CRYSTAL else None
1346
+ if lattice is not None and not (finite or lattice.reorients):
1347
+ lattice = None
1348
+ if lattice is not None:
1349
+ from morphogen.orientations import matrix_to_euler
1350
+
1351
+ initial = table.rotations[table.mat[0]]
1352
+ rec["euler"] = [matrix_to_euler(initial)[0]]
1353
+ iterations = []
1354
+ steps = _Steps(path, max_cuts)
1355
+ history = None # (segment, dt, increment of the unknowns) of the last converged step
1356
+
1357
+ def evaluate(e, dt, temp, values, guess, ratio):
1358
+ """Macroscopic stress, tangent and residual of a trial strain (None on failure)."""
1359
+ grads = fin.gradient_of(e)[None] if finite else e[None]
1360
+ failed = _update(finite, beh.kind, table.mat, beh.pmat, beh.data, grads, temp, dt, old,
1361
+ new, stress, tangents, guess, ratio, symmetric) # fmt: skip
1362
+ if points is not None:
1363
+ failed += points.integrate(grads, temp, dt, old, new, stress, tangents)
1364
+ if failed:
1365
+ return None
1366
+ s6, k6 = _macro_stress(finite, stress[0], tangents[0])
1367
+ return s6, k6, s6[unknown] - values[unknown]
1368
+
1369
+ t0 = time.perf_counter()
1370
+ while not steps.done:
1371
+ t_new = steps.next()
1372
+ dt = t_new - steps.t
1373
+ values, temp = path.at(t_new)
1374
+ seg = steps.segment(t_new)
1375
+ e = strain.copy()
1376
+ e[controls] = values[controls]
1377
+ same = history is not None and history[0] == seg
1378
+ if same: # extrapolation of the unknown components
1379
+ e[unknown] += dt / history[1] * history[2]
1380
+ res = evaluate(e, dt, temp, values, 2 if same else 0, dt / history[1] if same else 1.0)
1381
+ ok, its = False, 0
1382
+ for its in range(max_newton): # noqa: B007
1383
+ if res is None:
1384
+ break
1385
+ s6, k6, r = res
1386
+ scale = float(np.abs(s6).max() + np.abs(values[unknown]).max(initial=0.0))
1387
+ # the round-off of the stresses of the strain: reached by a solution at zero
1388
+ # stress (a free thermal expansion), where the relative tolerance asks for zeros;
1389
+ # in finite strains that of the gradient I + H, which does not vanish with H (a
1390
+ # crack that has closed again at no strain: no stress, but for the round-off)
1391
+ stiff = float(np.abs(k6).max())
1392
+ floor = _ROUND_OFF * stiff * float(np.abs(e).max())
1393
+ if finite:
1394
+ floor += _ROUND_OFF_UNIT * stiff
1395
+ if np.all(np.abs(r) <= max(tol * scale, floor) + 1e-300):
1396
+ ok = True
1397
+ break
1398
+ de = -np.linalg.solve(k6[np.ix_(unknown, unknown)], r)
1399
+ trial = partial(evaluate, dt=dt, temp=temp, values=values, guess=1, ratio=1.0)
1400
+ e, res = _line_search(trial, e, unknown, de, float(r @ r), _point_merit)
1401
+ if not ok:
1402
+ steps.reject()
1403
+ history = None
1404
+ continue
1405
+ iterations.append(its)
1406
+ steps.accept(t_new)
1407
+ history = (seg, dt, e[unknown] - strain[unknown])
1408
+ strain = e
1409
+ old, new = new, old
1410
+ if crystal is not None and crystal.by_grain: # the lattice that its twins turn
1411
+ turn_twins(crystal, old, new, table.mat, beh.data[4], finite=finite)
1412
+ rec["t"].append(t_new)
1413
+ rec["e"].append(strain.copy())
1414
+ rec["s"].append(s6.copy())
1415
+ rec["full"].append(stress[0].copy())
1416
+ rec["T"].append(temp)
1417
+ rec["p"].append(float(old[0, STATE_P]))
1418
+ if porous:
1419
+ rec["f"].append(float(porosity(old, beh.data[2], beh.pmat)[0]))
1420
+ if crystal is not None:
1421
+ turned = crystal.state_fields(old, finite, table.rotations[table.mat])
1422
+ for name, values in turned.items():
1423
+ rec["crystal"][name].append(float(values[0]))
1424
+ if lattice is not None:
1425
+ grads = fin.gradient_of(strain)[None] if finite else strain[None]
1426
+ turn = _lattice_turns(lattice, finite, grads, old)[0]
1427
+ rec["euler"].append(matrix_to_euler(initial @ turn.T)[0])
1428
+ p = np.array(rec["p"])
1429
+ extra = {"porosity": np.array(rec["f"])} if porous else {}
1430
+ if lattice is not None:
1431
+ extra["orientation"] = np.array(rec["euler"])
1432
+ if crystal is not None:
1433
+ extra["series"] = {name: np.array(values) for name, values in rec["crystal"].items()}
1434
+ if finite:
1435
+ grads = fin.gradient_of(np.array(rec["e"]))
1436
+ extra["cauchy"] = fin.cauchy(np.array(rec["full"]), grads)
1437
+ extra["log_strain"] = fin.log_strain(grads)
1438
+ return PathResult(
1439
+ name=name,
1440
+ bc="point",
1441
+ path=path,
1442
+ times=np.array(rec["t"]),
1443
+ strain=np.array(rec["e"]),
1444
+ stress=np.array(rec["s"]),
1445
+ temperature=np.array(rec["T"]),
1446
+ plastic=p,
1447
+ iterations=np.array(iterations, dtype=int),
1448
+ info={"cuts": steps.cuts, "time_s": round(time.perf_counter() - t0, 4)},
1449
+ kinematics=kinematics,
1450
+ **extra,
1451
+ )
1452
+
1453
+
1454
+ class _PathSolver:
1455
+ """Loading paths of the periodic element: the time stepping and Newton's method
1456
+ shared by the finite element solver (:class:`NonlinearFEProblem`) and the FFT solver
1457
+ of voxel images (:class:`morphogen.homogenization.fft_nonlinear.NonlinearFFTProblem`).
1458
+
1459
+ The solvers give the behaviours of their integration points
1460
+ (:meth:`_point_behaviours`), the options of the iterations (:meth:`_path_options`)
1461
+ and their discretization (:meth:`_discretization`), an object with:
1462
+
1463
+ * ``n_q``: the number of unknowns of the fluctuation;
1464
+ * ``measures(q, e, grads, wts)``: the measures of strain of the integration points
1465
+ (and their weights) for the fluctuation ``q`` and the macroscopic strain ``e``;
1466
+ * ``forces(sigma, wts)``: the residual of the equilibrium on the unknowns, the
1467
+ integral of the stress and the norm of the nodal forces before they cancel (it may
1468
+ replace the stresses of the points by those conjugate to its measures of strain,
1469
+ as B-bar and F-bar do; the outputs then report them);
1470
+ * ``linearize(tangent, wts, first, symmetric=None)``: the solver of the tangent
1471
+ operator (``first``: the first iteration of a step), with ``solve(b, x0=None,
1472
+ tol=None)`` and ``method``: conjugate gradients (or LU) on symmetrized tangents
1473
+ (``symmetric``, by default :attr:`symmetrize`), GMRES (or LU) on full ones;
1474
+ * ``iterative``: whether that solver is a Krylov method, ``asymmetry(tangent, wts)``
1475
+ the asymmetry of the tangents of the points (:func:`asymmetry`) and
1476
+ ``symmetrize(tangent)`` their symmetrization in place, for the tangents that
1477
+ :attr:`measured` decides;
1478
+ * ``coupling(tangent, wts, unknown)``: the columns ``unknown`` of ``K_wE`` on the
1479
+ unknowns, and ``K_EE`` (6 x 6);
1480
+ * ``macro_response(tangent, wts, v)``: ``K_Ew v``, the integral of the stress
1481
+ increments of the fluctuation ``v`` (6), which is ``K_wE^T v`` for symmetric
1482
+ tangents;
1483
+ * ``displacement(q, e)``: the displacement field of the outputs;
1484
+ * the arrays of the points and the integration of their behaviours, as
1485
+ :class:`_PointArrays` provides them on the CPU.
1486
+ """
1487
+
1488
+ #: Largest order of the prediction of a step from the steps before it (the starting
1489
+ #: point of its Newton iterations): 1, the rate of the last step; 2, that rate and its
1490
+ #: change over the last two steps, where it would have predicted the last step better
1491
+ #: (:func:`_second_order`)
1492
+ prediction = 2
1493
+ #: The microdamage of regularized cleavage planes (:class:`_Microdamage`): the largest
1494
+ #: change, over the damage that breaks a plane, at which it has settled, and the
1495
+ #: most passes of a step (beyond, the step is kept as it is and the microdamage goes on
1496
+ #: with the next one: a crack that runs across the cell at a fixed loading takes some
1497
+ #: passes per element that it crosses)
1498
+ microdamage_tol = 1e-3
1499
+ microdamage_passes = 200
1500
+ #: Whether the alternate scheme of the microdamage is accelerated: its updates
1501
+ #: extrapolated or relaxed (:meth:`_Microdamage._accelerate`), and the equilibria
1502
+ #: between them solved to a share of its last change (:data:`_SHARE`), the last one of
1503
+ #: a step to the tolerance of Newton's iteration
1504
+ microdamage_acceleration = True
1505
+
1506
+ def microdamage_options(self, tolerance=None, passes=None, acceleration=None) -> None:
1507
+ """The options of the alternate scheme of the microdamage of regularized
1508
+ cleavage planes (those left as they are when not given): the ``tolerance`` on
1509
+ the change of the microdamage between two equilibria of a step, over the damage
1510
+ that breaks a plane (1e-3); the most ``passes`` of a step (200); whether the
1511
+ scheme is accelerated (true)."""
1512
+ if tolerance is not None:
1513
+ if isinstance(tolerance, bool) or not 0.0 < float(tolerance) < 1.0:
1514
+ raise ValueError("microdamage: a tolerance in (0, 1)")
1515
+ self.microdamage_tol = float(tolerance)
1516
+ if passes is not None:
1517
+ if isinstance(passes, bool) or int(passes) != passes or passes < 1:
1518
+ raise ValueError("microdamage: a positive number of passes")
1519
+ self.microdamage_passes = int(passes)
1520
+ if acceleration is not None:
1521
+ if not isinstance(acceleration, bool):
1522
+ raise ValueError("microdamage: acceleration, true or false")
1523
+ self.microdamage_acceleration = acceleration
1524
+
1525
+ def _smooth(self, elements, values, length) -> np.ndarray:
1526
+ """The solution of ``chi - length^2 lap chi = values`` at the ``elements`` (the
1527
+ equation of the microdamage of cleavage planes): the solvers of voxel images and
1528
+ of meshes have it."""
1529
+ raise ValueError(
1530
+ "the microdamage of cleavage planes (cleavage.regularization): with the solvers "
1531
+ "of the loading paths on voxel images (FFT) and on meshes (FE)"
1532
+ )
1533
+
1534
+ def _path_options(self, newton_tol, max_newton, max_cuts, kinematics,
1535
+ tangent: str = "auto") -> None: # fmt: skip
1536
+ if not 0.0 < newton_tol < 1.0:
1537
+ raise ValueError("newton_tol: a number in (0, 1)")
1538
+ if tangent not in TANGENTS:
1539
+ raise ValueError(f"tangent: one of {TANGENTS}, got {tangent!r}")
1540
+ self.finite = kinematics_of(kinematics)
1541
+ self.kinematics = kinematics
1542
+ self.newton_tol = float(newton_tol)
1543
+ self.max_newton = int(max_newton)
1544
+ self.max_cuts = int(max_cuts)
1545
+ self.tangent = tangent
1546
+ #: Whether the consistent tangents of the points are symmetrized (conjugate
1547
+ #: gradients), or kept full (GMRES): :data:`TANGENTS`, ``auto`` decided by the laws
1548
+ #: of the phases (:attr:`Behaviours.symmetric`), and then by the asymmetry of their
1549
+ #: tangents (:attr:`measured`)
1550
+ self.symmetrize = tangent != "full"
1551
+ self.measured = False
1552
+
1553
+ def _point_behaviours(self, beh: Behaviours, mat, group, ng: int) -> None:
1554
+ """Behaviours of the integration points: ``ng`` per element, the elements of
1555
+ materials ``mat`` and of groups ``group`` (indices of :attr:`groups`)."""
1556
+ self.behaviours = beh
1557
+ self.symmetrize = self.tangent == "symmetric" or (self.tangent == "auto" and beh.symmetric)
1558
+ #: Whether the Krylov solvers decide at each linearization from the measured
1559
+ #: asymmetry of the full tangents of the points (:data:`ASYMMETRY`): ``auto`` with
1560
+ #: laws that are not all symmetric
1561
+ self.measured = self.tangent == "auto" and not beh.symmetric
1562
+ self.ng = int(ng)
1563
+ self.kind = np.ascontiguousarray(np.repeat(beh.kind, ng))
1564
+ self.pmat = np.ascontiguousarray(np.repeat(beh.pmat, ng))
1565
+ self.point_mat = np.ascontiguousarray(np.repeat(mat, ng))
1566
+ self.point_group = np.ascontiguousarray(np.repeat(group, ng))
1567
+
1568
+ def _discretization(self):
1569
+ raise NotImplementedError
1570
+
1571
+ def _support(self):
1572
+ """The support of the fields of the outputs (mesh or image)."""
1573
+ raise NotImplementedError
1574
+
1575
+ @without_blas_threads
1576
+ def run(self, path, *, name: str = "path", fields=False, monitor=None) -> PathResult:
1577
+ """Response of the volume element to a loading path (:class:`LoadingPath`, or a
1578
+ mapping for :meth:`LoadingPath.from_spec`). ``fields``: true for the element
1579
+ fields at the end of each segment of the path, ``"steps"`` at the end of each of
1580
+ its planned steps, or a list of such times. ``monitor``: a function called with the
1581
+ :class:`StepState` of every converged step (the stability analyses of
1582
+ :func:`morphogen.homogenization.bifurcation.path_bifurcation`); a true return
1583
+ value ends the path there."""
1584
+ path = LoadingPath.from_spec(path)
1585
+ t_start = time.perf_counter()
1586
+ if self.empty:
1587
+ return self._empty_path(path, name)
1588
+ finite = self.finite
1589
+ beh = self.behaviours
1590
+ disc = self._discretization()
1591
+ n_pts = self.kind.size
1592
+ nc = 9 if finite else 6
1593
+ grads, wts, sigma, tangent, old, new = disc.arrays(n_pts, nc, beh.width)
1594
+ controls = path.strain_controlled
1595
+ unknown = np.flatnonzero(~controls)
1596
+ volume = self.box_volume
1597
+ n_groups = len(self.groups)
1598
+ field_times = self._field_times(path, fields)
1599
+ # the crystals whose cleavage planes are regularized by their microdamage: the
1600
+ # step is solved again with the microdamage of the damage reached, until it settles
1601
+ micro = _Microdamage(self) or None
1602
+ unloaded = _UNLOADED if micro is None else _CUT
1603
+
1604
+ def evaluate(q, e, dtemp, dt, target, guess, ratio):
1605
+ """Residuals of a trial state (None if the integration fails)."""
1606
+ disc.measures(q, e, grads, wts)
1607
+ failed = disc.integrate(grads, dtemp, dt, old, new, sigma, tangent, guess, ratio)
1608
+ if failed:
1609
+ state["why"] = f"the integration failed at {failed} points"
1610
+ return None
1611
+ r_q, total, fscale = disc.forces(sigma, wts)
1612
+ if finite:
1613
+ total = fin.macro_part(total)
1614
+ r_e = total[unknown] - volume * target[unknown]
1615
+ escale = disc.stress_scale(sigma, wts)
1616
+ escale += volume * float(np.abs(target[unknown]).max(initial=0.0))
1617
+ # an unloaded state keeps a share of the largest scales reached before it
1618
+ fscale = max(fscale, unloaded * state["fmax"])
1619
+ escale = max(escale, unloaded * state["emax"])
1620
+ return r_q, r_e, fscale, escale
1621
+
1622
+ state = {"y": None, "schur": None, "stale": True, "lin": 0, "why": "",
1623
+ "asymmetry": 0.0, "full": 0, "stalled": 0, "fmax": 0.0, "emax": 0.0,
1624
+ "secant": None, "rho": None} # fmt: skip
1625
+ measured = self.measured and disc.iterative
1626
+
1627
+ def correction(r_q, r_e, first: bool, refresh: bool, eta: float):
1628
+ """Newton correction of the fluctuation and of the unknown components of E,
1629
+ the equilibrium solved to the relative residual ``eta``. The macroscopic block
1630
+ is condensed with ``Y = K_ww^-1 K_wE``, computed again (from the previous
1631
+ ``Y``) when ``refresh``, and kept otherwise: a quasi-Newton iteration for the
1632
+ macroscopic unknowns. ``K_Ew`` is ``K_wE^T`` with symmetrized tangents, the
1633
+ integral of the stress increments of the fluctuations with full ones. Measured
1634
+ tangents (:attr:`measured`) less asymmetric than :data:`ASYMMETRY` are
1635
+ symmetrized here."""
1636
+ symmetric = self.symmetrize
1637
+ if measured:
1638
+ value = disc.asymmetry(tangent, wts)
1639
+ state["asymmetry"] = max(state["asymmetry"], value)
1640
+ symmetric = value < ASYMMETRY
1641
+ if symmetric:
1642
+ disc.symmetrize(tangent)
1643
+ else:
1644
+ state["full"] += 1
1645
+ solver = disc.linearize(tangent, wts, first, symmetric)
1646
+ y0, info = solver.solve(-r_q, tol=eta)
1647
+ state["lin"] += info.iterations
1648
+ if not symmetric and disc.iterative: # GMRES: the corrections that stagnate
1649
+ state["stalled"] = state["stalled"] + 1 if info.residual > eta else 0
1650
+ if state["stalled"] >= _STALLED:
1651
+ state["why"] = f"GMRES stagnated at {_STALLED} iterations in a row"
1652
+ return None, None
1653
+ if unknown.size == 0:
1654
+ return y0, np.zeros(0)
1655
+ g, kee = disc.coupling(tangent, wts, unknown)
1656
+
1657
+ def k_ew(v):
1658
+ if symmetric:
1659
+ return times(g.T, v)
1660
+ return disc.macro_response(tangent, wts, v)[unknown]
1661
+
1662
+ renewed = refresh or state["schur"] is None or solver.method == "direct"
1663
+ if renewed:
1664
+ previous = state["y"]
1665
+ ys = []
1666
+ coarse = max(self.tol, _MACRO_TOL)
1667
+ if micro is not None: # between its updates: as loosely as the equilibrium
1668
+ coarse = max(coarse, min(_COARSE, 10.0 * slack))
1669
+ for j in range(unknown.size):
1670
+ x0 = None if previous is None else previous[:, j]
1671
+ y, info = solver.solve(g[:, j], x0, tol=coarse)
1672
+ state["lin"] += info.iterations
1673
+ ys.append(y)
1674
+ state["y"] = np.column_stack(ys)
1675
+ state["stale"] = False
1676
+ if renewed or micro is not None:
1677
+ # (with a microdamage the tangents change at every pass: the condensed
1678
+ # block is that of the tangents as they are, for the ``Y`` kept)
1679
+ if symmetric:
1680
+ coupled = times(g.T, state["y"])
1681
+ else:
1682
+ coupled = np.column_stack([k_ew(y) for y in state["y"].T])
1683
+ state["schur"] = kee[np.ix_(unknown, unknown)] - coupled
1684
+ rho = r_e + k_ew(y0) # the condensed residual of the macroscopic unknowns
1685
+ if state["secant"] is not None and not renewed and micro is None:
1686
+ # the block kept from an earlier linearization: updated by the secant of
1687
+ # the last correction (the tangents have changed since it was computed)
1688
+ state["schur"] = _secant(state["schur"], *state["secant"], rho, symmetric)
1689
+ state["rho"] = rho
1690
+ de = np.linalg.solve(state["schur"], -rho)
1691
+ return y0 - times(state["y"], de), de
1692
+
1693
+ slack = self.newton_tol # (the tolerance of the equilibrium being solved)
1694
+ q = np.zeros(disc.n_q)
1695
+ e = np.zeros(6)
1696
+ n_q = q.size
1697
+ moving = np.concatenate([np.arange(n_q), n_q + unknown]) # the unknowns in (q, E)
1698
+ rec = {"t": [], "e": [], "s": [], "T": [], "p": [], "groups": [], "fields": {}}
1699
+ rec.update({"cauchy": [], "log": [], "f": [], "crystals": {}})
1700
+ self._record(rec, path.times[0], e, 0.0, None, None, None, None, n_groups, first=True)
1701
+ self._record_porosity(rec, None, None, n_groups)
1702
+ self._record_crystals(rec, None, None)
1703
+ steps = _Steps(path, self.max_cuts)
1704
+ iterations: list[int] = []
1705
+ history = None # (segment, dt, dq, de) of the last converged step
1706
+ earlier = None # of the step before it
1707
+ second = False # whether the next step is predicted at the second order
1708
+ # the hooks of the problems whose own state follows the solution: ``_settle(state)``
1709
+ # updates it on a converged state and tells whether to solve the step again;
1710
+ # ``_rollback()`` restores it when a step is divided
1711
+ settle = getattr(self, "_settle", None)
1712
+ rollback = getattr(self, "_rollback", None)
1713
+ # the crystals whose lattices are turned by their twins grain by grain, after a step
1714
+ turning = any(cp.by_grain for cp in beh.crystals)
1715
+ scales = [0.0, 0.0]
1716
+
1717
+ def merit(out) -> float:
1718
+ """The merit of the residuals of a trial state, with scales no smaller than
1719
+ those kept (the largest ones of the iterates of a step where planes break:
1720
+ the stresses of a cell that a crack cuts fall within one correction, and its
1721
+ residuals with them — relative to the scales of the trial state, they would
1722
+ not decrease along the correction that brings it there)."""
1723
+ r_q, r_e, fscale, escale = out
1724
+ return _fe_merit((r_q, r_e, max(fscale, scales[0]), max(escale, scales[1])))
1725
+
1726
+ while not steps.done:
1727
+ t_new = steps.next()
1728
+ dt = t_new - steps.t
1729
+ values, temp = path.at(t_new)
1730
+ seg = steps.segment(t_new)
1731
+ q_try = q.copy()
1732
+ e_try = e.copy()
1733
+ e_try[controls] = values[controls]
1734
+ same = history is not None and history[0] == seg
1735
+ if same:
1736
+ dq, de = _predicted(dt, history, earlier if second else None)
1737
+ q_try += dq
1738
+ e_try[unknown] += de
1739
+ guess, gratio = (2, dt / history[1]) if same else (0, 1.0)
1740
+ state["why"], state["stalled"] = "", 0
1741
+ total = 0 # the Newton iterations of the step, over its settlings
1742
+ # the merits of the last iterates: one for a monotone line search, several
1743
+ # (``_window``) for the problems whose residual is not smooth (interfaces)
1744
+ window = getattr(self, "_window", 1)
1745
+ if micro is not None:
1746
+ # (a plane that breaks is a kink of the residual: as the interfaces)
1747
+ window = max(window, _MICRO_WINDOW)
1748
+ micro.begin(old)
1749
+ merits = deque(maxlen=window)
1750
+ scales[0] = scales[1] = 0.0
1751
+ passes = 0
1752
+ # the tolerance of the equilibria of the step: that of Newton's iteration, or a
1753
+ # looser one between the updates of a microdamage that has not settled
1754
+ slack = self.newton_tol
1755
+ closing = False # the last equilibrium of a step whose passes are spent
1756
+ while True:
1757
+ state["secant"] = None # (no secant across two equilibria)
1758
+ res = evaluate(q_try, e_try, temp, dt, values, guess, gratio)
1759
+ if micro is not None: # its passes after the first: from the state reached
1760
+ guess, gratio = 1, 1.0
1761
+ ok, its = False, 0
1762
+ for its in range(self.max_newton + 1):
1763
+ if res is None:
1764
+ break
1765
+ r_q, r_e, fscale, escale = res
1766
+ if micro is not None:
1767
+ scales[0], scales[1] = max(scales[0], fscale), max(scales[1], escale)
1768
+ # (a pass makes one correction at least, unless it has converged)
1769
+ tol = slack if its else self.newton_tol
1770
+ if norm(r_q) <= tol * fscale and np.all(np.abs(r_e) <= tol * escale):
1771
+ ok = True
1772
+ break
1773
+ if its == self.max_newton:
1774
+ break
1775
+ # inexact Newton: the error of the correction below the expected residual
1776
+ ratio_r = norm(r_q) / max(fscale, 1e-300)
1777
+ eta = min(
1778
+ _MAX_FORCING, max(self.tol, ratio_r, 0.1 * slack / max(ratio_r, 1e-300))
1779
+ )
1780
+ refresh = (its == 0 and state["stale"]) or its == _REFRESH_AFTER
1781
+ current = merit(res)
1782
+ if micro is not None and its and current > _POOR * merits[-1]:
1783
+ # (a plane that breaks changes the tangents of its cell wholesale)
1784
+ refresh = True
1785
+ dq, de = correction(r_q, r_e, first=its == 0, refresh=refresh, eta=eta)
1786
+ if dq is None or not (np.all(np.isfinite(dq)) and np.all(np.isfinite(de))):
1787
+ break
1788
+ trial = partial(_split, evaluate, n_q, temp, dt, values)
1789
+ x0, dx = np.concatenate([q_try, e_try]), np.concatenate([dq, de])
1790
+ merits.append(current)
1791
+ x, found = _line_search(trial, x0, moving, dx, max(merits), merit)
1792
+ if found is None and micro is not None and not refresh and unknown.size:
1793
+ # a correction of no use with the condensation kept from an
1794
+ # earlier pass: again, with that of the tangents as they are
1795
+ state["why"] = ""
1796
+ dq, de = correction(r_q, r_e, first=False, refresh=True, eta=eta)
1797
+ if dq is not None and np.all(np.isfinite(dq)) and np.all(np.isfinite(de)):
1798
+ dx = np.concatenate([dq, de])
1799
+ x, found = _line_search(trial, x0, moving, dx, max(merits), merit)
1800
+ res = found
1801
+ if res is None and not state["why"]:
1802
+ state["why"] = "no decrease of the residual along the correction"
1803
+ # the step of the macroscopic unknowns and their condensed residual
1804
+ # before it: the secant of the next correction, if this one converges
1805
+ state["secant"] = None
1806
+ if (found is not None and unknown.size and state["rho"] is not None
1807
+ and merit(found) <= _TRUSTED * current): # fmt: skip
1808
+ state["secant"] = (x[n_q:][unknown] - e_try[unknown], state["rho"])
1809
+ q_try, e_try = x[:n_q], x[n_q:]
1810
+ total += its
1811
+ if ok and micro is not None and not closing:
1812
+ passes += 1
1813
+ change = micro.settle(old, new, wts, passes >= micro.most)
1814
+ # (the condensation is kept from a pass to the next: a poor
1815
+ # correction, or one of no use, computes it again)
1816
+ if change > micro.tol and passes < micro.most:
1817
+ if micro.accelerated:
1818
+ slack = min(_LOOSE, max(self.newton_tol, _SHARE * change))
1819
+ continue
1820
+ if change > micro.tol:
1821
+ # the passes of the step are spent (a crack that runs across the
1822
+ # cell at a fixed loading): its last equilibrium is kept, and the
1823
+ # microdamage goes on with the next step
1824
+ micro.unsettled += 1
1825
+ closing = True
1826
+ log.info(
1827
+ "step to t = %.6g: the microdamage has not settled in %d passes "
1828
+ "(it goes on with the next step)",
1829
+ t_new,
1830
+ passes,
1831
+ )
1832
+ if slack > self.newton_tol: # the last equilibrium: to the tolerance
1833
+ slack = self.newton_tol
1834
+ continue
1835
+ # a problem whose own state follows the solution (the damage of a phase
1836
+ # field) settles it on the state reached: the step is then solved again
1837
+ if not ok or settle is None:
1838
+ break
1839
+ if not settle(StepState(t_new, e_try.copy(), q_try.copy(), unknown, disc,
1840
+ grads, wts, sigma, tangent)): # fmt: skip
1841
+ break
1842
+ state["stale"] = True
1843
+ if not ok:
1844
+ stalled = state["stalled"] >= _STALLED
1845
+ why = state["why"] if res is None or stalled else f"{its} iterations"
1846
+ log.info("step to t = %.6g not converged (%s): divided", t_new, why)
1847
+ steps.reject()
1848
+ if rollback is not None:
1849
+ rollback()
1850
+ if micro is not None:
1851
+ micro.rollback(old)
1852
+ history, earlier, second = None, None, False
1853
+ state["stale"] = True
1854
+ continue
1855
+ its = total
1856
+ if its > _REFRESH_AFTER:
1857
+ state["stale"] = True
1858
+ step = (seg, dt, q_try - q, e_try[unknown] - e[unknown])
1859
+ second = self.prediction > 1 and _second_order(step, history, earlier)
1860
+ history, earlier = step, history
1861
+ state["fmax"] = max(state["fmax"], float(res[2]))
1862
+ state["emax"] = max(state["emax"], float(res[3]))
1863
+ q, e = q_try, e_try
1864
+ old, new = new, old
1865
+ if turning:
1866
+ self._turn_twins(old, new, wts)
1867
+ steps.accept(t_new)
1868
+ iterations.append(its)
1869
+ self._record(rec, t_new, e, temp, *disc.host(wts, sigma, grads, old[:, STATE_P]),
1870
+ n_groups) # fmt: skip
1871
+ if np.any(self.kind == POROUS): # the porosity of the porous points, on the host
1872
+ self._record_porosity(rec, *disc.host(wts, old[:, : STATE_FN + 1]), n_groups)
1873
+ if rec["crystals"]: # the twins and the cleavage planes of the crystals
1874
+ self._record_crystals(rec, *disc.host(wts, old))
1875
+ if field_times.size and np.any(np.isclose(t_new, field_times, rtol=1e-12, atol=0)):
1876
+ u = disc.displacement(q, e)
1877
+ rec["fields"][float(t_new)] = self._fields(*disc.host(sigma, grads, old), u)
1878
+ if monitor is not None and monitor(
1879
+ StepState(t_new, e.copy(), q.copy(), unknown, disc, grads, wts, sigma, tangent)
1880
+ ):
1881
+ break
1882
+ result = self._result(
1883
+ rec, path, name, iterations, steps.cuts, state["lin"], n_q, unknown.size,
1884
+ time.perf_counter() - t_start,
1885
+ ) # fmt: skip
1886
+ if measured: # the largest asymmetry, and the linearizations of full tangents
1887
+ result.info.update(asymmetry=float(state["asymmetry"]), full_tangents=state["full"])
1888
+ if micro is not None: # the equilibria solved for the microdamage of the planes
1889
+ result.info["microdamage_passes"] = micro.passes
1890
+ result.info["microdamage_unsettled"] = micro.unsettled
1891
+ recycling = getattr(disc, "recycling", None)
1892
+ if recycling is not None and recycling.solves: # GMRES solves from recycled vectors
1893
+ result.info["recycled"] = recycling.solves
1894
+ return result
1895
+
1896
+ # -- outputs -------------------------------------------------------------------------
1897
+
1898
+ def _extra_stress(self):
1899
+ """A part of the macroscopic stress that the points do not carry (the forces of
1900
+ contacts through the faces of a cell: :mod:`morphogen.contact.periodic`), in the
1901
+ components of their stresses; none here."""
1902
+ return 0.0
1903
+
1904
+ def _field_times(self, path: LoadingPath, fields) -> np.ndarray:
1905
+ if isinstance(fields, str):
1906
+ if fields != "steps":
1907
+ raise ValueError("fields: true, 'steps' or a list of times of the path")
1908
+ return path.schedule()
1909
+ if fields is True:
1910
+ return np.asarray(path.times[1:], dtype=float)
1911
+ if not fields:
1912
+ return np.zeros(0)
1913
+ times = np.asarray(fields, dtype=float).ravel()
1914
+ planned = path.schedule()
1915
+ missing = [t for t in times if not np.any(np.isclose(t, planned, rtol=1e-12, atol=0))]
1916
+ if missing:
1917
+ raise ValueError(f"fields: times {missing} are not ends of the steps of the path")
1918
+ return times
1919
+
1920
+ def _element_mean(self, values) -> np.ndarray:
1921
+ return values.reshape(-1, self.ng, *values.shape[1:]).mean(axis=1)
1922
+
1923
+ def _point_porosity(self, state) -> np.ndarray | None:
1924
+ """The porosity of the porous points (NaN at the others), or None without them;
1925
+ ``state`` None: the initial porosity."""
1926
+ mask = self.kind == POROUS
1927
+ if not mask.any():
1928
+ return None
1929
+ params = self.behaviours.data[2]
1930
+ out = np.full(self.kind.size, np.nan)
1931
+ if state is None:
1932
+ out[mask] = params[self.pmat[mask], P_F0]
1933
+ else:
1934
+ out[mask] = porosity(state[mask], params, self.pmat[mask])
1935
+ return out
1936
+
1937
+ def _crystal_values(self, state) -> dict[str, np.ndarray]:
1938
+ """The fields of the crystals that twin or cleave (:data:`~morphogen.
1939
+ homogenization.crystal.FIELDS`) at the integration points, NaN at the others;
1940
+ none without such crystals."""
1941
+ out: dict[str, np.ndarray] = {}
1942
+ for c, cp in enumerate(self.behaviours.crystals):
1943
+ if not cp.extended:
1944
+ continue
1945
+ pts = np.flatnonzero((self.kind == CRYSTAL) & (self.pmat == c))
1946
+ if pts.size == 0:
1947
+ continue
1948
+ axes = self.table.rotations[self.point_mat[pts]] # of the grains of the points
1949
+ for name, values in cp.state_fields(state[pts], self.finite, axes).items():
1950
+ out.setdefault(name, np.full(self.kind.size, np.nan))[pts] = values
1951
+ return out
1952
+
1953
+ def _turn_twins(self, state, before, wts) -> None:
1954
+ """The lattices that the twins of the grains turn at the end of a step (``state``;
1955
+ ``before``: at its start), for the crystals that turn them grain by grain
1956
+ (:func:`~morphogen.homogenization.crystal.turn_twins`): the grains are the
1957
+ materials of the points, each with its orientation."""
1958
+ beh = self.behaviours
1959
+ for c, cp in enumerate(beh.crystals):
1960
+ if not cp.by_grain:
1961
+ continue
1962
+ pts = np.flatnonzero((self.kind == CRYSTAL) & (self.pmat == c))
1963
+ if pts.size:
1964
+ turn_twins(cp, state, before, self.point_mat[pts], beh.data[4], points=pts,
1965
+ finite=self.finite, weights=np.asarray(wts)[pts]) # fmt: skip
1966
+
1967
+ def _record_crystals(self, rec, wts, state) -> None:
1968
+ """The means of the fields of the crystals that twin or cleave over their points,
1969
+ at the end of a step (zero without ``state``: the initial ones)."""
1970
+ if not any(cp.extended for cp in self.behaviours.crystals):
1971
+ return
1972
+ if state is None:
1973
+ names = [name for cp in self.behaviours.crystals for name in cp.field_names]
1974
+ for name in dict.fromkeys(names):
1975
+ rec["crystals"].setdefault(name, []).append(0.0)
1976
+ return
1977
+ for name, values in self._crystal_values(state).items():
1978
+ there = ~np.isnan(values)
1979
+ w = np.ones(int(there.sum())) if wts is None else np.abs(np.asarray(wts)[there])
1980
+ rec["crystals"].setdefault(name, []).append(float(w @ values[there] / w.sum()))
1981
+
1982
+ def _record_porosity(self, rec, wts, state, n_groups) -> None:
1983
+ """The integrals of the porosity and the volumes of the porous points of each group
1984
+ at the end of a step (the initial porosity without ``state``)."""
1985
+ f = self._point_porosity(state)
1986
+ if f is None:
1987
+ return
1988
+ mask = ~np.isnan(f)
1989
+ w = np.ones(mask.sum()) if wts is None else np.asarray(wts)[mask]
1990
+ g = self.point_group[mask]
1991
+ rec["f"].append(np.stack([np.bincount(g, w * f[mask], minlength=n_groups),
1992
+ np.bincount(g, w, minlength=n_groups)])) # fmt: skip
1993
+
1994
+ def _fields(self, sigma, grads, state, u) -> dict[str, np.ndarray]:
1995
+ """Element means of the stress (Cauchy), strain (logarithmic in finite strains)
1996
+ and plastic strain (tensor components), cumulated plastic strain and von Mises
1997
+ stress; the displacement of the nodes; in finite strains, and where their twins
1998
+ turn them, the orientation of the lattice of the crystals (Bunge angles in
1999
+ degrees, NaN elsewhere)."""
2000
+ if self.finite:
2001
+ stress = self._element_mean(fin.cauchy(sigma, grads))
2002
+ strain = self._element_mean(fin.log_strain(grads) * _HALF_SHEAR)
2003
+ else:
2004
+ stress = self._element_mean(sigma)
2005
+ strain = self._element_mean(grads * _HALF_SHEAR)
2006
+ out = {
2007
+ "stress": stress,
2008
+ "strain": strain,
2009
+ "plastic_strain": self._element_mean(state[:, :6]),
2010
+ "p": self._element_mean(state[:, STATE_P]),
2011
+ "mises": mises(stress),
2012
+ "displacement": u.reshape(-1, 3),
2013
+ }
2014
+ f = self._point_porosity(state)
2015
+ if f is not None:
2016
+ out["porosity"] = self._element_mean(f)
2017
+ for name, values in self._crystal_values(state).items():
2018
+ out[name] = self._element_mean(values)
2019
+ crystals = self.behaviours.crystals
2020
+ if crystals and (self.finite or any(cp.reorients for cp in crystals)):
2021
+ out["orientation"] = self._orientations(grads, state)
2022
+ return out
2023
+
2024
+ def _orientations(self, grads, state) -> np.ndarray:
2025
+ """Current orientation of the lattice of each crystal element: ``g R_e^T`` with
2026
+ the rotation ``R_e`` of the lattice in finite strains (none in small strains), ``g
2027
+ R_t^T R_e^T`` for a lattice that its twins turned by ``R_t``. An element whose
2028
+ points do not have the same lattice (some turned by a twin, others not) has that
2029
+ of most of them."""
2030
+ from morphogen.orientations import matrix_to_euler
2031
+
2032
+ beh = self.behaviours
2033
+ out = np.full((beh.kind.size, 3), np.nan)
2034
+ rotations = self.table.rotations
2035
+ mats = self.point_mat[:: self.ng]
2036
+ for c, cp in enumerate(beh.crystals):
2037
+ el = np.flatnonzero((beh.kind == CRYSTAL) & (beh.pmat == c))
2038
+ if el.size == 0:
2039
+ continue
2040
+ pts = (el[:, None] * self.ng + np.arange(self.ng)).ravel()
2041
+ if self.finite:
2042
+ off = CP_ALPHA + 2 * cp.n_systems
2043
+ fp_inv = state[pts, off : off + 9] + np.eye(3).ravel()
2044
+ re = fin.lattice_rotations(grads[pts], fp_inv)
2045
+ else:
2046
+ re = np.broadcast_to(np.eye(3), (pts.size, 3, 3))
2047
+ share = np.ones((el.size, self.ng)) # of the points in the mean of their element
2048
+ if cp.reorients: # the lattice of the twin, then the rotation of the lattice
2049
+ first = cp_width(cp.n_systems, self.finite)
2050
+ twin = state[pts, first : first + 9]
2051
+ re = re @ (twin.reshape(-1, 3, 3) + np.eye(3))
2052
+ share = _majority(twin.reshape(el.size, self.ng, 9))
2053
+ re = re.reshape(el.size, self.ng, 3, 3)
2054
+ # mean rotation of the element: the rotation of the mean matrix
2055
+ u, _, vt = np.linalg.svd(np.einsum("ep,epij->eij", share, re))
2056
+ mean = u @ vt
2057
+ g0 = rotations[mats[el]]
2058
+ out[el] = matrix_to_euler(g0 @ np.swapaxes(mean, -1, -2))
2059
+ return out
2060
+
2061
+ def _record(self, rec, t, e, temp, wts, sigma, grads, p, n_groups, first=False):
2062
+ """The macroscopic state and the integrals over the groups at the end of a step:
2063
+ ``p`` is the cumulated plastic strain of the points (unused, as the arrays, for the
2064
+ initial state: ``first``)."""
2065
+ rec["t"].append(float(t))
2066
+ rec["e"].append(np.array(e, dtype=float))
2067
+ rec["T"].append(float(temp))
2068
+ width = 21 if self.finite else 14
2069
+ if first:
2070
+ sums = np.zeros((n_groups, width))
2071
+ sums[:, 13] = 1.0
2072
+ if self.finite:
2073
+ sums[:, 20] = 1.0
2074
+ full = np.zeros(9 if self.finite else 6)
2075
+ elif self.finite:
2076
+ sums = fin.group_sums(self.point_group, n_groups, wts, sigma, grads, p)
2077
+ full = np.einsum("i,ij->j", wts, sigma) / self.box_volume + self._extra_stress()
2078
+ else:
2079
+ sums = _group_sums(self.point_group, n_groups, wts, sigma, grads, p)
2080
+ full = np.einsum("i,ij->j", wts, sigma) / self.box_volume + self._extra_stress()
2081
+ rec["groups"].append(sums)
2082
+ vol = sums[:, 13].sum()
2083
+ rec["p"].append(float(sums[:, 12].sum() / vol) if vol > 0 else 0.0)
2084
+ if self.finite:
2085
+ grad = fin.gradient_of(e)
2086
+ rec["s"].append(fin.macro_part(full))
2087
+ rec["cauchy"].append(fin.cauchy(full, grad))
2088
+ rec["log"].append(fin.log_strain(grad))
2089
+ else:
2090
+ rec["s"].append(full)
2091
+
2092
+ def _result(self, rec, path, name, iterations, cuts, linear, n_q, n_macro, elapsed):
2093
+ groups = np.array(rec["groups"]) # steps x groups x 14 (21)
2094
+ phases = {}
2095
+ for g, phase in enumerate(self.groups):
2096
+ vol = groups[:, g, 13]
2097
+ if not np.any(vol > 0):
2098
+ continue
2099
+ safe = np.where(vol > 0, vol, 1.0)[:, None]
2100
+ phases[int(phase)] = {
2101
+ "stress": groups[:, g, 0:6] / safe,
2102
+ "strain": groups[:, g, 6:12] / safe,
2103
+ "plastic": groups[:, g, 12] / safe[:, 0],
2104
+ }
2105
+ if self.finite:
2106
+ jac = groups[:, g, 20]
2107
+ phases[int(phase)]["cauchy"] = (
2108
+ groups[:, g, 14:20] / np.where(jac > 0, jac, 1.0)[:, None]
2109
+ )
2110
+ info = {
2111
+ "n_dofs": int(n_q + n_macro),
2112
+ "cuts": int(cuts),
2113
+ "linear_iterations": int(linear),
2114
+ "time_s": round(float(elapsed), 4),
2115
+ }
2116
+ extra = {}
2117
+ if self.finite:
2118
+ extra = {"cauchy": np.array(rec["cauchy"]), "log_strain": np.array(rec["log"])}
2119
+ if rec["f"]:
2120
+ sums = np.array(rec["f"]) # steps x 2 x groups
2121
+ for g, phase in enumerate(self.groups):
2122
+ vol = sums[:, 1, g]
2123
+ if int(phase) in phases and np.all(vol > 0):
2124
+ phases[int(phase)]["porosity"] = sums[:, 0, g] / vol
2125
+ extra["porosity"] = sums[:, 0].sum(axis=1) / sums[:, 1].sum(axis=1)
2126
+ if rec.get("crystals"):
2127
+ extra["series"] = {name: np.array(values) for name, values in rec["crystals"].items()}
2128
+ return PathResult(
2129
+ name=name,
2130
+ bc=self.bc,
2131
+ path=path,
2132
+ times=np.array(rec["t"]),
2133
+ strain=np.array(rec["e"]),
2134
+ stress=np.array(rec["s"]),
2135
+ temperature=np.array(rec["T"]),
2136
+ plastic=np.array(rec["p"]),
2137
+ phases=phases,
2138
+ iterations=np.array(iterations, dtype=int),
2139
+ info=info,
2140
+ fields=rec["fields"],
2141
+ support=self._support() if rec["fields"] else None,
2142
+ kinematics=self.kinematics,
2143
+ **extra,
2144
+ )
2145
+
2146
+ def _empty_path(self, path, name) -> PathResult:
2147
+ """Response of a sample without load-carrying material: zero stress."""
2148
+ times = np.concatenate([[path.times[0]], path.schedule()])
2149
+ strain = np.zeros((times.size, 6))
2150
+ controls = path.strain_controlled
2151
+ for k, t in enumerate(times):
2152
+ strain[k, controls] = path.at(t)[0][controls]
2153
+ extra = {}
2154
+ if self.finite:
2155
+ extra = {
2156
+ "cauchy": np.zeros((times.size, 6)),
2157
+ "log_strain": fin.log_strain(fin.gradient_of(strain)),
2158
+ }
2159
+ return PathResult(
2160
+ name=name,
2161
+ bc=self.bc,
2162
+ path=path,
2163
+ times=times,
2164
+ strain=strain,
2165
+ stress=np.zeros((times.size, 6)),
2166
+ temperature=np.array([path.at(t)[1] for t in times]),
2167
+ plastic=np.zeros(times.size),
2168
+ info={"n_dofs": 0},
2169
+ kinematics=self.kinematics,
2170
+ **extra,
2171
+ )
2172
+
2173
+
2174
+ class _FEPaths(_PointArrays):
2175
+ """Discretization of the loading paths by finite elements (see :class:`_PathSolver`):
2176
+ the unknowns of the fluctuation reduced by the periodic links or the kinematic
2177
+ conditions; the tangent assembled at each iteration and solved by sparse LU, or by
2178
+ conjugate gradients with algebraic multigrid whose hierarchy is built at the first
2179
+ iteration of each step (GMRES with the multigrid of its symmetric part for full
2180
+ tangents). With the integration ``"bbar"`` of the problem, the measures of strain of
2181
+ the 10-node tetrahedra are those of the mean dilatation, the stresses their
2182
+ conjugates and the tangent that of their energy
2183
+ (:mod:`morphogen.homogenization.dilatation`)."""
2184
+
2185
+ def __init__(self, problem: NonlinearFEProblem):
2186
+ m = problem.mesh
2187
+ self.problem = problem
2188
+ self.mesh = m
2189
+ self.finite = problem.finite
2190
+ self.gp, self.gw = GAUSS[m.order]
2191
+ self.key = (problem.bc,)
2192
+ self.t_mat, self.rep = problem._reduction(self.key)
2193
+ self.t_tr = self.t_mat.T.tocsr()
2194
+ self.n_q = self.t_mat.shape[1]
2195
+ self.indptr_n, self.indices_n = node_pattern(m.elements, m.n_nodes)
2196
+ # the elements by colours: those of a colour are assembled in parallel
2197
+ self.by_colour, self.colours = element_colours(m.elements, m.n_nodes)
2198
+ self.data = np.zeros(9 * int(self.indptr_n[-1]))
2199
+ indices = _expand_columns(self.indptr_n, self.indices_n, 3)
2200
+ lengths = np.repeat(np.diff(self.indptr_n) * 3, 3)
2201
+ indptr = np.zeros(3 * m.n_nodes + 1, dtype=np.int64)
2202
+ np.cumsum(lengths, out=indptr[1:])
2203
+ if indptr[-1] < 2**31 - 1:
2204
+ indices, indptr = indices.astype(np.int32), indptr.astype(np.int32)
2205
+ self.indices, self.indptr = indices, indptr
2206
+ self.n_dofs = 3 * m.n_nodes
2207
+ self.nodal = np.zeros(self.n_dofs)
2208
+ self.columns = np.zeros((self.n_dofs, 6))
2209
+ self.kee = np.zeros((6, 6))
2210
+ self.solver = None
2211
+ #: Multigrid with conjugate gradients or GMRES, rather than LU (whose iterations
2212
+ #: are exact Newton ones with full tangents, whatever their asymmetry)
2213
+ self.iterative = choose_method(problem.solver_method, self.n_q) != "direct"
2214
+ #: The volume change of each element as its mean (10-node tetrahedra)
2215
+ self.bbar = problem.integration == "bbar" and m.order == 2
2216
+ keep = m.n_elements * self.gp.shape[0] if self.bbar and self.finite else 1
2217
+ # F-bar: the gradients of the points and the stresses of their behaviours
2218
+ self.base = np.zeros((keep, 9))
2219
+ self.kept = np.zeros((keep, 9))
2220
+ self._bar = None # the moduli and the vectors of the tangent of B-bar
2221
+ self._k = None # the tangent of all the degrees of freedom, as last linearized
2222
+ self._plan = False # the reduction of the tangents (none: by sparse products)
2223
+ self._unit = None # the displacements of the six unit macroscopic strains
2224
+
2225
+ def displacement(self, q, e) -> np.ndarray:
2226
+ if self.finite:
2227
+ macro = fin.gradient_of(e).reshape(3, 3)
2228
+ else:
2229
+ macro = voigt_to_tensor(e, strain=True)
2230
+ return times(self.mesh.nodes, macro.T).ravel() + self.t_mat @ q
2231
+
2232
+ def measures(self, q, e, grads, wts) -> None:
2233
+ m = self.mesh
2234
+ u = self.displacement(q, e)
2235
+ kernel = fin.point_gradients if self.finite else _point_strains
2236
+ kernel(m.nodes, m.elements, m.order, u, self.gp, self.gw, grads, wts)
2237
+ if self.bbar:
2238
+ if self.finite:
2239
+ dilatation.mean_gradients(grads, wts, self.gp.shape[0], self.base)
2240
+ else:
2241
+ dilatation.mean_strains(grads, wts, self.gp.shape[0])
2242
+
2243
+ def forces(self, sigma, wts):
2244
+ """With ``bbar``, the stresses of the points are first replaced by their
2245
+ conjugates: the outputs report them."""
2246
+ m = self.mesh
2247
+ if self.bbar:
2248
+ if self.finite:
2249
+ dilatation.conjugate_piola(sigma, wts, self.gp.shape[0], self.base, self.kept)
2250
+ else:
2251
+ dilatation.conjugate_stresses(sigma, wts, self.gp.shape[0])
2252
+ kernel = fin.internal_forces if self.finite else _internal_forces
2253
+ total, fscale = kernel(m.nodes, m.elements, m.order, self.gp, sigma, wts,
2254
+ self.by_colour, self.colours, self.nodal) # fmt: skip
2255
+ return self.t_tr @ self.nodal, total, fscale
2256
+
2257
+ def _fill(self, tangent, wts, data) -> None:
2258
+ """The values of the tangent of all the degrees of freedom, into ``data``."""
2259
+ m = self.mesh
2260
+ if not self.bbar:
2261
+ fill = fin.fill_tangent if self.finite else _fill_tangent
2262
+ fill(m.nodes, m.elements, m.order, self.gp, tangent, wts, self.indptr_n,
2263
+ self.indices_n, self.by_colour, self.colours, data) # fmt: skip
2264
+ return
2265
+ nc = 9 if self.finite else 6
2266
+ if self._bar is None:
2267
+ n = wts.size
2268
+ self._bar = (np.zeros((n, nc, nc)), np.zeros((n, nc)), np.zeros((n, nc)),
2269
+ np.zeros(n), np.zeros((n if self.finite else 1, 9))) # fmt: skip
2270
+ moduli, vl, vr, kappa, fvec = self._bar
2271
+ if self.finite:
2272
+ dilatation.bar_moduli_finite(tangent, wts, self.gp.shape[0], self.base, self.kept,
2273
+ moduli, vl, vr, kappa, fvec) # fmt: skip
2274
+ else:
2275
+ dilatation.bar_moduli(tangent, moduli, vl, vr, kappa)
2276
+ dilatation.fill_bar(m.nodes, m.elements, m.order, self.gp, wts, self.finite, moduli,
2277
+ vl, vr, kappa, fvec, self.indptr_n, self.indices_n, self.by_colour,
2278
+ self.colours, data) # fmt: skip
2279
+
2280
+ def _macro_fields(self) -> np.ndarray:
2281
+ """The nodal displacements of the six unit macroscopic strains (n_dofs x 6)."""
2282
+ if self._unit is None:
2283
+ unit = np.zeros((self.n_dofs, 6))
2284
+ for j in range(6):
2285
+ e = np.zeros(6)
2286
+ e[j] = 1.0
2287
+ unit[:, j] = self.displacement(np.zeros(self.n_q), e)
2288
+ self._unit = unit
2289
+ return self._unit
2290
+
2291
+ def linearize(self, tangent, wts, first: bool, symmetric: bool | None = None):
2292
+ self._fill(tangent, wts, self.data)
2293
+ k = sp.csr_matrix((self.data, self.indices, self.indptr), shape=(self.n_dofs, self.n_dofs))
2294
+ self._k = k
2295
+ if self._plan is False: # (found at the first linearization: the pattern is fixed)
2296
+ self._plan = Reduction.of(self.t_mat, self.indptr, self.indices)
2297
+ if self._plan is None:
2298
+ kqq = self.problem._reduce(self.key, k, self.t_mat, self.rep)
2299
+ else:
2300
+ kqq = self.problem._regularized(self._plan(self.data))
2301
+ symmetric = self.problem.symmetrize if symmetric is None else symmetric
2302
+ # the preconditioner of the last step is kept while it serves (its sweeps take
2303
+ # the values of each tangent): built again at the start of a step once it is worn
2304
+ if self.solver is None or (first and self.solver.worn()):
2305
+ self.solver = self.problem._linear_solver(kqq, self.t_mat, self.rep, symmetric)
2306
+ else:
2307
+ self.solver = self.solver.updated(kqq, symmetric)
2308
+ return self.solver
2309
+
2310
+ def macro_response(self, tangent, wts, v) -> np.ndarray:
2311
+ """``K_Ew v``: the integral of the stress increments ``C : B v`` of the points (``A :
2312
+ grad v`` in finite strains, its components of the macroscopic strains) for the
2313
+ reduced unknowns ``v`` of the fluctuation."""
2314
+ m = self.mesh
2315
+ u = self.t_mat @ v
2316
+ if self.bbar: # the work of the nodal forces on the fields of the unit strains
2317
+ return times(self._macro_fields().T, self._k @ u)
2318
+ nc = 9 if self.finite else 6
2319
+ grads, weights = np.zeros((wts.size, nc)), np.zeros(wts.size)
2320
+ kernel = fin.point_gradients if self.finite else _point_strains
2321
+ kernel(m.nodes, m.elements, m.order, u, self.gp, self.gw, grads, weights)
2322
+ total = np.einsum("p,pij,pj->i", wts, tangent, grads)
2323
+ return fin.macro_part(total) if self.finite else total
2324
+
2325
+ def coupling(self, tangent, wts, unknown):
2326
+ m = self.mesh
2327
+ if self.bbar: # with the tangent of the last linearization
2328
+ unit = self._macro_fields()
2329
+ self.columns[:, :] = self._k @ unit
2330
+ self.kee[:, :] = times(unit.T, self.columns)
2331
+ return self.t_tr @ self.columns[:, unknown], self.kee
2332
+ couple = fin.coupling if self.finite else _coupling
2333
+ couple(m.nodes, m.elements, m.order, self.gp, tangent, wts, self.by_colour, self.colours,
2334
+ self.columns, self.kee) # fmt: skip
2335
+ return self.t_tr @ self.columns[:, unknown], self.kee
2336
+
2337
+ def full_tangent(self, tangent, wts) -> sp.csr_matrix:
2338
+ """The tangent stiffness of all the degrees of freedom of the mesh, before the
2339
+ reduction by the boundary conditions: ``sum_e int B^T C B``, or ``int grad N . A .
2340
+ grad N`` in finite strains (its geometric part included)."""
2341
+ data = np.zeros_like(self.data)
2342
+ self._fill(tangent, wts, data)
2343
+ return sp.csr_matrix((data, self.indices, self.indptr), shape=(self.n_dofs, self.n_dofs))
2344
+
2345
+ def macro_columns(self, tangent, wts) -> tuple[np.ndarray, np.ndarray]:
2346
+ """The nodal forces of the six unit macroscopic strains on all the degrees of
2347
+ freedom (``int B^T C``, n_dofs x 6) and ``int C`` (6 x 6)."""
2348
+ m = self.mesh
2349
+ if self.bbar:
2350
+ unit = self._macro_fields()
2351
+ columns = self.full_tangent(tangent, wts) @ unit
2352
+ return columns, times(unit.T, columns)
2353
+ couple = fin.coupling if self.finite else _coupling
2354
+ columns, kee = np.zeros((self.n_dofs, 6)), np.zeros((6, 6))
2355
+ couple(m.nodes, m.elements, m.order, self.gp, tangent, wts, self.by_colour, self.colours,
2356
+ columns, kee) # fmt: skip
2357
+ return columns, kee
2358
+
2359
+
2360
+ class Extended:
2361
+ """The nodes of a cell and the images of some of them across its faces: ``node`` the
2362
+ node of each extended node (the nodes of the mesh first), ``offset`` its translation
2363
+ (zero for the nodes themselves) and ``reference`` its position; ``fold``, the dofs of
2364
+ the extended nodes from those of the nodes. The image of a node of displacement ``u``
2365
+ translated by ``L`` is displaced by ``u + H L``, ``H`` the macroscopic displacement
2366
+ gradient: the cell deforms with it."""
2367
+
2368
+ def __init__(self, nodes: np.ndarray, node=None, offset=None):
2369
+ n = len(nodes)
2370
+ extra = np.zeros(0, dtype=np.int64) if node is None else np.asarray(node, dtype=np.int64)
2371
+ shifts = np.zeros((0, 3)) if offset is None else np.asarray(offset, dtype=float)
2372
+ self.node = np.concatenate([np.arange(n), extra])
2373
+ self.offset = np.concatenate([np.zeros((n, 3)), shifts.reshape(-1, 3)])
2374
+ self.reference = np.ascontiguousarray(nodes[self.node] + self.offset)
2375
+ n_ext = len(self.node)
2376
+ columns = (3 * self.node[:, None] + np.arange(3)).ravel()
2377
+ self.fold = sp.csr_matrix(
2378
+ (np.ones(3 * n_ext), (np.arange(3 * n_ext), columns)), shape=(3 * n_ext, 3 * n)
2379
+ )
2380
+
2381
+ def positions(self, u, macro) -> np.ndarray:
2382
+ """The positions of the extended nodes for the displacements ``u`` of the nodes
2383
+ and the macroscopic displacement gradient ``macro``."""
2384
+ return np.ascontiguousarray(
2385
+ self.reference + u.reshape(-1, 3)[self.node] + self.offset @ macro.T
2386
+ )
2387
+
2388
+
2389
+ class _SurfacePaths(_FEPaths):
2390
+ """The discretization of the loading paths of a cell with forces between the nodes of
2391
+ its surfaces and their images across its faces: the contact of the walls of its pores
2392
+ (:mod:`morphogen.contact.periodic`), the cohesive interfaces of its phases
2393
+ (:mod:`morphogen.fracture.periodic`).
2394
+
2395
+ The problem gives its extended nodes (``_extended``: :class:`Extended`) and the forces
2396
+ on them, ``_surface_forces(x, tangent, first)``: the forces (and their tangent, or
2397
+ None) at the positions ``x`` of the extended nodes; ``first``: the first linearization
2398
+ of a step. These forces are added to those of the points; their work in a change of the
2399
+ macroscopic gradient, ``Σ f ⊗ X`` over the extended nodes (nothing for opposite forces
2400
+ at one place; the force that crosses a face of the cell times the period), is added to
2401
+ the integral of the stress, kept in ``_virial`` for the macroscopic stress of the
2402
+ results, and its derivatives go into the tangent of the macroscopic unknowns.
2403
+ ``_floor`` and ``_floor_stress``: floors of the scales of the residuals, for parts
2404
+ that nothing loads yet; ``_dt``: the time step being tried."""
2405
+
2406
+ def __init__(self, problem):
2407
+ super().__init__(problem)
2408
+ self.cell = problem
2409
+ self._u = np.zeros(self.n_dofs)
2410
+ self._macro = np.zeros((3, 3))
2411
+ self._terms = None # of the tangent: K_s U, U^T K_s, U^T K_s U
2412
+ ext = problem._extended
2413
+ unit = self._macro_fields()
2414
+ shifted = np.zeros((len(ext.node), 3, 6))
2415
+ for j in range(6):
2416
+ e = np.zeros(6)
2417
+ e[j] = 1.0
2418
+ shifted[:, :, j] = ext.offset @ self._gradient(e).T
2419
+ #: the displacements of the extended nodes for the six unit macroscopic strains
2420
+ self.unit_ext = ext.fold @ unit + shifted.reshape(-1, 6)
2421
+
2422
+ def _gradient(self, e) -> np.ndarray:
2423
+ if self.finite:
2424
+ return fin.gradient_of(e).reshape(3, 3)
2425
+ return voigt_to_tensor(e, strain=True)
2426
+
2427
+ def measures(self, q, e, grads, wts) -> None:
2428
+ super().measures(q, e, grads, wts)
2429
+ self._u = self.displacement(q, e)
2430
+ self._macro = self._gradient(e)
2431
+
2432
+ def integrate(self, grads, dtemp, dt, old, new, stress, tangent, guess, ratio) -> int:
2433
+ self.cell._dt = float(dt)
2434
+ return super().integrate(grads, dtemp, dt, old, new, stress, tangent, guess, ratio)
2435
+
2436
+ def forces(self, sigma, wts):
2437
+ r_q, total, fscale = super().forces(sigma, wts)
2438
+ cell, ext = self.cell, self.cell._extended
2439
+ f, _ = cell._surface_forces(ext.positions(self._u, self._macro), False, False)
2440
+ if self.finite: # the work of the forces in the nine components of the gradient
2441
+ virial = np.einsum("ni,nj->ij", f.reshape(-1, 3), ext.reference).ravel()
2442
+ else:
2443
+ virial = self.unit_ext.T @ f
2444
+ cell._virial = virial
2445
+ f = ext.fold.T @ f
2446
+ # the scale of the forces: with a floor, for parts that nothing loads until they
2447
+ # touch (their forces are zero, and no residual is small against them)
2448
+ fscale += float(np.linalg.norm(f)) + cell._floor
2449
+ return r_q + self.t_tr @ f, total + virial, fscale
2450
+
2451
+ def stress_scale(self, sigma, wts) -> float:
2452
+ # with a floor, as the scale of the forces: a cell that nothing loads yet
2453
+ return super().stress_scale(sigma, wts) + self.cell._floor_stress
2454
+
2455
+ def linearize(self, tangent, wts, first: bool, symmetric: bool | None = None):
2456
+ from morphogen.fracture.cohesive import plus
2457
+
2458
+ self._fill(tangent, wts, self.data)
2459
+ k = sp.csr_matrix((self.data, self.indices, self.indptr), shape=(self.n_dofs, self.n_dofs))
2460
+ cell, ext = self.cell, self.cell._extended
2461
+ _, ks = cell._surface_forces(ext.positions(self._u, self._macro), True, first)
2462
+ self._terms = None
2463
+ if ks is not None:
2464
+ columns = ks @ self.unit_ext # the forces of the unit macroscopic strains
2465
+ self._terms = (
2466
+ ext.fold.T @ columns,
2467
+ (ks.T @ self.unit_ext).T @ ext.fold,
2468
+ self.unit_ext.T @ columns,
2469
+ )
2470
+ k = plus(k, (ext.fold.T @ ks @ ext.fold).tocsr())
2471
+ self._k = k
2472
+ kqq = self.problem._reduce(self.key, k, self.t_mat, self.rep)
2473
+ symmetric = self.problem.symmetrize if symmetric is None else symmetric
2474
+ if first or self.solver is None:
2475
+ self.solver = self.problem._linear_solver(kqq, self.t_mat, self.rep, symmetric)
2476
+ else:
2477
+ self.solver = self.solver.updated(kqq, symmetric)
2478
+ return self.solver
2479
+
2480
+ def macro_response(self, tangent, wts, v) -> np.ndarray:
2481
+ out = super().macro_response(tangent, wts, v)
2482
+ if self._terms is not None:
2483
+ out = out + self._terms[1] @ (self.t_mat @ v)
2484
+ return out
2485
+
2486
+ def coupling(self, tangent, wts, unknown):
2487
+ g, kee = super().coupling(tangent, wts, unknown)
2488
+ if self._terms is None:
2489
+ return g, kee
2490
+ return g + self.t_tr @ self._terms[0][:, unknown], kee + self._terms[2]
2491
+
2492
+
2493
+ class NonlinearFEProblem(_PathSolver, FEElasticProblem):
2494
+ """Nonlinear behaviours of the phases (von Mises elasto-(visco)plasticity, crystal
2495
+ plasticity) on a tetrahedral mesh, loaded along paths: periodic conditions (the
2496
+ periodic element, whose macroscopic strain components are degrees of freedom) or
2497
+ kinematic ones (``kubc``: ``u = E x`` on the boundary, ``E`` likewise), in small or
2498
+ finite strains (``kinematics``).
2499
+
2500
+ ``newton_tol``: relative residual of convergence of the equilibrium (to the norm of
2501
+ the nodal forces before they cancel) and of the macroscopic stress (to the integral
2502
+ of the norm of the stress); ``max_newton`` iterations per step; ``max_cuts``
2503
+ divisions of a step by two. ``tangent``: the consistent tangents of the points
2504
+ symmetrized (``"symmetric"``: conjugate gradients with multigrid), full (``"full"``:
2505
+ GMRES with the multigrid of their symmetric part; LU either way for small systems)
2506
+ or, by default (``"auto"``), symmetrized when the laws of all the phases have
2507
+ symmetric tangents (:func:`behaviour_table`), and otherwise kept full by LU and, with
2508
+ multigrid, symmetrized at each linearization where their asymmetry is below
2509
+ :data:`ASYMMETRY`.
2510
+
2511
+ ``integration``: ``"full"``, the behaviours integrated with the strain of each point,
2512
+ or ``"bbar"``, with the volume change of each 10-node tetrahedron as its mean
2513
+ (``B``-bar; ``F``-bar in finite strains: :mod:`morphogen.homogenization.dilatation`),
2514
+ for nearly incompressible phases — elastomers — and isochoric plastic flow.
2515
+ """
2516
+
2517
+ def __init__(
2518
+ self,
2519
+ mesh,
2520
+ materials: dict[int, Material],
2521
+ bc: str = "periodic",
2522
+ *,
2523
+ solver: str = "auto",
2524
+ tol: float = 1e-8,
2525
+ maxiter: int | None = None,
2526
+ newton_tol: float = 1e-6,
2527
+ max_newton: int = 25,
2528
+ max_cuts: int = 10,
2529
+ kinematics: str = "small",
2530
+ tangent: str = "auto",
2531
+ integration: str = "full",
2532
+ ):
2533
+ super().__init__(
2534
+ mesh, materials, bc, solver=solver, tol=tol, maxiter=maxiter, integration=integration
2535
+ )
2536
+ if self.bc not in ("periodic", "kubc"):
2537
+ raise ValueError(
2538
+ "loading paths: periodic or kinematic (kubc) boundary conditions; static "
2539
+ "and mixed conditions prescribe the strain or the stress only"
2540
+ )
2541
+ self._path_options(newton_tol, max_newton, max_cuts, kinematics, tangent)
2542
+ self.materials = materials
2543
+ self._smoothing: dict = {}
2544
+ if not self.empty:
2545
+ gp, _ = GAUSS[self.mesh.order]
2546
+ beh = behaviour_table(self.mesh.phase, materials, self.table, finite=self.finite)
2547
+ self._point_behaviours(beh, self.mat, self.group, gp.shape[0])
2548
+ if self.mesh.order == 1 and beh.nonlinear:
2549
+ log.warning(
2550
+ "linear tetrahedra lock under isochoric plastic flow: prefer quadratic "
2551
+ "elements (mesh order 2) for plasticity"
2552
+ )
2553
+
2554
+ def _discretization(self) -> _FEPaths:
2555
+ return _FEPaths(self)
2556
+
2557
+ def _support(self):
2558
+ return self.mesh
2559
+
2560
+ def _smoother(self, length: float):
2561
+ """The solver of the equation of the microdamage for a length (kept): the
2562
+ factorized operator ``M + length^2 K`` of the nodes (the masters of the periodic
2563
+ conditions), the loads of the nodes for a unit value in each element (nodes x
2564
+ elements) and the volumes of the elements."""
2565
+ found = self._smoothing.get(length)
2566
+ if found is not None:
2567
+ return found
2568
+ from scipy.sparse.linalg import splu
2569
+
2570
+ from morphogen.homogenization.bloch import MASS, mass_matrix
2571
+ from morphogen.homogenization.fe import assemble, periodic_map
2572
+
2573
+ mesh = self.mesh
2574
+ count = mesh.n_elements
2575
+ volumes = np.abs(mesh.volumes())
2576
+ share = MASS[mesh.order].sum(axis=1) # the integral of each function over a unit volume
2577
+ nodes = mesh.elements.shape[1]
2578
+ load = sp.csr_matrix(
2579
+ (
2580
+ (volumes[:, None] * share[None, :]).ravel(),
2581
+ (mesh.elements.ravel(), np.repeat(np.arange(count), nodes)),
2582
+ ),
2583
+ shape=(mesh.n_nodes, count),
2584
+ )
2585
+ stiffness = assemble(mesh, 1, np.zeros(count, dtype=np.int64), np.eye(3)[None])
2586
+ operator = mass_matrix(mesh, np.ones(count)) + length**2 * stiffness
2587
+ reduce = None
2588
+ if self.bc == "periodic":
2589
+ reduce = periodic_map(mesh)[0]
2590
+ operator = reduce.T @ operator @ reduce
2591
+ factor = splu(sp.csc_matrix(operator))
2592
+
2593
+ def solve(rhs):
2594
+ if reduce is None:
2595
+ return factor.solve(rhs)
2596
+ return reduce @ factor.solve(reduce.T @ rhs)
2597
+
2598
+ found = self._smoothing[length] = (solve, load, volumes)
2599
+ return found
2600
+
2601
+ def _smooth(self, elements, values, length) -> np.ndarray:
2602
+ """The equation of the microdamage on the mesh, ``chi - length^2 lap chi =
2603
+ values`` with the ``values`` of the ``elements`` (nothing in the others), by
2604
+ finite elements of the order of the mesh: the field of the nodes — periodic with
2605
+ the conditions of the cell, and with no flux through the other boundaries, those
2606
+ of the pores and the faces of the box under kinematic conditions — and its means
2607
+ in the elements."""
2608
+ solve, load, volumes = self._smoother(float(length))
2609
+ source = np.zeros(volumes.size)
2610
+ source[elements] = values
2611
+ field = solve(load @ source)
2612
+ return (load.T @ field)[elements] / volumes[elements]