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,2967 @@
1
+ """Crystal plasticity of Méric & Cailletaud (1991).
2
+
3
+ Plastic flow is the sum of the slips ``gamma^s`` on the slip systems ``s`` of the lattice
4
+ (plane normal ``n^s``, slip direction ``l^s``), driven by the resolved shear stress
5
+ ``tau^s = sigma : m^s``, ``m^s = sym(l^s (x) n^s)``:
6
+
7
+ * viscoplastic slip ``dgamma^s/dt = <(|tau^s - x^s| - r^s) / K>^n sign(tau^s - x^s)``;
8
+ * kinematic hardening of each system ``x^s = C alpha^s``, ``dalpha^s = dgamma^s - D
9
+ alpha^s |dgamma^s|``;
10
+ * isotropic hardening ``r^s = tau_0 + Q sum_r h_sr (1 - exp(-b v^r))`` with the cumulated
11
+ slips ``v^r`` (``dv^r = |dgamma^r|``) and the interaction matrix ``h``;
12
+ * ``deps_p = sum_s dgamma^s m^s`` in small strains; ``dF_p F_p^-1 = sum_s dgamma^s l^s (x)
13
+ n^s`` in finite strains (multiplicative decomposition ``F = F_e F_p``, the slip systems
14
+ fixed in the intermediate configuration, the lattice rotating with ``F_e``).
15
+
16
+ The parameters ``tau_0, Q, b, C, D, K, n`` belong to the families of slip systems. Slip
17
+ systems are given in the axes of the crystal; each grain turns them by its orientation,
18
+ as its elasticity (:mod:`morphogen.homogenization.materials`).
19
+
20
+ Families: ``octahedral`` {111}<110> and ``cube`` {100}<110> (face-centred cubic crystals,
21
+ and the cube slip of nickel-base superalloys), ``bcc110`` {110}<111> and ``bcc112``
22
+ {112}<111> (body-centred cubic crystals); for hexagonal crystals of ratio ``c_over_a``
23
+ (axis c along the third axis of the crystal, a_1 along the first), ``basal`` (0001)<11-20>,
24
+ ``prismatic`` {10-10}<11-20>, ``pyramidal_a`` {10-11}<11-20>, ``pyramidal_ca`` {10-11}<11-23>
25
+ and ``pyramidal2_ca`` {11-22}<11-23>.
26
+
27
+ **Twinning** (``twins``) is a slip in one sense (the pseudo-slip of Kalidindi 1998):
28
+ a twin system of plane ``K_1`` and direction ``eta_1`` shears by ``gamma`` when the
29
+ fraction ``f = gamma / gamma_tw`` of the crystal has twinned, ``gamma_tw`` the shear of the
30
+ twin (the one that leaves the second plane ``K_2`` undistorted). Its flow rule is that of
31
+ a slip system for a positive resolved shear stress, with a resistance that grows without
32
+ bound as the twinned fraction ``F = sum_t gamma^t / gamma_tw^t`` comes to its saturation
33
+ ``F_sat`` (a barrier: 1 % of ``tau_0`` at 90 % of the saturation, ``tau_0`` at 99.9 %)::
34
+
35
+ dgamma^t/dt = <(tau^t - x^t - r^t - 10^-3 tau_0 F / (F_sat - F)) / K>^n,
36
+
37
+ so that the twins stop there, whatever the stress. Under a stress that is reversed the
38
+ twins shear back, down to none (detwinning, at the resistance of the twinning without
39
+ its barrier, or at a share of it: ``twin_detwinning``, a number; ``false``: they stay).
40
+ Families: ``twin111`` {111}<11-2>
41
+ (face-centred cubic, shear 1 / sqrt 2), ``twin112`` {112}<11-1> (body-centred cubic, 1 /
42
+ sqrt 2), and for hexagonal crystals ``twin1012`` {10-12}<10-1-1> (which extends the axis c
43
+ below ``c / a = sqrt 3``: magnesium, titanium, and shortens it above: zinc), ``twin1011``
44
+ {10-11}<10-1-2>, ``twin1122`` {11-22}<11-2-3> and ``twin1121`` {11-21}<-1-126>.
45
+
46
+ **The lattice of a twin** (``twin_reorientation``, a twinned fraction): when the twinned
47
+ fraction of a point comes to it at the end of a step, the lattice of the point becomes
48
+ that of its predominant twin (Van Houtte 1978; Tomé, Lebensohn & Kocks 1991, at each
49
+ integration point): turned by half a turn about the normal of the twin plane, ``Q = 2 n
50
+ (x) n - I``, with its systems, its elasticity and its thermal strain. Its twins start
51
+ again from nothing; in the new lattice the system of that twin shears the other way and
52
+ brings the first lattice back, the other twins of its family being held. With ``{threshold,
53
+ growth}`` the lattices are turned grain by grain after each step (:func:`turn_twins`): the
54
+ most twinned points first, while the turned volume of the grain is below its twinned
55
+ volume. Without it the lattice of the twinned fraction is not turned: the slip of the
56
+ twins is not followed.
57
+
58
+ **Cleavage** (``cleavage``) opens crystallographic planes (the damage systems of Marchal,
59
+ Forest, Rémy & Duvinage 2006, see Aslan & Forest 2009): a plane of normal ``n`` has an
60
+ opening system, whose strain is ``delta n (x) n`` and which flows under a positive normal
61
+ stress ``n . sigma . n``, and accommodation systems ``sym(n (x) l)`` along directions
62
+ ``l`` of the plane, which release its shear stresses once it has opened. Their flow rule
63
+ is that of the slip systems, with a strength that softens with the opening and the
64
+ slips of the plane::
65
+
66
+ Y = Y_0 exp(-w d), d = delta + sum_i |delta_i|,
67
+
68
+ (``shear`` times ``Y_0`` for the accommodation systems): the energy dissipated by a plane
69
+ that breaks is ``Y_0 / w`` per unit volume, a fracture energy ``G_c`` per unit area for
70
+ elements of size ``h`` when ``w = Y_0 h / G_c`` (the crack band of Bažant & Oh 1983),
71
+ which requires ``w Y_0`` below the stiffness of the opening (``h < E G_c / Y_0^2``).
72
+ Planes: ``cube`` {100}, ``dodecahedral`` {110} and ``octahedral`` {111} of cubic crystals,
73
+ ``basal`` (0001) and ``prismatic`` {10-10} of hexagonal ones. Under pressure a plane
74
+ closes: its opening follows the sign of the normal stress, back to nothing (Aslan &
75
+ Forest 2009), and the closed plane carries the pressure as the sound crystal (the
76
+ unilateral condition; ``closure: false``: the opening stays, and the lattice alone is
77
+ pressed; a number: the share of its strength at which the plane closes). With a
78
+ ``coupling`` the slip of the crystal nucleates its cleavage (Aslan, Cordero, Gaubert &
79
+ Forest 2011): the strength of the planes falls with the cumulated slip of the slip
80
+ systems, ``Y = Y_0 exp(-w d) exp(-Theta gamma_cum)``, and their damage takes ``Theta
81
+ exp(-Theta gamma_cum) sum_p (Y_0 / w) (1 - exp(-w d_p))`` off the resistance of the slip
82
+ systems (the two derive from one energy). With a ``regularization`` the planes are those
83
+ of the microdamage theory of Aslan & Forest (2009): the planes of a point have one
84
+ threshold, which softens linearly with the damage ``d`` of them all and hardens with
85
+ this damage less the microdamage of the point, ``Y = Y_0 (1 - w d) + chi_H (d - chi_d)``,
86
+ the microdamage ``chi_d`` following the damage over a length, ``chi_d - ell^2 lap chi_d
87
+ = d`` (the solvers of the loading paths solve it, and break through the planes whose
88
+ strength has come to nothing): a crack is then a band of a width that the elements do
89
+ not set (:func:`microdamage_band`). The lips of a plane under pressure rub: the strength
90
+ of its accommodation systems has Coulomb's ``friction`` times the pressure (0 by
91
+ default).
92
+
93
+ The interaction matrix is uniform (Taylor hardening) by default; ``[h_self, h_latent]``;
94
+ the six coefficients of Franciosi for the octahedral systems, in the order self,
95
+ coplanar, Hirth lock, collinear, glissile junction, Lomer lock; or a full matrix.
96
+
97
+ Integration is implicit (backward Euler, the Armstrong-Frederick variables in closed
98
+ form): Newton's method on the magnitudes of the slips of an active set of systems, with
99
+ the flow rule written as stresses (see the kernels below), and substeps when it fails;
100
+ its linearization gives the consistent tangent, symmetric in small strains without
101
+ isotropic hardening (``Q b = 0``) and not otherwise (the latent hardening of a system by
102
+ the slips of the others; the multiplicative decomposition of finite strains), symmetrized
103
+ for the conjugate gradient solvers or kept whole for GMRES (``sym``).
104
+ """
105
+
106
+ from __future__ import annotations
107
+
108
+ import itertools
109
+ import math
110
+ from dataclasses import dataclass
111
+ from functools import cache
112
+
113
+ import numpy as np
114
+ from numba import njit
115
+
116
+ from morphogen.homogenization.tensors import (
117
+ elastic_stress,
118
+ gauss_solve,
119
+ inverse3,
120
+ matmul3,
121
+ matmult3,
122
+ project,
123
+ stress_tensor,
124
+ symmetrize,
125
+ tmatmul3,
126
+ )
127
+
128
+ #: Parameters of a family of slip systems, in the order of the kernels
129
+ PARAMS = ("tau0", "Q", "b", "C", "D", "K", "n")
130
+ _DEFAULTS = {"tau0": None, "Q": 0.0, "b": 0.0, "C": 0.0, "D": 0.0, "K": None, "n": None}
131
+ _ALIASES = {"r0": "tau0", "R0": "tau0", "q": "Q", "c": "C", "d": "D", "k": "K", "N": "n"}
132
+ #: Order of the six interaction coefficients of the octahedral systems
133
+ INTERACTIONS = ("self", "coplanar", "hirth", "collinear", "glissile", "lomer")
134
+
135
+
136
+ def _canonical(v) -> tuple[int, ...]:
137
+ """The direction ``v`` or ``-v``: its first nonzero component positive."""
138
+ v = tuple(int(x) for x in v)
139
+ first = next(x for x in v if x != 0)
140
+ return v if first > 0 else tuple(-x for x in v)
141
+
142
+
143
+ def _family_vectors(normals_type, directions_type):
144
+ """Slip systems (normal, direction) of the cubic vectors of the given types: all the
145
+ pairs of a plane normal and a perpendicular slip direction, normals and directions
146
+ taken once up to their sign."""
147
+
148
+ def vectors(kind):
149
+ out = set()
150
+ for perm in set(itertools.permutations(kind)):
151
+ for signs in itertools.product((1, -1), repeat=3):
152
+ v = tuple(s * p for s, p in zip(signs, perm, strict=True))
153
+ if any(v):
154
+ out.add(_canonical(v))
155
+ return sorted(out, reverse=True)
156
+
157
+ systems = []
158
+ for n in vectors(normals_type):
159
+ for d in vectors(directions_type):
160
+ if sum(a * b for a, b in zip(n, d, strict=True)) == 0:
161
+ systems.append((n, d))
162
+ return systems
163
+
164
+
165
+ #: Slip families: (normal type, direction type) of the cubic lattice
166
+ FAMILIES = {
167
+ "octahedral": ((1, 1, 1), (1, 1, 0)),
168
+ "cube": ((1, 0, 0), (1, 1, 0)),
169
+ "bcc110": ((1, 1, 0), (1, 1, 1)),
170
+ "bcc112": ((1, 1, 2), (1, 1, 1)),
171
+ }
172
+
173
+
174
+ #: Slip families of the hexagonal lattice: the plane (hkil) and the direction [uvtw] of
175
+ #: one of their systems
176
+ HEXAGONAL = {
177
+ "basal": ((0, 0, 0, 1), (1, 1, -2, 0)),
178
+ "prismatic": ((1, 0, -1, 0), (1, -2, 1, 0)),
179
+ "pyramidal_a": ((1, 0, -1, 1), (1, -2, 1, 0)),
180
+ "pyramidal_ca": ((1, 0, -1, 1), (-1, -1, 2, 3)),
181
+ "pyramidal2_ca": ((1, 1, -2, 2), (-1, -1, 2, 3)),
182
+ }
183
+ #: Twinning modes: the lattice, the plane K_1 and the direction eta_1 of one of their
184
+ #: systems, and the direction eta_2 of its second undistorted plane (which sets the shear)
185
+ TWINS = {
186
+ "twin111": ("cubic", (1, 1, 1), (1, 1, -2), (1, 1, 2)),
187
+ "twin112": ("cubic", (1, 1, 2), (-1, -1, 1), (1, 1, 1)),
188
+ "twin1012": ("hexagonal", (1, 0, -1, 2), (-1, 0, 1, 1), (1, 0, -1, 1)),
189
+ "twin1011": ("hexagonal", (1, 0, -1, 1), (1, 0, -1, -2), (3, 0, -3, 2)),
190
+ "twin1122": ("hexagonal", (1, 1, -2, 2), (1, 1, -2, -3), (2, 2, -4, 3)),
191
+ "twin1121": ("hexagonal", (1, 1, -2, 1), (-1, -1, 2, 6), (1, 1, -2, 0)),
192
+ }
193
+ #: Cleavage planes: the lattice, one plane and the directions of its accommodation systems
194
+ CLEAVAGE = {
195
+ "cube": ("cubic", (1, 0, 0), ((0, 1, 0), (0, 0, 1))),
196
+ "dodecahedral": ("cubic", (1, 1, 0), ((0, 0, 1), (1, -1, 0))),
197
+ "octahedral": ("cubic", (1, 1, 1), ((1, -1, 0), (1, 0, -1), (0, 1, -1))),
198
+ "basal": ("hexagonal", (0, 0, 0, 1), ((1, 1, -2, 0), (1, -2, 1, 0), (-2, 1, 1, 0))),
199
+ "prismatic": ("hexagonal", (1, 0, -1, 0), ((1, -2, 1, 0), (0, 0, 0, 1))),
200
+ }
201
+ #: Kinds of the systems of a crystal: slip, twin (in one sense), opening of a cleavage
202
+ #: plane (in one sense), accommodation of a cleavage plane
203
+ SLIP, TWIN, OPENING, ACCOMMODATION = 0, 1, 2, 3
204
+ #: The fields of the crystals that twin or cleave, and the curves of their means along a
205
+ #: loading path (:meth:`CrystalPlasticity.point_fields`)
206
+ FIELDS = (
207
+ "twin_fraction",
208
+ "twin_reoriented",
209
+ "twin_misorientation",
210
+ "cleavage_opening",
211
+ "cleavage_damage",
212
+ "cleavage_microdamage",
213
+ )
214
+
215
+
216
+ def lattice_of(family: str) -> str:
217
+ """The lattice (``"cubic"`` or ``"hexagonal"``) of a family of slip systems, of twins
218
+ or of cleavage planes."""
219
+ if family in FAMILIES:
220
+ return "cubic"
221
+ if family in HEXAGONAL:
222
+ return "hexagonal"
223
+ for table in (TWINS, CLEAVAGE):
224
+ if family in table:
225
+ return table[family][0]
226
+ raise ValueError(f"crystal: unknown family {family!r}")
227
+
228
+
229
+ @cache
230
+ def _rotations(lattice: str) -> tuple:
231
+ """The proper rotations of the point group of a lattice (24 of the cube, 12 of the
232
+ hexagonal prism), in the axes of the crystal."""
233
+ out = []
234
+ if lattice == "cubic":
235
+ for perm in itertools.permutations(range(3)):
236
+ for signs in itertools.product((1.0, -1.0), repeat=3):
237
+ m = np.zeros((3, 3))
238
+ for i, (p, s) in enumerate(zip(perm, signs, strict=True)):
239
+ m[i, p] = s
240
+ if np.linalg.det(m) > 0:
241
+ out.append(m)
242
+ return tuple(out)
243
+ for k in range(6):
244
+ a = k * math.pi / 3.0
245
+ c, s = math.cos(a), math.sin(a)
246
+ out.append(np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]))
247
+ b = k * math.pi / 6.0 # a two-fold axis of the basal plane
248
+ u = np.array([math.cos(b), math.sin(b), 0.0])
249
+ out.append(2.0 * np.outer(u, u) - np.eye(3))
250
+ return tuple(out)
251
+
252
+
253
+ def disorientation(rotations, lattice: str) -> np.ndarray:
254
+ """The disorientation (degrees) of lattices turned by ``rotations`` (..., 3, 3; in the
255
+ axes of the crystal) from the one that they were: the smallest angle of the rotations
256
+ that bring the one onto the other, over the symmetries of the lattice (60 degrees for
257
+ the twins of cubic crystals, 86.3 for the {10-12} twin of magnesium)."""
258
+ ops = np.array(_rotations(lattice))
259
+ traces = np.einsum("...ij,kji->...k", np.asarray(rotations, dtype=float), ops)
260
+ cosine = np.clip(0.5 * (traces.max(axis=-1) - 1.0), -1.0, 1.0)
261
+ return np.degrees(np.arccos(cosine))
262
+
263
+
264
+ def _ratio(c_over_a, family: str) -> float:
265
+ if c_over_a is None:
266
+ raise ValueError(f"crystal: the hexagonal family {family!r} needs the ratio c_over_a")
267
+ ratio = float(c_over_a)
268
+ if not (math.isfinite(ratio) and ratio > 0):
269
+ raise ValueError(f"crystal: c_over_a is a positive number, got {c_over_a!r}")
270
+ return ratio
271
+
272
+
273
+ def _vector(indices, lattice: str, ratio: float | None, plane: bool) -> np.ndarray:
274
+ """The normal of a plane or a direction of a lattice in the Cartesian axes of the
275
+ crystal (not normalized): Miller indices of the cube; Miller-Bravais indices of the
276
+ hexagonal lattice, ``a_1`` along the first axis and ``c`` along the third."""
277
+ if lattice == "cubic":
278
+ return np.array(indices, dtype=float)
279
+ h, k, i, last = indices
280
+ if h + k + i != 0:
281
+ raise ValueError(f"crystal: Miller-Bravais indices {indices}: the first three sum to 0")
282
+ if plane:
283
+ return np.array([h, (h + 2.0 * k) / math.sqrt(3.0), last / ratio])
284
+ u, v = h - i, k - i # the three-index direction
285
+ return np.array([u - 0.5 * v, 0.5 * math.sqrt(3.0) * v, last * ratio])
286
+
287
+
288
+ def _key(*vectors) -> tuple:
289
+ return tuple(np.round(np.concatenate(vectors), 9) + 0.0)
290
+
291
+
292
+ def _variants(normal, direction, lattice: str, polar: bool) -> list[tuple]:
293
+ """The systems (unit normal, unit direction) that the rotations of the lattice make of
294
+ one: once each up to the signs of the normal and of the direction (slip), or up to
295
+ the sign of both together (``polar``: a twin, sheared in one sense)."""
296
+ n0 = np.asarray(normal, dtype=float) / np.linalg.norm(normal)
297
+ l0 = np.asarray(direction, dtype=float) / np.linalg.norm(direction)
298
+ if abs(n0 @ l0) > 1e-9:
299
+ raise ValueError("crystal: the direction of a system lies in its plane")
300
+ signs = [(1, 1), (-1, -1)] if polar else [(1, 1), (1, -1), (-1, 1), (-1, -1)]
301
+ seen: set = set()
302
+ out = []
303
+ for r in _rotations(lattice):
304
+ n, d = r @ n0, r @ l0
305
+ keys = [_key(a * n, b * d) for a, b in signs]
306
+ if not any(k in seen for k in keys):
307
+ seen.add(keys[0])
308
+ out.append((n, d))
309
+ return out
310
+
311
+
312
+ def slip_systems(family: str, c_over_a: float | None = None) -> tuple[np.ndarray, np.ndarray]:
313
+ """Unit plane normals and slip directions (N x 3 each, axes of the crystal) of a
314
+ family of slip systems; ``c_over_a``: the ratio of the hexagonal lattice."""
315
+ if family in HEXAGONAL:
316
+ ratio = _ratio(c_over_a, family)
317
+ plane, direction = HEXAGONAL[family]
318
+ pairs = _variants(
319
+ _vector(plane, "hexagonal", ratio, True),
320
+ _vector(direction, "hexagonal", ratio, False),
321
+ "hexagonal",
322
+ False,
323
+ )
324
+ return np.array([p[0] for p in pairs]), np.array([p[1] for p in pairs])
325
+ if family not in FAMILIES:
326
+ raise ValueError(
327
+ f"slip family: one of {sorted(FAMILIES) + sorted(HEXAGONAL)}, got {family!r}"
328
+ )
329
+ pairs = _family_vectors(*FAMILIES[family])
330
+ n = np.array([p[0] for p in pairs], dtype=float)
331
+ d = np.array([p[1] for p in pairs], dtype=float)
332
+ return n / np.linalg.norm(n, axis=1)[:, None], d / np.linalg.norm(d, axis=1)[:, None]
333
+
334
+
335
+ def twin_systems(family: str, c_over_a: float | None = None):
336
+ """Unit normals of the twin planes ``K_1`` and directions of their shear (N x 3 each,
337
+ axes of the crystal) of a family of twins, and the shear of the twin: the one that
338
+ leaves the direction ``eta_2`` of the second undistorted plane with its length,
339
+ ``gamma_tw = 2 |eta_2 . l| / (eta_2 . n)``; the directions are those of the shear
340
+ (the twin does not form in the other sense)."""
341
+ if family not in TWINS:
342
+ raise ValueError(f"twin family: one of {sorted(TWINS)}, got {family!r}")
343
+ lattice, plane, direction, second = TWINS[family]
344
+ ratio = _ratio(c_over_a, family) if lattice == "hexagonal" else None
345
+ n = _vector(plane, lattice, ratio, True)
346
+ d = _vector(direction, lattice, ratio, False)
347
+ eta2 = _vector(second, lattice, ratio, False)
348
+ shear = -2.0 * (eta2 @ d) / np.linalg.norm(d) / ((eta2 @ n) / np.linalg.norm(n))
349
+ if abs(shear) < 1e-9:
350
+ raise ValueError(f"twin family {family!r}: no shear at c_over_a = {c_over_a}")
351
+ pairs = _variants(n, d if shear > 0 else -d, lattice, True)
352
+ return np.array([p[0] for p in pairs]), np.array([p[1] for p in pairs]), abs(float(shear))
353
+
354
+
355
+ def cleavage_systems(planes: str, c_over_a: float | None = None):
356
+ """The systems of a family of cleavage planes: unit normals and directions (N x 3
357
+ each, axes of the crystal), their kinds (:data:`OPENING`, whose direction is the
358
+ normal, then the :data:`ACCOMMODATION` systems of the plane) and the plane of each
359
+ (its index in the family)."""
360
+ if planes not in CLEAVAGE:
361
+ raise ValueError(f"cleavage planes: one of {sorted(CLEAVAGE)}, got {planes!r}")
362
+ lattice, plane, directions = CLEAVAGE[planes]
363
+ ratio = _ratio(c_over_a, planes) if lattice == "hexagonal" else None
364
+ n0 = _vector(plane, lattice, ratio, True)
365
+ n0 /= np.linalg.norm(n0)
366
+ in_plane = [_vector(d, lattice, ratio, False) for d in directions]
367
+ in_plane = [d / np.linalg.norm(d) for d in in_plane]
368
+ seen: set = set()
369
+ normals, slips, kinds, groups = [], [], [], []
370
+ for r in _rotations(lattice):
371
+ n = r @ n0
372
+ if _key(n) in seen or _key(-n) in seen:
373
+ continue
374
+ seen.add(_key(n))
375
+ group = len(seen) - 1
376
+ normals.append(n)
377
+ slips.append(n)
378
+ kinds.append(OPENING)
379
+ groups.append(group)
380
+ for d in in_plane:
381
+ normals.append(n)
382
+ slips.append(r @ d)
383
+ kinds.append(ACCOMMODATION)
384
+ groups.append(group)
385
+ return np.array(normals), np.array(slips), np.array(kinds), np.array(groups)
386
+
387
+
388
+ def interaction_types(normals, directions) -> np.ndarray:
389
+ """Type of the interaction of each pair of octahedral systems (index in
390
+ :data:`INTERACTIONS`): self, coplanar, Hirth lock (orthogonal Burgers vectors),
391
+ collinear, and for the other pairs a glissile junction when the junction ``b_s +-
392
+ b_r`` lies in one of the two planes, a Lomer lock otherwise."""
393
+ n, b = np.asarray(normals, float), np.asarray(directions, float)
394
+ count = len(n)
395
+ out = np.zeros((count, count), dtype=np.int64)
396
+ for s in range(count):
397
+ for r in range(count):
398
+ if s == r:
399
+ continue
400
+ if abs(abs(n[s] @ n[r]) - 1.0) < 1e-9:
401
+ out[s, r] = 1
402
+ elif abs(abs(b[s] @ b[r]) - 1.0) < 1e-9:
403
+ out[s, r] = 3
404
+ elif abs(b[s] @ b[r]) < 1e-9:
405
+ out[s, r] = 2
406
+ else:
407
+ junction = b[s] - b[r] if b[s] @ b[r] > 0 else b[s] + b[r]
408
+ glissile = abs(junction @ n[s]) < 1e-9 or abs(junction @ n[r]) < 1e-9
409
+ out[s, r] = 4 if glissile else 5
410
+ return out
411
+
412
+
413
+ def _family_params(name: str, spec: dict, defaults: dict) -> tuple[float, ...]:
414
+ values = dict(defaults)
415
+ for key, value in spec.items():
416
+ key = _ALIASES.get(key, key)
417
+ if key not in PARAMS:
418
+ raise ValueError(f"crystal_plasticity.{name}: unknown parameter {key!r} ({PARAMS})")
419
+ values[key] = float(value)
420
+ missing = [k for k in PARAMS if values.get(k) is None]
421
+ if missing:
422
+ raise ValueError(f"crystal_plasticity.{name}: give {missing}")
423
+ tau0, q, b, c, d, k, n = (values[p] for p in PARAMS)
424
+ checks = [
425
+ (tau0 >= 0, "tau0 >= 0"),
426
+ (q >= 0, "Q >= 0"),
427
+ (b > 0 or q == 0, "b > 0 with Q"),
428
+ (c >= 0 and d >= 0, "C >= 0 and D >= 0"),
429
+ (k > 0, "K > 0"),
430
+ (n >= 1, "n >= 1"),
431
+ ]
432
+ for ok, text in checks:
433
+ if not (ok and all(math.isfinite(v) for v in (tau0, q, b, c, d, k, n))):
434
+ raise ValueError(f"crystal_plasticity.{name}: {text}")
435
+ return (tau0, q, b, c, d, k, n)
436
+
437
+
438
+ #: Parameters of a family of cleavage planes: the normal stress that opens them, the rate
439
+ #: of their softening (per unit of opening strain), the ratio of the strength of their
440
+ #: accommodation systems to it, and the viscosity (``K``, ``n``) of their flow
441
+ CLEAVAGE_PARAMS = ("strength", "softening", "shear", "K", "n")
442
+
443
+
444
+ def _cleavage_params(name: str, spec: dict, defaults: dict) -> tuple[float, ...]:
445
+ """The parameters of a family of cleavage planes (:data:`CLEAVAGE_PARAMS`) from a
446
+ mapping: the ``softening``, or the fracture ``energy`` of the planes and the
447
+ ``length`` of the elements that dissipate it (``softening = strength length /
448
+ energy``); ``K`` and ``n`` are those of the crystal unless given."""
449
+ where = f"crystal_plasticity.cleavage.{name}"
450
+ values = {"shear": 1.0, "K": defaults.get("K"), "n": defaults.get("n")}
451
+ allowed = (*CLEAVAGE_PARAMS, "energy", "length")
452
+ for key, value in spec.items():
453
+ key = _ALIASES.get(key, key)
454
+ if key not in allowed:
455
+ raise ValueError(f"{where}: unknown parameter {key!r} {allowed}")
456
+ try:
457
+ values[key] = float(value)
458
+ except (TypeError, ValueError):
459
+ raise ValueError(f"{where}.{key}: a number, got {value!r}") from None
460
+ if values.get("strength") is None:
461
+ raise ValueError(f"{where}: give the strength (the normal stress that opens the planes)")
462
+ banded = "energy" in values or "length" in values
463
+ if banded == ("softening" in values) or (banded and not {"energy", "length"} <= set(values)):
464
+ raise ValueError(
465
+ f"{where}: give the softening, or the fracture energy of the planes and the "
466
+ "length of the elements (softening = strength length / energy)"
467
+ )
468
+ if banded:
469
+ if not (values["energy"] > 0 and values["length"] > 0):
470
+ raise ValueError(f"{where}: energy > 0 and length > 0")
471
+ values["softening"] = values["strength"] * values["length"] / values["energy"]
472
+ missing = [k for k in ("K", "n") if values.get(k) is None]
473
+ if missing:
474
+ raise ValueError(f"{where}: give {missing} (those of the crystal, or of the planes)")
475
+ out = tuple(values[k] for k in CLEAVAGE_PARAMS)
476
+ strength, softening, shear, k, n = out
477
+ checks = [
478
+ (strength > 0, "strength > 0"),
479
+ (softening > 0, "softening > 0"),
480
+ (shear > 0, "shear > 0"),
481
+ (k > 0, "K > 0"),
482
+ (n >= 1, "n >= 1"),
483
+ ]
484
+ for ok, text in checks:
485
+ if not (ok and all(math.isfinite(v) for v in out)):
486
+ raise ValueError(f"{where}: {text}")
487
+ return out
488
+
489
+
490
+ def _band_angle(ratio: float) -> float:
491
+ """The phase ``omega x`` at the edge of the damage band of regularized cleavage
492
+ planes, ``pi - atan sqrt(r / (1 - r))`` with ``r = |H| / chi_H`` the ratio of their
493
+ softening modulus to their micromorphic one (:func:`microdamage_band`)."""
494
+ return math.pi - math.atan(math.sqrt(ratio / (1.0 - ratio)))
495
+
496
+
497
+ def microdamage_band(strength: float, softening: float, modulus: float, length: float):
498
+ """The damage band of cleavage planes regularized by their microdamage (Aslan &
499
+ Forest 2009), when a plane breaks across a bar normal to it: its width and the
500
+ fracture energy of the planes (per unit area).
501
+
502
+ ``strength``: ``Y_0``; ``softening``: ``w``, their linear softening ``Y_0 (1 - w
503
+ d)``, of modulus ``H = -w Y_0``; ``modulus``: the micromorphic modulus ``chi_H``, above
504
+ ``w Y_0``; ``length``: ``ell = sqrt(A / chi_H)``, that of the equation of the microdamage,
505
+ ``chi_d - ell^2 lap chi_d = d``. With ``r = w Y_0 / chi_H`` and ``theta = pi - atan sqrt(r /
506
+ (1 - r))``, the damage is ``(Y_0 - sigma) / |H| + beta cos(omega x)`` over the width
507
+ ``b = 2 theta / omega``, ``omega = sqrt(r / (1 - r)) / ell``; the bar softens linearly
508
+ from ``Y_0`` to nothing as the band opens by ``Y_0 (b + 2 ell) / |H|``, and the work
509
+ that breaks it is ``G_c = Y_0^2 (b + 2 ell) / (2 |H|)``."""
510
+ softening_modulus = softening * strength
511
+ if not 0.0 < softening_modulus < modulus:
512
+ raise ValueError(
513
+ "microdamage: a micromorphic modulus above softening x strength = "
514
+ f"{softening_modulus:.4g} (the planes harden at a fixed microdamage)"
515
+ )
516
+ ratio = softening_modulus / modulus
517
+ width = 2.0 * _band_angle(ratio) * length * math.sqrt((1.0 - ratio) / ratio)
518
+ energy = strength * strength * (width + 2.0 * length) / (2.0 * softening_modulus)
519
+ return width, energy
520
+
521
+
522
+ def microdamage_parameters(strength: float, energy: float, width: float, ratio: float = 1 / 3):
523
+ """The parameters of cleavage planes regularized by their microdamage from the
524
+ fracture ``energy`` of the planes (per unit area) and the ``width`` of their damage
525
+ band (:func:`microdamage_band`, inverted): their ``softening`` ``w`` (linear: ``Y_0 (1
526
+ - w d)``), their micromorphic ``modulus`` ``chi_H = w Y_0 / ratio`` and the ``length``
527
+ of the equation of the microdamage (a mapping of the three). ``ratio``: that of the
528
+ softening modulus to the micromorphic one, in ]0, 1[ (a third by default, as in the
529
+ reference): the band is ``2 theta sqrt((1 - r) / r)`` lengths wide."""
530
+ if not (strength > 0 and energy > 0 and width > 0 and 0.0 < ratio < 1.0):
531
+ raise ValueError(
532
+ "microdamage: strength > 0, energy > 0, width > 0 and a ratio of the softening "
533
+ "modulus to the micromorphic one in ]0, 1["
534
+ )
535
+ length = width / (2.0 * _band_angle(ratio) * math.sqrt((1.0 - ratio) / ratio))
536
+ softening_modulus = strength * strength * (width + 2.0 * length) / (2.0 * energy)
537
+ return {
538
+ "softening": softening_modulus / strength,
539
+ "modulus": softening_modulus / ratio,
540
+ "length": length,
541
+ }
542
+
543
+
544
+ def _regularization(name: str, spec: dict, band) -> tuple[dict, tuple[float, float]]:
545
+ """The parameters of a family of cleavage planes regularized by their microdamage
546
+ (``band``, the mapping ``regularization`` of the planes): ``{modulus, length}``, with
547
+ the linear softening of the family; or ``{width, ratio}``, the width of its damage
548
+ band, with its fracture energy (:func:`microdamage_parameters`). Returns the
549
+ parameters of the family, with its softening, and the modulus and the length."""
550
+ where = f"crystal_plasticity.cleavage.{name}"
551
+ if not isinstance(band, dict) or not (
552
+ set(band) == {"modulus", "length"} or {"width"} <= set(band) <= {"width", "ratio"}
553
+ ):
554
+ raise ValueError(
555
+ "crystal_plasticity.cleavage.regularization: {modulus, length} (with the "
556
+ "softening of the planes), or {width, ratio} of their damage band (with their "
557
+ "fracture energy)"
558
+ )
559
+ try:
560
+ values = {key: float(value) for key, value in band.items()}
561
+ if "width" not in values:
562
+ return spec, (values["modulus"], values["length"])
563
+ if "softening" in spec or "length" in spec or "energy" not in spec:
564
+ raise ValueError(
565
+ f"{where}: with the width of the damage band, the fracture energy of the "
566
+ "planes (no softening, no length of elements)"
567
+ )
568
+ found = microdamage_parameters(
569
+ float(spec.get("strength", math.nan)),
570
+ float(spec["energy"]),
571
+ values["width"],
572
+ values.get("ratio", 1 / 3),
573
+ )
574
+ except (TypeError, ValueError) as exc:
575
+ if str(exc).startswith(("crystal_plasticity", "microdamage")):
576
+ raise ValueError(str(exc).replace("microdamage:", f"{where}.regularization:")) from None
577
+ raise ValueError(f"{where}.regularization: numbers") from None
578
+ spec = {k: v for k, v in spec.items() if k != "energy"}
579
+ spec["softening"] = found["softening"]
580
+ return spec, (found["modulus"], found["length"])
581
+
582
+
583
+ def _share(value, what: str) -> float:
584
+ """The share of its resistance at which a system goes back to nothing: all of it
585
+ (true, 1), none of the way (false, 0: it does not go back), or a number."""
586
+ if isinstance(value, bool):
587
+ return 1.0 if value else 0.0
588
+ try:
589
+ share = float(value)
590
+ except (TypeError, ValueError):
591
+ share = math.nan
592
+ if not (math.isfinite(share) and share >= 0.0):
593
+ raise ValueError(
594
+ f"crystal_plasticity.{what}: true, false, or the share of the resistance at "
595
+ f"which the system goes back (a number of 0 or more), got {value!r}"
596
+ )
597
+ return share
598
+
599
+
600
+ def _named(value, what: str) -> list[tuple[str, dict]]:
601
+ """The families of a configuration: a name, a list of names, or a mapping of the
602
+ names to their own parameters."""
603
+ if isinstance(value, str):
604
+ return [(value, {})]
605
+ if isinstance(value, dict):
606
+ return [(str(name), dict(own or {})) for name, own in value.items()]
607
+ try:
608
+ return [(str(name), {}) for name in value]
609
+ except TypeError:
610
+ raise ValueError(f"crystal_plasticity.{what}: a name, a list or a mapping") from None
611
+
612
+
613
+ @dataclass(frozen=True)
614
+ class CrystalPlasticity:
615
+ """Méric-Cailletaud crystal plasticity: families of slip systems with their
616
+ parameters (``tau0, Q, b, C, D, K, n``, see :data:`PARAMS`) and the interaction
617
+ matrix (``()``: uniform; ``(h_self, h_latent)``; the six coefficients of
618
+ :data:`INTERACTIONS` for the octahedral family; or a full matrix). ``twins``:
619
+ families of twins (:data:`TWINS`) with the same parameters, which shear in one sense
620
+ until the fraction ``twin_saturation`` of the crystal has twinned; ``cleavage``:
621
+ families of cleavage planes (:data:`CLEAVAGE`) with their parameters
622
+ (:data:`CLEAVAGE_PARAMS`), which open under a normal stress; ``c_over_a``: the ratio
623
+ of a hexagonal lattice (its families are those of :data:`HEXAGONAL`). The systems of
624
+ a crystal are its slip systems, then its twins, then those of its cleavage planes.
625
+
626
+ ``twin_detwinning`` and ``cleavage_closure``: whether the twins shear back and the
627
+ planes close when the stress is reversed, or the share of their resistance at which
628
+ they do (true: 1). ``twin_reorientation``: the twinned fraction at which the lattice
629
+ of a point becomes that of its predominant twin; with ``twin_reorientation_growth``,
630
+ the lattices are turned grain by grain (:func:`turn_twins`), the threshold of a grain
631
+ growing by it times the share of its twinned volume that is turned.
632
+ ``cleavage_coupling``: the rate at which the cumulated slip of the crystal lowers the
633
+ strength of its cleavage planes (Aslan et al. 2011), the damage of the planes
634
+ easing its slip in return. ``cleavage_regularization``: the micromorphic modulus and
635
+ the length of the microdamage that regularizes the planes (Aslan & Forest 2009:
636
+ :func:`microdamage_band`), whose softening is then linear."""
637
+
638
+ families: tuple[tuple[str, tuple[float, ...]], ...]
639
+ interaction: tuple = ()
640
+ twins: tuple[tuple[str, tuple[float, ...]], ...] = ()
641
+ cleavage: tuple[tuple[str, tuple[float, ...]], ...] = ()
642
+ c_over_a: float | None = None
643
+ twin_saturation: float = 1.0
644
+ twin_reorientation: float | None = None
645
+ twin_detwinning: bool | float = True
646
+ cleavage_closure: bool | float = True
647
+ cleavage_friction: float = 0.0
648
+ twin_reorientation_growth: float | None = None
649
+ cleavage_coupling: float = 0.0
650
+ cleavage_regularization: tuple[float, float] | None = None
651
+
652
+ def __post_init__(self) -> None:
653
+ fams = []
654
+ for name, values in self.families:
655
+ if name not in FAMILIES and name not in HEXAGONAL:
656
+ raise ValueError(
657
+ f"crystal_plasticity: slip family {name!r}; "
658
+ f"{sorted(FAMILIES) + sorted(HEXAGONAL)}"
659
+ )
660
+ if len(values) != len(PARAMS):
661
+ raise ValueError(f"crystal_plasticity.{name}: the parameters {PARAMS}")
662
+ fams.append((name, _family_params(name, dict(zip(PARAMS, values, strict=True)), {})))
663
+ twins = []
664
+ for name, values in self.twins:
665
+ if name not in TWINS:
666
+ raise ValueError(f"crystal_plasticity: twin family {name!r}; {sorted(TWINS)}")
667
+ if len(values) != len(PARAMS):
668
+ raise ValueError(f"crystal_plasticity.twins.{name}: the parameters {PARAMS}")
669
+ spec = dict(zip(PARAMS, values, strict=True))
670
+ twins.append((name, _family_params(f"twins.{name}", spec, {})))
671
+ planes = []
672
+ for name, values in self.cleavage:
673
+ if name not in CLEAVAGE:
674
+ raise ValueError(
675
+ f"crystal_plasticity: cleavage planes {name!r}; {sorted(CLEAVAGE)}"
676
+ )
677
+ if len(values) != len(CLEAVAGE_PARAMS):
678
+ raise ValueError(
679
+ f"crystal_plasticity.cleavage.{name}: the parameters {CLEAVAGE_PARAMS}"
680
+ )
681
+ spec = dict(zip(CLEAVAGE_PARAMS, values, strict=True))
682
+ planes.append((name, _cleavage_params(name, spec, {})))
683
+ if not fams and not twins and not planes:
684
+ raise ValueError("crystal_plasticity: give at least one slip family")
685
+ for what, group in (("slip family", fams), ("twin family", twins), ("cleavage", planes)):
686
+ if len({f[0] for f in group}) != len(group):
687
+ raise ValueError(f"crystal_plasticity: a {what} given twice")
688
+ lattices = {lattice_of(name) for name, _ in (*fams, *twins, *planes)}
689
+ if len(lattices) > 1:
690
+ raise ValueError(
691
+ "crystal_plasticity: the families of one lattice, cubic "
692
+ f"({sorted(FAMILIES)}, twin111, twin112; cleavage: cube, dodecahedral, "
693
+ f"octahedral) or hexagonal ({sorted(HEXAGONAL)}, twin10..; cleavage: basal, "
694
+ "prismatic)"
695
+ )
696
+ ratio = self.c_over_a
697
+ if lattices == {"hexagonal"}:
698
+ ratio = _ratio(ratio, next(iter((*fams, *twins, *planes)))[0])
699
+ elif ratio is not None:
700
+ raise ValueError("crystal_plasticity: c_over_a is the ratio of a hexagonal lattice")
701
+ object.__setattr__(self, "c_over_a", ratio)
702
+ saturation = float(self.twin_saturation)
703
+ if not 0.0 < saturation <= 1.0:
704
+ raise ValueError("crystal_plasticity: twin_saturation, a fraction in ]0, 1]")
705
+ object.__setattr__(self, "twin_saturation", saturation)
706
+ turn = self.twin_reorientation
707
+ growth = self.twin_reorientation_growth
708
+ if turn is not None:
709
+ turn = float(turn)
710
+ if not twins:
711
+ raise ValueError("crystal_plasticity: twin_reorientation is that of twins")
712
+ if not 0.0 < turn < saturation:
713
+ raise ValueError(
714
+ "crystal_plasticity: twin_reorientation, the twinned fraction at which the "
715
+ f"lattice is turned, in ]0, twin_saturation = {saturation:g}["
716
+ )
717
+ if growth is not None:
718
+ growth = float(growth)
719
+ if not (math.isfinite(growth) and growth >= 0.0):
720
+ raise ValueError(
721
+ "crystal_plasticity.twin_reorientation: a growth of 0 or more (the "
722
+ "threshold of a grain grows by it times the share of its twinned "
723
+ "volume that is turned)"
724
+ )
725
+ elif growth is not None:
726
+ raise ValueError(
727
+ "crystal_plasticity: twin_reorientation_growth is that of a "
728
+ "twin_reorientation threshold"
729
+ )
730
+ object.__setattr__(self, "twin_reorientation", turn)
731
+ object.__setattr__(self, "twin_reorientation_growth", growth)
732
+ untwins = _share(self.twin_detwinning, "twin_detwinning")
733
+ object.__setattr__(self, "twin_detwinning", untwins)
734
+ closes = _share(self.cleavage_closure, "cleavage.closure")
735
+ object.__setattr__(self, "cleavage_closure", closes)
736
+ friction = float(self.cleavage_friction)
737
+ if not (math.isfinite(friction) and friction >= 0.0):
738
+ raise ValueError("crystal_plasticity.cleavage: a friction of 0 or more")
739
+ if friction > 0.0 and not self.cleavage_closure:
740
+ raise ValueError(
741
+ "crystal_plasticity.cleavage: the friction is that of planes that close "
742
+ "(closure: true)"
743
+ )
744
+ object.__setattr__(self, "cleavage_friction", friction)
745
+ coupling = float(self.cleavage_coupling)
746
+ if not (math.isfinite(coupling) and coupling >= 0.0):
747
+ raise ValueError("crystal_plasticity.cleavage: a coupling of 0 or more")
748
+ if coupling > 0.0:
749
+ if not planes:
750
+ raise ValueError("crystal_plasticity: cleavage_coupling is that of cleavage planes")
751
+ # what the planes take off the resistance of the slip once they are broken
752
+ # through: coupling x sum over the planes of strength / softening
753
+ energy = sum(
754
+ (int(cleavage_systems(name, ratio)[3].max()) + 1) * values[0] / values[1]
755
+ for name, values in planes
756
+ )
757
+ weakest = min((values[0] for _, values in fams), default=math.inf)
758
+ if coupling * energy >= weakest:
759
+ raise ValueError(
760
+ "crystal_plasticity.cleavage: the coupling of the planes with the slip "
761
+ f"would leave no resistance to the slip systems of {weakest:.4g} once the "
762
+ f"planes are broken (it falls by coupling x sum of strength / softening = "
763
+ f"{coupling * energy:.4g}): a coupling below {weakest / energy:.4g}"
764
+ )
765
+ object.__setattr__(self, "cleavage_coupling", coupling)
766
+ regular = self.cleavage_regularization
767
+ if regular is not None:
768
+ if not planes:
769
+ raise ValueError(
770
+ "crystal_plasticity: cleavage_regularization is that of cleavage planes"
771
+ )
772
+ try:
773
+ modulus, length = (float(v) for v in regular)
774
+ except (TypeError, ValueError):
775
+ raise ValueError(
776
+ "crystal_plasticity.cleavage.regularization: the micromorphic modulus "
777
+ "and the length of the microdamage"
778
+ ) from None
779
+ if not (math.isfinite(modulus) and math.isfinite(length) and length > 0.0):
780
+ raise ValueError("crystal_plasticity.cleavage.regularization: a length > 0")
781
+ for name, values in planes:
782
+ if not modulus > values[1] * values[0]:
783
+ raise ValueError(
784
+ f"crystal_plasticity.cleavage.{name}: a micromorphic modulus above "
785
+ f"softening x strength = {values[1] * values[0]:.4g} (the planes "
786
+ "harden at a fixed microdamage; they soften as it follows their damage)"
787
+ )
788
+ regular = (modulus, length)
789
+ object.__setattr__(self, "cleavage_regularization", regular)
790
+ object.__setattr__(self, "families", tuple(fams))
791
+ object.__setattr__(self, "twins", tuple(twins))
792
+ object.__setattr__(self, "cleavage", tuple(planes))
793
+ h = np.asarray(self.interaction, dtype=float)
794
+ count = self.n_slip + self.n_twins
795
+ if h.ndim == 2:
796
+ if h.shape != (count, count):
797
+ raise ValueError(f"crystal_plasticity.interaction: a {count} x {count} matrix")
798
+ value = tuple(tuple(float(x) for x in row) for row in h)
799
+ else:
800
+ value = tuple(float(x) for x in h.ravel())
801
+ if len(value) not in (0, 2, len(INTERACTIONS)):
802
+ raise ValueError(
803
+ "crystal_plasticity.interaction: [h_self, h_latent], six coefficients "
804
+ f"{INTERACTIONS} (octahedral systems) or a full matrix"
805
+ )
806
+ alone = [f[0] for f in fams] == ["octahedral"] and not twins
807
+ if len(value) == len(INTERACTIONS) and not alone:
808
+ raise ValueError(
809
+ "crystal_plasticity.interaction: the six coefficients classify the "
810
+ "octahedral systems only; give [h_self, h_latent] or a full matrix"
811
+ )
812
+ if not np.all(np.isfinite(h)) or np.any(h < 0):
813
+ raise ValueError("crystal_plasticity.interaction: non-negative coefficients")
814
+ object.__setattr__(self, "interaction", value)
815
+
816
+ @property
817
+ def n_slip(self) -> int:
818
+ """The slip systems."""
819
+ return sum(len(slip_systems(name, self.c_over_a)[0]) for name, _ in self.families)
820
+
821
+ @property
822
+ def n_twins(self) -> int:
823
+ """The twin systems."""
824
+ return sum(len(twin_systems(name, self.c_over_a)[0]) for name, _ in self.twins)
825
+
826
+ @property
827
+ def n_cleavage(self) -> int:
828
+ """The systems of the cleavage planes (openings and accommodations)."""
829
+ return sum(len(cleavage_systems(name, self.c_over_a)[0]) for name, _ in self.cleavage)
830
+
831
+ @property
832
+ def n_systems(self) -> int:
833
+ return self.n_slip + self.n_twins + self.n_cleavage
834
+
835
+ @property
836
+ def extended(self) -> bool:
837
+ """Whether the crystal twins or cleaves (systems that are not slip systems)."""
838
+ return bool(self.twins or self.cleavage)
839
+
840
+ @property
841
+ def reorients(self) -> bool:
842
+ """Whether the twins of the crystal turn its lattice (``twin_reorientation``):
843
+ its points then keep their rotation (:data:`CP_TURNED` internal variables more)."""
844
+ return self.twin_reorientation is not None
845
+
846
+ @property
847
+ def regularized(self) -> bool:
848
+ """Whether the cleavage planes are regularized by their microdamage
849
+ (``cleavage_regularization``): their points then keep it
850
+ (:attr:`micro_width` internal variables more), and the solvers of the loading
851
+ paths solve its equation."""
852
+ return self.cleavage_regularization is not None
853
+
854
+ @property
855
+ def n_planes(self) -> int:
856
+ """The cleavage planes of the crystal."""
857
+ ratio = self.c_over_a
858
+ return sum(int(cleavage_systems(name, ratio)[3].max()) + 1 for name, _ in self.cleavage)
859
+
860
+ @property
861
+ def micro_width(self) -> int:
862
+ """The internal variables of the microdamage of a point (:func:`state_width`):
863
+ the microdamage, and the mark of each plane (0, or 1 + the damage that it had
864
+ when it was broken through); none for planes that are not regularized."""
865
+ return 1 + self.n_planes if self.regularized else 0
866
+
867
+ @property
868
+ def by_grain(self) -> bool:
869
+ """Whether the lattices are turned grain by grain, after each step
870
+ (:func:`turn_twins`: ``twin_reorientation_growth``), not point by point."""
871
+ return self.twin_reorientation_growth is not None
872
+
873
+ def systems(self) -> tuple[np.ndarray, np.ndarray]:
874
+ """Unit normals and slip directions of all the systems (axes of the crystal): the
875
+ direction of the opening of a cleavage plane is its normal."""
876
+ ratio = self.c_over_a
877
+ parts = [slip_systems(name, ratio) for name, _ in self.families]
878
+ parts += [twin_systems(name, ratio)[:2] for name, _ in self.twins]
879
+ parts += [cleavage_systems(name, ratio)[:2] for name, _ in self.cleavage]
880
+ return np.concatenate([p[0] for p in parts]), np.concatenate([p[1] for p in parts])
881
+
882
+ def params_array(self) -> np.ndarray:
883
+ """Parameters of each system (N x 7, see :data:`PARAMS`): of a cleavage system,
884
+ its strength (``tau0``) and its viscosity (``K``, ``n``)."""
885
+ ratio = self.c_over_a
886
+ rows = []
887
+ for name, values in self.families:
888
+ rows.extend([values] * len(slip_systems(name, ratio)[0]))
889
+ for name, values in self.twins:
890
+ rows.extend([values] * len(twin_systems(name, ratio)[0]))
891
+ for name, (strength, _, shear, k, n) in self.cleavage:
892
+ for kind in cleavage_systems(name, ratio)[2]:
893
+ scale = 1.0 if kind == OPENING else shear
894
+ rows.append((scale * strength, 0.0, 0.0, 0.0, 0.0, k, n))
895
+ return np.array(rows, dtype=float).reshape(-1, len(PARAMS))
896
+
897
+ def kinds_array(self) -> np.ndarray:
898
+ """What each system is, beside its parameters (N x 9): its kind (:data:`SLIP`,
899
+ :data:`TWIN`, :data:`OPENING`, :data:`ACCOMMODATION`), the rate of its softening
900
+ (cleavage), its share of the saturation per unit of shear, ``1 / (gamma_tw
901
+ F_sat)`` (twins), its cleavage plane (-1 for the others), the share of its
902
+ resistance at which it goes back to nothing (a twin that untwins, the opening of
903
+ a plane that closes; 0: it does not) or the friction of its plane under pressure
904
+ (an accommodation system), its share per unit of shear of the fraction at which
905
+ the lattice is turned, ``1 / (gamma_tw F_turn)`` (twins that turn it; -1 where the
906
+ lattices are turned grain by grain), the opening system of its plane (an
907
+ accommodation system; -1 for the others), its family (a twin; -1 for the others),
908
+ its twinned fraction per unit of shear, ``1 / gamma_tw`` (a twin), the rate at
909
+ which the slip of the crystal lowers its strength and the micromorphic modulus of
910
+ its regularization (the systems of the cleavage planes: ``cleavage_coupling``,
911
+ ``cleavage_regularization``)."""
912
+ ratio = self.c_over_a
913
+ out = np.zeros((self.n_systems, 11))
914
+ out[:, 3] = -1.0
915
+ out[:, 6:8] = -1.0
916
+ row = self.n_slip
917
+ for family, (name, _) in enumerate(self.twins):
918
+ count = len(twin_systems(name, ratio)[0])
919
+ shear = twin_systems(name, ratio)[2]
920
+ out[row : row + count, 0] = TWIN
921
+ out[row : row + count, 2] = 1.0 / (shear * self.twin_saturation)
922
+ out[row : row + count, 4] = self.twin_detwinning
923
+ out[row : row + count, 7] = family
924
+ out[row : row + count, 8] = 1.0 / shear
925
+ if self.by_grain:
926
+ out[row : row + count, 5] = -1.0
927
+ elif self.reorients:
928
+ out[row : row + count, 5] = 1.0 / (shear * self.twin_reorientation)
929
+ row += count
930
+ plane = 0
931
+ for name, (_, softening, *_rest) in self.cleavage:
932
+ _, _, kinds, groups = cleavage_systems(name, ratio)
933
+ out[row : row + len(kinds), 0] = kinds
934
+ out[row : row + len(kinds), 1] = softening
935
+ out[row : row + len(kinds), 3] = plane + groups
936
+ opening = kinds == OPENING
937
+ out[row : row + len(kinds), 4] = np.where(
938
+ opening, self.cleavage_closure, self.cleavage_friction
939
+ )
940
+ # the opening system of the plane of each accommodation system
941
+ first = row + np.flatnonzero(opening)
942
+ out[row : row + len(kinds), 6] = np.where(opening, -1.0, first[groups])
943
+ out[row : row + len(kinds), 9] = self.cleavage_coupling
944
+ if self.regularized:
945
+ out[row : row + len(kinds), 10] = self.cleavage_regularization[0]
946
+ row += len(kinds)
947
+ plane += int(groups.max()) + 1
948
+ return out
949
+
950
+ def interaction_matrix(self) -> np.ndarray:
951
+ """The interaction of the slip systems and of the twins (none with the systems of
952
+ the cleavage planes)."""
953
+ count = self.n_slip + self.n_twins
954
+ h = self.interaction
955
+ if not h:
956
+ block = np.ones((count, count))
957
+ elif isinstance(h[0], tuple):
958
+ block = np.array(h, dtype=float)
959
+ elif len(h) == 2:
960
+ block = np.full((count, count), h[1])
961
+ np.fill_diagonal(block, h[0])
962
+ else:
963
+ normals, directions = self.systems()
964
+ block = np.asarray(h)[interaction_types(normals[:count], directions[:count])]
965
+ out = np.zeros((self.n_systems, self.n_systems))
966
+ out[:count, :count] = block
967
+ return out
968
+
969
+ @property
970
+ def lattice(self) -> str:
971
+ """The lattice of the families of the crystal, ``"cubic"`` or ``"hexagonal"``."""
972
+ return lattice_of(next(iter((*self.families, *self.twins, *self.cleavage)))[0])
973
+
974
+ @property
975
+ def field_names(self) -> tuple[str, ...]:
976
+ """The fields of the crystal beside those of every behaviour (among
977
+ :data:`FIELDS`): those of its twins (the lattices that they turn with
978
+ ``twin_reorientation``, and their disorientation) and of its cleavage planes."""
979
+ twins = ("twin_fraction",) if self.twins else ()
980
+ if self.reorients:
981
+ twins += ("twin_reoriented", "twin_misorientation")
982
+ planes = ("cleavage_opening", "cleavage_damage") if self.cleavage else ()
983
+ if self.regularized:
984
+ planes += ("cleavage_microdamage",)
985
+ return twins + planes
986
+
987
+ def check_softening(self, stiffness, force: bool = False) -> None:
988
+ """Refuse cleavage planes that soften faster than the crystal unloads
989
+ (``stiffness``: its 6 x 6 matrix in its axes): the opening ``delta`` of a point
990
+ whose strain is held releases the stress ``(n (x) n) : C : (n (x) n) delta``,
991
+ and its strength must fall more slowly, ``w Y_0 < (n (x) n) : C : (n (x) n)``
992
+ (likewise for the accommodation systems), for the state of the point to follow
993
+ its strain. With the fracture energy ``G_c`` of the planes dissipated in elements
994
+ of size ``h`` (``w = Y_0 h / G_c``): ``h < C_nn G_c / Y_0^2``. Not for planes
995
+ regularized by their microdamage, which harden at a fixed microdamage (``force``:
996
+ for them too, as a point alone softens with its damage)."""
997
+ if not self.cleavage or (self.regularized and not force):
998
+ return
999
+ c = np.asarray(stiffness, dtype=float)
1000
+ normals, directions = self.systems()
1001
+ par, kinds = self.params_array(), self.kinds_array()
1002
+ names = []
1003
+ for name, _ in self.cleavage:
1004
+ names += [name] * len(cleavage_systems(name, self.c_over_a)[0])
1005
+ first = self.n_slip + self.n_twins
1006
+ for s in range(first, self.n_systems):
1007
+ m = 0.5 * (np.outer(directions[s], normals[s]) + np.outer(normals[s], directions[s]))
1008
+ voigt = np.array([m[0, 0], m[1, 1], m[2, 2], 2 * m[1, 2], 2 * m[2, 0], 2 * m[0, 1]])
1009
+ modulus = float(voigt @ c @ voigt)
1010
+ if kinds[s, 1] * par[s, 0] >= modulus:
1011
+ what = "opening" if kinds[s, 0] == OPENING else "accommodation"
1012
+ raise ValueError(
1013
+ f"crystal_plasticity.cleavage.{names[s - first]}: the {what} of the planes "
1014
+ f"softens faster (softening x strength = {kinds[s, 1] * par[s, 0]:.4g}) than "
1015
+ f"the crystal unloads (stiffness {modulus:.4g}): a softening below "
1016
+ f"{modulus / par[s, 0]:.4g} (smaller elements for this fracture energy: "
1017
+ "length < stiffness x energy / strength^2)"
1018
+ )
1019
+
1020
+ def point_fields(
1021
+ self, slips, *, openings=None, turned=None, orientations=None, micro=None
1022
+ ) -> dict:
1023
+ """The fields of points from the cumulated slips of their systems (points x N):
1024
+ the ``twin_fraction`` (with twins), the ``cleavage_opening`` (the opening strain
1025
+ of the planes) and the ``cleavage_damage`` of the most damaged plane, the share of
1026
+ its strength that its damage has taken (with cleavage planes: ``1 - exp(-w d)``;
1027
+ for planes regularized by their microdamage, what the damage of the planes of
1028
+ the point and its microdamage have taken, ``w d - chi_H (d - chi_d) / Y_0``
1029
+ between 0 and 1, and 1 for a plane broken through); for these, the
1030
+ ``cleavage_microdamage`` of the points (``micro``, points x :attr:`micro_width`:
1031
+ the microdamage — of a point alone, a negative value: the damage of its planes —
1032
+ and the marks of the planes broken through).
1033
+
1034
+ ``openings``: the slips of the systems now (points x N, the variables ``alpha``):
1035
+ the opening is then that of the planes now, less than what they have opened once
1036
+ they close. ``turned``: the variables of the lattices that their twins turn
1037
+ (points x :data:`CP_TURNED`): the twinned fraction of a turned lattice is the one
1038
+ that it had when it was turned, less the fraction of the twin that brings the
1039
+ first lattice back (detwinning) — the fraction of the shears of the twins, which
1040
+ a turn does not change; ``twin_reoriented`` is 1 where the lattice is that of a
1041
+ twin (its mean: the turned volume) and ``twin_misorientation`` its
1042
+ :func:`disorientation` from the lattice of the grain (degrees; with the
1043
+ ``orientations`` of the grains of the points, points x 3 x 3, their axes in those
1044
+ of the sample: the rotations are kept in the latter)."""
1045
+ slips = np.asarray(slips, dtype=float)
1046
+ kinds = self.kinds_array()
1047
+ out = {}
1048
+ if self.twins:
1049
+ shares = kinds[:, 8] # the twinned fraction per unit of shear
1050
+ fraction = slips @ shares
1051
+ if turned is not None and self.reorients:
1052
+ turned = np.asarray(turned, dtype=float)
1053
+ moved = np.any(turned[:, :9] != 0.0, axis=1)
1054
+ back = np.zeros(len(slips))
1055
+ known = np.flatnonzero(moved & (turned[:, 9] > 0))
1056
+ undo = turned[known, 9].astype(np.int64) - 1
1057
+ back[known] = shares[undo] * slips[known, undo]
1058
+ # what it had, less what is undone, and the twins of the new lattice
1059
+ kept = np.maximum(turned[:, 10] + fraction - 2.0 * back, 0.0)
1060
+ fraction = np.where(moved, kept, fraction)
1061
+ angle = np.zeros(len(slips))
1062
+ if moved.any():
1063
+ rotation = turned[moved, :9].reshape(-1, 3, 3) + np.eye(3)
1064
+ if orientations is not None: # into the axes of the crystal: g R g^T
1065
+ g = np.asarray(orientations, dtype=float)[moved]
1066
+ rotation = np.einsum("pij,pjk,plk->pil", g, rotation, g)
1067
+ angle[moved] = disorientation(rotation, self.lattice)
1068
+ out["twin_fraction"] = fraction
1069
+ out["twin_reoriented"] = moved.astype(float)
1070
+ out["twin_misorientation"] = angle
1071
+ else:
1072
+ out["twin_fraction"] = fraction
1073
+ if self.cleavage:
1074
+ opened = slips if openings is None else np.asarray(openings, dtype=float)
1075
+ out["cleavage_opening"] = opened[:, kinds[:, 0] == OPENING].sum(axis=1)
1076
+ damage = np.zeros(slips.shape[0])
1077
+ planes = np.unique(kinds[kinds[:, 3] >= 0, 3]).astype(np.int64)
1078
+ own = np.stack([slips[:, kinds[:, 3] == p].sum(axis=1) for p in planes], axis=1)
1079
+ if self.regularized:
1080
+ # the damage of the planes of the point (that which a plane had when it was
1081
+ # broken through: what it opens since is a crack) and its microdamage
1082
+ marks = np.zeros_like(own)
1083
+ if micro is not None:
1084
+ micro = np.asarray(micro, dtype=float).reshape(len(slips), -1)
1085
+ marks = micro[:, 1 : 1 + planes.size]
1086
+ whole = np.where(marks > 0.5, marks - 1.0, own).sum(axis=1)
1087
+ follows = (
1088
+ whole if micro is None else np.where(micro[:, 0] < 0.0, whole, micro[:, 0])
1089
+ )
1090
+ out["cleavage_microdamage"] = follows
1091
+ modulus = self.cleavage_regularization[0]
1092
+ strength = self.params_array()[:, 0]
1093
+ for k, plane in enumerate(planes):
1094
+ members = np.flatnonzero(kinds[:, 3] == plane)
1095
+ rate = kinds[members[0], 1]
1096
+ if self.regularized:
1097
+ first = members[kinds[members, 0] == OPENING][0]
1098
+ lost = rate * whole - modulus / strength[first] * (whole - follows)
1099
+ lost = np.where(marks[:, k] > 0.5, 1.0, np.clip(lost, 0.0, 1.0))
1100
+ else:
1101
+ lost = -np.expm1(-rate * own[:, k])
1102
+ damage = np.maximum(damage, lost)
1103
+ out["cleavage_damage"] = damage
1104
+ return out
1105
+
1106
+ def state_fields(self, state, finite: bool = False, orientations=None) -> dict:
1107
+ """The fields of points (:meth:`point_fields`) from their internal variables
1108
+ (points x width, those of the kernels in small or ``finite`` strains)."""
1109
+ state = np.asarray(state, dtype=float)
1110
+ n = self.n_systems
1111
+ turned = None
1112
+ if self.reorients:
1113
+ first = state_width(n, finite)
1114
+ turned = state[:, first : first + CP_TURNED]
1115
+ micro = None
1116
+ if self.regularized:
1117
+ first = state_width(n, finite, self.reorients)
1118
+ micro = state[:, first : first + self.micro_width]
1119
+ return self.point_fields(
1120
+ state[:, CP_ALPHA + n : CP_ALPHA + 2 * n],
1121
+ openings=state[:, CP_ALPHA : CP_ALPHA + n],
1122
+ turned=turned,
1123
+ orientations=orientations,
1124
+ micro=micro,
1125
+ )
1126
+
1127
+ def to_config(self) -> dict:
1128
+ families = {name: dict(zip(PARAMS, v, strict=True)) for name, v in self.families}
1129
+ out: dict = {"families": families}
1130
+ if self.c_over_a is not None:
1131
+ out["c_over_a"] = self.c_over_a
1132
+ if self.twins:
1133
+ out["twins"] = {name: dict(zip(PARAMS, v, strict=True)) for name, v in self.twins}
1134
+ if self.twin_saturation != 1.0:
1135
+ out["twin_saturation"] = self.twin_saturation
1136
+ if self.by_grain:
1137
+ out["twin_reorientation"] = {
1138
+ "threshold": self.twin_reorientation,
1139
+ "growth": self.twin_reorientation_growth,
1140
+ }
1141
+ elif self.reorients:
1142
+ out["twin_reorientation"] = self.twin_reorientation
1143
+ if self.twin_detwinning != 1.0:
1144
+ out["twin_detwinning"] = self.twin_detwinning or False
1145
+ if self.cleavage:
1146
+ planes = {n: dict(zip(CLEAVAGE_PARAMS, v, strict=True)) for n, v in self.cleavage}
1147
+ out["cleavage"] = {"planes": planes}
1148
+ if self.cleavage_closure != 1.0:
1149
+ out["cleavage"]["closure"] = self.cleavage_closure or False
1150
+ if self.cleavage_friction:
1151
+ out["cleavage"]["friction"] = self.cleavage_friction
1152
+ if self.cleavage_coupling:
1153
+ out["cleavage"]["coupling"] = self.cleavage_coupling
1154
+ if self.regularized:
1155
+ modulus, length = self.cleavage_regularization
1156
+ out["cleavage"]["regularization"] = {"modulus": modulus, "length": length}
1157
+ if self.interaction:
1158
+ h = self.interaction
1159
+ out["interaction"] = [list(r) for r in h] if isinstance(h[0], tuple) else list(h)
1160
+ return out
1161
+
1162
+ @classmethod
1163
+ def from_config(cls, spec) -> CrystalPlasticity:
1164
+ """``{families: [octahedral, ...] or {octahedral: {tau0: ..}, ...}, tau0, Q, b, C, D,
1165
+ K, n, interaction}``: the parameters given at the top apply to every family, and
1166
+ those of a family override them. ``twins``: families of twins, given as the slip
1167
+ families (``twin_saturation``: the fraction at which they stop;
1168
+ ``twin_reorientation``: the fraction at which the lattice of a point becomes that
1169
+ of its predominant twin, none by default, or ``{threshold, growth}``: the
1170
+ lattices are turned grain by grain, the most twinned points first while the
1171
+ turned volume of the grain is below its twinned volume, past a threshold that
1172
+ grows by ``growth`` times their ratio; ``twin_detwinning: false``: the twins do
1173
+ not shear back, or the share of their resistance at which they do); ``cleavage``:
1174
+ ``{planes: basal, or a list, or {basal: {strength: ..}}, strength, softening (or
1175
+ energy and length), shear, K, n, closure, friction, coupling}`` (``closure:
1176
+ false``: the planes do not close, or the share of their strength at which they
1177
+ do; ``friction``: Coulomb's, of the planes under pressure; ``coupling``: the rate
1178
+ at which the cumulated slip lowers their strength; ``regularization``: the
1179
+ microdamage of the planes, ``{modulus, length}`` with their linear ``softening``,
1180
+ or ``{width, ratio}`` of their damage band with their fracture ``energy``:
1181
+ :func:`microdamage_parameters`); ``c_over_a``: the ratio
1182
+ of a hexagonal lattice. The slip families default to the octahedral one, to none
1183
+ with twins or cleavage planes."""
1184
+ if isinstance(spec, CrystalPlasticity):
1185
+ return spec
1186
+ if not isinstance(spec, dict):
1187
+ raise ValueError("crystal_plasticity: a mapping (families, parameters, interaction)")
1188
+ spec = dict(spec)
1189
+ twins = spec.pop("twins", None)
1190
+ cleavage = spec.pop("cleavage", None)
1191
+ none = twins is not None or cleavage is not None
1192
+ families = spec.pop("families", [] if none else ["octahedral"])
1193
+ interaction = spec.pop("interaction", ())
1194
+ ratio = spec.pop("c_over_a", None)
1195
+ saturation = spec.pop("twin_saturation", 1.0)
1196
+ turn = spec.pop("twin_reorientation", None)
1197
+ growth = None
1198
+ if isinstance(turn, dict):
1199
+ if "threshold" not in turn or set(turn) - {"threshold", "growth"}:
1200
+ raise ValueError(
1201
+ "crystal_plasticity.twin_reorientation: a twinned fraction, or "
1202
+ "{threshold, growth} (the lattices turned grain by grain: the threshold "
1203
+ "of a grain grows with the share of its twinned volume that is turned)"
1204
+ )
1205
+ growth = turn.get("growth", 0.0)
1206
+ turn = turn["threshold"]
1207
+ untwins = _share(spec.pop("twin_detwinning", True), "twin_detwinning")
1208
+ defaults = dict(_DEFAULTS)
1209
+ for key, value in spec.items():
1210
+ key = _ALIASES.get(key, key)
1211
+ if key not in PARAMS:
1212
+ raise ValueError(
1213
+ f"crystal_plasticity: unknown key {key!r}; parameters {PARAMS}, families, "
1214
+ "interaction, twins, twin_saturation, twin_reorientation, "
1215
+ "twin_detwinning, cleavage, c_over_a"
1216
+ )
1217
+ defaults[key] = float(value)
1218
+ fams = []
1219
+ for name, own in _named(families if families is not None else [], "families"):
1220
+ if name not in FAMILIES and name not in HEXAGONAL:
1221
+ raise ValueError(
1222
+ f"crystal_plasticity: slip family {name!r}; "
1223
+ f"{sorted(FAMILIES) + sorted(HEXAGONAL)}"
1224
+ )
1225
+ fams.append((name, _family_params(name, own, defaults)))
1226
+ twinned = []
1227
+ for name, own in _named(twins if twins is not None else [], "twins"):
1228
+ if name not in TWINS:
1229
+ raise ValueError(f"crystal_plasticity: twin family {name!r}; {sorted(TWINS)}")
1230
+ twinned.append((name, _family_params(f"twins.{name}", own, defaults)))
1231
+ planes = []
1232
+ closure, friction, coupling, regular = True, 0.0, 0.0, None
1233
+ if cleavage is not None:
1234
+ if not isinstance(cleavage, dict) or cleavage.get("planes") is None:
1235
+ raise ValueError(
1236
+ "crystal_plasticity.cleavage: a mapping of its planes "
1237
+ f"({sorted(CLEAVAGE)}) and of their parameters {CLEAVAGE_PARAMS}"
1238
+ )
1239
+ common = dict(cleavage)
1240
+ closure = _share(common.pop("closure", True), "cleavage.closure")
1241
+ try:
1242
+ friction = float(common.pop("friction", 0.0))
1243
+ except (TypeError, ValueError):
1244
+ raise ValueError("crystal_plasticity.cleavage.friction: a number") from None
1245
+ try:
1246
+ coupling = float(common.pop("coupling", 0.0))
1247
+ except (TypeError, ValueError):
1248
+ raise ValueError("crystal_plasticity.cleavage.coupling: a number") from None
1249
+ band = common.pop("regularization", None)
1250
+ for name, own in _named(common.pop("planes"), "cleavage.planes"):
1251
+ if name not in CLEAVAGE:
1252
+ raise ValueError(
1253
+ f"crystal_plasticity: cleavage planes {name!r}; {sorted(CLEAVAGE)}"
1254
+ )
1255
+ merged = {**common, **own}
1256
+ if band is not None:
1257
+ merged, found = _regularization(name, merged, band)
1258
+ if regular is not None and not np.allclose(found, regular, rtol=1e-12):
1259
+ raise ValueError(
1260
+ "crystal_plasticity.cleavage.regularization: one microdamage for "
1261
+ "the planes of a crystal; give its {modulus, length}, and the "
1262
+ "softening of each family of planes"
1263
+ )
1264
+ regular = found
1265
+ planes.append((name, _cleavage_params(name, merged, defaults)))
1266
+ try:
1267
+ saturation = float(saturation)
1268
+ ratio = None if ratio is None else float(ratio)
1269
+ turn = None if turn is None else float(turn)
1270
+ growth = None if growth is None else float(growth)
1271
+ except (TypeError, ValueError):
1272
+ raise ValueError(
1273
+ "crystal_plasticity: c_over_a, twin_saturation and twin_reorientation are numbers"
1274
+ ) from None
1275
+ return cls(
1276
+ tuple(fams),
1277
+ interaction if interaction is not None else (),
1278
+ twins=tuple(twinned),
1279
+ cleavage=tuple(planes),
1280
+ c_over_a=ratio,
1281
+ twin_saturation=saturation,
1282
+ twin_reorientation=turn,
1283
+ twin_detwinning=untwins,
1284
+ cleavage_closure=closure,
1285
+ cleavage_friction=friction,
1286
+ twin_reorientation_growth=growth,
1287
+ cleavage_coupling=coupling,
1288
+ cleavage_regularization=regular,
1289
+ )
1290
+
1291
+
1292
+ # -- integration kernels ---------------------------------------------------------------------
1293
+ #
1294
+ # Internal variables of a crystal point: the plastic strain (6, tensor components; the
1295
+ # Green-Lagrange plastic strain in finite strains), the cumulated plastic strain p, then
1296
+ # alpha (N) and v (N) and, in small strains, the mechanical strain (6, engineering), in
1297
+ # finite strains F_p^-1 - I and the displacement gradient (9 each, row by row), at the end
1298
+ # of the step: the start of the substeps of the next one; then, for a lattice that its
1299
+ # twins turn, its rotation less the identity (9), the twin that brings it back (1) and
1300
+ # the twinned fraction that the point had when it was turned (1); then, for cleavage
1301
+ # planes regularized by their microdamage, the microdamage of the point (1) and the mark
1302
+ # of each plane (1 each): 0, or once it is broken through 1 + the damage that it had.
1303
+ #
1304
+ # The slips of a step solve, for the active systems (those whose slip over the step
1305
+ # exceeds _SLIP_FLOOR), the flow rule written as stresses,
1306
+ #
1307
+ # R_s = sign_s (tau_s - x_s) - r_s - K (|dgamma_s| / dt)^(1/n) = 0,
1308
+ #
1309
+ # with ``dgamma_s = sign_s delta_s``, ``delta_s > 0``: Newton's method on the magnitudes,
1310
+ # from below (each R_s is convex and decreasing in delta_s, so that the iteration does not
1311
+ # overshoot, however large the elastic trial overstress), the other systems inactive;
1312
+ # then the inactive systems whose overstress exceeds the floor join the active set, until
1313
+ # it is stable. (The flow rule written as rates, ``dgamma = dt <f/K>^n``, stalls under
1314
+ # large overstresses: its Jacobian spans tens of orders of magnitude.) When the iteration
1315
+ # fails (many redundant systems under a large overstress), the step is divided into 4,
1316
+ # then 16 and 64 substeps along which the strain varies linearly; the tangent is then
1317
+ # that of the last substep.
1318
+ #
1319
+ # Twins and cleavage planes are systems of the same iteration (their kinds and the
1320
+ # numbers of ``CP_KIND ... CP_FAMILY`` after the parameters of each system): a twin and
1321
+ # the opening of a cleavage plane flow in one sense (their overstress is ``tau - x - r``,
1322
+ # not ``|tau - x| - r``) and, unless told not to, back to nothing (at a share of their
1323
+ # resistance, ``CP_CLOSE``): the second variable of a twin is then its net shear, and a
1324
+ # system that goes back by all that it has over a step is held there (its slip fixed, out
1325
+ # of the active set; released if the others leave its flow rule short of it). The
1326
+ # resistance of a twin has the barrier ``_BARRIER tau0 (1 / phi - 1)`` with ``phi = 1 -
1327
+ # sum_t sat_t v_t`` the share of the crystal left to twin (a twin
1328
+ # does not flow below ``_PHI_FLOOR``, and slips that would exhaust it are refused: the line
1329
+ # search shortens them); the strength of the systems of a cleavage plane is ``tau0 exp(-w d)``,
1330
+ # ``d`` the sum of the cumulated slips of the systems of the plane. The cumulated plastic
1331
+ # strain counts the slips and the twins, not the systems of the cleavage planes.
1332
+ #
1333
+ # Work arrays of a kernel (``work``): vectors (26, N): residual, resolved shear stresses,
1334
+ # overstresses, signs, trial resolved shear stresses (small strains), trial slips, trial
1335
+ # residual, slips, active flags, trial overstresses, the exponentials of the isotropic
1336
+ # hardening, the softening of the cleavage planes, the systems held at nothing, the
1337
+ # friction of the planes, the derivatives of the strength of the planes (with their
1338
+ # damage, with that of all the planes, with the slip) and of what they take off the slip,
1339
+ # the active systems on their way out, the systems of the planes broken through, the
1340
+ # damage of the plane of each opening system, the slips below which a system does not
1341
+ # start with the viscosity that they were computed for (3), the exponential of the
1342
+ # damage of the plane of each opening system, and the systems whose resolved stresses
1343
+ # are derived (finite strains);
1344
+ # matrices (4, N, N): Jacobian, its
1345
+ # factorization, d tau / d dgamma, m_s : C : m_r; right-hand sides (N, 9); 3 x 3 tensors
1346
+ # (24, 3, 3); their derivatives with respect to each slip (3, N, 3, 3); Schmid tensors
1347
+ # and C : m (2, N, 6); vectors (6, 9); indices of the active systems (N); the internal
1348
+ # variables of two substeps (2, width); the share of the crystal left to twin, the
1349
+ # microdamage of the point, the twin that brings a turned lattice back, the damage that
1350
+ # the planes broken through had, the derivatives that the last evaluation of the slips
1351
+ # had (0: none, 1: those of the active systems, 2: of all), the time step of the
1352
+ # starting slips kept, and the material whose Schmid tensors are kept (its key + 1; 0:
1353
+ # none) (7); the systems, the elasticity and the thermal strain of a turned lattice
1354
+ # ((N, 6) and (3, 6, 6)); the indices of the systems that slip (small strains) and of
1355
+ # those that have slipped, which harden the others (N each).
1356
+ #
1357
+ # What a point does not need is not computed, with the same results to the bit: a point
1358
+ # whose systems all stay below their thresholds is evaluated once, without derivatives;
1359
+ # the derivatives of the resolved stresses are those of the active systems, and of the
1360
+ # others only where one of them starts; the correction that the line search accepts is
1361
+ # evaluated with its derivatives, and is the next iterate.
1362
+
1363
+ #: Index of alpha among the internal variables
1364
+ CP_ALPHA = 7
1365
+ #: Columns of the parameters of a system after those of :data:`PARAMS`, which the kernels
1366
+ #: read when the array has them (:meth:`CrystalPlasticity.kinds_array`): its kind, the
1367
+ #: rate of its softening, its share of the saturation of the twins, its cleavage plane,
1368
+ #: the share of its resistance at which it goes back to nothing (a twin that untwins, the
1369
+ #: opening of a plane that closes; 0: it does not) or the friction of its plane under
1370
+ #: pressure (an accommodation system), its share of the twinned fraction at which the
1371
+ #: lattice is turned into that of the twin (negative: the lattices are turned grain by
1372
+ #: grain, :func:`turn_twins`), the opening system of its plane (an accommodation system;
1373
+ #: -1 for the others), its family (a twin; -1 for the others), the twinned fraction per
1374
+ #: unit of its shear, ``1 / gamma_tw`` (a twin), the rate at which the slip of the crystal
1375
+ #: lowers its strength, and the micromorphic modulus of the planes that their microdamage
1376
+ #: regularizes (the systems of the cleavage planes; 0: a local softening)
1377
+ CP_KIND, CP_SOFT, CP_SAT, CP_GROUP, CP_CLOSE, CP_TURN, CP_OPEN, CP_FAMILY, CP_SHEAR = range(7, 16)
1378
+ CP_COUPLE, CP_MICRO = 16, 17
1379
+ #: Width of the parameters of a system for the kernels
1380
+ CP_WIDTH = 18
1381
+ #: The internal variables of a lattice that its twins turn, after the others: its rotation
1382
+ #: from that of the grain, less the identity (9), the twin that would bring it back (its
1383
+ #: index + 1; 0 without one, -1 for a lattice turned more than once) and the twinned
1384
+ #: fraction of the point when it was turned
1385
+ CP_TURNED = 11
1386
+ #: Share of the crystal left to twin below which its twins do not flow
1387
+ _PHI_FLOOR = 1e-12
1388
+ #: The barrier of the saturation of the twins: their resistance grows by this fraction of
1389
+ #: ``tau0`` times ``F / (F_sat - F)``
1390
+ _BARRIER = 1e-3
1391
+ #: Slips below this magnitude (over a step) are not resolved
1392
+ _SLIP_FLOOR = 1e-15
1393
+ #: Residual of the local iteration, relative to the scale of the stresses
1394
+ _LOCAL_TOL = 1e-10
1395
+ _MAX_LOCAL = 100
1396
+ _MAX_ROUNDS = 20
1397
+ #: Largest relative decrease of a slip in one iteration
1398
+ _SHRINK = 1e-3
1399
+ #: Divisions of a step into 4**k substeps, k = 1 ... _SUBSTEP_LEVELS
1400
+ _SUBSTEP_LEVELS = 3
1401
+ #: The share of its strength that a regularized cleavage plane keeps once it is broken
1402
+ #: through (its linear softening stops there: no threshold below nothing)
1403
+ _BROKEN = 1e-6
1404
+ #: Twins whose fractions are within this (relative) of the largest are as predominant: the
1405
+ #: first of them turns the lattice (variants that the symmetry of a loading makes equal
1406
+ #: differ by their round-off, from a point to the next)
1407
+ _TIE = 1e-6
1408
+
1409
+
1410
+ def state_width(n_systems: int, finite: bool = False, turns: bool = False, micro: int = 0) -> int:
1411
+ """Internal variables of a crystal point with ``n_systems`` slip systems; ``turns``:
1412
+ its twins turn its lattice (:data:`CP_TURNED` more); ``micro``: those of the
1413
+ microdamage that regularizes its cleavage planes, the last ones (the microdamage,
1414
+ then the mark of each plane, 1 + its damage when it was broken through:
1415
+ :attr:`CrystalPlasticity.micro_width`)."""
1416
+ width = CP_ALPHA + 2 * int(n_systems) + (18 if finite else 6)
1417
+ return width + (CP_TURNED if turns else 0) + int(micro)
1418
+
1419
+
1420
+ @njit(cache=True)
1421
+ def work_blocks(count, n_max):
1422
+ """``count`` sets of work arrays of the kernels for at most ``n_max`` slip systems:
1423
+ those of :func:`work_arrays` with one more axis, the first one (:func:`work_block`
1424
+ takes a set)."""
1425
+ n = max(n_max, 1)
1426
+ return (
1427
+ np.zeros((count, 26, n)),
1428
+ np.zeros((count, 4, n, n)),
1429
+ np.zeros((count, n, 9)),
1430
+ np.zeros((count, 24, 3, 3)),
1431
+ np.zeros((count, 3, n, 3, 3)),
1432
+ np.zeros((count, 2, n, 6)),
1433
+ np.zeros((count, 6, 9)),
1434
+ np.zeros((count, n), dtype=np.int64),
1435
+ np.zeros((count, 2, CP_ALPHA + 2 * n + 18 + CP_TURNED + 1 + n)),
1436
+ np.zeros((count, 7)),
1437
+ np.zeros((count, n, 6)),
1438
+ np.zeros((count, 3, 6, 6)),
1439
+ np.zeros((count, n), dtype=np.int64),
1440
+ np.zeros((count, n), dtype=np.int64),
1441
+ )
1442
+
1443
+
1444
+ @njit(cache=True)
1445
+ def work_block(blocks, k):
1446
+ """The set ``k`` of the work arrays of :func:`work_blocks` (views).
1447
+
1448
+ The kernels take rows of their work arrays at each call. Rows of arrays that the
1449
+ compiled code manages count their references, atomically: a third to a half of the
1450
+ time of a point where the arrays are allocated in the loop over the points. The
1451
+ loops over the points (:func:`morphogen.homogenization.behaviours.update_points`,
1452
+ :func:`morphogen.homogenization.finite.update_points_finite`) allocate instead the
1453
+ sets of all their chunks of points before their parallel loop, which then holds them
1454
+ as plain memory, and take the set of each chunk."""
1455
+ return (
1456
+ blocks[0][k],
1457
+ blocks[1][k],
1458
+ blocks[2][k],
1459
+ blocks[3][k],
1460
+ blocks[4][k],
1461
+ blocks[5][k],
1462
+ blocks[6][k],
1463
+ blocks[7][k],
1464
+ blocks[8][k],
1465
+ blocks[9][k],
1466
+ blocks[10][k],
1467
+ blocks[11][k],
1468
+ blocks[12][k],
1469
+ blocks[13][k],
1470
+ )
1471
+
1472
+
1473
+ @njit(cache=True)
1474
+ def work_arrays(n_max):
1475
+ """Work arrays of the kernels for at most ``n_max`` slip systems."""
1476
+ return work_block(work_blocks(1, n_max), 0)
1477
+
1478
+
1479
+ @njit(cache=True, inline="always")
1480
+ def _ddot6(a, b):
1481
+ """a : b of two symmetric tensors given by their Voigt components."""
1482
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + 2.0 * (a[3] * b[3] + a[4] * b[4] + a[5] * b[5])
1483
+
1484
+
1485
+ @njit(cache=True)
1486
+ def _tau_small(ns, dg, tau_tr, amat, tau, slipping):
1487
+ """Resolved shear stresses in small strains: ``tau = tau_tr - A dgamma``, summed over
1488
+ the systems that slip (``slipping``: work array of their indices). Their derivatives
1489
+ with respect to the slips, ``-A``, are kept with the Schmid tensors
1490
+ (:func:`_schmid_small`)."""
1491
+ count = 0
1492
+ for r in range(ns):
1493
+ if dg[r] != 0.0:
1494
+ slipping[count] = r
1495
+ count += 1
1496
+ for s in range(ns):
1497
+ t = tau_tr[s]
1498
+ for j in range(count):
1499
+ r = slipping[j]
1500
+ t -= amat[s, r] * dg[r]
1501
+ tau[s] = t
1502
+
1503
+
1504
+ @njit(cache=True)
1505
+ def _tau_finite(ns, dg, sys, fe_tr, dm, eth, tau, dtau, with_jac, w3, wg, s6, act, every,
1506
+ rows): # fmt: skip
1507
+ """Resolved shear stresses in finite strains: ``tau_s = l_s . M . n_s``, the Mandel
1508
+ stress ``M = C_e S_e`` of ``F_e = F_e^tr (I - G + G^2 / 2)``, ``G = sum dgamma_r
1509
+ l_r (x) n_r``, ``S_e = C : (E_e - E_th)``. Leaves in ``w3`` G (0), I - G + G^2/2 (1),
1510
+ F_e (2), C_e (3), S_e (4) and, with the Jacobian, the derivatives of the second one,
1511
+ of C_e and of S_e with respect to the slips in ``wg``: those of the active systems
1512
+ (``act``), or of ``every`` system. The derivatives of the resolved stresses: of the
1513
+ systems of ``rows`` with respect to the slips of the active ones, and of each of the
1514
+ others with respect to its own slip (``every``: what a system that starts needs)."""
1515
+ gam = w3[0]
1516
+ g = w3[1]
1517
+ fe = w3[2]
1518
+ ce = w3[3]
1519
+ se = w3[4]
1520
+ mm = w3[5]
1521
+ t1 = w3[6]
1522
+ t2 = w3[7]
1523
+ ee = w3[8]
1524
+ for i in range(3):
1525
+ for j in range(3):
1526
+ gam[i, j] = 0.0
1527
+ for r in range(ns):
1528
+ d = dg[r]
1529
+ if d != 0.0:
1530
+ for i in range(3):
1531
+ for j in range(3):
1532
+ gam[i, j] += d * sys[r, i] * sys[r, 3 + j]
1533
+ matmul3(gam, gam, t1)
1534
+ for i in range(3):
1535
+ for j in range(3):
1536
+ g[i, j] = (1.0 if i == j else 0.0) - gam[i, j] + 0.5 * t1[i, j]
1537
+ matmul3(fe_tr, g, fe)
1538
+ tmatmul3(fe, fe, ce)
1539
+ for i in range(3):
1540
+ for j in range(3):
1541
+ ee[i, j] = 0.5 * (ce[i, j] - (1.0 if i == j else 0.0)) - eth[i, j]
1542
+ elastic_stress(dm, ee, se, s6[0], s6[1])
1543
+ matmul3(ce, se, mm)
1544
+ for s in range(ns):
1545
+ tau[s] = project(sys[s, 0:3], sys[s, 3:6], mm)
1546
+ if not with_jac:
1547
+ return
1548
+ av = s6[2]
1549
+ for r in range(ns):
1550
+ if not every and act[r] < 0.5:
1551
+ continue
1552
+ dgr = wg[0, r]
1553
+ dce = wg[1, r]
1554
+ dsr = wg[2, r]
1555
+ lr = sys[r, 0:3]
1556
+ nr = sys[r, 3:6]
1557
+ for i in range(3):
1558
+ av[i] = gam[0, i] * nr[0] + gam[1, i] * nr[1] + gam[2, i] * nr[2]
1559
+ av[3 + i] = gam[i, 0] * lr[0] + gam[i, 1] * lr[1] + gam[i, 2] * lr[2]
1560
+ for i in range(3):
1561
+ for j in range(3):
1562
+ dgr[i, j] = -lr[i] * nr[j] + 0.5 * (lr[i] * av[j] + av[3 + i] * nr[j])
1563
+ matmul3(fe_tr, dgr, t1)
1564
+ tmatmul3(t1, fe, t2)
1565
+ for i in range(3):
1566
+ for j in range(3):
1567
+ dce[i, j] = t2[i, j] + t2[j, i]
1568
+ ee[i, j] = 0.5 * dce[i, j]
1569
+ elastic_stress(dm, ee, dsr, s6[0], s6[1])
1570
+ matmul3(dce, se, t1)
1571
+ matmul3(ce, dsr, t2)
1572
+ for i in range(3):
1573
+ for j in range(3):
1574
+ t1[i, j] += t2[i, j]
1575
+ if act[r] > 0.5:
1576
+ for s in range(ns):
1577
+ if rows[s] > 0.5:
1578
+ dtau[s, r] = project(sys[s, 0:3], sys[s, 3:6], t1)
1579
+ else:
1580
+ dtau[r, r] = project(sys[r, 0:3], sys[r, 3:6], t1)
1581
+
1582
+
1583
+ @njit(cache=True, inline="always")
1584
+ def _one_sense(par, s):
1585
+ """Whether a system flows in one sense only: a twin that does not untwin, the
1586
+ opening of a cleavage plane that does not close."""
1587
+ kind = par[s, CP_KIND]
1588
+ return (kind == 1.0 or kind == 2.0) and par[s, CP_CLOSE] == 0.0
1589
+
1590
+
1591
+ @njit(cache=True, inline="always")
1592
+ def _returns(par, s):
1593
+ """Whether a system flows in one sense and back to nothing, no further: a twin that
1594
+ untwins, the opening of a cleavage plane that closes."""
1595
+ kind = par[s, CP_KIND]
1596
+ return (kind == 1.0 or kind == 2.0) and par[s, CP_CLOSE] > 0.0
1597
+
1598
+
1599
+ @njit(cache=True, inline="always")
1600
+ def _net(par, s):
1601
+ """Whether the second variable of a system is its net slip, not the cumulated one:
1602
+ a twin that untwins (its shear is the fraction that has twinned)."""
1603
+ return par[s, CP_KIND] == 1.0 and par[s, CP_CLOSE] > 0.0
1604
+
1605
+
1606
+ @njit(cache=True, inline="always")
1607
+ def _room(par, s, alpha0, v0):
1608
+ """How far a system that returns may go back over a step: the shear of a twin, the
1609
+ opening of a plane, at its start."""
1610
+ return v0[s] if par[s, CP_KIND] == 1.0 else alpha0[s]
1611
+
1612
+
1613
+ @njit(cache=True)
1614
+ def _cp_eval(finite, par, h, ns, dt, alpha0, v0, dg, act, sgn, sys, dm, fe_tr, eth, work, res, fv,
1615
+ with_jac): # fmt: skip
1616
+ """Resolved shear stresses at the slips ``dg``, the overstresses ``fv = |tau - x| - r`` of
1617
+ all the systems (``tau - x - r`` for those that flow in one sense; the larger of the
1618
+ two senses for a twin that untwins; what would bring it back further for a system
1619
+ held at nothing), the residual ``res`` of the active ones (``act``, signs ``sgn``)
1620
+ and, if ``with_jac``, its Jacobian with respect to the magnitudes of their slips
1621
+ (1, or true; 2: with the derivatives of the resolved stresses with respect to the
1622
+ slips of the inactive systems too, which one that starts needs).
1623
+ Returns the largest |R_s|: infinite when the slips of the active twins exhaust the
1624
+ crystal."""
1625
+ wv = work[0]
1626
+ wm = work[1]
1627
+ tau = wv[1]
1628
+ dtau = wm[2]
1629
+ ex = wv[10] # exp(-b v_r) of the systems r for the b of the last family
1630
+ soft = wv[11] # exp(-w d) of the cleavage plane of each system
1631
+ bound = wv[12] # the systems held at nothing (a crack closed, a twin undone)
1632
+ press = wv[13] # the friction of the plane of an accommodation system, if pressed
1633
+ b_ex = 0.0
1634
+ have = False
1635
+ hardening = work[13] # the systems that have slipped (for the ``b`` of ``ex``): those
1636
+ count = 0 # that harden the others
1637
+ extended = par.shape[1] > CP_KIND
1638
+ if finite:
1639
+ rows = wv[25] # the systems whose resolved stresses are derived: the active ones,
1640
+ if with_jac > 0: # and the opening of the planes whose pressure holds one of them
1641
+ for s in range(ns):
1642
+ rows[s] = act[s]
1643
+ if extended:
1644
+ for s in range(ns):
1645
+ if act[s] > 0.5 and par[s, CP_KIND] == 3.0 and par[s, CP_CLOSE] > 0.0:
1646
+ rows[int(par[s, CP_OPEN])] = 1.0
1647
+ _tau_finite(ns, dg, sys, fe_tr, dm, eth, tau, dtau, with_jac > 0, work[3], work[4],
1648
+ work[6], act, with_jac > 1, rows) # fmt: skip
1649
+ else:
1650
+ _tau_small(ns, dg, wv[4], wm[3], tau, work[12])
1651
+ phi = 1.0 # the share of the crystal left to twin
1652
+ back = int(work[9][2]) - 1 # the twin that brings a turned lattice back (-1: none)
1653
+ coupled = 0.0 # the rate at which the slip lowers the strength of the cleavage planes
1654
+ released = 0.0 # what the damage of the planes takes off the resistance of the slip
1655
+ dreleased = 0.0 # its derivative with respect to the cumulated slip
1656
+ # the derivatives of the share ``soft`` of its strength that a system of a plane has:
1657
+ # with the damage of its plane (less), with that of all the planes, with the cumulated
1658
+ # slip (less); and of ``released`` with the damage of the plane of each system
1659
+ slope = wv[14] # (the planes that their microdamage regularizes: none of their own)
1660
+ lift = wv[15]
1661
+ drop = wv[16]
1662
+ gain = wv[17]
1663
+ gone = wv[19] # of the systems of the regularized planes broken through: 1 + their damage
1664
+ if extended:
1665
+ fall = 1.0 # of the strength of the planes with the cumulated slip
1666
+ stiff = 0.0 # the micromorphic modulus of the planes that their microdamage regularizes
1667
+ for s in range(ns):
1668
+ coupled = max(coupled, par[s, CP_COUPLE])
1669
+ stiff = max(stiff, par[s, CP_MICRO])
1670
+ if coupled > 0.0:
1671
+ slipped = 0.0
1672
+ for r in range(ns):
1673
+ if par[r, CP_KIND] == 0.0:
1674
+ slipped += v0[r] + abs(dg[r])
1675
+ fall = math.exp(-coupled * slipped)
1676
+ # the microdamage of the point (negative: a point alone, whose microdamage is its
1677
+ # damage) and the damage of all its planes
1678
+ micro = work[9][1]
1679
+ total = 0.0
1680
+ if stiff > 0.0:
1681
+ total = work[9][3] # of the planes broken through: the damage that they had
1682
+ for r in range(ns):
1683
+ if par[r, CP_SOFT] > 0.0 and gone[r] < 0.5:
1684
+ total += v0[r] + abs(dg[r])
1685
+ capped = 0.0 # strength / softening of the regularized planes broken through
1686
+ planes = wv[20] # the damage of the plane of each opening system
1687
+ keeps = wv[24] # exp(-w d) of this plane, where it softens so
1688
+ for s in range(ns):
1689
+ if par[s, CP_SOFT] > 0.0 and par[s, CP_KIND] == 2.0:
1690
+ acc = 0.0
1691
+ for r in range(ns):
1692
+ if par[r, CP_GROUP] == par[s, CP_GROUP]:
1693
+ acc += v0[r] + abs(dg[r])
1694
+ planes[s] = acc
1695
+ if par[s, CP_MICRO] <= 0.0: # (a plane that has not opened: no exponential)
1696
+ keeps[s] = 1.0 if acc == 0.0 else math.exp(-par[s, CP_SOFT] * acc)
1697
+ for s in range(ns):
1698
+ soft[s] = 1.0
1699
+ slope[s] = 0.0
1700
+ lift[s] = 0.0
1701
+ drop[s] = 0.0
1702
+ gain[s] = 0.0
1703
+ w = par[s, CP_SOFT]
1704
+ if w > 0.0:
1705
+ opening = par[s, CP_KIND] == 2.0
1706
+ o = s if opening else int(par[s, CP_OPEN])
1707
+ acc = planes[o]
1708
+ y0 = par[o, 0] # the strength of the plane
1709
+ if par[s, CP_MICRO] > 0.0:
1710
+ # regularized: a linear softening with the damage of all the planes of
1711
+ # the point (one threshold for them, as in Aslan & Forest 2009: the
1712
+ # planes of a point harden alike at a fixed microdamage, none against
1713
+ # the others), down to nothing, and the micromorphic term of this
1714
+ # damage less the microdamage
1715
+ value = fall - w * total
1716
+ rise = -w
1717
+ if micro >= 0.0:
1718
+ value += stiff * (total - micro) / y0
1719
+ rise += stiff / y0
1720
+ if gone[s] > 0.5:
1721
+ # broken through: no strength left, whatever it opens (a crack),
1722
+ # and its damage is that which it had
1723
+ soft[s] = _BROKEN
1724
+ acc = gone[s] - 1.0
1725
+ elif value > _BROKEN:
1726
+ soft[s] = value
1727
+ lift[s] = rise
1728
+ drop[s] = coupled * fall
1729
+ else:
1730
+ soft[s] = _BROKEN
1731
+ if coupled > 0.0:
1732
+ # the energy of the plane that the slip releases: Y_0 d, up to the
1733
+ # damage that breaks it
1734
+ if acc < fall / w:
1735
+ if gone[s] < 0.5:
1736
+ gain[s] = coupled * fall * y0
1737
+ if opening:
1738
+ released += y0 * acc
1739
+ elif opening:
1740
+ released += y0 * fall / w
1741
+ capped += y0 / w
1742
+ else:
1743
+ # (the exponential of its plane, for the systems that soften alike)
1744
+ if w == par[o, CP_SOFT] and par[o, CP_MICRO] <= 0.0:
1745
+ kept = keeps[o]
1746
+ else:
1747
+ kept = math.exp(-w * acc)
1748
+ soft[s] = kept * fall
1749
+ slope[s] = w * soft[s]
1750
+ drop[s] = coupled * soft[s]
1751
+ if coupled > 0.0:
1752
+ gain[s] = coupled * y0 * soft[s]
1753
+ if opening:
1754
+ # the energy that the plane has dissipated, per unit of its strength
1755
+ released -= y0 * math.expm1(-w * acc) / w
1756
+ if par[s, CP_SAT] > 0.0:
1757
+ phi -= par[s, CP_SAT] * (v0[s] + (dg[s] if _net(par, s) else abs(dg[s])))
1758
+ released *= coupled * fall
1759
+ dreleased = -coupled * released - (coupled * fall) ** 2 * capped
1760
+ work[9][0] = phi
1761
+ worst = 0.0
1762
+ for s in range(ns):
1763
+ tau0 = par[s, 0]
1764
+ q = par[s, 1]
1765
+ b = par[s, 2]
1766
+ c = par[s, 3]
1767
+ d = par[s, 4]
1768
+ k = par[s, 5]
1769
+ n = par[s, 6]
1770
+ mag = abs(dg[s])
1771
+ over = tau[s] - c * (alpha0[s] + dg[s]) / (1.0 + d * mag)
1772
+ iso = tau0
1773
+ wall = 0.0 # the barrier of the saturation of the twins, in the sense that twins
1774
+ one_sense = False
1775
+ returns = False
1776
+ eased = 1.0 # the share of its resistance at which a system goes back to nothing
1777
+ if extended:
1778
+ iso = tau0 * soft[s]
1779
+ if par[s, CP_KIND] == 0.0:
1780
+ iso -= released # the slip of a crystal whose planes are damaged
1781
+ one_sense = _one_sense(par, s)
1782
+ returns = _returns(par, s)
1783
+ if returns:
1784
+ eased = par[s, CP_CLOSE]
1785
+ press[s] = 0.0
1786
+ if par[s, CP_KIND] == 3.0 and par[s, CP_CLOSE] > 0.0:
1787
+ # Coulomb friction: the pressure on the plane holds its lips together
1788
+ normal = tau[int(par[s, CP_OPEN])]
1789
+ if normal < 0.0:
1790
+ press[s] = par[s, CP_CLOSE]
1791
+ iso -= press[s] * normal
1792
+ if par[s, CP_SAT] > 0.0:
1793
+ # the lattice of a twin: it twins back, and not again on the family of its twin
1794
+ if back >= 0 and s != back and par[s, CP_FAMILY] == par[back, CP_FAMILY]:
1795
+ if act[s] > 0.5:
1796
+ return math.inf
1797
+ fv[s] = -1.0
1798
+ res[s] = 0.0
1799
+ continue
1800
+ if phi <= _PHI_FLOOR: # the crystal has twinned as far as it may
1801
+ if act[s] > 0.5 and sgn[s] > 0.0:
1802
+ return math.inf
1803
+ wall = math.inf
1804
+ else:
1805
+ wall = _BARRIER * tau0 * (1.0 / phi - 1.0)
1806
+ if q != 0.0:
1807
+ if not have or b != b_ex: # the systems of a family share their b
1808
+ count = 0
1809
+ for r in range(ns):
1810
+ turned = extended and _net(par, r)
1811
+ slipped = v0[r] + (dg[r] if turned else abs(dg[r]))
1812
+ if slipped == 0.0: # (a system that has not slipped: no exponential)
1813
+ ex[r] = 1.0
1814
+ else:
1815
+ ex[r] = math.exp(-b * slipped)
1816
+ hardening[count] = r
1817
+ count += 1
1818
+ b_ex = b
1819
+ have = True
1820
+ if count > 0:
1821
+ acc = 0.0
1822
+ for j in range(count):
1823
+ r = hardening[j]
1824
+ acc += h[s, r] * (1.0 - ex[r])
1825
+ iso += q * acc
1826
+ if extended and bound[s] > 0.5:
1827
+ fv[s] = -over - eased * iso
1828
+ elif one_sense:
1829
+ fv[s] = over - iso - wall
1830
+ elif returns:
1831
+ fv[s] = max(over - iso - wall, -over - eased * iso)
1832
+ else:
1833
+ fv[s] = abs(over) - iso
1834
+ if act[s] > 0.5:
1835
+ if sgn[s] > 0.0:
1836
+ res[s] = over - iso - wall - k * (mag / dt) ** (1.0 / n)
1837
+ else:
1838
+ res[s] = -over - eased * iso - k * (mag / dt) ** (1.0 / n)
1839
+ worst = max(worst, abs(res[s]))
1840
+ else:
1841
+ res[s] = 0.0
1842
+ if not math.isfinite(worst):
1843
+ return math.inf
1844
+ work[9][4] = 1.0 * with_jac # the derivatives that this evaluation has
1845
+ if with_jac > 0:
1846
+ jac = wm[0]
1847
+ for s in range(ns):
1848
+ if act[s] < 0.5:
1849
+ continue
1850
+ tau0 = par[s, 0]
1851
+ q = par[s, 1]
1852
+ b = par[s, 2]
1853
+ c = par[s, 3]
1854
+ d = par[s, 4]
1855
+ k = par[s, 5]
1856
+ n = par[s, 6]
1857
+ mag = abs(dg[s])
1858
+ w = 0.0
1859
+ twin = False
1860
+ rub = 0.0
1861
+ o = 0
1862
+ eased = 1.0 # the share of the resistance of a system on its way back
1863
+ if extended:
1864
+ w = par[s, CP_SOFT]
1865
+ twin = par[s, CP_SAT] > 0.0 and sgn[s] > 0.0
1866
+ rub = press[s]
1867
+ o = int(par[s, CP_OPEN]) if rub > 0.0 else 0
1868
+ if sgn[s] < 0.0 and _returns(par, s):
1869
+ eased = par[s, CP_CLOSE]
1870
+ if q != 0.0 and (not have or b != b_ex):
1871
+ for r in range(ns):
1872
+ turned = extended and _net(par, r)
1873
+ slipped = v0[r] + (dg[r] if turned else abs(dg[r]))
1874
+ ex[r] = 1.0 if slipped == 0.0 else math.exp(-b * slipped)
1875
+ b_ex = b
1876
+ have = True
1877
+ for r in range(ns):
1878
+ if act[r] < 0.5:
1879
+ continue
1880
+ v = sgn[s] * sgn[r] * dtau[s, r]
1881
+ # the slip that hardens and saturates: cumulated, or the net one of a twin
1882
+ way = sgn[r] if extended and _net(par, r) else 1.0
1883
+ if q != 0.0:
1884
+ v -= eased * q * h[s, r] * b * ex[r] * way
1885
+ if extended:
1886
+ if w > 0.0: # a system of a cleavage plane: its strength
1887
+ if par[r, CP_GROUP] == par[s, CP_GROUP]:
1888
+ v += eased * tau0 * slope[s] # softens with the damage of its plane
1889
+ if par[r, CP_SOFT] > 0.0 and gone[r] < 0.5:
1890
+ v -= eased * tau0 * lift[s] # the micromorphic term: all the planes
1891
+ elif par[r, CP_KIND] == 0.0:
1892
+ v += eased * tau0 * drop[s] # the slip lowers it
1893
+ elif coupled > 0.0 and par[s, CP_KIND] == 0.0:
1894
+ # a slip system: what the damage of the planes takes off its resistance
1895
+ if par[r, CP_KIND] == 0.0:
1896
+ v += dreleased
1897
+ elif par[r, CP_SOFT] > 0.0:
1898
+ v += gain[r]
1899
+ if twin and par[r, CP_SAT] > 0.0:
1900
+ v -= _BARRIER * tau0 * par[r, CP_SAT] / (phi * phi) * way
1901
+ if rub > 0.0: # the pressure of the plane changes with the slips
1902
+ v += rub * sgn[r] * dtau[o, r]
1903
+ if r == s:
1904
+ v -= c * (1.0 - d * sgn[s] * alpha0[s]) / (1.0 + d * mag) ** 2
1905
+ v -= k / (n * dt) * (mag / dt) ** (1.0 / n - 1.0)
1906
+ jac[s, r] = v
1907
+ return worst
1908
+
1909
+
1910
+ @njit(cache=True)
1911
+ def _active_indices(act, ns, idx):
1912
+ na = 0
1913
+ for s in range(ns):
1914
+ if act[s] > 0.5:
1915
+ idx[na] = s
1916
+ na += 1
1917
+ return na
1918
+
1919
+
1920
+ @njit(cache=True)
1921
+ def _active_newton(finite, par, h, ns, dt, alpha0, v0, sys, dm, fe_tr, eth, work, tol, first):
1922
+ """Newton's method on the magnitudes of the slips of the active systems, from those in
1923
+ ``dg``, with a backtracking line search; a system brought down to the floor by a
1924
+ negative residual leaves the active set. ``first``: the largest residual of these
1925
+ slips where the caller has just evaluated them (with the Jacobian if any system is
1926
+ active), negative otherwise. Returns 0 (the state of the slips evaluated, with the
1927
+ Jacobian of its active systems), or 1 on failure."""
1928
+ wv = work[0]
1929
+ wm = work[1]
1930
+ wr = work[2]
1931
+ idx = work[7]
1932
+ res = wv[0]
1933
+ fv = wv[2]
1934
+ sgn = wv[3]
1935
+ trial = wv[5]
1936
+ res_t = wv[6]
1937
+ dg = wv[7]
1938
+ act = wv[8]
1939
+ fv_t = wv[9]
1940
+ bound = wv[12]
1941
+ leave = wv[18] # the active systems on their way out
1942
+ jac = wm[0]
1943
+ lu = wm[1]
1944
+ extended = par.shape[1] > CP_KIND
1945
+ for _ in range(_MAX_LOCAL):
1946
+ if first >= 0.0:
1947
+ worst = first
1948
+ first = -1.0
1949
+ else:
1950
+ worst = _cp_eval(finite, par, h, ns, dt, alpha0, v0, dg, act, sgn, sys, dm, fe_tr,
1951
+ eth, work, res, fv, 1) # fmt: skip
1952
+ if not math.isfinite(worst):
1953
+ return 1
1954
+ if worst <= tol:
1955
+ return 0
1956
+ if extended:
1957
+ # a crack that closes (a twin that untwins) as far as it may, and would go
1958
+ # further: held at nothing
1959
+ held = False
1960
+ for s in range(ns):
1961
+ if act[s] > 0.5 and sgn[s] < 0.0 and res[s] > 0.0 and _returns(par, s):
1962
+ room = _room(par, s, alpha0, v0)
1963
+ if abs(dg[s]) >= room * (1.0 - 1e-12):
1964
+ act[s] = 0.0
1965
+ bound[s] = 1.0
1966
+ dg[s] = -room
1967
+ held = True
1968
+ if held:
1969
+ continue
1970
+ dropped = False
1971
+ for s in range(ns):
1972
+ if act[s] > 0.5 and abs(dg[s]) <= _SLIP_FLOOR and res[s] < 0.0:
1973
+ act[s] = 0.0
1974
+ dg[s] = 0.0
1975
+ dropped = True
1976
+ if dropped:
1977
+ continue
1978
+ na = _active_indices(act, ns, idx)
1979
+ for a in range(na):
1980
+ for c in range(na):
1981
+ lu[a, c] = jac[idx[a], idx[c]]
1982
+ wr[a, 0] = -res[idx[a]]
1983
+ if gauss_solve(lu, wr, na, 1) != 0:
1984
+ return 1
1985
+ if extended:
1986
+ # a step that would bring a crack (a twin) back beyond nothing: held there, and
1987
+ # the others solved again (it is released later if they leave it short of it)
1988
+ held = False
1989
+ for a in range(na):
1990
+ s = idx[a]
1991
+ if sgn[s] < 0.0 and _returns(par, s):
1992
+ room = _room(par, s, alpha0, v0)
1993
+ if abs(dg[s]) + wr[a, 0] >= room:
1994
+ act[s] = 0.0
1995
+ bound[s] = 1.0
1996
+ dg[s] = -room
1997
+ held = True
1998
+ if held:
1999
+ continue
2000
+ # a system that the others have relaxed below its threshold — with no slip of
2001
+ # its own and no viscous stress it would still be below it — and that the
2002
+ # correction would bring to nothing is on its way out of the active set: its slip
2003
+ # shrinks (by _SHRINK at a time) and no step brings its residual down. The
2004
+ # correction of the others is solved again without it (it cannot go where the
2005
+ # whole correction sends it), it does not count in the decrease that the step
2006
+ # must bring as long as it stays below its flow rule, and it is out once the
2007
+ # others are at theirs (it comes back if they leave it an overstress). A system
2008
+ # above its threshold that its viscous stress alone holds back is not one of
2009
+ # them: its slip is smaller, not nil.
2010
+ some = False
2011
+ nf = 0
2012
+ free_worst = 0.0
2013
+ norm0 = 0.0
2014
+ for a in range(na):
2015
+ s = idx[a]
2016
+ leave[s] = 0.0
2017
+ mag = abs(dg[s])
2018
+ if res[s] < 0.0 and mag + wr[a, 0] <= 0.0:
2019
+ k = par[s, 5]
2020
+ n = par[s, 6]
2021
+ viscous = k * (mag / dt) ** (1.0 / n)
2022
+ # the residual without the viscous stress, brought back to no slip
2023
+ still = res[s] + viscous - (jac[s, s] + viscous / (n * mag)) * mag
2024
+ if still < 0.0:
2025
+ leave[s] = 1.0
2026
+ some = True
2027
+ if leave[s] < 0.5:
2028
+ nf += 1
2029
+ free_worst = max(free_worst, abs(res[s]))
2030
+ norm0 += res[s] ** 2
2031
+ if some:
2032
+ if free_worst <= tol:
2033
+ for a in range(na):
2034
+ s = idx[a]
2035
+ if leave[s] > 0.5:
2036
+ act[s] = 0.0
2037
+ dg[s] = 0.0
2038
+ continue
2039
+ # the correction of the others, for the slips of those that leave shrunk
2040
+ b = 0
2041
+ for a in range(na):
2042
+ if leave[idx[a]] > 0.5:
2043
+ continue
2044
+ c = 0
2045
+ rhs = -res[idx[a]]
2046
+ for a2 in range(na):
2047
+ s2 = idx[a2]
2048
+ if leave[s2] < 0.5:
2049
+ lu[b, c] = jac[idx[a], s2]
2050
+ c += 1
2051
+ else:
2052
+ rhs += jac[idx[a], s2] * (1.0 - _SHRINK) * abs(dg[s2])
2053
+ wr[b, 0] = rhs
2054
+ b += 1
2055
+ if gauss_solve(lu, wr, nf, 1) != 0:
2056
+ return 1
2057
+ b = nf - 1
2058
+ for a in range(na - 1, -1, -1):
2059
+ s = idx[a]
2060
+ if leave[s] > 0.5:
2061
+ wr[a, 0] = -(1.0 - _SHRINK) * abs(dg[s])
2062
+ else:
2063
+ wr[a, 0] = wr[b, 0]
2064
+ b -= 1
2065
+ t = 1.0
2066
+ accepted = False
2067
+ for _ls in range(30):
2068
+ for s in range(ns):
2069
+ trial[s] = dg[s]
2070
+ for a in range(na):
2071
+ s = idx[a]
2072
+ mag = max(abs(dg[s]) + t * wr[a, 0], _SHRINK * abs(dg[s]), _SLIP_FLOOR)
2073
+ if extended and sgn[s] < 0.0 and _returns(par, s):
2074
+ # a crack closes by its opening at most, a twin untwins by its shear
2075
+ mag = min(mag, _room(par, s, alpha0, v0))
2076
+ trial[s] = sgn[s] * mag
2077
+ # (the whole correction: with its derivatives — if it is accepted it is the
2078
+ # next iterate, which is then not evaluated again)
2079
+ lead = _ls == 0
2080
+ w = _cp_eval(finite, par, h, ns, dt, alpha0, v0, trial, act, sgn, sys, dm, fe_tr, eth,
2081
+ work, res_t, fv_t, 1 if lead else 0) # fmt: skip
2082
+ norm1 = 0.0
2083
+ for a in range(na):
2084
+ if leave[idx[a]] < 0.5 or res_t[idx[a]] > 0.0:
2085
+ norm1 += res_t[idx[a]] ** 2
2086
+ if math.isfinite(w) and norm1 <= (1.0 - 1e-4 * t) * norm0:
2087
+ accepted = True
2088
+ break
2089
+ t *= 0.5
2090
+ if not accepted:
2091
+ # stagnation at the level of rounding errors
2092
+ _cp_eval(finite, par, h, ns, dt, alpha0, v0, dg, act, sgn, sys, dm, fe_tr, eth, work,
2093
+ res, fv, 1) # fmt: skip
2094
+ if not some:
2095
+ return 0 if worst <= 1e3 * tol else 1
2096
+ if free_worst > 1e3 * tol:
2097
+ return 1
2098
+ for a in range(na): # the others stagnate at their flow rules
2099
+ s = idx[a]
2100
+ if leave[s] > 0.5:
2101
+ act[s] = 0.0
2102
+ dg[s] = 0.0
2103
+ continue
2104
+ for s in range(ns):
2105
+ dg[s] = trial[s]
2106
+ if lead: # evaluated with its derivatives: the residuals of the next iterate
2107
+ for s in range(ns):
2108
+ res[s] = res_t[s]
2109
+ fv[s] = fv_t[s]
2110
+ first = w
2111
+ return 1
2112
+
2113
+
2114
+ @njit(cache=True)
2115
+ def _released(par, ns, dt, alpha0, v0, fv, act, sgn, bound, tol):
2116
+ """The systems held at nothing (``bound``: a crack whose opening, a twin whose shear
2117
+ has gone back to zero over the step) after an iteration on the active set: one whose
2118
+ flow rule would bring it back less is released, and flows again. Returns whether the
2119
+ active set changed."""
2120
+ changed = False
2121
+ for s in range(ns):
2122
+ if bound[s] < 0.5:
2123
+ continue
2124
+ k = par[s, 5]
2125
+ n = par[s, 6]
2126
+ # its flow rule where it is held: -(tau - x) - r - K (what it went back / dt)^(1/n)
2127
+ rest = fv[s] - k * (_room(par, s, alpha0, v0) / dt) ** (1.0 / n)
2128
+ if rest < -tol:
2129
+ bound[s] = 0.0
2130
+ act[s] = 1.0
2131
+ sgn[s] = -1.0
2132
+ changed = True
2133
+ return changed
2134
+
2135
+
2136
+ @njit(cache=True)
2137
+ def _cp_solve(finite, par, h, ns, dt, alpha0, v0, sys, dm, fe_tr, eth, work):
2138
+ """Slips of the step (``work[0][7]``, holding the initial guess) by the active set
2139
+ strategy. Returns 0, or 1 on failure."""
2140
+ wv = work[0]
2141
+ wm = work[1]
2142
+ res = wv[0]
2143
+ tau = wv[1]
2144
+ fv = wv[2]
2145
+ sgn = wv[3]
2146
+ dg = wv[7]
2147
+ act = wv[8]
2148
+ bound = wv[12] # the openings of the cracks held closed: their slips are fixed
2149
+ extended = par.shape[1] > CP_KIND
2150
+ twins = 0
2151
+ active = False
2152
+ for s in range(ns):
2153
+ bound[s] = 0.0
2154
+ one_sense = extended and _one_sense(par, s)
2155
+ if extended and par[s, CP_SAT] > 0.0:
2156
+ twins += 1
2157
+ if extended and dg[s] < 0.0 and _returns(par, s) and -dg[s] >= _room(par, s, alpha0, v0):
2158
+ act[s] = 0.0 # a crack closes by its opening at most, a twin untwins by its shear
2159
+ dg[s] = 0.0
2160
+ room = _room(par, s, alpha0, v0)
2161
+ if room > _SLIP_FLOOR:
2162
+ dg[s] = -room
2163
+ bound[s] = 1.0
2164
+ elif abs(dg[s]) > _SLIP_FLOOR and not (one_sense and dg[s] < 0.0):
2165
+ act[s] = 1.0
2166
+ sgn[s] = 1.0 if dg[s] > 0.0 else -1.0
2167
+ active = True
2168
+ else:
2169
+ act[s] = 0.0
2170
+ dg[s] = 0.0
2171
+ # (the derivatives of the resolved stresses: only with active systems, or where one
2172
+ # starts — a point that stays elastic is evaluated once, without them)
2173
+ worst = _cp_eval(finite, par, h, ns, dt, alpha0, v0, dg, act, sgn, sys, dm, fe_tr, eth, work,
2174
+ res, fv, 1 if active else 0) # fmt: skip
2175
+ if not math.isfinite(worst):
2176
+ return 1
2177
+ scale = 0.0
2178
+ for s in range(ns):
2179
+ scale = max(scale, abs(tau[s]) + par[s, 0] + par[s, 5])
2180
+ tol = _LOCAL_TOL * scale
2181
+ first = worst # the slips are evaluated: the iteration starts from there
2182
+ # the slips below which a system does not start: kept from a point to the next, for
2183
+ # the viscosity of each system and the time step
2184
+ floors = wv[21]
2185
+ floor_k = wv[22]
2186
+ floor_n = wv[23]
2187
+ if work[9][5] != dt:
2188
+ for s in range(ns):
2189
+ floor_k[s] = -1.0
2190
+ work[9][5] = dt
2191
+ for _ in range(_MAX_ROUNDS):
2192
+ if _active_newton(finite, par, h, ns, dt, alpha0, v0, sys, dm, fe_tr, eth, work, tol,
2193
+ first): # fmt: skip
2194
+ return 1
2195
+ first = -1.0
2196
+ changed = False
2197
+ if extended:
2198
+ changed = _released(par, ns, dt, alpha0, v0, fv, act, sgn, bound, tol)
2199
+ for s in range(ns):
2200
+ if act[s] > 0.5 or bound[s] > 0.5:
2201
+ continue
2202
+ c = par[s, 3]
2203
+ k = par[s, 5]
2204
+ n = par[s, 6]
2205
+ if floor_k[s] != k or floor_n[s] != n:
2206
+ floors[s] = k * (_SLIP_FLOOR / dt) ** (1.0 / n)
2207
+ floor_k[s] = k
2208
+ floor_n[s] = n
2209
+ if fv[s] <= floors[s] + tol:
2210
+ continue
2211
+ sign = 1.0 if tau[s] - c * alpha0[s] >= 0.0 else -1.0
2212
+ room = math.inf
2213
+ if extended and sign < 0.0 and _returns(par, s):
2214
+ room = _room(par, s, alpha0, v0)
2215
+ if room <= _SLIP_FLOOR:
2216
+ continue # a closed crack carries the pressure; no twin to undo
2217
+ if work[9][4] < 1.5: # the derivatives with respect to its slip, now needed
2218
+ _cp_eval(finite, par, h, ns, dt, alpha0, v0, dg, act, sgn, sys, dm, fe_tr, eth,
2219
+ work, res, fv, 2) # fmt: skip
2220
+ # a new active system, from below: a slip that relaxes a tenth of its
2221
+ # overstress at most, with a viscous stress half of it at most
2222
+ act[s] = 1.0
2223
+ sgn[s] = sign
2224
+ relax = abs(wm[2][s, s]) + c
2225
+ d0 = min(dt * (0.5 * fv[s] / k) ** n, 0.1 * fv[s] / max(relax, 1e-300))
2226
+ if extended and par[s, CP_SAT] > 0.0 and sign > 0.0:
2227
+ # a twin: half of the share of the crystal left to those that may start
2228
+ d0 = min(d0, 0.5 * work[9][0] / (par[s, CP_SAT] * twins))
2229
+ dg[s] = sgn[s] * min(max(d0, _SLIP_FLOOR), 0.5 * room)
2230
+ changed = True
2231
+ if not changed:
2232
+ return 0
2233
+ return 1
2234
+
2235
+
2236
+ @njit(cache=True)
2237
+ def _initial_slips(old, new, par, ns, dg, guess, ratio, rot):
2238
+ """Initial slips of the local iteration: zero (``guess`` 0); those of the current
2239
+ iterate of the step (1: ``new`` holds it); those of the previous step times ``ratio``
2240
+ (2: ``new`` holds the state before ``old``). ``|dgamma| = dv`` and ``dgamma = alpha
2241
+ (1 + D |dgamma|) - alpha_n`` invert the update of the internal variables. None across
2242
+ a turn of the lattice (``rot``: where its rotation is kept, -1 without one): the slips
2243
+ of the one are not those of the other."""
2244
+ for s in range(ns):
2245
+ dg[s] = 0.0
2246
+ if guess == 0:
2247
+ return
2248
+ if rot >= 0:
2249
+ for r in range(CP_TURNED):
2250
+ if old[rot + r] != new[rot + r]:
2251
+ return
2252
+ extended = par.shape[1] > CP_KIND
2253
+ a = CP_ALPHA
2254
+ for s in range(ns):
2255
+ d = par[s, 4]
2256
+ if guess == 1:
2257
+ mag = new[a + ns + s] - old[a + ns + s]
2258
+ val = new[a + s] * (1.0 + d * mag) - old[a + s]
2259
+ else:
2260
+ mag = old[a + ns + s] - new[a + ns + s]
2261
+ val = ratio * (old[a + s] * (1.0 + d * mag) - new[a + s])
2262
+ if extended and _net(par, s): # a twin that untwins: its net shear
2263
+ if guess == 1:
2264
+ val = new[a + ns + s] - old[a + ns + s]
2265
+ else:
2266
+ val = ratio * (old[a + ns + s] - new[a + ns + s])
2267
+ if math.isfinite(val):
2268
+ dg[s] = val
2269
+
2270
+
2271
+ @njit(cache=True)
2272
+ def _solve_slips(finite, par, h, ns, dt, old, new, sys, dm, fe_tr, eth, guess, ratio, work):
2273
+ """Slips of the step from the initial guess, again from zero if that fails."""
2274
+ dg = work[0][7]
2275
+ alpha0 = old[CP_ALPHA : CP_ALPHA + ns]
2276
+ v0 = old[CP_ALPHA + ns : CP_ALPHA + 2 * ns]
2277
+ rot = CP_ALPHA + 2 * ns + (18 if finite else 6) if _turns(par, ns) else -1
2278
+ _initial_slips(old, new, par, ns, dg, guess, ratio, rot)
2279
+ if _cp_solve(finite, par, h, ns, dt, alpha0, v0, sys, dm, fe_tr, eth, work) == 0:
2280
+ return 0
2281
+ if guess == 0:
2282
+ return 1
2283
+ _initial_slips(old, new, par, ns, dg, 0, 1.0, rot)
2284
+ return _cp_solve(finite, par, h, ns, dt, alpha0, v0, sys, dm, fe_tr, eth, work)
2285
+
2286
+
2287
+ @njit(cache=True)
2288
+ def _update_hardening(par, ns, dg, old, new):
2289
+ extended = par.shape[1] > CP_KIND
2290
+ for s in range(ns):
2291
+ d = par[s, 4]
2292
+ new[CP_ALPHA + s] = (old[CP_ALPHA + s] + dg[s]) / (1.0 + d * abs(dg[s]))
2293
+ new[CP_ALPHA + ns + s] = old[CP_ALPHA + ns + s] + abs(dg[s])
2294
+ if extended and _returns(par, s):
2295
+ if par[s, CP_KIND] == 1.0: # the shear of a twin that untwins: the net one
2296
+ new[CP_ALPHA + ns + s] = old[CP_ALPHA + ns + s] + dg[s]
2297
+ if new[CP_ALPHA + ns + s] < _SLIP_FLOOR:
2298
+ new[CP_ALPHA + ns + s] = 0.0
2299
+ elif new[CP_ALPHA + s] < _SLIP_FLOOR:
2300
+ new[CP_ALPHA + s] = 0.0 # the opening of a crack: nil when it is closed
2301
+
2302
+
2303
+ @njit(cache=True)
2304
+ def _regularized(par, ns):
2305
+ """Whether the cleavage planes of a crystal are regularized by their microdamage."""
2306
+ if par.shape[1] <= CP_MICRO:
2307
+ return False
2308
+ for s in range(ns):
2309
+ if par[s, CP_MICRO] > 0.0:
2310
+ return True
2311
+ return False
2312
+
2313
+
2314
+ @njit(cache=True)
2315
+ def _broken_planes(par, ns, old, slot, gone):
2316
+ """The systems of the regularized planes broken through (``gone``: the mark of
2317
+ their plane, 1 + the damage that it had then; 0 for the others; the marks at
2318
+ ``old[slot + 1:]``, after the microdamage, are those of the solver of the path,
2319
+ which breaks the planes as their microdamage settles). Returns the damage of these
2320
+ planes: what they open since is the opening of a crack, which would otherwise run
2321
+ ahead of the microdamage and give the planes their strength back."""
2322
+ kept = 0.0
2323
+ if par.shape[1] <= CP_MICRO:
2324
+ for s in range(ns):
2325
+ gone[s] = 0.0
2326
+ return kept
2327
+ for s in range(ns):
2328
+ gone[s] = 0.0
2329
+ if par[s, CP_MICRO] > 0.0:
2330
+ mark = old[slot + 1 + int(par[s, CP_GROUP])]
2331
+ if mark > 0.5:
2332
+ gone[s] = mark
2333
+ if par[s, CP_KIND] == 2.0: # once for the plane: its opening system
2334
+ kept += mark - 1.0
2335
+ return kept
2336
+
2337
+
2338
+ @njit(cache=True)
2339
+ def _turns(par, ns):
2340
+ """Whether the twins of a crystal turn its lattice."""
2341
+ if par.shape[1] <= CP_TURN:
2342
+ return False
2343
+ for s in range(ns):
2344
+ if par[s, CP_TURN] != 0.0:
2345
+ return True
2346
+ return False
2347
+
2348
+
2349
+ @njit(cache=True)
2350
+ def rotate_stiffness(dm, rot, out, bond, tmp):
2351
+ """The stiffness ``dm`` (6 x 6, stresses for engineering strains) of a lattice turned
2352
+ by the rotation ``rot`` (its vectors ``v`` become ``rot v``): ``out = K dm K^T``, with
2353
+ ``K`` (left in ``bond``) the matrix of the tensor components of a turned symmetric
2354
+ tensor, ``(rot a rot^T) = K a``."""
2355
+ for p in range(6):
2356
+ i = p if p < 3 else (p - 2) % 3
2357
+ j = p if p < 3 else (p - 1) % 3
2358
+ for q in range(6):
2359
+ k = q if q < 3 else (q - 2) % 3
2360
+ ll = q if q < 3 else (q - 1) % 3
2361
+ v = rot[i, k] * rot[j, ll]
2362
+ if q >= 3:
2363
+ v += rot[i, ll] * rot[j, k]
2364
+ bond[p, q] = v
2365
+ for p in range(6):
2366
+ for q in range(6):
2367
+ acc = 0.0
2368
+ for r in range(6):
2369
+ acc += bond[p, r] * dm[r, q]
2370
+ tmp[p, q] = acc
2371
+ for p in range(6):
2372
+ for q in range(6):
2373
+ acc = 0.0
2374
+ for r in range(6):
2375
+ acc += tmp[p, r] * bond[q, r]
2376
+ out[p, q] = acc
2377
+
2378
+
2379
+ @njit(cache=True)
2380
+ def _turned_lattice(old, rot, ns, sys, dm, eth, work):
2381
+ """The lattice of a point that its twins turned (the rotation at ``old[rot:]``, less
2382
+ the identity): fills ``work[10]`` with its systems, ``work[11][0]`` with its
2383
+ elasticity and ``work[11][2][0]`` with its thermal strain (tensor components), those
2384
+ of the grain turned. Returns False, and fills nothing, for a lattice that was not
2385
+ turned."""
2386
+ turned = False
2387
+ for r in range(9):
2388
+ if old[rot + r] != 0.0:
2389
+ turned = True
2390
+ if not turned:
2391
+ return False
2392
+ q = work[3][20]
2393
+ for i in range(3):
2394
+ for j in range(3):
2395
+ q[i, j] = old[rot + 3 * i + j] + (1.0 if i == j else 0.0)
2396
+ out = work[10]
2397
+ for s in range(ns):
2398
+ for i in range(3):
2399
+ out[s, i] = q[i, 0] * sys[s, 0] + q[i, 1] * sys[s, 1] + q[i, 2] * sys[s, 2]
2400
+ out[s, 3 + i] = q[i, 0] * sys[s, 3] + q[i, 1] * sys[s, 4] + q[i, 2] * sys[s, 5]
2401
+ mats = work[11]
2402
+ rotate_stiffness(dm, q, mats[0], mats[1], mats[2])
2403
+ turned_eth = mats[2][0] # free once the stiffness is turned
2404
+ for p in range(6):
2405
+ acc = 0.0
2406
+ for r in range(6):
2407
+ acc += mats[1][p, r] * eth[r]
2408
+ turned_eth[p] = acc
2409
+ return True
2410
+
2411
+
2412
+ @njit(cache=True)
2413
+ def turn_lattice(par, ns, normal, new, rot, best):
2414
+ """Turn the lattice of a point (its internal variables ``new``, the rotation at
2415
+ ``new[rot:]``) into that of its twin ``best``, of plane ``normal`` (axes of the
2416
+ sample, in the lattice as it is): by half a turn about the normal, ``Q = 2 n (x) n -
2417
+ I``, a rotation that composes with those of the earlier twins. Its twins start again
2418
+ from nothing: in the new lattice, the system of that twin shears the other way and
2419
+ brings the first lattice back (detwinning), the other systems of its family being
2420
+ held (the conjugate twin of a twin of small shear deforms the lattice as the
2421
+ detwinning does, under the same resolved stress, and would otherwise share it). The
2422
+ point keeps the twinned fraction that it had (by the shears of its twins); when the
2423
+ lattice of the grain comes back, what is left of it is the shear of that twin, which
2424
+ goes on shearing back."""
2425
+ a = CP_ALPHA
2426
+ total = 0.0 # the fractions of the twins of the lattice as it is
2427
+ for s in range(ns):
2428
+ total += par[s, CP_SHEAR] * new[a + ns + s]
2429
+ before = new[rot + 10] # the twinned fraction of the point when it was turned
2430
+ undo = int(new[rot + 9]) - 1 # the twin that brings the earlier lattice back
2431
+ undone = par[undo, CP_SHEAR] * new[a + ns + undo] if undo >= 0 else 0.0
2432
+ twinned = max(before + total - 2.0 * undone, 0.0) # of the point, as it is turned
2433
+ n0, n1, n2 = normal[0], normal[1], normal[2]
2434
+ r0 = np.empty((3, 3))
2435
+ for i in range(3):
2436
+ for j in range(3):
2437
+ r0[i, j] = new[rot + 3 * i + j] + (1.0 if i == j else 0.0)
2438
+ off = 0.0
2439
+ for j in range(3):
2440
+ along = n0 * r0[0, j] + n1 * r0[1, j] + n2 * r0[2, j]
2441
+ for i in range(3):
2442
+ ni = n0 if i == 0 else (n1 if i == 1 else n2)
2443
+ value = 2.0 * ni * along - r0[i, j] - (1.0 if i == j else 0.0)
2444
+ new[rot + 3 * i + j] = value
2445
+ off = max(off, abs(value))
2446
+ for s in range(ns):
2447
+ if par[s, CP_SAT] > 0.0:
2448
+ new[a + s] = 0.0
2449
+ new[a + ns + s] = 0.0
2450
+ if off < 1e-9: # the lattice of the grain again, exactly
2451
+ for r in range(CP_TURNED):
2452
+ new[rot + r] = 0.0
2453
+ if undo == best and before > undone: # what is left of the twin that turned it
2454
+ new[a + ns + best] = (before - undone) / par[best, CP_SHEAR]
2455
+ elif undo == best:
2456
+ new[rot + 9] = -1.0 # a lattice turned more than once: no single twin undoes it
2457
+ new[rot + 10] = twinned
2458
+ else:
2459
+ new[rot + 9] = best + 1.0
2460
+ new[rot + 10] = twinned
2461
+
2462
+
2463
+ @njit(cache=True)
2464
+ def _turn_lattice(par, ns, sys, new, rot):
2465
+ """The twins of a point turn its lattice at the end of a step (``new``): when its
2466
+ twinned fraction has come to the threshold (``sum_t CP_TURN_t v_t >= 1``), the lattice
2467
+ becomes that of its predominant twin, the one of the largest fraction (the first of
2468
+ those within :data:`_TIE` of it; :func:`turn_lattice`). ``sys``: the systems of the
2469
+ lattice of the step (axes of the sample). Not where the lattices are turned grain by
2470
+ grain (a negative ``CP_TURN``: :func:`turn_twins`, after the step)."""
2471
+ a = CP_ALPHA
2472
+ total = 0.0
2473
+ most = 0.0
2474
+ for s in range(ns):
2475
+ if par[s, CP_TURN] < 0.0:
2476
+ return
2477
+ share = par[s, CP_TURN] * new[a + ns + s]
2478
+ total += share
2479
+ most = max(most, share)
2480
+ if total < 1.0 or most <= 0.0:
2481
+ return
2482
+ for s in range(ns):
2483
+ if par[s, CP_TURN] * new[a + ns + s] >= (1.0 - _TIE) * most:
2484
+ turn_lattice(par, ns, sys[s, 3:6], new, rot, s)
2485
+ return
2486
+
2487
+
2488
+ def turn_twins(
2489
+ crystal, state, before, grains, systems, *, points=None, finite: bool = False, weights=None
2490
+ ) -> int:
2491
+ """The lattices that the twins of grains turn at the end of a step, grain by grain:
2492
+ the predominant twin reorientation of Tomé, Lebensohn & Kocks (1991), with the points
2493
+ of a grain in place of the grains of an aggregate. In each grain, of twinned volume
2494
+ ``V_acc`` (the mean of the twinned fractions of its points, by the shears of their
2495
+ twins) and turned volume ``V_eff`` (that of its points whose lattice is that of a
2496
+ twin), the points whose twinned fraction has grown over the step past the threshold
2497
+
2498
+ F_T = min(1, A_1 + A_2 V_eff / V_acc)
2499
+
2500
+ take the lattice of their predominant twin (:func:`turn_lattice`; the first of the
2501
+ twins within :data:`_TIE` of the largest fraction), the most twinned first, while the
2502
+ turned volume is below the twinned one. When the twins shear back, the lattices come
2503
+ back — the points whose twin has been undone the most first, by ``A_1`` at least,
2504
+ while the turned volume is above the twinned one — and those whose twin is undone
2505
+ altogether in any case.
2506
+
2507
+ ``crystal``: a :class:`CrystalPlasticity` with ``twin_reorientation`` (``A_1``) and
2508
+ ``twin_reorientation_growth`` (``A_2``); ``state`` and ``before``: the internal
2509
+ variables of points at the end and at the start of the step (rows x width; ``state``
2510
+ is changed in place); ``points``: the rows of the points of the crystal (all by
2511
+ default), ``grains`` the grain of each of them, ``systems`` the systems of the
2512
+ lattices of the grains (grains x N x 6: direction and normal, axes of the sample) and
2513
+ ``weights`` their volumes (equal by default). Returns the number of lattices turned."""
2514
+ if not crystal.by_grain:
2515
+ return 0
2516
+ rows = np.arange(len(state)) if points is None else np.asarray(points, dtype=np.int64)
2517
+ if rows.size == 0:
2518
+ return 0
2519
+ n = crystal.n_systems
2520
+ par = np.zeros((n, CP_WIDTH))
2521
+ par[:, :CP_KIND] = crystal.params_array()
2522
+ par[:, CP_KIND:] = crystal.kinds_array()
2523
+ shares = par[:, CP_SHEAR]
2524
+ rot = state_width(n, finite)
2525
+ a = CP_ALPHA + n
2526
+ grains = np.asarray(grains)
2527
+ now = state[rows, a : a + n] * shares # the fractions of the twins of the lattices
2528
+ was = before[rows, a : a + n] * shares
2529
+ total = now.sum(axis=1)
2530
+ turned = np.any(state[rows, rot : rot + 9] != 0.0, axis=1)
2531
+ undo = state[rows, rot + 9].astype(np.int64) - 1
2532
+ known = turned & (undo >= 0)
2533
+ index = np.arange(rows.size)
2534
+ back = np.where(known, now[index, np.maximum(undo, 0)], 0.0)
2535
+ kept = state[rows, rot + 10]
2536
+ twinned = np.where(turned, np.maximum(kept + total - 2.0 * back, 0.0), total)
2537
+ # the twins that grow: those of the grain, or the one that brings its lattice back
2538
+ grows = np.where(known, back > was[index, np.maximum(undo, 0)], total > was.sum(axis=1))
2539
+ w = np.ones(rows.size) if weights is None else np.abs(np.asarray(weights, dtype=float))
2540
+ first, growth = crystal.twin_reorientation, crystal.twin_reorientation_growth
2541
+ count = 0
2542
+ for g in np.unique(grains):
2543
+ pts = np.flatnonzero(grains == g)
2544
+ share = w[pts] / w[pts].sum()
2545
+ acc = float(share @ twinned[pts])
2546
+ eff = float(share[turned[pts]].sum())
2547
+ if acc > 0.0 and eff < acc:
2548
+ threshold = min(1.0, first + growth * eff / acc)
2549
+ ready = np.flatnonzero(~turned[pts] & grows[pts] & (total[pts] >= threshold))
2550
+ for k in ready[np.argsort(-total[pts[ready]], kind="stable")]:
2551
+ if eff >= acc:
2552
+ break
2553
+ p = pts[k]
2554
+ best = int(np.flatnonzero(now[p] >= (1.0 - _TIE) * now[p].max())[0])
2555
+ normal = np.ascontiguousarray(systems[g, best, 3:6], dtype=float)
2556
+ turn_lattice(par, n, normal, state[rows[p]], rot, best)
2557
+ eff += share[k]
2558
+ count += 1
2559
+ ready = np.flatnonzero(known[pts] & grows[pts])
2560
+ if ready.size == 0:
2561
+ continue
2562
+ for k in ready[np.argsort(-back[pts[ready]], kind="stable")]:
2563
+ p = pts[k]
2564
+ gone = back[p] >= kept[p] # the twin of the point is undone altogether
2565
+ if not gone and not (eff > acc and back[p] >= first):
2566
+ continue
2567
+ row = state[rows[p]]
2568
+ lattice = row[rot : rot + 9].reshape(3, 3) + np.eye(3)
2569
+ normal = np.ascontiguousarray(lattice @ systems[g, undo[p], 3:6])
2570
+ turn_lattice(par, n, normal, row, rot, int(undo[p]))
2571
+ eff -= share[k]
2572
+ count += 1
2573
+ return count
2574
+
2575
+
2576
+ @njit(cache=True)
2577
+ def _schmid_small(sys, ns, dm, m, cm, me, amat, dtau):
2578
+ """Schmid tensors ``m = sym(l (x) n)`` (tensor components), ``C : m``, the
2579
+ interaction of the systems through the elasticity, ``A_sr = m_s : C : m_r``, and the
2580
+ derivatives of the resolved stresses with respect to the slips, ``dtau = -A``."""
2581
+ for s in range(ns):
2582
+ l0, l1, l2 = sys[s, 0], sys[s, 1], sys[s, 2]
2583
+ n0, n1, n2 = sys[s, 3], sys[s, 4], sys[s, 5]
2584
+ m[s, 0] = l0 * n0
2585
+ m[s, 1] = l1 * n1
2586
+ m[s, 2] = l2 * n2
2587
+ m[s, 3] = 0.5 * (l1 * n2 + l2 * n1)
2588
+ m[s, 4] = 0.5 * (l2 * n0 + l0 * n2)
2589
+ m[s, 5] = 0.5 * (l0 * n1 + l1 * n0)
2590
+ for r in range(6):
2591
+ me[r] = m[s, r] if r < 3 else 2.0 * m[s, r]
2592
+ for r in range(6):
2593
+ acc = 0.0
2594
+ for c in range(6):
2595
+ acc += dm[r, c] * me[c]
2596
+ cm[s, r] = acc
2597
+ for s in range(ns):
2598
+ for r in range(ns):
2599
+ amat[s, r] = _ddot6(m[s], cm[r])
2600
+ dtau[s, r] = -amat[s, r]
2601
+
2602
+
2603
+ @njit(cache=True)
2604
+ def _small_step(sys, par, h, ns, dm, emech, dt, old, new, sig, guess, ratio, work):
2605
+ """Backward Euler step of a small-strain point from the internal variables ``old`` to
2606
+ the mechanical strain ``emech`` (engineering, without the thermal strain): the slips,
2607
+ the stress and ``new`` (but the strain). Returns 0, or 1 on failure."""
2608
+ wv = work[0]
2609
+ w3 = work[3]
2610
+ w6 = work[5]
2611
+ s6 = work[6]
2612
+ m = w6[0]
2613
+ cm = w6[1]
2614
+ tau_tr = wv[4]
2615
+ ee = s6[0]
2616
+ for r in range(6):
2617
+ ee[r] = emech[r] - old[r] * (1.0 if r < 3 else 2.0)
2618
+ for r in range(6):
2619
+ acc = 0.0
2620
+ for c in range(6):
2621
+ acc += dm[r, c] * ee[c]
2622
+ sig[r] = acc
2623
+ for s in range(ns):
2624
+ tau_tr[s] = _ddot6(m[s], sig)
2625
+ if _solve_slips(False, par, h, ns, dt, old, new, sys, dm, w3[0], w3[0], guess, ratio, work):
2626
+ return 1
2627
+ for r in range(old.shape[0]):
2628
+ new[r] = old[r]
2629
+ dg = wv[7]
2630
+ dep = s6[1]
2631
+ flow = s6[2] # of the slips and of the twins: the plastic strain of p
2632
+ extended = par.shape[1] > CP_KIND
2633
+ for r in range(6):
2634
+ dep[r] = 0.0
2635
+ flow[r] = 0.0
2636
+ for s in range(ns):
2637
+ if dg[s] == 0.0:
2638
+ continue
2639
+ plastic = not extended or par[s, CP_KIND] < 1.5
2640
+ for r in range(6):
2641
+ dep[r] += dg[s] * m[s, r]
2642
+ sig[r] -= dg[s] * cm[s, r]
2643
+ if plastic:
2644
+ flow[r] += dg[s] * m[s, r]
2645
+ for r in range(6):
2646
+ new[r] = old[r] + dep[r]
2647
+ new[6] = old[6] + math.sqrt(max(2.0 / 3.0 * _ddot6(flow, flow), 0.0))
2648
+ _update_hardening(par, ns, dg, old, new)
2649
+ return 0
2650
+
2651
+
2652
+ @njit(cache=True)
2653
+ def cp_small(sys, par, h, ns, dm, eps, eth, dt, old, new, sig, tan, guess, ratio, work,
2654
+ sym=True, key=-1): # fmt: skip
2655
+ """Implicit update of a Méric-Cailletaud point in small strains over a step ``dt``:
2656
+ strain ``eps`` (engineering), thermal strain ``eth`` (tensor components), slip
2657
+ systems ``sys`` (slip direction, plane normal) and elasticity ``dm`` in the axes of the
2658
+ sample. Fills the stress, the internal variables and the consistent tangent
2659
+ (symmetrized with ``sym``); returns 1 if the local iteration fails, even in
2660
+ substeps. ``key``: a number of the material of the point (its systems and its
2661
+ elasticity), 0 or more: the Schmid tensors of the last point integrated with these
2662
+ ``work`` arrays are kept for a point of the same key (-1: computed for each point)."""
2663
+ wv = work[0]
2664
+ wm = work[1]
2665
+ wr = work[2]
2666
+ w6 = work[5]
2667
+ s6 = work[6]
2668
+ m = w6[0]
2669
+ cm = w6[1]
2670
+ slot = CP_ALPHA + 2 * ns
2671
+ turns = _turns(par, ns)
2672
+ work[9][2] = 0.0
2673
+ work[9][1] = -1.0 # the microdamage of the point, after its other internal variables
2674
+ mslot = slot + 6 + (CP_TURNED if turns else 0)
2675
+ regular = _regularized(par, ns)
2676
+ if regular:
2677
+ work[9][1] = old[mslot]
2678
+ work[9][3] = _broken_planes(par, ns, old, mslot, wv[19])
2679
+ kept = key >= 0 and work[9][6] == key + 1.0
2680
+ if turns and _turned_lattice(old, slot + 6, ns, sys, dm, eth, work):
2681
+ sys = work[10] # the lattice of a twin: its systems, elasticity, thermal strain
2682
+ dm = work[11][0]
2683
+ eth = work[11][2][0]
2684
+ work[9][2] = max(old[slot + 15], 0.0) # the twin that brings it back
2685
+ kept = False
2686
+ key = -1
2687
+ if not kept: # (those of the last point otherwise: the same material)
2688
+ _schmid_small(sys, ns, dm, m, cm, s6[3], wm[3], wm[2])
2689
+ work[9][6] = key + 1.0
2690
+ emech = s6[4]
2691
+ for r in range(6):
2692
+ emech[r] = eps[r] - eth[r] * (1.0 if r < 3 else 2.0)
2693
+ if _small_step(sys, par, h, ns, dm, emech, dt, old, new, sig, guess, ratio, work) != 0:
2694
+ bufs = work[8]
2695
+ width = min(old.shape[0], bufs.shape[1])
2696
+ ek = s6[5]
2697
+ done = False
2698
+ for level in range(_SUBSTEP_LEVELS):
2699
+ count = 4 ** (level + 1)
2700
+ cur = bufs[0, :width]
2701
+ nxt = bufs[1, :width]
2702
+ for r in range(width):
2703
+ cur[r] = old[r]
2704
+ ok = True
2705
+ for k in range(1, count + 1):
2706
+ for r in range(6):
2707
+ ek[r] = old[slot + r] + k / count * (emech[r] - old[slot + r])
2708
+ if _small_step(sys, par, h, ns, dm, ek, dt / count, cur, nxt, sig,
2709
+ 2 if k > 1 else 0, 1.0, work): # fmt: skip
2710
+ ok = False
2711
+ break
2712
+ cur, nxt = nxt, cur
2713
+ if ok:
2714
+ for r in range(width):
2715
+ new[r] = cur[r]
2716
+ done = True
2717
+ break
2718
+ if not done:
2719
+ return 1
2720
+ for r in range(6):
2721
+ new[slot + r] = emech[r]
2722
+ if turns: # the lattice of the next step: that of the predominant twin, past the threshold
2723
+ _turn_lattice(par, ns, sys, new, slot + 6)
2724
+ # consistent tangent (of the last substep): d delta_a / d eps = -J^-1 sign_a d tau_a /
2725
+ # d eps on the active systems, d tau / d eps = C : m
2726
+ sgn = wv[3]
2727
+ idx = work[7]
2728
+ for r in range(6):
2729
+ for c in range(6):
2730
+ tan[r, c] = dm[r, c]
2731
+ na = _active_indices(wv[8], ns, idx)
2732
+ if na == 0:
2733
+ return 0
2734
+ jac = wm[0]
2735
+ lu = wm[1]
2736
+ extended = par.shape[1] > CP_KIND
2737
+ press = wv[13]
2738
+ for a in range(na):
2739
+ s = idx[a]
2740
+ for b in range(na):
2741
+ lu[a, b] = jac[s, idx[b]]
2742
+ for j in range(6):
2743
+ wr[a, j] = -sgn[s] * cm[s, j]
2744
+ if extended and press[s] > 0.0: # the friction follows the pressure of its plane
2745
+ o = int(par[s, CP_OPEN])
2746
+ for j in range(6):
2747
+ wr[a, j] -= press[s] * cm[o, j]
2748
+ if gauss_solve(lu, wr, na, 6) != 0:
2749
+ return 1
2750
+ for j in range(6):
2751
+ for r in range(6):
2752
+ acc = 0.0
2753
+ for a in range(na):
2754
+ s = idx[a]
2755
+ acc += sgn[s] * cm[s, r] * wr[a, j]
2756
+ tan[r, j] -= acc
2757
+ if sym:
2758
+ symmetrize(tan)
2759
+ return 0
2760
+
2761
+
2762
+ @njit(cache=True)
2763
+ def _finite_step(sys, par, h, ns, dm, hg, eth, dt, old, new, guess, ratio, work):
2764
+ """Backward Euler step of a finite-strain point from the internal variables ``old`` to
2765
+ the displacement gradient ``hg``: the slips and ``new`` (but the gradient). Leaves in
2766
+ the 3 x 3 work tensors F (9), F_p^-1 at the start (10) and the end (13) of the step and
2767
+ those of ``_tau_finite``. Returns 0, or 1 on failure."""
2768
+ w3 = work[3]
2769
+ f = w3[9]
2770
+ fpn = w3[10]
2771
+ fe_tr = w3[11]
2772
+ fpi = w3[13]
2773
+ t1 = w3[15]
2774
+ t2 = w3[16]
2775
+ off = CP_ALPHA + 2 * ns
2776
+ for i in range(3):
2777
+ for j in range(3):
2778
+ f[i, j] = (1.0 if i == j else 0.0) + hg[3 * i + j]
2779
+ fpn[i, j] = (1.0 if i == j else 0.0) + old[off + 3 * i + j]
2780
+ matmul3(f, fpn, fe_tr)
2781
+ if _solve_slips(True, par, h, ns, dt, old, new, sys, dm, fe_tr, eth, guess, ratio, work):
2782
+ return 1
2783
+ for r in range(old.shape[0]):
2784
+ new[r] = old[r]
2785
+ gam = w3[0]
2786
+ matmul3(fpn, w3[1], fpi)
2787
+ for i in range(3):
2788
+ for j in range(3):
2789
+ new[off + 3 * i + j] = fpi[i, j] - (1.0 if i == j else 0.0)
2790
+ inverse3(fpi, t1)
2791
+ tmatmul3(t1, t1, t2)
2792
+ new[0] = 0.5 * (t2[0, 0] - 1.0)
2793
+ new[1] = 0.5 * (t2[1, 1] - 1.0)
2794
+ new[2] = 0.5 * (t2[2, 2] - 1.0)
2795
+ new[3] = 0.5 * t2[1, 2]
2796
+ new[4] = 0.5 * t2[2, 0]
2797
+ new[5] = 0.5 * t2[0, 1]
2798
+ if par.shape[1] > CP_KIND: # the slips and the twins: the plastic strain of p
2799
+ dg = work[0][7]
2800
+ for i in range(3):
2801
+ for j in range(3):
2802
+ t1[i, j] = 0.0
2803
+ for r in range(ns):
2804
+ if par[r, CP_KIND] < 1.5 and dg[r] != 0.0:
2805
+ for i in range(3):
2806
+ for j in range(3):
2807
+ t1[i, j] += dg[r] * sys[r, i] * sys[r, 3 + j]
2808
+ gam = t1
2809
+ acc = 0.0
2810
+ for i in range(3):
2811
+ for j in range(3):
2812
+ sym = 0.5 * (gam[i, j] + gam[j, i])
2813
+ acc += sym * sym
2814
+ new[6] = old[6] + math.sqrt(2.0 / 3.0 * acc)
2815
+ _update_hardening(par, ns, work[0][7], old, new)
2816
+ return 0
2817
+
2818
+
2819
+ @njit(cache=True)
2820
+ def cp_finite(sys, par, h, ns, dm, hg, eth6, dt, old, new, pk1, tan, guess, ratio, work):
2821
+ """Implicit update of a Méric-Cailletaud point in finite strains: displacement gradient
2822
+ ``hg`` (``F - I``, 9 components row by row), thermal strain ``eth6`` (tensor
2823
+ components, Green-Lagrange, of the lattice), slip systems ``sys`` and elasticity
2824
+ ``dm`` of the lattice in the intermediate configuration, axes of the sample. Fills
2825
+ the first Piola-Kirchhoff stress ``pk1``, the internal variables and the tangent
2826
+ ``tan = d P / d F`` (9 x 9); returns 1 if the local iteration fails, even in
2827
+ substeps."""
2828
+ wv = work[0]
2829
+ wm = work[1]
2830
+ wr = work[2]
2831
+ w3 = work[3]
2832
+ wg = work[4]
2833
+ s6 = work[6]
2834
+ eth = w3[12]
2835
+ hslot = CP_ALPHA + 2 * ns + 9
2836
+ turns = _turns(par, ns)
2837
+ work[9][2] = 0.0
2838
+ work[9][1] = -1.0 # the microdamage of the point, after its other internal variables
2839
+ mslot = hslot + 9 + (CP_TURNED if turns else 0)
2840
+ regular = _regularized(par, ns)
2841
+ if regular:
2842
+ work[9][1] = old[mslot]
2843
+ work[9][3] = _broken_planes(par, ns, old, mslot, wv[19])
2844
+ if turns and _turned_lattice(old, hslot + 9, ns, sys, dm, eth6, work):
2845
+ sys = work[10] # the lattice of a twin: its systems, elasticity, thermal strain
2846
+ dm = work[11][0]
2847
+ eth6 = work[11][2][0]
2848
+ work[9][2] = max(old[hslot + 18], 0.0) # the twin that brings it back
2849
+ stress_tensor(eth6, eth)
2850
+ if _finite_step(sys, par, h, ns, dm, hg, eth, dt, old, new, guess, ratio, work) != 0:
2851
+ bufs = work[8]
2852
+ width = min(old.shape[0], bufs.shape[1])
2853
+ hk = s6[5]
2854
+ done = False
2855
+ for level in range(_SUBSTEP_LEVELS):
2856
+ count = 4 ** (level + 1)
2857
+ cur = bufs[0, :width]
2858
+ nxt = bufs[1, :width]
2859
+ for r in range(width):
2860
+ cur[r] = old[r]
2861
+ ok = True
2862
+ for k in range(1, count + 1):
2863
+ for r in range(9):
2864
+ hk[r] = old[hslot + r] + k / count * (hg[r] - old[hslot + r])
2865
+ if _finite_step(sys, par, h, ns, dm, hk, eth, dt / count, cur, nxt,
2866
+ 2 if k > 1 else 0, 1.0, work): # fmt: skip
2867
+ ok = False
2868
+ break
2869
+ cur, nxt = nxt, cur
2870
+ if ok:
2871
+ for r in range(width):
2872
+ new[r] = cur[r]
2873
+ done = True
2874
+ break
2875
+ if not done:
2876
+ return 1
2877
+ for r in range(9):
2878
+ new[hslot + r] = hg[r]
2879
+ if turns: # the lattice of the next step: that of the predominant twin, past the threshold
2880
+ _turn_lattice(par, ns, sys, new, hslot + 9)
2881
+ # stress and tangent of the (last sub)step
2882
+ f = w3[9]
2883
+ fpn = w3[10]
2884
+ fpi = w3[13]
2885
+ s2 = w3[14]
2886
+ t1 = w3[15]
2887
+ t2 = w3[16]
2888
+ t3 = w3[17]
2889
+ t4 = w3[18]
2890
+ dpr = w3[19]
2891
+ fe = w3[2]
2892
+ ce = w3[3]
2893
+ se = w3[4]
2894
+ ee = w3[8]
2895
+ sgn = wv[3]
2896
+ idx = work[7]
2897
+ extended = par.shape[1] > CP_KIND
2898
+ na = _active_indices(wv[8], ns, idx)
2899
+ matmul3(fpi, se, t1)
2900
+ matmult3(t1, fpi, s2)
2901
+ matmul3(f, s2, t1)
2902
+ for i in range(3):
2903
+ for j in range(3):
2904
+ pk1[3 * i + j] = t1[i, j]
2905
+ # tangent at fixed slips, and d tau / d F
2906
+ for kl in range(9):
2907
+ k = kl // 3
2908
+ ll = kl % 3
2909
+ for i in range(3):
2910
+ for j in range(3):
2911
+ t1[i, j] = fpi[ll, i] * fe[k, j]
2912
+ for i in range(3):
2913
+ for j in range(3):
2914
+ t2[i, j] = t1[i, j] + t1[j, i]
2915
+ ee[i, j] = 0.5 * t2[i, j]
2916
+ elastic_stress(dm, ee, t3, s6[0], s6[1])
2917
+ matmul3(t2, se, t1)
2918
+ matmul3(ce, t3, t4)
2919
+ for i in range(3):
2920
+ for j in range(3):
2921
+ t1[i, j] += t4[i, j]
2922
+ for a in range(na):
2923
+ s = idx[a]
2924
+ wr[a, kl] = -sgn[s] * project(sys[s, 0:3], sys[s, 3:6], t1)
2925
+ if extended and wv[13][s] > 0.0: # the friction follows the pressure of its plane
2926
+ o = int(par[s, CP_OPEN])
2927
+ wr[a, kl] -= wv[13][s] * project(sys[o, 0:3], sys[o, 3:6], t1)
2928
+ matmul3(fe, t3, t1)
2929
+ matmult3(t1, fpi, t2)
2930
+ for i in range(3):
2931
+ for j in range(3):
2932
+ v = t2[i, j]
2933
+ if i == k:
2934
+ v += s2[ll, j]
2935
+ tan[3 * i + j, kl] = v
2936
+ if na > 0:
2937
+ jac = wm[0]
2938
+ lu = wm[1]
2939
+ for a in range(na):
2940
+ for b in range(na):
2941
+ lu[a, b] = jac[idx[a], idx[b]]
2942
+ if gauss_solve(lu, wr, na, 9) != 0:
2943
+ return 1
2944
+ matmul3(fe, se, t4)
2945
+ for a in range(na):
2946
+ r = idx[a]
2947
+ # d P / d dgamma_r, with d F_p^-1 = F_p^-1(n) dG_r
2948
+ matmul3(fpn, wg[0, r], t1)
2949
+ matmul3(f, t1, t2)
2950
+ matmul3(t2, se, t3)
2951
+ matmult3(t3, fpi, dpr)
2952
+ matmul3(fe, wg[2, r], t2)
2953
+ matmult3(t2, fpi, t3)
2954
+ for i in range(3):
2955
+ for j in range(3):
2956
+ dpr[i, j] += t3[i, j]
2957
+ matmult3(t4, t1, t3)
2958
+ for i in range(3):
2959
+ for j in range(3):
2960
+ dpr[i, j] += t3[i, j]
2961
+ for kl in range(9):
2962
+ x = sgn[r] * wr[a, kl]
2963
+ if x != 0.0:
2964
+ for i in range(3):
2965
+ for j in range(3):
2966
+ tan[3 * i + j, kl] += dpr[i, j] * x
2967
+ return 0