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,589 @@
1
+ """MFront behaviours (TFEL, https://thelfer.github.io/tfel) in the solvers of morphoGen,
2
+ through MGIS (MFrontGenericInterfaceSupport).
3
+
4
+ A material whose ``mfront`` names a behaviour (:class:`MFrontBehaviour`: a library
5
+ compiled with the ``generic`` interface, or a ``.mfront`` source that morphoGen compiles
6
+ with ``mfront --obuild --interface=generic`` and caches) has its integration points
7
+ integrated by MGIS along loading paths, by finite elements and on voxels, in small and
8
+ finite strains: the stresses, the internal state variables and the consistent tangent of
9
+ every point, the rest of the solvers unchanged (the periodic element, Newton's method,
10
+ the outputs). Its elastic constants (``young`` and ``poisson``, or a crystal stiffness)
11
+ remain those of the reference medium of the FFT solver and of the linear problems.
12
+
13
+ Conventions. MGIS stores symmetric tensors in the order of TFEL, (11, 22, 33, 12, 13, 23)
14
+ (that of Cast3M, Code_Aster and Abaqus, not the usual order of Voigt, (11, 22, 33, 23,
15
+ 13, 12)), with a factor sqrt(2) on their shear components (Mandel's normalization; the
16
+ tangents likewise), and the deformation gradient and the first Piola-Kirchhoff stress in
17
+ the order (11, 22, 33, 12, 21, 13, 31, 23, 32). morphoGen keeps the usual order (11, 22,
18
+ 33, 23, 31, 12) with engineering shear strains, and tensors of 9 components row by row:
19
+ the components are converted at the calls of MGIS only. Finite strain
20
+ behaviours are loaded for the first Piola-Kirchhoff stress and its derivative with
21
+ respect to the deformation gradient. The gradients of the points of a crystal go to the
22
+ axes of its lattice (the orientation of its grain), the stresses and the tangents come
23
+ back to the axes of the sample. The tangents are symmetrized for the conjugate gradients
24
+ of the solvers whose laws all have symmetric tangents, and passed whole to GMRES
25
+ otherwise (and to Newton's method at a material point): a behaviour has a symmetric
26
+ tangent when it declares one (``@ProvidesSymmetricTangentOperator``, which MFront writes
27
+ in the traits of the behaviour, ``isConsistentTangentOperatorSymmetric``, in the header
28
+ that it generates next to the library: :func:`declared_symmetric`; the ``generic``
29
+ interface does not export it).
30
+
31
+ State. The internal state variables of MGIS live in morphoGen's arrays of the internal
32
+ variables of the points, after the change of temperature, the gradients and the
33
+ thermodynamic forces at the end of the step (the start of the next one); tensors of 9
34
+ components there hold their difference to the identity, so that the natural state is
35
+ zero. Every integration starts from them, so that divided steps and the iterations of
36
+ Newton's method need no special care. The cumulated plastic strain of the outputs is the
37
+ internal variable ``plastic_strain`` (by default ``EquivalentPlasticStrain`` or
38
+ ``EquivalentViscoplasticStrain`` when the behaviour has one), and the plastic strain
39
+ tensor, in small strains, the strain minus ``ElasticStrain``.
40
+
41
+ The parameters of a behaviour (``parameters``) are global to its library in the process:
42
+ materials that share a behaviour share them.
43
+
44
+ MGIS and MFront are not on PyPI: ``conda install -c conda-forge mgis mfront`` (a C++
45
+ compiler, such as ``cxx-compiler``, builds the behaviours).
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import hashlib
51
+ import math
52
+ import os
53
+ import re
54
+ import shutil
55
+ import subprocess
56
+ from dataclasses import dataclass, field
57
+ from pathlib import Path
58
+
59
+ import numpy as np
60
+
61
+ from morphogen.homogenization.behaviours import MFRONT, STATE_P
62
+
63
+ INSTALL = "conda install -c conda-forge mgis mfront cxx-compiler"
64
+ _SQRT2 = math.sqrt(2.0)
65
+ #: Slots of the state of an MFront point: the plastic strain (tensor components) and the
66
+ #: cumulated plastic strain (STATE_P) of the outputs, the change of temperature, then
67
+ #: the gradients, the thermodynamic forces and the internal state variables of MGIS
68
+ _TEMP = STATE_P + 1
69
+ _FIRST = STATE_P + 2
70
+ #: MGIS's index of the component (i, j) of a symmetric tensor (TFEL's order: the shears
71
+ #: 12, 13, 23 after the diagonal), and the factor of that component (sqrt(2) off it)
72
+ _MGIS_INDEX = np.array([[0, 3, 4], [3, 1, 5], [4, 5, 2]])
73
+ _WEIGHT = np.where(np.eye(3, dtype=bool), 1.0, _SQRT2)
74
+ #: row-by-row index (3 i + j) of MGIS's components of tensors of 9 components
75
+ _ROWS = np.array([0, 4, 8, 1, 3, 2, 6, 5, 7])
76
+ #: morphoGen's Voigt pairs (11, 22, 33, 23, 31, 12)
77
+ _PAIRS = ((0, 0), (1, 1), (2, 2), (1, 2), (2, 0), (0, 1))
78
+
79
+
80
+ def _mgis():
81
+ try:
82
+ import mgis
83
+ import mgis.behaviour
84
+ except ImportError:
85
+ raise ImportError(f"MFront behaviours need MGIS: {INSTALL}") from None
86
+ return mgis
87
+
88
+
89
+ def available() -> bool:
90
+ """Whether MGIS can be imported (MFront behaviours can be integrated)."""
91
+ try:
92
+ _mgis()
93
+ except ImportError:
94
+ return False
95
+ return True
96
+
97
+
98
+ def info() -> dict:
99
+ """MGIS and the MFront code generator (the version of TFEL), or why MFront behaviours
100
+ are not available."""
101
+ try:
102
+ _mgis()
103
+ except ImportError as exc:
104
+ return {"mgis": False, "mfront": None, "tfel": None, "reason": str(exc)}
105
+ exe = shutil.which("mfront")
106
+ out = {"mgis": True, "mfront": exe, "tfel": None}
107
+ if exe is not None:
108
+ try:
109
+ run = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=60)
110
+ except (OSError, subprocess.SubprocessError):
111
+ return out
112
+ for line in run.stdout.splitlines():
113
+ if line.startswith("Version"):
114
+ out["tfel"] = line.partition(":")[2].strip()
115
+ return out
116
+
117
+
118
+ def _pairs(value, name: str) -> tuple[tuple[str, float], ...]:
119
+ if value is None:
120
+ return ()
121
+ if isinstance(value, dict):
122
+ items = value.items()
123
+ else:
124
+ items = [tuple(v) for v in value]
125
+ out = []
126
+ for key, v in items:
127
+ v = float(v)
128
+ if not math.isfinite(v):
129
+ raise ValueError(f"mfront.{name}.{key}: a finite number")
130
+ out.append((str(key), v))
131
+ return tuple(sorted(out))
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class MFrontBehaviour:
136
+ """An MFront behaviour of a material: ``library`` (compiled with the ``generic``
137
+ interface) or ``source`` (a ``.mfront`` file, compiled on first use by
138
+ :func:`compile_mfront`), ``behaviour`` (its name; by default the stem of the
139
+ source), the values of its ``material_properties`` and ``parameters``, its
140
+ ``external_state_variables`` other than the temperature (constants), the absolute
141
+ ``temperature`` of the natural state (the changes of temperature of the loading paths
142
+ add to it) and the internal variable that gives the cumulated plastic strain of the
143
+ outputs (``plastic_strain``)."""
144
+
145
+ library: str | None = None
146
+ source: str | None = None
147
+ behaviour: str | None = None
148
+ material_properties: tuple = ()
149
+ parameters: tuple = ()
150
+ external_state_variables: tuple = ()
151
+ temperature: float = 293.15
152
+ plastic_strain: str | None = None
153
+
154
+ def __post_init__(self) -> None:
155
+ if (self.library is None) == (self.source is None):
156
+ raise ValueError("mfront: give the library or the source of the behaviour")
157
+ name = self.behaviour
158
+ if name is None:
159
+ if self.source is None:
160
+ raise ValueError("mfront: the name of the behaviour of the library")
161
+ name = Path(self.source).stem
162
+ object.__setattr__(self, "behaviour", str(name))
163
+ for key in ("library", "source"):
164
+ if getattr(self, key) is not None:
165
+ object.__setattr__(self, key, str(getattr(self, key)))
166
+ object.__setattr__(self, "material_properties",
167
+ _pairs(self.material_properties, "material_properties")) # fmt: skip
168
+ object.__setattr__(self, "parameters", _pairs(self.parameters, "parameters"))
169
+ esvs = _pairs(self.external_state_variables, "external_state_variables")
170
+ object.__setattr__(self, "external_state_variables", esvs)
171
+ t = float(self.temperature)
172
+ if not (math.isfinite(t) and t > 0):
173
+ raise ValueError("mfront.temperature: an absolute temperature (K)")
174
+ object.__setattr__(self, "temperature", t)
175
+
176
+ @classmethod
177
+ def from_config(cls, spec) -> MFrontBehaviour:
178
+ """A mapping with ``library`` or ``source``, and optionally ``behaviour``,
179
+ ``material_properties``, ``parameters``, ``external_state_variables`` (mappings
180
+ of names to values), ``temperature`` and ``plastic_strain``."""
181
+ if isinstance(spec, MFrontBehaviour):
182
+ return spec
183
+ if isinstance(spec, str):
184
+ spec = {"source" if spec.endswith(".mfront") else "library": spec}
185
+ if not isinstance(spec, dict):
186
+ raise ValueError("mfront: a mapping (library or source, behaviour, ...)")
187
+ allowed = {"library", "source", "behaviour", "material_properties", "parameters",
188
+ "external_state_variables", "temperature", "plastic_strain"} # fmt: skip
189
+ unknown = sorted(set(spec) - allowed)
190
+ if unknown:
191
+ raise ValueError(f"mfront: unknown keys {unknown}; allowed: {sorted(allowed)}")
192
+ return cls(**spec)
193
+
194
+ def to_config(self) -> dict:
195
+ out: dict = {"library": self.library} if self.library else {"source": self.source}
196
+ out["behaviour"] = self.behaviour
197
+ for key in ("material_properties", "parameters", "external_state_variables"):
198
+ if getattr(self, key):
199
+ out[key] = dict(getattr(self, key))
200
+ out["temperature"] = self.temperature
201
+ if self.plastic_strain is not None:
202
+ out["plastic_strain"] = self.plastic_strain
203
+ return out
204
+
205
+
206
+ # -- compilation -----------------------------------------------------------------------------
207
+
208
+
209
+ def _library_of(directory: Path) -> Path | None:
210
+ for pattern in ("libBehaviour.so", "libBehaviour.dylib", "libBehaviour.dll", "Behaviour.dll"):
211
+ found = sorted(directory.rglob(pattern))
212
+ if found:
213
+ return found[0]
214
+ return None
215
+
216
+
217
+ def compile_mfront(source, *, directory=None) -> Path:
218
+ """The library (``generic`` interface) of an MFront source, built by ``mfront
219
+ --obuild --interface=generic`` in a cache directory named after its stem and the hash
220
+ of its contents (``directory``; by default ``MORPHOGEN_MFRONT_CACHE`` or
221
+ ``~/.cache/morphogen/mfront``), and reused while the source does not change."""
222
+ source = Path(source).resolve()
223
+ if not source.is_file():
224
+ raise FileNotFoundError(f"mfront: no source {source}")
225
+ exe = shutil.which("mfront")
226
+ if exe is None:
227
+ raise RuntimeError(f"mfront: the MFront code generator is not on the PATH ({INSTALL})")
228
+ key = hashlib.sha256(source.read_bytes()).hexdigest()[:16]
229
+ base = directory or os.environ.get("MORPHOGEN_MFRONT_CACHE")
230
+ base = Path(base) if base else Path.home() / ".cache" / "morphogen" / "mfront"
231
+ target = base / f"{source.stem}-{key}"
232
+ library = _library_of(target) if target.exists() else None
233
+ if library is not None:
234
+ return library
235
+ target.mkdir(parents=True, exist_ok=True)
236
+ shutil.copy(source, target / source.name)
237
+ run = subprocess.run([exe, "--obuild", "--interface=generic", source.name], cwd=target,
238
+ capture_output=True, text=True, check=False) # fmt: skip
239
+ library = _library_of(target)
240
+ if run.returncode != 0 or library is None:
241
+ tail = "\n".join((run.stdout + run.stderr).strip().splitlines()[-15:])
242
+ raise RuntimeError(f"mfront: {source.name} did not compile:\n{tail}")
243
+ return library
244
+
245
+
246
+ # -- loading -------------------------------------------------------------------------------------
247
+
248
+
249
+ @dataclass
250
+ class MFrontLaw:
251
+ """A behaviour loaded by MGIS for the integration points of a material: its sizes,
252
+ the offsets of its internal state variables of 9 components (stored minus the
253
+ identity) and of the variables of the outputs, whether it is orthotropic (its points
254
+ are turned to the axes of their grains) and whether its consistent tangent is
255
+ symmetric (:func:`declared_symmetric`)."""
256
+
257
+ spec: MFrontBehaviour
258
+ behaviour: object
259
+ finite: bool
260
+ n_grad: int
261
+ n_force: int
262
+ n_isv: int
263
+ identity: np.ndarray = field(default_factory=lambda: np.zeros(0))
264
+ p_offset: int | None = None
265
+ elastic_offset: int | None = None
266
+ orthotropic: bool = False
267
+ symmetric: bool = False
268
+
269
+ @property
270
+ def width(self) -> int:
271
+ """Internal variables of a point in morphoGen's arrays."""
272
+ return _FIRST + self.n_grad + self.n_force + self.n_isv
273
+
274
+
275
+ #: Parameters set on the behaviours of each library (the parameters are global)
276
+ _PARAMETERS: dict[tuple[str, str], tuple] = {}
277
+ #: The traits of the tangent of a behaviour in the header that MFront generates: its
278
+ #: class (the hypothesis of the specialization, or ``hypothesis`` for the general one)
279
+ #: and whether its tangent is symmetric
280
+ _TRAITS = r"class MechanicalBehaviourTraits<::tfel::material::{name}<([^,<>]+),[^>]*>\s*>"
281
+ _SYMMETRIC_TRAIT = re.compile(r"isConsistentTangentOperatorSymmetric\s*=\s*(true|false)")
282
+
283
+
284
+ def declared_symmetric(library, behaviour: str) -> bool | None:
285
+ """Whether the behaviour ``behaviour`` of the MFront ``library`` declares a symmetric
286
+ consistent tangent (``@ProvidesSymmetricTangentOperator``): the trait
287
+ ``isConsistentTangentOperatorSymmetric`` of its tridimensional hypothesis in the header
288
+ ``include/TFEL/Material/<behaviour>.hxx`` that ``mfront --obuild`` writes beside the
289
+ directory of the library (that of :func:`compile_mfront`); None without that header."""
290
+ library = Path(library).resolve()
291
+ for root in (library.parent.parent, library.parent):
292
+ header = root / "include" / "TFEL" / "Material" / f"{behaviour}.hxx"
293
+ if header.is_file():
294
+ break
295
+ else:
296
+ return None
297
+ text = header.read_text(encoding="utf-8", errors="replace")
298
+ pattern = re.compile(_TRAITS.format(name=re.escape(behaviour)))
299
+ traits = {}
300
+ matches = list(pattern.finditer(text))
301
+ for k, match in enumerate(matches):
302
+ end = matches[k + 1].start() if k + 1 < len(matches) else len(text)
303
+ found = _SYMMETRIC_TRAIT.search(text, match.end(), end)
304
+ if found:
305
+ traits[match.group(1).strip()] = found.group(1) == "true"
306
+ for hypothesis in ("ModellingHypothesis::TRIDIMENSIONAL", "hypothesis"):
307
+ if hypothesis in traits:
308
+ return traits[hypothesis]
309
+ return None
310
+
311
+
312
+ def load_behaviour(spec: MFrontBehaviour, *, finite: bool) -> MFrontLaw:
313
+ """The behaviour of ``spec`` loaded by MGIS for three-dimensional points (finite
314
+ strains: for the first Piola-Kirchhoff stress and its derivative with respect to F),
315
+ checked against the kinematics of the solver, its material properties and parameters
316
+ set."""
317
+ mgis = _mgis()
318
+ bv = mgis.behaviour
319
+ library = Path(spec.library) if spec.library else compile_mfront(spec.source)
320
+ h = bv.Hypothesis.Tridimensional
321
+ # each form of load refuses the behaviours of the other kinematics: the behaviour is
322
+ # loaded as it is, its type checked against the solver below
323
+ if bv.isStandardFiniteStrainBehaviour(str(library), spec.behaviour):
324
+ opts = bv.FiniteStrainBehaviourOptions()
325
+ opts.stress_measure = bv.FiniteStrainBehaviourOptionsStressMeasure.PK1
326
+ opts.tangent_operator = bv.FiniteStrainBehaviourOptionsTangentOperator.DPK1_DF
327
+ b = bv.load(opts, str(library), spec.behaviour, h)
328
+ else:
329
+ b = bv.load(str(library), spec.behaviour, h)
330
+ standard = (bv.BehaviourType.STANDARDFINITESTRAINBEHAVIOUR if finite
331
+ else bv.BehaviourType.STANDARDSTRAINBASEDBEHAVIOUR) # fmt: skip
332
+ if b.btype != standard:
333
+ kind = "finite" if finite else "small"
334
+ raise ValueError(
335
+ f"mfront: {spec.behaviour} is a {b.btype.name} behaviour; the loading paths in "
336
+ f"{kind} strains need a {standard.name} behaviour"
337
+ )
338
+ n_grad = bv.getArraySize(b.gradients, h)
339
+ n_force = bv.getArraySize(b.thermodynamic_forces, h)
340
+ if (n_grad, n_force) != ((9, 9) if finite else (6, 6)):
341
+ raise ValueError(f"mfront: {spec.behaviour}: unexpected gradients ({n_grad})")
342
+ given = dict(spec.material_properties)
343
+ names = [v.name for v in b.mps]
344
+ missing = sorted(set(names) - set(given))
345
+ extra = sorted(set(given) - set(names))
346
+ if missing or extra:
347
+ raise ValueError(f"mfront: {spec.behaviour} has the material properties {names}; "
348
+ f"missing {missing}, unknown {extra}") # fmt: skip
349
+ params = dict(spec.parameters)
350
+ unknown = sorted(set(params) - set(b.params))
351
+ if unknown:
352
+ raise ValueError(f"mfront: {spec.behaviour} has no parameters {unknown}; {b.params}")
353
+ key = (str(library.resolve()), spec.behaviour)
354
+ previous = _PARAMETERS.get(key)
355
+ if previous is not None and previous != spec.parameters:
356
+ raise ValueError(
357
+ f"mfront: {spec.behaviour} of {library.name} with other parameters: the parameters "
358
+ "of a behaviour are global to its library"
359
+ )
360
+ for name, value in params.items():
361
+ b.setParameter(name, value)
362
+ _PARAMETERS[key] = spec.parameters
363
+ esvs = [v.name for v in b.esvs]
364
+ other = dict(spec.external_state_variables)
365
+ lacking = sorted(set(esvs) - {"Temperature"} - set(other))
366
+ if lacking:
367
+ raise ValueError(f"mfront: give the external state variables {lacking}")
368
+ n_isv = bv.getArraySize(b.isvs, h)
369
+ identity = []
370
+ for v in b.isvs:
371
+ if bv.getVariableSize(v, h) == 9 and v.type == bv.VariableType.Tensor:
372
+ offset = bv.getVariableOffset(b.isvs, v.name, h)
373
+ identity.extend(offset + k for k in (0, 1, 2))
374
+ p_name = spec.plastic_strain
375
+ isv_names = {v.name: v for v in b.isvs}
376
+ if p_name is None:
377
+ p_name = next((n for n in ("EquivalentPlasticStrain", "EquivalentViscoplasticStrain")
378
+ if n in isv_names), None) # fmt: skip
379
+ elif p_name not in isv_names:
380
+ raise ValueError(f"mfront: {spec.behaviour} has no internal variable {p_name!r}")
381
+ p_offset = None if p_name is None else bv.getVariableOffset(b.isvs, p_name, h)
382
+ elastic = None
383
+ if not finite and "ElasticStrain" in isv_names:
384
+ elastic = bv.getVariableOffset(b.isvs, "ElasticStrain", h)
385
+ orthotropic = b.symmetry == bv.BehaviourSymmetry.ORTHOTROPIC
386
+ symmetric = bool(declared_symmetric(library, spec.behaviour)) # unknown: not symmetric
387
+ return MFrontLaw(spec, b, finite, n_grad, n_force, n_isv, np.array(identity, dtype=int),
388
+ p_offset, elastic, orthotropic, symmetric) # fmt: skip
389
+
390
+
391
+ # -- conventions -----------------------------------------------------------------------------
392
+
393
+
394
+ def _tensors(e) -> np.ndarray:
395
+ """Symmetric tensors (n, 3, 3) of engineering Voigt strains (n, 6)."""
396
+ t = np.empty((e.shape[0], 3, 3))
397
+ for k, (i, j) in enumerate(_PAIRS):
398
+ v = e[:, k] if i == j else 0.5 * e[:, k]
399
+ t[:, i, j] = v
400
+ t[:, j, i] = v
401
+ return t
402
+
403
+
404
+ def _to_mgis(t) -> np.ndarray:
405
+ """MGIS's components (n, 6) of symmetric tensors (n, 3, 3): 11, 22, 33, then
406
+ sqrt(2) times 12, 13, 23."""
407
+ out = np.empty((t.shape[0], 6))
408
+ out[:, 0], out[:, 1], out[:, 2] = t[:, 0, 0], t[:, 1, 1], t[:, 2, 2]
409
+ out[:, 3] = _SQRT2 * t[:, 0, 1]
410
+ out[:, 4] = _SQRT2 * t[:, 0, 2]
411
+ out[:, 5] = _SQRT2 * t[:, 1, 2]
412
+ return out
413
+
414
+
415
+ def _from_mgis(m) -> np.ndarray:
416
+ """Symmetric tensors (n, 3, 3) of MGIS's components (n, 6)."""
417
+ return m[:, _MGIS_INDEX] / _WEIGHT
418
+
419
+
420
+ def _voigt(t) -> np.ndarray:
421
+ """morphoGen's Voigt components (n, 6) of symmetric tensors (tensor shears)."""
422
+ return np.stack([t[:, i, j] for i, j in _PAIRS], axis=1)
423
+
424
+
425
+ def _turn(t, g, back: bool):
426
+ """Tensors (n, 3, 3) in the axes of the lattice (``g t g^T``) or back (``g^T t g``)."""
427
+ if g is None:
428
+ return t
429
+ if back:
430
+ return np.einsum("npi,npq,nqj->nij", g, t, g)
431
+ return np.einsum("nip,npq,njq->nij", g, t, g)
432
+
433
+
434
+ def _turn4(a, g):
435
+ """Fourth-order tensors (n, 3, 3, 3, 3) from the axes of the lattice to the sample."""
436
+ if g is None:
437
+ return a
438
+ return np.einsum("npi,nqj,nrk,nsl,npqrs->nijkl", g, g, g, g, a, optimize=True)
439
+
440
+
441
+ def _strains_in(e, g) -> np.ndarray:
442
+ return _to_mgis(_turn(_tensors(e), g, back=False))
443
+
444
+
445
+ def _gradients_in(hg, g) -> np.ndarray:
446
+ f = np.eye(3) + hg.reshape(-1, 3, 3)
447
+ return _turn(f, g, back=False).reshape(-1, 9)[:, _ROWS]
448
+
449
+
450
+ def _stress_out(m, g) -> np.ndarray:
451
+ return _voigt(_turn(_from_mgis(m), g, back=True))
452
+
453
+
454
+ def _pk1_out(p, g) -> np.ndarray:
455
+ rows = np.empty_like(p)
456
+ rows[:, _ROWS] = p
457
+ return _turn(rows.reshape(-1, 3, 3), g, back=True).reshape(-1, 9)
458
+
459
+
460
+ def _tangent_out(k, g, symmetric: bool = True) -> np.ndarray:
461
+ """morphoGen's Voigt tangent (engineering strains, n x 6 x 6) of MGIS's (TFEL's order,
462
+ factors sqrt(2)), symmetrized with ``symmetric``."""
463
+ from morphogen.homogenization.materials import tensor4_to_voigt
464
+
465
+ c = k[:, _MGIS_INDEX[:, :, None, None], _MGIS_INDEX[None, None, :, :]]
466
+ c = c / (_WEIGHT[:, :, None, None] * _WEIGHT[None, None, :, :])
467
+ d = tensor4_to_voigt(_turn4(c, g))
468
+ return 0.5 * (d + np.swapaxes(d, 1, 2)) if symmetric else np.ascontiguousarray(d)
469
+
470
+
471
+ def _dpdf_out(k, g, symmetric: bool = True) -> np.ndarray:
472
+ """dP/dF row by row (n x 9 x 9) of MGIS's (its order of the components), symmetrized
473
+ with ``symmetric``."""
474
+ a = np.empty_like(k)
475
+ a[:, _ROWS[:, None], _ROWS[None, :]] = k
476
+ if g is not None:
477
+ a = _turn4(a.reshape(-1, 3, 3, 3, 3), g).reshape(-1, 9, 9)
478
+ return 0.5 * (a + np.swapaxes(a, 1, 2)) if symmetric else a
479
+
480
+
481
+ # -- integration ---------------------------------------------------------------------------------
482
+
483
+
484
+ class MFrontPoints:
485
+ """The integration points of the materials with an MFront behaviour, integrated by
486
+ MGIS: one manager of the data of the points per material, the rotations of the points
487
+ of crystals, a pool of threads. ``kind``, ``pmat`` and ``point_mat`` are those of the
488
+ points of a solver, ``rotations`` the orientation matrix of each of its materials
489
+ (``crystal = g @ sample``); ``symmetric``: the tangents symmetrized (for the conjugate
490
+ gradients), or passed whole (for GMRES and at a material point)."""
491
+
492
+ def __init__(self, laws, kind, pmat, point_mat, rotations, finite: bool, threads=None,
493
+ symmetric: bool = True): # fmt: skip
494
+ mgis = _mgis()
495
+ bv = mgis.behaviour
496
+ import numba
497
+
498
+ self.finite = bool(finite)
499
+ self.symmetric = bool(symmetric)
500
+ self.points = np.flatnonzero(np.asarray(kind) == MFRONT)
501
+ self.groups = []
502
+ pmat = np.asarray(pmat)[self.points]
503
+ point_mat = np.asarray(point_mat)[self.points]
504
+ for c, law in enumerate(laws):
505
+ if law.finite != self.finite:
506
+ raise ValueError("mfront: the behaviour and the solver have other kinematics")
507
+ local = np.flatnonzero(pmat == c)
508
+ if local.size == 0:
509
+ continue
510
+ m = bv.MaterialDataManager(law.behaviour, local.size)
511
+ for state in (m.s0, m.s1):
512
+ for name, value in law.spec.material_properties:
513
+ bv.setMaterialProperty(state, name, value)
514
+ for name, value in law.spec.external_state_variables:
515
+ bv.setExternalStateVariable(state, name, value)
516
+ # orthotropic behaviours (crystals) in the axes of their grains; isotropic ones
517
+ # are not turned
518
+ g = np.asarray(rotations)[point_mat[local]]
519
+ if not law.orthotropic or np.allclose(g, np.eye(3), rtol=0, atol=1e-14):
520
+ g = None
521
+ self.groups.append((law, local, m, g))
522
+ self.pool = mgis.ThreadPool(int(threads or numba.get_num_threads()))
523
+ self.integration = bv.IntegrationType.IntegrationWithConsistentTangentOperator
524
+ self._bv = bv
525
+
526
+ def integrate(self, grads, dtemp, dt, old, new, stress, tangent) -> int:
527
+ """Integration of the MFront points of the arrays of all the points (see
528
+ :meth:`~morphogen.homogenization.nonlinear._PointArrays.integrate`); returns the
529
+ number of points of the materials whose integration failed."""
530
+ idx = self.points
531
+ out = [new[idx], stress[idx], tangent[idx]]
532
+ failed = self.integrate_compact(grads[idx], dtemp, dt, old[idx], *out)
533
+ new[idx], stress[idx], tangent[idx] = out
534
+ return failed
535
+
536
+ def integrate_compact(self, grads, dtemp, dt, old, new, stress, tangent) -> int:
537
+ """The same for the arrays of the MFront points only (in the order of
538
+ :attr:`points`), on the CPU."""
539
+ bv = self._bv
540
+ failed = 0
541
+ for law, local, m, g in self.groups:
542
+ o = old[local]
543
+ a, b = _FIRST, _FIRST + law.n_grad
544
+ c, d = b + law.n_force, b + law.n_force + law.n_isv
545
+ start = o[:, a:b].copy()
546
+ if self.finite:
547
+ start[:, :3] += 1.0
548
+ m.s0.gradients[:] = start
549
+ m.s0.thermodynamic_forces[:] = o[:, b:c]
550
+ isv = o[:, c:d].copy()
551
+ if law.identity.size:
552
+ isv[:, law.identity] += 1.0
553
+ if law.n_isv: # MGIS divides by the size in the views of the arrays
554
+ m.s0.internal_state_variables[:] = isv
555
+ t_ref = law.spec.temperature
556
+ bv.setExternalStateVariable(m.s0, "Temperature", t_ref + float(o[0, _TEMP]))
557
+ bv.setExternalStateVariable(m.s1, "Temperature", t_ref + float(dtemp))
558
+ gi = _gradients_in(grads[local], g) if self.finite else _strains_in(grads[local], g)
559
+ m.s1.gradients[:] = gi
560
+ if bv.integrate(self.pool, m, self.integration, float(dt)) < 0:
561
+ failed += local.size
562
+ continue
563
+ forces = np.array(m.s1.thermodynamic_forces)
564
+ k = np.array(m.K).reshape(local.size, law.n_force, law.n_grad)
565
+ if self.finite:
566
+ stress[local] = _pk1_out(forces, g)
567
+ tangent[local] = _dpdf_out(k, g, self.symmetric)
568
+ else:
569
+ stress[local] = _stress_out(forces, g)
570
+ tangent[local] = _tangent_out(k, g, self.symmetric)
571
+ if law.n_isv:
572
+ isv = np.array(m.s1.internal_state_variables)
573
+ state = np.zeros((local.size, new.shape[1]))
574
+ if law.elastic_offset is not None:
575
+ ee = _turn(_from_mgis(isv[:, law.elastic_offset : law.elastic_offset + 6]), g,
576
+ back=True) # fmt: skip
577
+ state[:, :6] = _voigt(_tensors(grads[local]) - ee)
578
+ if law.p_offset is not None:
579
+ state[:, STATE_P] = isv[:, law.p_offset]
580
+ state[:, _TEMP] = dtemp
581
+ state[:, a:b] = gi
582
+ if self.finite:
583
+ state[:, a : a + 3] -= 1.0
584
+ state[:, b:c] = forces
585
+ if law.identity.size:
586
+ isv[:, law.identity] -= 1.0
587
+ state[:, c:d] = isv
588
+ new[local] = state
589
+ return failed