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,1614 @@
1
+ """Cohesive zone elements: the interfaces of composites and fracture along given surfaces,
2
+ in small and finite strains.
3
+
4
+ Traction-separation laws, per unit area of the reference interface (``δ = u⁺ - u⁻`` the
5
+ separation, ``n`` the normal from side ``-`` to side ``+``, ``δ_n = δ · n`` and ``δ_s = δ -
6
+ δ_n n``):
7
+
8
+ * :class:`Bilinear` (Camanho & Dávila 2002; Turon, Camanho, Costa & Dávila 2006): a penalty
9
+ stiffness ``K``, the onset tractions ``N`` (normal) and ``S`` (shear), the fracture
10
+ energies ``G_Ic`` and ``G_IIc`` and the exponent ``η`` of the mixed-mode criterion of
11
+ Benzeggagh & Kenane. The equivalent separation ``λ = sqrt(<δ_n>² + |δ_s|²)`` and the mode
12
+ mixity ``B = |δ_s|² / λ²`` give the separations of onset, ``λ0² = δn0² + (δs0² - δn0²)
13
+ B^η``, and of failure, ``λf = (δn0 δnf + (δs0 δsf - δn0 δnf) B^η) / λ0`` (``δn0 = N/K``,
14
+ ``δs0 = S/K``, ``δnf = 2 G_Ic / N``, ``δsf = 2 G_IIc / S``), hence the damage ``d = λf (λ -
15
+ λ0) / (λ (λf - λ0))``, irreversible (its largest value); the traction is ``(1 - d) K δ``,
16
+ except in compression, ``t_n = K δ_n`` (no interpenetration, no damage). The energy of
17
+ a separation at fixed mixity is ``G_Ic + (G_IIc - G_Ic) B^η``.
18
+ * :class:`Exponential` (Ortiz & Pandolfi 1999): the effective opening ``δ = sqrt(<δ_n>² +
19
+ β² |δ_s|²)`` and the effective traction ``e σc (δ/δc) exp(-δ/δc)`` along its envelope
20
+ (``G_c = e σc δc``), unloading linearly to the origin; ``t = (t_eff / δ) (<δ_n> n + β²
21
+ δ_s)``, and a penalty ``K_c`` in compression.
22
+ * :class:`Contact`: the contact of the lips of a crack, a penalty against their
23
+ interpenetration and no normal traction otherwise (:mod:`morphogen.fracture.mixed`),
24
+ frictionless or with Coulomb's friction.
25
+
26
+ Friction (the three laws take a coefficient ``friction`` μ; Alfano & Sacco 2006): a point of
27
+ damage ``d`` is a share ``1 - d`` of sound interface, which carries the traction of its law,
28
+ and a share ``d`` of broken interface, whose lips touch under a negative ``δ_n`` (the
29
+ pressure ``p = K <-δ_n>`` of the penalty) and rub: an elastic stick, ``τ = K_t (δ_s - δ_s^p)``,
30
+ within Coulomb's cone ``|τ| <= μ p``, and beyond it a slip ``δ_s^p`` along ``τ`` (a
31
+ non-associated flow: the slip opens nothing), integrated by a radial return, ``τ = μ p τ_trial
32
+ / |τ_trial|`` and ``δ_s^p = δ_s - τ / K_t``. The shear traction is ``(1 - d) K δ_s + d τ``: that
33
+ of the sound law alone while the interface is intact, Coulomb's ``μ p`` once it is broken,
34
+ and the lips of a crack (:class:`Contact`: ``d = 1``) stick or slide. Lips apart carry
35
+ nothing and forget their slip. The slip of each point (two components in its frame, which
36
+ turns with the interface in finite strains) and the energy that friction dissipated there
37
+ per unit area, ``∫ d τ · dδ_s^p``, are kept with the history of its law; the tangent, the
38
+ derivative of the tractions of the radial return, is not symmetric where the lips slide
39
+ (``∂τ/∂δ_n = -μ K τ/|τ|``).
40
+
41
+ Interface elements: zero-thickness elements of six nodes between the faces of two linear
42
+ tetrahedra, integrated at three points of their mid-surface; of twelve nodes between the
43
+ faces of two 10-node tetrahedra (the six nodes of each face: the separation is quadratic,
44
+ as the displacements of the two sides), integrated at six points (a rule exact to degree
45
+ 4: three points would leave openings without traction), with the normal and the area
46
+ element of each point: their faces may be curved, as those of the meshes whose nodes lie
47
+ on the interfaces of the phases (:mod:`morphogen.mesh.curved`). In finite strains the
48
+ normal and tangents are those of the current mid-surface (the tractions turn with the
49
+ interface: frame-indifferent under rigid rotations), and the tangent of an element is the
50
+ derivative of its forces by central differences.
51
+
52
+ Insertion (:func:`insert_interfaces`): the faces between elements of different phases
53
+ (the interfaces of composites), or the faces chosen by a mask or a function of their
54
+ centroids (a crack path), are opened by duplicating their nodes: the elements around each
55
+ of their nodes are grouped by the faces (through that node) by which they remain
56
+ connected, and each group gets its own copy, so that the nodes of a crack front, around
57
+ which the two sides remain connected, are not split. A mesh of 10-node elements is opened
58
+ by its corners, and the mid-edge nodes of the two lips made again where they were (on the
59
+ curved interfaces of the phases).
60
+
61
+ Solver (:class:`CohesiveProblem`): quasi-static, the displacements prescribed on node sets
62
+ (and dead loads) grown with a load factor; Newton's method on the bulk (linear elasticity
63
+ of the materials in small strains; a compressible neo-Hookean solid, ``W = μ/2 (I1 - 3) -
64
+ μ ln J + λ/2 (ln J)²``, total Lagrangian, in finite strains, both with 4- or 10-node
65
+ elements; or the behaviours of morphoGen's points, elasto-viscoplastic, crystalline or
66
+ MFront, with their internal variables, on 4-node elements:
67
+ :mod:`morphogen.fracture.bulk`) and the interfaces, with a
68
+ line search and the steps divided when they fail; results: the reactions, the damage and
69
+ the cracked area at each step, and optionally the displacements. The local instabilities
70
+ of softening interfaces (an element failing at once: no equilibrium beyond a limit point
71
+ under the prescribed displacements) are passed by the viscous regularization of Gao &
72
+ Bower (2004), the load factor as time: ``d = (d_n + Δt/ζ d_∞) / (1 + Δt/ζ)``, the steps
73
+ being divided until the damage, slowed, lets Newton's method converge; the solution tends
74
+ to the rate-independent one as the viscosity ``ζ`` tends to 0.
75
+
76
+ Calibration (Turon, Dávila, Camanho & Costa 2007; Linke & Lammering 2023): the length of
77
+ the cohesive zone ``l_cz = M E G / T²``, the strength that coarse meshes need, ``T =
78
+ sqrt(9π E G / (32 N_e l_e))``, and the corrected beam theory of the double cantilever
79
+ beam (load and crack length against the opening).
80
+ """
81
+
82
+ from __future__ import annotations
83
+
84
+ import math
85
+ import time
86
+ from dataclasses import dataclass, field
87
+
88
+ import numpy as np
89
+ import scipy.sparse as sp
90
+ import scipy.sparse.linalg as spla
91
+ from numba import njit, prange
92
+
93
+ from morphogen.homogenization.fe import GAUSS, _geometry, _point_gradients
94
+ from morphogen.mesh.tetra import TET_EDGES, TET_FACES, TetMesh
95
+
96
+ BILINEAR = 0
97
+ EXPONENTIAL = 1
98
+ CONTACT = 2
99
+ #: The values kept at an interface point: the history of its law (the damage, or the
100
+ #: largest effective opening), the two components of the frictional slip of its broken
101
+ #: share, the energy dissipated there by friction per unit area, and its normal separation
102
+ #: (negative or zero: lips that touch)
103
+ STATE = 5
104
+ #: Damage above which an integration point is broken (its area counts as cracked)
105
+ BROKEN = 0.999
106
+ _GAUSS = np.array([[1 / 6, 1 / 6], [2 / 3, 1 / 6], [1 / 6, 2 / 3]])
107
+ #: The rule of the triangle exact to degree 4 (Dunavant): ξ, η and the weights (sum 1) of
108
+ #: its six points, for the interface elements of six nodes a side
109
+ _GA, _GB = 0.445948490915965, 0.091576213509771
110
+ _GAUSS6 = np.array(
111
+ [
112
+ [_GA, _GA, 0.223381589678011],
113
+ [1.0 - 2.0 * _GA, _GA, 0.223381589678011],
114
+ [_GA, 1.0 - 2.0 * _GA, 0.223381589678011],
115
+ [_GB, _GB, 0.109951743655322],
116
+ [1.0 - 2.0 * _GB, _GB, 0.109951743655322],
117
+ [_GB, 1.0 - 2.0 * _GB, 0.109951743655322],
118
+ ]
119
+ )
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class Bilinear:
124
+ """The bilinear mixed-mode law (see the module): ``stiffness`` K (penalty),
125
+ ``normal_strength`` N, ``shear_strength`` S, the fracture energies ``mode_I`` and
126
+ ``mode_II`` (G_Ic, G_IIc) and the exponent ``eta`` of Benzeggagh & Kenane."""
127
+
128
+ stiffness: float
129
+ normal_strength: float
130
+ shear_strength: float
131
+ mode_I: float
132
+ mode_II: float
133
+ eta: float = 2.0
134
+ friction: float = 0.0
135
+
136
+ def __post_init__(self) -> None:
137
+ values = (
138
+ self.stiffness,
139
+ self.normal_strength,
140
+ self.shear_strength,
141
+ self.mode_I,
142
+ self.mode_II,
143
+ self.eta,
144
+ )
145
+ if not all(math.isfinite(v) and v > 0 for v in values):
146
+ raise ValueError("Bilinear: positive stiffness, strengths, energies and eta")
147
+ _check_friction("Bilinear", self.friction)
148
+ for strength, energy, name in (
149
+ (self.normal_strength, self.mode_I, "normal"),
150
+ (self.shear_strength, self.mode_II, "shear"),
151
+ ):
152
+ if 2 * energy / strength <= strength / self.stiffness:
153
+ raise ValueError(
154
+ f"Bilinear: the {name} failure separation 2 G / T must exceed "
155
+ "the onset T / K (a stiffer penalty or more energy)"
156
+ )
157
+
158
+ def params(self) -> np.ndarray:
159
+ scale = min(self.normal_strength, self.shear_strength) / self.stiffness
160
+ return np.array(
161
+ [
162
+ self.stiffness,
163
+ self.normal_strength,
164
+ self.shear_strength,
165
+ self.mode_I,
166
+ self.mode_II,
167
+ self.eta,
168
+ 0.0,
169
+ 1e-6 * scale,
170
+ self.friction,
171
+ self.stiffness,
172
+ 0.0,
173
+ ]
174
+ )
175
+
176
+ kind = BILINEAR
177
+
178
+
179
+ @dataclass(frozen=True)
180
+ class Exponential:
181
+ """The irreversible exponential law of Ortiz & Pandolfi (see the module): the cohesive
182
+ ``strength`` σc, the fracture ``energy`` G_c, the shear-to-normal ratio ``beta``, the
183
+ ``penalty`` stiffness in compression (by default ``10 e σc / δc``), which is also that
184
+ of the stick of the broken share, and the coefficient of ``friction`` of that share."""
185
+
186
+ strength: float
187
+ energy: float
188
+ beta: float = 1.0
189
+ penalty: float | None = None
190
+ friction: float = 0.0
191
+
192
+ def __post_init__(self) -> None:
193
+ if not all(math.isfinite(v) and v > 0 for v in (self.strength, self.energy, self.beta)):
194
+ raise ValueError("Exponential: positive strength, energy and beta")
195
+ _check_friction("Exponential", self.friction)
196
+
197
+ @property
198
+ def critical_opening(self) -> float:
199
+ """``δc = G_c / (e σc)``."""
200
+ return self.energy / (math.e * self.strength)
201
+
202
+ def params(self) -> np.ndarray:
203
+ dc = self.critical_opening
204
+ penalty = self.penalty if self.penalty is not None else 10 * math.e * self.strength / dc
205
+ return np.array(
206
+ [self.strength, self.energy, self.beta, penalty, 0.0, 0.0, 0.0, 1e-6 * dc,
207
+ self.friction, penalty, 0.0]
208
+ ) # fmt: skip
209
+
210
+ kind = EXPONENTIAL
211
+
212
+
213
+ @dataclass(frozen=True)
214
+ class Contact:
215
+ """Contact of the lips of a crack: a penalty ``stiffness`` against their
216
+ interpenetration (``t_n = K min(δ_n, 0)``), no normal traction otherwise; with a
217
+ coefficient of ``friction``, lips in contact stick (the ``tangential`` stiffness of
218
+ the stick, by default that of the penalty) or slide under Coulomb's ``μ |t_n|`` (see
219
+ the module). Points whose history is negative (:meth:`CohesiveProblem.run`) are
220
+ bonded by the two stiffnesses, in tension as in compression: the ligament ahead of
221
+ the front of a crack whose lips rub (:func:`morphogen.fracture.mixed.solve_crack`)."""
222
+
223
+ stiffness: float
224
+ friction: float = 0.0
225
+ tangential: float | None = None
226
+
227
+ def __post_init__(self) -> None:
228
+ if not (math.isfinite(self.stiffness) and self.stiffness > 0):
229
+ raise ValueError("Contact: a positive stiffness")
230
+ _check_friction("Contact", self.friction)
231
+ if self.tangential is not None and not (
232
+ math.isfinite(self.tangential) and self.tangential > 0
233
+ ):
234
+ raise ValueError("Contact: a positive tangential stiffness")
235
+
236
+ def params(self) -> np.ndarray:
237
+ stick = self.stiffness if self.tangential is None else self.tangential
238
+ return np.array(
239
+ [self.stiffness, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e-9, self.friction, stick, 0.0]
240
+ )
241
+
242
+ kind = CONTACT
243
+
244
+
245
+ def _check_friction(name: str, friction: float) -> None:
246
+ if not (math.isfinite(friction) and friction >= 0):
247
+ raise ValueError(f"{name}: a coefficient of friction of 0 or more")
248
+
249
+
250
+ # -- laws ------------------------------------------------------------------------------------
251
+
252
+
253
+ @njit(cache=True)
254
+ def _friction(mu, stick, pressure, s1, s2, old, new, predict):
255
+ """Coulomb's friction of the broken share of a point under the ``pressure`` of its
256
+ lips (see the module): the shear traction of the tangential separation ``(s1, s2)``
257
+ from the slip of ``old``, by a radial return; the slip of ``new``. ``predict``: lips
258
+ that stick, whatever their pressure (the predictor of a step). A negative ``stick``
259
+ is an elastic slip: the stiffness of the stick is then that which reaches Coulomb's
260
+ bound at this slip, ``μ p / |stick|`` — the bound is reached over one length whatever
261
+ the pressure, and lips that come to touch, whose pressure and slip both start from
262
+ nothing, stick first (the direction of a slip that starts has no meaning)."""
263
+ if mu <= 0.0:
264
+ new[1], new[2] = old[1], old[2]
265
+ return 0.0, 0.0
266
+ if pressure <= 0.0 and (not predict or stick < 0.0):
267
+ # lips apart: no traction, the slip forgotten
268
+ new[1], new[2] = s1, s2
269
+ return 0.0, 0.0
270
+ if stick < 0.0:
271
+ stick = mu * pressure / -stick
272
+ t1 = stick * (s1 - old[1])
273
+ t2 = stick * (s2 - old[2])
274
+ norm = math.sqrt(t1 * t1 + t2 * t2)
275
+ limit = mu * pressure
276
+ if norm <= limit or predict:
277
+ new[1], new[2] = old[1], old[2]
278
+ return t1, t2
279
+ t1 *= limit / norm
280
+ t2 *= limit / norm
281
+ new[1] = s1 - t1 / stick
282
+ new[2] = s2 - t2 / stick
283
+ return t1, t2
284
+
285
+
286
+ @njit(cache=True)
287
+ def _law(kind, par, d, old, new):
288
+ """Traction (local components: normal, shears) of the separation ``d`` from the state
289
+ ``old`` of the point (:data:`STATE` values: the history of the law, bilinear: the
290
+ damage, exponential: the largest effective opening; the frictional slip; the energy
291
+ dissipated by friction; the normal separation), and its state ``new``. With the
292
+ switch ``par[10]``, the law of the predictor of a step: the lips that touched at its
293
+ start (a normal separation of 0 or less) stay closed (the penalty, whatever the sign
294
+ of their separation) and stick."""
295
+ t = np.empty(3)
296
+ dn, s1, s2 = d[0], d[1], d[2]
297
+ dt2 = s1 * s1 + s2 * s2
298
+ dnp = dn if dn > 0.0 else 0.0
299
+ hist = old[0]
300
+ new[4] = dn
301
+ predict = par[10] > 0.0 and old[4] <= 0.0
302
+ if kind == 0:
303
+ k, nn, ss, gi, gii, eta = par[0], par[1], par[2], par[3], par[4], par[5]
304
+ lam2 = dnp * dnp + dt2
305
+ lam = math.sqrt(lam2)
306
+ dn0, ds0 = nn / k, ss / k
307
+ dnf, dsf = 2.0 * gi / nn, 2.0 * gii / ss
308
+ b = dt2 / lam2 if lam2 > 0.0 else 0.0
309
+ bh = b**eta
310
+ lam0 = math.sqrt(dn0 * dn0 + (ds0 * ds0 - dn0 * dn0) * bh)
311
+ lamf = (dn0 * dnf + (ds0 * dsf - dn0 * dnf) * bh) / lam0
312
+ dmg = 0.0
313
+ if lam > lam0:
314
+ dmg = min(1.0, lamf * (lam - lam0) / (lam * (lamf - lam0)))
315
+ dmg = max(dmg, hist)
316
+ if par[6] > 0.0: # viscous regularization (Gao & Bower 2004): the damage lags
317
+ dmg = (hist + par[6] * dmg) / (1.0 + par[6])
318
+ new[0] = dmg
319
+ tau1, tau2 = _friction(
320
+ par[8], par[9], -k * dn if dn < 0.0 else 0.0, s1, s2, old, new, predict
321
+ )
322
+ t[0] = (1.0 - dmg) * k * dn if dn > 0.0 and not predict else k * dn
323
+ t[1] = (1.0 - dmg) * k * s1 + dmg * tau1
324
+ t[2] = (1.0 - dmg) * k * s2 + dmg * tau2
325
+ new[3] = old[3] + dmg * (tau1 * (new[1] - old[1]) + tau2 * (new[2] - old[2]))
326
+ return t
327
+ if kind == 2: # contact: interpenetration only, and the friction of the lips
328
+ new[0] = hist
329
+ if hist < 0.0: # a bonded point (the ligament ahead of a front): the penalty alone
330
+ t[0] = par[0] * dn
331
+ t[1] = par[9] * s1
332
+ t[2] = par[9] * s2
333
+ new[1], new[2], new[3] = old[1], old[2], old[3]
334
+ return t
335
+ tau1, tau2 = _friction(
336
+ par[8], par[9], -par[0] * dn if dn < 0.0 else 0.0, s1, s2, old, new, predict
337
+ )
338
+ t[0] = par[0] * dn if dn < 0.0 or predict else 0.0
339
+ t[1] = tau1
340
+ t[2] = tau2
341
+ new[3] = old[3] + tau1 * (new[1] - old[1]) + tau2 * (new[2] - old[2])
342
+ return t
343
+ sc, gc, beta, kc = par[0], par[1], par[2], par[3]
344
+ dc = gc / (math.e * sc)
345
+ de = math.sqrt(dnp * dnp + beta * beta * dt2)
346
+ kap = max(hist, de)
347
+ if par[6] > 0.0:
348
+ kap = (hist + par[6] * kap) / (1.0 + par[6])
349
+ new[0] = kap
350
+ decay = math.exp(-kap / dc)
351
+ ratio = math.e * sc / dc * decay # the secant at the largest opening
352
+ tau1, tau2 = _friction(par[8], par[9], -kc * dn if dn < 0.0 else 0.0, s1, s2, old, new, predict)
353
+ t[0] = ratio * dnp + (kc * dn if dn < 0.0 or predict else 0.0)
354
+ t[1] = ratio * beta * beta * s1 + (1.0 - decay) * tau1
355
+ t[2] = ratio * beta * beta * s2 + (1.0 - decay) * tau2
356
+ new[3] = old[3] + (1.0 - decay) * (tau1 * (new[1] - old[1]) + tau2 * (new[2] - old[2]))
357
+ return t
358
+
359
+
360
+ @njit(cache=True)
361
+ def _law_tangent(kind, par, d, old):
362
+ """Derivative of the traction by the separation (central differences, the state of
363
+ the start of the step)."""
364
+ h = par[7]
365
+ out = np.empty((3, 3))
366
+ new = np.empty(STATE)
367
+ for j in range(3):
368
+ dp = d.copy()
369
+ dp[j] += h
370
+ tp = _law(kind, par, dp, old, new)
371
+ dm = d.copy()
372
+ dm[j] -= h
373
+ tm = _law(kind, par, dm, old, new)
374
+ for i in range(3):
375
+ out[i, j] = (tp[i] - tm[i]) / (2.0 * h)
376
+ return out
377
+
378
+
379
+ @njit(cache=True)
380
+ def _damage(kind, par, hist):
381
+ if kind == 2:
382
+ return 1.0 if hist >= 0.0 else 0.0 # the lips of a crack: broken; bonded points: sound
383
+ if kind == 0:
384
+ return hist
385
+ dc = par[1] / (math.e * par[0])
386
+ return 1.0 - math.exp(-hist / dc)
387
+
388
+
389
+ def traction(law, separation, history=0.0, slip=None):
390
+ """The traction (local components: normal, shear, shear) of a law for a separation
391
+ (local components) from a ``history`` (damage or largest opening), and the new
392
+ history: a material point of the interfaces. With ``slip`` (the frictional slip of
393
+ the point at the start: two components, zeros for a new point), also the new slip
394
+ and the energy that friction dissipated per unit area on the way."""
395
+ old = np.zeros(STATE)
396
+ old[0] = float(history)
397
+ if slip is not None:
398
+ old[1:3] = np.asarray(slip, dtype=float)
399
+ new = np.zeros(STATE)
400
+ t = _law(law.kind, law.params(), np.asarray(separation, dtype=float), old, new)
401
+ if slip is None:
402
+ return t, float(new[0])
403
+ return t, float(new[0]), new[1:3].copy(), float(new[3])
404
+
405
+
406
+ @njit(cache=True)
407
+ def _point_tractions(kind, par, local, state, out):
408
+ """The tractions (local components) of the separations ``local`` (elements x points x
409
+ 3) of points in the states ``state``."""
410
+ new = np.empty(STATE)
411
+ for e in range(local.shape[0]):
412
+ for g in range(local.shape[1]):
413
+ out[e, g] = _law(kind, par, local[e, g], state[e, g], new)
414
+
415
+
416
+ def lip_tractions(nodes, interfaces, displacement, law, result=None, finite: bool = False):
417
+ """The tractions that the points of interface elements of three nodes a side carry at
418
+ the end of a solution: ``(tractions, jumps)``, elements x 3 points x 3, in global
419
+ components; the traction is that on the side ``-`` (its opposite on the side ``+``),
420
+ of the separation of ``displacement`` (nodes x 3) from the history and the frictional
421
+ slip of ``result`` (a :class:`CohesiveResult`; none: new points)."""
422
+ minus, plus = interfaces.minus[:, :3], interfaces.plus[:, :3]
423
+ u = np.asarray(displacement, dtype=float).reshape(-1, 3)
424
+ x = nodes[minus]
425
+ if finite: # the frame of the current mid-surface
426
+ x = x + 0.5 * (u[minus] + u[plus])
427
+ a, b = x[:, 1] - x[:, 0], x[:, 2] - x[:, 0]
428
+ normal = np.cross(a, b)
429
+ normal /= np.linalg.norm(normal, axis=1, keepdims=True)
430
+ t1 = a / np.linalg.norm(a, axis=1, keepdims=True)
431
+ frame = np.stack([normal, t1, np.cross(normal, t1)], axis=1) # rows: n, t1, t2
432
+ shapes = np.array([[1.0 - xi - eta, xi, eta] for xi, eta in _GAUSS])
433
+ jumps = np.einsum("gi,eic->egc", shapes, u[plus] - u[minus])
434
+ local = np.ascontiguousarray(np.einsum("eab,egb->ega", frame, jumps))
435
+ state = np.zeros((len(minus), 3, STATE))
436
+ if result is not None and len(minus):
437
+ state[..., 0] = result.history
438
+ if result.slip is not None:
439
+ state[..., 1:3] = result.slip
440
+ out = np.zeros_like(local)
441
+ if len(minus):
442
+ _point_tractions(law.kind, law.params(), local, state, out)
443
+ return np.einsum("eab,ega->egb", frame, out), jumps
444
+
445
+
446
+ # -- interface elements ------------------------------------------------------------------------
447
+
448
+
449
+ @njit(cache=True)
450
+ def _frame(x0, x1, x2):
451
+ """The normal, two tangents and twice the area of a triangle."""
452
+ a = x1 - x0
453
+ b = x2 - x0
454
+ nrm = np.array(
455
+ [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
456
+ )
457
+ area2 = math.sqrt(nrm[0] ** 2 + nrm[1] ** 2 + nrm[2] ** 2)
458
+ n = nrm / area2
459
+ t1 = a / math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2)
460
+ t2 = np.array(
461
+ [n[1] * t1[2] - n[2] * t1[1], n[2] * t1[0] - n[0] * t1[2], n[0] * t1[1] - n[1] * t1[0]]
462
+ )
463
+ r = np.empty((3, 3))
464
+ r[0], r[1], r[2] = n, t1, t2
465
+ return r, area2
466
+
467
+
468
+ @njit(cache=True)
469
+ def _element_forces(xr, ue, finite, kind, par, hist, hist_new, gauss):
470
+ """Forces (18: the three nodes of side - then of side +) of an interface element of
471
+ reference positions ``xr`` (3 x 3, its mid-surface) and nodal displacements ``ue`` (6
472
+ x 3), and the new state of its points (``hist``, ``hist_new``: points x STATE)."""
473
+ x = xr.copy()
474
+ if finite: # the current mid-surface
475
+ for i in range(3):
476
+ x[i] = xr[i] + 0.5 * (ue[i] + ue[3 + i])
477
+ r, _ = _frame(x[0], x[1], x[2])
478
+ _, area_ref = _frame(xr[0], xr[1], xr[2])
479
+ f = np.zeros(18)
480
+ for g in range(3):
481
+ xi, eta = gauss[g, 0], gauss[g, 1]
482
+ shape = np.array([1.0 - xi - eta, xi, eta])
483
+ w = area_ref / 6.0
484
+ delta = np.zeros(3)
485
+ for i in range(3):
486
+ delta += shape[i] * (ue[3 + i] - ue[i])
487
+ local = r @ delta
488
+ t = _law(kind, par, local, hist[g], hist_new[g])
489
+ tg = r.T @ t
490
+ for i in range(3):
491
+ for c in range(3):
492
+ f[9 + 3 * i + c] += w * shape[i] * tg[c]
493
+ f[3 * i + c] -= w * shape[i] * tg[c]
494
+ return f
495
+
496
+
497
+ @njit(parallel=True, cache=True)
498
+ def _interfaces(nodes, minus, plus, u, finite, kind, par, hist, hist_new, gauss, tangent, fe, ke):
499
+ """Forces and tangents of all the interface elements (rows: elements)."""
500
+ for e in prange(minus.shape[0]):
501
+ xr = np.empty((3, 3))
502
+ ue = np.empty((6, 3))
503
+ for i in range(3):
504
+ xr[i] = nodes[minus[e, i]]
505
+ ue[i] = u[minus[e, i]]
506
+ ue[3 + i] = u[plus[e, i]]
507
+ hn = np.empty((3, STATE))
508
+ fe[e] = _element_forces(xr, ue, finite, kind, par, hist[e], hn, gauss)
509
+ hist_new[e, :, :] = hn
510
+ if not tangent:
511
+ continue
512
+ if not finite: # B^T D B, D the derivative of the law in the reference frame
513
+ r, area2 = _frame(xr[0], xr[1], xr[2])
514
+ k = np.zeros((18, 18))
515
+ for g in range(3):
516
+ xi, eta = gauss[g, 0], gauss[g, 1]
517
+ shape = np.array([1.0 - xi - eta, xi, eta])
518
+ delta = np.zeros(3)
519
+ for i in range(3):
520
+ delta += shape[i] * (ue[3 + i] - ue[i])
521
+ d = r.T @ _law_tangent(kind, par, r @ delta, hist[e, g]) @ r
522
+ w = area2 / 6.0
523
+ for i in range(3):
524
+ for j in range(3):
525
+ for a in range(3):
526
+ for b in range(3):
527
+ v = w * shape[i] * shape[j] * d[a, b]
528
+ k[9 + 3 * i + a, 9 + 3 * j + b] += v
529
+ k[3 * i + a, 3 * j + b] += v
530
+ k[9 + 3 * i + a, 3 * j + b] -= v
531
+ k[3 * i + a, 9 + 3 * j + b] -= v
532
+ ke[e] = k
533
+ else: # central differences of the forces: the turning frame included
534
+ scale = 1e-7 * math.sqrt(area2_of(xr))
535
+ dummy = np.empty((3, STATE))
536
+ for j in range(18):
537
+ node, c = j // 3, j % 3
538
+ up = ue.copy()
539
+ up[node, c] += scale
540
+ fp = _element_forces(xr, up, finite, kind, par, hist[e], dummy, gauss)
541
+ um = ue.copy()
542
+ um[node, c] -= scale
543
+ fm = _element_forces(xr, um, finite, kind, par, hist[e], dummy, gauss)
544
+ for i in range(18):
545
+ ke[e, i, j] = (fp[i] - fm[i]) / (2.0 * scale)
546
+
547
+
548
+ @njit(cache=True)
549
+ def area2_of(xr):
550
+ _, a2 = _frame(xr[0], xr[1], xr[2])
551
+ return a2
552
+
553
+
554
+ @njit(cache=True)
555
+ def _shape6(xi, eta, shape, dxi, deta):
556
+ """The functions of the six nodes of a triangle (corners, then the middles of the
557
+ edges 0-1, 1-2 and 2-0) at a point, and their derivatives."""
558
+ zeta = 1.0 - xi - eta
559
+ shape[0] = zeta * (2.0 * zeta - 1.0)
560
+ shape[1] = xi * (2.0 * xi - 1.0)
561
+ shape[2] = eta * (2.0 * eta - 1.0)
562
+ shape[3] = 4.0 * zeta * xi
563
+ shape[4] = 4.0 * xi * eta
564
+ shape[5] = 4.0 * eta * zeta
565
+ dxi[0] = 1.0 - 4.0 * zeta
566
+ dxi[1] = 4.0 * xi - 1.0
567
+ dxi[2] = 0.0
568
+ dxi[3] = 4.0 * (zeta - xi)
569
+ dxi[4] = 4.0 * eta
570
+ dxi[5] = -4.0 * eta
571
+ deta[0] = 1.0 - 4.0 * zeta
572
+ deta[1] = 0.0
573
+ deta[2] = 4.0 * eta - 1.0
574
+ deta[3] = -4.0 * xi
575
+ deta[4] = 4.0 * xi
576
+ deta[5] = 4.0 * (zeta - eta)
577
+
578
+
579
+ @njit(cache=True)
580
+ def _frame6(x, dxi, deta):
581
+ """The normal and two tangents of a triangle of six nodes at a point (the derivatives
582
+ of its functions there), and twice its area element."""
583
+ a = np.zeros(3)
584
+ b = np.zeros(3)
585
+ for i in range(6):
586
+ for c in range(3):
587
+ a[c] += dxi[i] * x[i, c]
588
+ b[c] += deta[i] * x[i, c]
589
+ nrm = np.array(
590
+ [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
591
+ )
592
+ area2 = math.sqrt(nrm[0] ** 2 + nrm[1] ** 2 + nrm[2] ** 2)
593
+ n = nrm / area2
594
+ t1 = a / math.sqrt(a[0] ** 2 + a[1] ** 2 + a[2] ** 2)
595
+ t2 = np.array(
596
+ [n[1] * t1[2] - n[2] * t1[1], n[2] * t1[0] - n[0] * t1[2], n[0] * t1[1] - n[1] * t1[0]]
597
+ )
598
+ r = np.empty((3, 3))
599
+ r[0], r[1], r[2] = n, t1, t2
600
+ return r, area2
601
+
602
+
603
+ @njit(cache=True)
604
+ def _element_forces6(xr, ue, finite, kind, par, hist, hist_new, gauss):
605
+ """Forces (36: the six nodes of side - then of side +) of an interface element of
606
+ reference positions ``xr`` (6 x 3, its mid-surface, which may be curved) and nodal
607
+ displacements ``ue`` (12 x 3), and the new state of its six points."""
608
+ x = xr.copy()
609
+ if finite: # the current mid-surface
610
+ for i in range(6):
611
+ x[i] = xr[i] + 0.5 * (ue[i] + ue[6 + i])
612
+ shape = np.empty(6)
613
+ dxi = np.empty(6)
614
+ deta = np.empty(6)
615
+ f = np.zeros(36)
616
+ for g in range(6):
617
+ _shape6(gauss[g, 0], gauss[g, 1], shape, dxi, deta)
618
+ r, _ = _frame6(x, dxi, deta)
619
+ _, area_ref = _frame6(xr, dxi, deta)
620
+ w = 0.5 * gauss[g, 2] * area_ref
621
+ delta = np.zeros(3)
622
+ for i in range(6):
623
+ delta += shape[i] * (ue[6 + i] - ue[i])
624
+ t = _law(kind, par, r @ delta, hist[g], hist_new[g])
625
+ tg = r.T @ t
626
+ for i in range(6):
627
+ for c in range(3):
628
+ f[18 + 3 * i + c] += w * shape[i] * tg[c]
629
+ f[3 * i + c] -= w * shape[i] * tg[c]
630
+ return f
631
+
632
+
633
+ @njit(parallel=True, cache=True)
634
+ def _interfaces6(nodes, minus, plus, u, finite, kind, par, hist, hist_new, gauss, tangent, fe, ke):
635
+ """Forces and tangents of all the interface elements of six nodes a side."""
636
+ for e in prange(minus.shape[0]):
637
+ xr = np.empty((6, 3))
638
+ ue = np.empty((12, 3))
639
+ for i in range(6):
640
+ xr[i] = nodes[minus[e, i]]
641
+ ue[i] = u[minus[e, i]]
642
+ ue[6 + i] = u[plus[e, i]]
643
+ hn = np.empty((6, STATE))
644
+ fe[e] = _element_forces6(xr, ue, finite, kind, par, hist[e], hn, gauss)
645
+ hist_new[e, :, :] = hn
646
+ if not tangent:
647
+ continue
648
+ if not finite: # B^T D B, D the derivative of the law in the frame of each point
649
+ shape = np.empty(6)
650
+ dxi = np.empty(6)
651
+ deta = np.empty(6)
652
+ k = np.zeros((36, 36))
653
+ for g in range(6):
654
+ _shape6(gauss[g, 0], gauss[g, 1], shape, dxi, deta)
655
+ r, area2 = _frame6(xr, dxi, deta)
656
+ delta = np.zeros(3)
657
+ for i in range(6):
658
+ delta += shape[i] * (ue[6 + i] - ue[i])
659
+ d = r.T @ _law_tangent(kind, par, r @ delta, hist[e, g]) @ r
660
+ w = 0.5 * gauss[g, 2] * area2
661
+ for i in range(6):
662
+ for j in range(6):
663
+ for a in range(3):
664
+ for b in range(3):
665
+ v = w * shape[i] * shape[j] * d[a, b]
666
+ k[18 + 3 * i + a, 18 + 3 * j + b] += v
667
+ k[3 * i + a, 3 * j + b] += v
668
+ k[18 + 3 * i + a, 3 * j + b] -= v
669
+ k[3 * i + a, 18 + 3 * j + b] -= v
670
+ ke[e] = k
671
+ else: # central differences of the forces: the turning frames included
672
+ scale = 1e-7 * math.sqrt(area2_of(xr))
673
+ dummy = np.empty((6, STATE))
674
+ for j in range(36):
675
+ node, c = j // 3, j % 3
676
+ up = ue.copy()
677
+ up[node, c] += scale
678
+ fp = _element_forces6(xr, up, finite, kind, par, hist[e], dummy, gauss)
679
+ um = ue.copy()
680
+ um[node, c] -= scale
681
+ fm = _element_forces6(xr, um, finite, kind, par, hist[e], dummy, gauss)
682
+ for i in range(36):
683
+ ke[e, i, j] = (fp[i] - fm[i]) / (2.0 * scale)
684
+
685
+
686
+ # -- bulk in finite strains --------------------------------------------------------------------
687
+
688
+
689
+ @njit(parallel=True, cache=True)
690
+ def _neo_hookean(grads, weights, elements, u, mu, lam, fe, ke, tangent):
691
+ """Forces and tangents of tetrahedra of a compressible neo-Hookean solid (total
692
+ Lagrangian): ``P = μ (F - F^-T) + λ ln J F^-T`` at the integration points of each
693
+ element (``grads``: elements x points x nodes x 3, the gradients of the functions of
694
+ its nodes in the reference configuration; ``weights``: their volumes)."""
695
+ nn = elements.shape[1]
696
+ for e in prange(elements.shape[0]):
697
+ out = np.zeros(3 * nn)
698
+ k = np.zeros((3 * nn, 3 * nn))
699
+ m, l = mu[e], lam[e]
700
+ for q in range(grads.shape[1]):
701
+ g = grads[e, q]
702
+ f = np.eye(3)
703
+ for a in range(nn):
704
+ ua = u[elements[e, a]]
705
+ for i in range(3):
706
+ for j in range(3):
707
+ f[i, j] += ua[i] * g[a, j]
708
+ jac = np.linalg.det(f)
709
+ if jac <= 0.0:
710
+ jac = 1e-12 # inverted: the residual becomes large, the step is divided
711
+ finv = np.linalg.inv(f)
712
+ lnj = math.log(jac)
713
+ p = m * (f - finv.T) + l * lnj * finv.T
714
+ v = weights[e, q]
715
+ for a in range(nn):
716
+ for i in range(3):
717
+ s = 0.0
718
+ for j in range(3):
719
+ s += p[i, j] * g[a, j]
720
+ out[3 * a + i] += v * s
721
+ if not tangent:
722
+ continue
723
+ c1 = m - l * lnj
724
+ # A_ijkl g_j g_l = μ δ_ik (g_a · g_b) + c1 (F^-1 g_b)_i (F^-1 g_a)_k
725
+ # + λ (F^-1 g_a)_i (F^-1 g_b)_k, with (F^-1 g)_i = g_j F^-1_ji
726
+ h = np.zeros((nn, 3))
727
+ for a in range(nn):
728
+ for i in range(3):
729
+ for jj in range(3):
730
+ h[a, i] += g[a, jj] * finv[jj, i]
731
+ for a in range(nn):
732
+ for b in range(nn):
733
+ dot = g[a, 0] * g[b, 0] + g[a, 1] * g[b, 1] + g[a, 2] * g[b, 2]
734
+ for i in range(3):
735
+ for kk in range(3):
736
+ s = c1 * h[b, i] * h[a, kk] + l * h[a, i] * h[b, kk]
737
+ if i == kk:
738
+ s += m * dot
739
+ k[3 * a + i, 3 * b + kk] += v * s
740
+ fe[e] = out
741
+ if tangent:
742
+ ke[e] = k
743
+
744
+
745
+ @njit(cache=True)
746
+ def _reference_gradients(nodes, elements, order, gp, gw, grads, weights):
747
+ """The gradients of the functions of the nodes of each element at its integration
748
+ points (those of the reference configuration; curved 10-node elements: with the
749
+ Jacobian of each point) and the volumes of the points."""
750
+ x = np.empty((4, 3))
751
+ gl = np.empty((4, 3))
752
+ dev = np.zeros((6, 3))
753
+ out = np.empty((elements.shape[1], 3))
754
+ for e in range(elements.shape[0]):
755
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
756
+ for q in range(gp.shape[0]):
757
+ ratio = _point_gradients(order, curved, gl, dev, gp[q], out)
758
+ grads[e, q] = out
759
+ weights[e, q] = abs(vol) * gw[q] * ratio
760
+
761
+
762
+ def _tet_gradients(nodes, elements):
763
+ """Gradients of the shape functions (elements x 4 x 3) and volumes of linear tetrahedra."""
764
+ x = nodes[elements]
765
+ dm = np.stack([x[:, 1] - x[:, 0], x[:, 2] - x[:, 0], x[:, 3] - x[:, 0]], axis=2)
766
+ inv = np.linalg.inv(dm) # rows: gradients of N1, N2, N3
767
+ grads = np.concatenate([-inv.sum(axis=1, keepdims=True), inv], axis=1)
768
+ return np.ascontiguousarray(grads), np.abs(np.linalg.det(dm)) / 6.0
769
+
770
+
771
+ def _gradients_at_points(nodes, elements):
772
+ """Gradients of the functions of the nodes (elements x points x nodes x 3) and volumes
773
+ (elements x points) at the integration points of tetrahedra of 4 nodes (one point) or
774
+ of 10 nodes (four)."""
775
+ order = 1 if elements.shape[1] == 4 else 2
776
+ gp, gw = GAUSS[order]
777
+ shape = (len(elements), len(gw))
778
+ grads = np.zeros((*shape, elements.shape[1], 3))
779
+ weights = np.zeros(shape)
780
+ _reference_gradients(
781
+ np.ascontiguousarray(nodes, dtype=float),
782
+ np.ascontiguousarray(elements, dtype=np.int64),
783
+ order,
784
+ gp,
785
+ gw,
786
+ grads,
787
+ weights,
788
+ )
789
+ return grads, weights
790
+
791
+
792
+ # -- insertion ---------------------------------------------------------------------------------
793
+
794
+
795
+ @dataclass
796
+ class Interfaces:
797
+ """Interface elements: the nodes of their side ``minus`` and of their side ``plus``
798
+ (matching; elements x 3 between 4-node tetrahedra, elements x 6 between 10-node ones:
799
+ the corners, then the mid-edge nodes of the edges 0-1, 1-2 and 2-0), the phases of the
800
+ two sides (elements x 2; -1 unknown); the normal goes from side - to side +."""
801
+
802
+ minus: np.ndarray
803
+ plus: np.ndarray
804
+ phases: np.ndarray
805
+
806
+ @property
807
+ def n_elements(self) -> int:
808
+ return len(self.minus)
809
+
810
+ @property
811
+ def order(self) -> int:
812
+ """1 for faces of three nodes, 2 for faces of six."""
813
+ return 1 if self.minus.shape[1] == 3 else 2
814
+
815
+ @property
816
+ def weights(self) -> np.ndarray:
817
+ """The shares of the area of an element of its integration points."""
818
+ return np.full(3, 1.0 / 3.0) if self.order == 1 else _GAUSS6[:, 2].copy()
819
+
820
+ def subset(self, keep) -> Interfaces:
821
+ """The interface elements ``keep`` (mask or indices)."""
822
+ keep = np.asarray(keep)
823
+ return Interfaces(self.minus[keep], self.plus[keep], self.phases[keep])
824
+
825
+ def centroids(self, mesh: TetMesh) -> np.ndarray:
826
+ return mesh.nodes[self.minus[:, :3]].mean(axis=1)
827
+
828
+ def areas(self, mesh: TetMesh) -> np.ndarray:
829
+ """The areas of the elements (of their side -; curved faces of six nodes: the
830
+ integral of their area element)."""
831
+ x = mesh.nodes[self.minus]
832
+ if self.order == 1:
833
+ return 0.5 * np.linalg.norm(np.cross(x[:, 1] - x[:, 0], x[:, 2] - x[:, 0]), axis=1)
834
+ shape, dxi, deta = np.empty(6), np.empty(6), np.empty(6)
835
+ out = np.zeros(len(x))
836
+ for xi, eta, weight in _GAUSS6:
837
+ _shape6(xi, eta, shape, dxi, deta)
838
+ a = np.einsum("i,eic->ec", dxi, x)
839
+ b = np.einsum("i,eic->ec", deta, x)
840
+ out += 0.5 * weight * np.linalg.norm(np.cross(a, b), axis=1)
841
+ return out
842
+
843
+
844
+ def _interior_faces(tets: np.ndarray):
845
+ """The faces shared by two tetrahedra: the sorted corners of the faces of the elements
846
+ (4 per element), and for each shared face its two places among them (the face ``k %
847
+ 4`` of the element ``k // 4``)."""
848
+ keys = np.sort(tets[:, np.asarray(TET_FACES)].reshape(-1, 3), axis=1)
849
+ order = np.lexsort(keys.T[::-1])
850
+ sorted_keys = keys[order]
851
+ same = np.all(sorted_keys[1:] == sorted_keys[:-1], axis=1)
852
+ return keys, order[:-1][same], order[1:][same]
853
+
854
+
855
+ def interior_faces(mesh: TetMesh) -> tuple[np.ndarray, np.ndarray]:
856
+ """The faces that two elements of a mesh share, in the order of the masks of
857
+ :func:`insert_interfaces`: their corners (faces x 3) and their two elements (faces x
858
+ 2)."""
859
+ tets = np.asarray(mesh.elements[:, :4], dtype=np.int64)
860
+ keys, first, second = _interior_faces(tets)
861
+ return keys[first], np.stack([first // 4, second // 4], axis=1)
862
+
863
+
864
+ def insert_interfaces(mesh: TetMesh, faces="phases", *, sides=None) -> tuple[TetMesh, Interfaces]:
865
+ """Open faces of a tetrahedral mesh (see the module): ``faces`` is ``"phases"`` (the
866
+ faces between different phases; side - the lower phase), a boolean mask of the
867
+ interior faces or a function of the centroids of their corners (rows) returning one.
868
+ Returns the mesh with the duplicated nodes and the interface elements of the opened
869
+ faces (all of them: keep a subset for the cohesive ones, the others being free crack
870
+ faces). ``sides``: a label per element, the faces kept only between different labels
871
+ (the two sides of a crack). A mesh of 10-node elements is opened by its corners; its
872
+ mid-edge nodes are made again, each lip with its own, where they were (the curved
873
+ edges of the interfaces of the phases stay curved), and the interface elements have
874
+ six nodes a side."""
875
+ if mesh.order == 2:
876
+ opened, interfaces = insert_interfaces(mesh.linear(), faces, sides=sides)
877
+ return _with_mid_nodes(mesh, opened, interfaces)
878
+ tets = np.array(mesh.elements, dtype=np.int64)
879
+ local = np.asarray(TET_FACES)
880
+ keys, first, second = _interior_faces(tets)
881
+ e1, f1, e2, f2 = first // 4, first % 4, second // 4, second % 4
882
+ centroids = mesh.nodes[keys[first]].mean(axis=1)
883
+ if isinstance(faces, str):
884
+ if faces != "phases":
885
+ raise ValueError("insert_interfaces: 'phases', a mask or a function of centroids")
886
+ selected = mesh.phase[e1] != mesh.phase[e2]
887
+ swap = mesh.phase[e1] > mesh.phase[e2] # side -: the lower phase (the matrix, say)
888
+ e1, e2 = np.where(swap, e2, e1), np.where(swap, e1, e2)
889
+ f1, f2 = np.where(swap, f2, f1), np.where(swap, f1, f2)
890
+ elif callable(faces):
891
+ selected = np.asarray(faces(centroids), dtype=bool)
892
+ else:
893
+ selected = np.asarray(faces, dtype=bool)
894
+ if selected.shape != (len(first),):
895
+ raise ValueError(f"insert_interfaces: one value per interior face ({len(first)})")
896
+ if sides is not None:
897
+ sides = np.asarray(sides)
898
+ selected = selected & (sides[e1] != sides[e2])
899
+ face_key = {tuple(k): i for i, k in enumerate(keys[first])}
900
+ split_faces = set(np.flatnonzero(selected).tolist())
901
+ on = np.unique(keys[first[selected]])
902
+ # the elements around each node
903
+ counts = np.bincount(tets.ravel(), minlength=mesh.n_nodes)
904
+ start = np.concatenate([[0], np.cumsum(counts)])
905
+ owners = np.argsort(tets.ravel(), kind="stable") // 4
906
+ nodes = [mesh.nodes]
907
+ next_id = mesh.n_nodes
908
+ new_tets = tets.copy()
909
+ for v in on.tolist():
910
+ star = owners[start[v] : start[v + 1]]
911
+ parent = {int(e): int(e) for e in star}
912
+
913
+ def find(a, parent=parent):
914
+ while parent[a] != a:
915
+ parent[a] = parent[parent[a]]
916
+ a = parent[a]
917
+ return a
918
+
919
+ for e in star.tolist():
920
+ for lf in range(4):
921
+ face = tets[e, local[lf]]
922
+ if v not in face:
923
+ continue
924
+ index = face_key.get(tuple(np.sort(face)))
925
+ if index is None or index in split_faces:
926
+ continue # a boundary face, or an opened one
927
+ other = int(e2[index]) if int(e1[index]) == e else int(e1[index])
928
+ parent[find(e)] = find(other)
929
+ groups: dict[int, list[int]] = {}
930
+ for e in star.tolist():
931
+ groups.setdefault(find(e), []).append(e)
932
+ for members in list(groups.values())[1:]:
933
+ nodes.append(mesh.nodes[v][None])
934
+ for e in members:
935
+ new_tets[e][tets[e] == v] = next_id
936
+ next_id += 1
937
+ sel = np.flatnonzero(selected)
938
+ minus = np.empty((len(sel), 3), dtype=np.int64)
939
+ plus = np.empty((len(sel), 3), dtype=np.int64)
940
+ all_nodes = np.concatenate(nodes)
941
+ for k, index in enumerate(sel.tolist()):
942
+ a, b, la = int(e1[index]), int(e2[index]), int(f1[index])
943
+ original = tets[a, local[la]]
944
+ for i, o in enumerate(original):
945
+ minus[k, i] = new_tets[a][tets[a] == o][0]
946
+ plus[k, i] = new_tets[b][tets[b] == o][0]
947
+ x = mesh.nodes[original]
948
+ normal = np.cross(x[1] - x[0], x[2] - x[0])
949
+ towards = mesh.nodes[tets[b]].mean(axis=0) - mesh.nodes[tets[a]].mean(axis=0)
950
+ if normal @ towards < 0: # the normal from side - (element a) to side +
951
+ minus[k, [1, 2]] = minus[k, [2, 1]]
952
+ plus[k, [1, 2]] = plus[k, [2, 1]]
953
+ phases = np.stack([mesh.phase[e1[sel]], mesh.phase[e2[sel]]], axis=1)
954
+ opened = TetMesh(
955
+ all_nodes,
956
+ new_tets,
957
+ mesh.phase,
958
+ mesh.lower,
959
+ mesh.upper,
960
+ periodic=False,
961
+ metadata=dict(mesh.metadata),
962
+ cell=mesh.cell,
963
+ orientations=mesh.orientations,
964
+ side=mesh.side,
965
+ )
966
+ return opened, Interfaces(minus, plus, phases)
967
+
968
+
969
+ def _with_mid_nodes(mesh: TetMesh, opened: TetMesh, interfaces: Interfaces):
970
+ """The 10-node mesh of the opened corners ``opened`` of the 10-node ``mesh`` (the same
971
+ elements), its mid-edge nodes where those of ``mesh`` are, and the interface elements
972
+ with the mid-edge nodes of their two faces."""
973
+ quad = opened.quadratic()
974
+ nodes = quad.nodes.copy()
975
+ nodes[quad.elements[:, 4:]] = mesh.nodes[mesh.elements[:, 4:]]
976
+ quad = quad._derived(nodes, quad.elements)
977
+ # the mid-edge node of each pair of corners
978
+ ends = np.sort(quad.elements[:, TET_EDGES].reshape(-1, 2), axis=1)
979
+ keys, first = np.unique(ends[:, 0] * quad.n_nodes + ends[:, 1], return_index=True)
980
+ mids = quad.elements[:, 4:].ravel()[first]
981
+
982
+ def six(corners: np.ndarray) -> np.ndarray:
983
+ out = [corners]
984
+ for i, j in ((0, 1), (1, 2), (2, 0)):
985
+ a, b = corners[:, i], corners[:, j]
986
+ key = np.minimum(a, b) * quad.n_nodes + np.maximum(a, b)
987
+ out.append(mids[np.searchsorted(keys, key)][:, None])
988
+ return np.concatenate(out, axis=1)
989
+
990
+ return quad, Interfaces(six(interfaces.minus), six(interfaces.plus), interfaces.phases)
991
+
992
+
993
+ # -- the problem -------------------------------------------------------------------------------
994
+
995
+
996
+ def plus(a, b):
997
+ """The sum of two sparse matrices with the stored entries of both, zeros included: the
998
+ sum of SciPy drops the zeros, and with them the full blocks of the three dofs of each
999
+ pair of nodes, on which the sparse factorization is several times faster."""
1000
+ a, b = a.tocoo(), b.tocoo()
1001
+ return sp.csr_matrix(
1002
+ (
1003
+ np.concatenate([a.data, b.data]),
1004
+ (np.concatenate([a.row, b.row]), np.concatenate([a.col, b.col])),
1005
+ ),
1006
+ shape=a.shape,
1007
+ )
1008
+
1009
+
1010
+ @dataclass
1011
+ class CohesiveResult:
1012
+ """The steps of a cohesive problem: load factors, reactions (steps x prescribed sets x
1013
+ 3, summed over the nodes of each set), cracked area and largest damage, Newton
1014
+ iterations, the history of the interface points at the end (elements x 3, or x 6
1015
+ for elements of six nodes a side) and their damage, the final displacement (nodes x
1016
+ 3), with ``fields`` the displacements of the steps, and the works at each step
1017
+ (``work``: ``"external"``, of the prescribed displacements and the forces; ``"bulk"``
1018
+ and ``"interfaces"``, of their internal forces: the energy stored and dissipated by
1019
+ each, which add up to the external work; with a law that rubs, ``"friction"``: the
1020
+ part of the work of the interfaces that friction dissipated). ``slip``: the
1021
+ frictional slip of the points at the end (elements x points x 2, in the frame of
1022
+ each point: the tangents of its mid-surface), and ``friction`` the energy that
1023
+ friction dissipated at each per unit area."""
1024
+
1025
+ loads: np.ndarray
1026
+ reactions: np.ndarray
1027
+ cracked: np.ndarray
1028
+ damage_max: np.ndarray
1029
+ iterations: np.ndarray
1030
+ history: np.ndarray
1031
+ damage: np.ndarray
1032
+ displacement: np.ndarray
1033
+ fields: list = field(default_factory=list, repr=False)
1034
+ time_s: float = 0.0
1035
+ work: dict = field(default_factory=dict, repr=False)
1036
+ slip: np.ndarray | None = field(default=None, repr=False)
1037
+ friction: np.ndarray | None = field(default=None, repr=False)
1038
+
1039
+ def rows(self) -> list[dict]:
1040
+ """One row per step: load factor, the reactions of each prescribed set, the cracked
1041
+ area and the largest damage."""
1042
+ out = []
1043
+ for k, lam in enumerate(self.loads):
1044
+ row = {"load": float(lam)}
1045
+ for s in range(self.reactions.shape[1]):
1046
+ for c, name in enumerate("xyz"):
1047
+ row[f"R{s + 1}{name}"] = float(self.reactions[k, s, c])
1048
+ row["cracked_area"] = float(self.cracked[k])
1049
+ row["damage_max"] = float(self.damage_max[k])
1050
+ for name, values in self.work.items():
1051
+ row[f"work_{name}"] = float(values[k])
1052
+ out.append(row)
1053
+ return out
1054
+
1055
+
1056
+ class CohesiveProblem:
1057
+ """A body with interface elements (see the module): ``mesh`` (tetrahedra of 4 or 10
1058
+ nodes, after :func:`insert_interfaces`), the cohesive ``interfaces`` (of three or six
1059
+ nodes a side, as the faces of the mesh), the ``materials`` of the phases, the cohesive
1060
+ ``law`` and the ``kinematics`` (``"small"`` or ``"finite"`` strains).
1061
+
1062
+ ``bulk``: ``"elastic"``, isotropic elasticity (Young's modulus and Poisson's ratio,
1063
+ which also give the neo-Hookean solid of finite strains); ``"points"``, the behaviours
1064
+ of morphoGen's points (:class:`~morphogen.fracture.bulk.PointBulk`: von Mises
1065
+ elasto-(visco)plasticity, crystal plasticity with the orientations of the grains,
1066
+ MFront laws, and Hencky's elasticity in finite strains), with their internal variables
1067
+ committed at each converged step, on 4-node elements; ``"auto"``, the points when a
1068
+ phase is inelastic, or anisotropic in finite strains."""
1069
+
1070
+ def __init__(
1071
+ self,
1072
+ mesh: TetMesh,
1073
+ interfaces: Interfaces,
1074
+ materials,
1075
+ law,
1076
+ *,
1077
+ kinematics="small",
1078
+ bulk: str = "auto",
1079
+ ):
1080
+ if kinematics not in ("small", "finite"):
1081
+ raise ValueError("kinematics: 'small' or 'finite'")
1082
+ if bulk not in ("auto", "elastic", "points"):
1083
+ raise ValueError("bulk: 'auto', 'elastic' or 'points'")
1084
+ if interfaces.n_elements and interfaces.order != mesh.order:
1085
+ raise ValueError(
1086
+ "CohesiveProblem: interface elements of three nodes a side for 4-node "
1087
+ "tetrahedra, of six for 10-node ones (insert_interfaces on the mesh itself)"
1088
+ )
1089
+ self.mesh, self.interfaces, self.law = mesh, interfaces, law
1090
+ self.finite = kinematics == "finite"
1091
+ self.materials = materials
1092
+ self.par = law.params()
1093
+ n = mesh.n_nodes
1094
+ self.n_dofs = 3 * n
1095
+ side = np.hstack([interfaces.minus, interfaces.plus])
1096
+ self._idofs = (3 * side[:, :, None] + np.arange(3)).reshape(len(side), 3 * side.shape[1])
1097
+ self._tdofs = (3 * mesh.elements[:, :, None] + np.arange(3)).reshape(
1098
+ mesh.n_elements, 3 * mesh.elements.shape[1]
1099
+ )
1100
+ self._points = 3 if side.shape[1] == 6 else 6 # of an interface element
1101
+ from morphogen.fracture.bulk import PointBulk, nonlinear_materials
1102
+
1103
+ inelastic = nonlinear_materials(materials, mesh.phase)
1104
+ if bulk == "elastic" and inelastic:
1105
+ raise ValueError("bulk 'elastic': the materials are inelastic")
1106
+ self.bulk = None
1107
+ self._dt = 1.0
1108
+ self._parts = (np.zeros(self.n_dofs), np.zeros(self.n_dofs))
1109
+ present = [materials[int(p)] for p in np.unique(mesh.phase) if int(p) in materials]
1110
+ anisotropic = self.finite and any(m.young is None for m in present if not m.void)
1111
+ if bulk == "points" or (bulk == "auto" and (inelastic or anisotropic)):
1112
+ if mesh.order != 1:
1113
+ raise ValueError(
1114
+ "CohesiveProblem: the behaviours of the points (inelastic materials, "
1115
+ "anisotropic ones in finite strains) take 4-node tetrahedra (mesh.linear())"
1116
+ )
1117
+ self.bulk = PointBulk(mesh, materials, self.finite)
1118
+ elif self.finite:
1119
+ grads, volumes = _gradients_at_points(mesh.nodes, mesh.elements)
1120
+ self._grads, self._volumes = grads, volumes
1121
+ mu = np.zeros(mesh.n_elements)
1122
+ lam = np.zeros(mesh.n_elements)
1123
+ for p, m in materials.items():
1124
+ if m.void or m.young is None:
1125
+ continue
1126
+ sel = mesh.phase == p
1127
+ mu[sel] = m.young / (2 * (1 + m.poisson))
1128
+ lam[sel] = m.young * m.poisson / ((1 + m.poisson) * (1 - 2 * m.poisson))
1129
+ if np.any((mu == 0) & np.isin(mesh.phase, list(materials))):
1130
+ raise ValueError("finite strains: isotropic materials (young, poisson)")
1131
+ self._mu, self._lam = mu, lam
1132
+ else:
1133
+ from morphogen.homogenization.fe import assemble
1134
+ from morphogen.homogenization.materials import material_table
1135
+
1136
+ table = material_table(
1137
+ mesh.phase, materials, "elastic", grains=mesh.cell, orientations=mesh.orientations
1138
+ ) # crystals: their grains
1139
+ self._kbulk = assemble(mesh, 3, table.mat, table.matrices).tocsr()
1140
+
1141
+ # -- forces --------------------------------------------------------------------------
1142
+
1143
+ def _forces(self, u, hist, tangent: bool, rate: float = 0.0, predict: bool = False):
1144
+ """The internal forces of the displacement ``u``, their tangent and the new state
1145
+ of the interface points. ``predict``: the tangent of the interfaces is that of
1146
+ the predictor of a step, lips that touched at its start closed and sticking
1147
+ (:func:`_law`), the forces those of the law."""
1148
+ n = self.n_dofs
1149
+ u3 = np.ascontiguousarray(u.reshape(-1, 3))
1150
+ ni = self.interfaces.n_elements
1151
+ nd = self._idofs.shape[1] # 18, or 36 for six nodes a side
1152
+ fe = np.zeros((ni, nd))
1153
+ ke = np.zeros((ni, nd, nd)) if tangent else np.zeros((1, nd, nd))
1154
+ hist_new = np.zeros_like(hist)
1155
+ if ni:
1156
+ par = self.par.copy()
1157
+ par[6] = rate
1158
+ kernel, gauss = (_interfaces, _GAUSS) if nd == 18 else (_interfaces6, _GAUSS6)
1159
+ shared = (self.mesh.nodes, self.interfaces.minus, self.interfaces.plus, u3,
1160
+ self.finite, self.law.kind) # fmt: skip
1161
+ predict = predict and tangent
1162
+ kernel(*shared, par, hist, hist_new, gauss, tangent and not predict, fe, ke)
1163
+ if predict: # the tangent of the lips that stay closed and stick
1164
+ par = par.copy()
1165
+ par[10] = 1.0
1166
+ kernel(*shared, par, hist, np.zeros_like(hist), gauss, True, np.zeros_like(fe), ke)
1167
+ f = np.bincount(self._idofs.ravel(), fe.ravel(), minlength=n) if ni else np.zeros(n)
1168
+ k = None
1169
+ if tangent and ni:
1170
+ rows = np.repeat(self._idofs, nd, axis=1).ravel()
1171
+ cols = np.tile(self._idofs, (1, nd)).ravel()
1172
+ k = sp.csr_matrix((ke.ravel(), (rows, cols)), shape=(n, n))
1173
+ f_interfaces = f.copy()
1174
+ if self.bulk is not None:
1175
+ out = self.bulk.evaluate(u, self._dt, tangent)
1176
+ if out is None: # a point failed: no residual, the step is divided
1177
+ return np.full(n, np.nan), sp.identity(n, format="csr"), hist_new
1178
+ fb, kb = out
1179
+ f += fb
1180
+ if tangent:
1181
+ k = kb if k is None else plus(k, kb)
1182
+ elif self.finite:
1183
+ nt, nb = self._tdofs.shape # 12 dofs an element, or 30
1184
+ fb = np.zeros((nt, nb))
1185
+ kb = np.zeros((nt, nb, nb)) if tangent else np.zeros((1, nb, nb))
1186
+ _neo_hookean(
1187
+ self._grads,
1188
+ self._volumes,
1189
+ self.mesh.elements,
1190
+ u3,
1191
+ self._mu,
1192
+ self._lam,
1193
+ fb,
1194
+ kb,
1195
+ tangent,
1196
+ )
1197
+ f += np.bincount(self._tdofs.ravel(), fb.ravel(), minlength=n)
1198
+ if tangent:
1199
+ rows = np.repeat(self._tdofs, nb, axis=1).ravel()
1200
+ cols = np.tile(self._tdofs, (1, nb)).ravel()
1201
+ kbulk = sp.csr_matrix((kb.ravel(), (rows, cols)), shape=(n, n))
1202
+ k = kbulk if k is None else plus(k, kbulk)
1203
+ else:
1204
+ f += self._kbulk @ u
1205
+ if tangent:
1206
+ k = self._kbulk if k is None else plus(self._kbulk, k)
1207
+ self._parts = (f_interfaces, f - f_interfaces)
1208
+ return f, k, hist_new
1209
+
1210
+ def _new_state(self) -> np.ndarray:
1211
+ """The state of the points of the interfaces before any loading (elements x
1212
+ points x :data:`STATE`)."""
1213
+ return np.zeros((self.interfaces.n_elements, self._points, STATE))
1214
+
1215
+ def _damage_of(self, hist) -> np.ndarray:
1216
+ """The damage of the points (elements x points) of their states."""
1217
+ if not hist.size:
1218
+ return hist[..., 0]
1219
+ return np.vectorize(lambda h: _damage(self.law.kind, self.par, h))(hist[..., 0])
1220
+
1221
+ def _areas(self) -> np.ndarray:
1222
+ if getattr(self, "_area", None) is None:
1223
+ self._area = self.interfaces.areas(self.mesh)
1224
+ return self._area
1225
+
1226
+ def _cracked(self, hist) -> tuple[float, float]:
1227
+ if not self.interfaces.n_elements:
1228
+ return 0.0, 0.0
1229
+ damage = self._damage_of(hist)
1230
+ broken = (damage >= BROKEN) @ self.interfaces.weights # the shares of the points
1231
+ return float(self._areas() @ broken), float(damage.max())
1232
+
1233
+ def _rubbed(self, hist) -> float:
1234
+ """The energy dissipated by friction over the interfaces."""
1235
+ if not self.interfaces.n_elements:
1236
+ return 0.0
1237
+ return float(self._areas() @ (hist[..., 3] @ self.interfaces.weights))
1238
+
1239
+ # -- solution --------------------------------------------------------------------------
1240
+
1241
+ # -- the seams of the solvers built on this one (morphogen.contact) -----------------------
1242
+
1243
+ def _predictor(self) -> bool:
1244
+ """Whether the first tangent of a step is that of its predictor (lips that touch
1245
+ or rub)."""
1246
+ return self.law.kind == CONTACT or self.par[8] > 0.0
1247
+
1248
+ def _part_names(self) -> tuple:
1249
+ """The names of the parts of the internal forces (``_parts``), whose works are
1250
+ results."""
1251
+ return ("interfaces", "bulk")
1252
+
1253
+ def _begin(self, u, load: float) -> None:
1254
+ """Before the first step, from the displacement ``u`` at the load factor ``load``."""
1255
+
1256
+ def _attempt(self, target: float) -> None:
1257
+ """A step is tried towards the load factor ``target``."""
1258
+
1259
+ def _augment(self) -> bool:
1260
+ """After Newton's method converged: whether the step is to be solved again."""
1261
+ return False
1262
+
1263
+ def _accept(self, u) -> None:
1264
+ """A step converged at the displacement ``u``."""
1265
+
1266
+ def _newton(self, u_try, hist, dofs, free, load_now, rate, tol, max_newton):
1267
+ """Newton's method with a line search on the residual under the dead loads
1268
+ ``load_now`` of the free dofs: whether it converged, its iterations, the
1269
+ displacement, the forces, the new history of the interfaces and these loads."""
1270
+ ok, iterations, scale = False, 0, None
1271
+ f = hist_try = None
1272
+ predictor = self._predictor()
1273
+ for iterations in range(1, max_newton + 1):
1274
+ f, k, hist_try = self._forces(u_try, hist, True, rate, predictor and iterations == 1)
1275
+ r = f[free] - load_now
1276
+ norm = float(np.linalg.norm(r))
1277
+ if scale is None:
1278
+ scale = max(
1279
+ float(np.linalg.norm(f[dofs])),
1280
+ float(np.linalg.norm(f)),
1281
+ float(np.linalg.norm(load_now)),
1282
+ 1e-30,
1283
+ )
1284
+ if norm <= tol * scale and iterations > 1:
1285
+ ok = True
1286
+ break
1287
+ kff = k[free][:, free].tocsc()
1288
+ # the ordering of the factorization: that of matrices of symmetric pattern is
1289
+ # three to five times faster on 10-node elements, slower on 4-node ones
1290
+ ordering = "MMD_AT_PLUS_A" if self.mesh.order == 2 else "COLAMD"
1291
+ try:
1292
+ du = spla.spsolve(kff, -r, permc_spec=ordering)
1293
+ except RuntimeError:
1294
+ break
1295
+ if not np.all(np.isfinite(du)):
1296
+ break
1297
+ alpha = 1.0
1298
+ for _ in range(4): # a backtracking line search on the residual
1299
+ trial = u_try.copy()
1300
+ trial[free] += alpha * du
1301
+ f_t, _, _ = self._forces(trial, hist, False, rate)
1302
+ if np.linalg.norm(f_t[free] - load_now) < norm or alpha < 0.2:
1303
+ break
1304
+ alpha *= 0.5
1305
+ u_try[free] += alpha * du
1306
+ scale = max(scale, float(np.linalg.norm(f_t[dofs])))
1307
+ return ok, iterations, u_try, f, hist_try, load_now
1308
+
1309
+ def run(
1310
+ self,
1311
+ prescribed,
1312
+ load: float = 1.0,
1313
+ *,
1314
+ steps: int = 20,
1315
+ tol: float = 1e-6,
1316
+ max_newton: int = 25,
1317
+ max_cuts: int = 12,
1318
+ fields: bool = False,
1319
+ viscosity: float = 0.0,
1320
+ forces=None,
1321
+ duration: float | None = None,
1322
+ start: float = 0.0,
1323
+ initial=None,
1324
+ equilibrate: bool = True,
1325
+ history=None,
1326
+ ) -> CohesiveResult:
1327
+ """Grow the prescribed displacements to ``load`` times their values in ``steps``
1328
+ steps (divided when Newton's method fails, ``max_cuts`` times in a row at most).
1329
+ ``prescribed``: entries ``(nodes, components, value)``, the displacement of the
1330
+ components (an index or a list) of the nodes being ``load factor x value`` (0:
1331
+ fixed; an array of the nodes x components: one value each), or ``value(load
1332
+ factor)`` when ``value`` is a function: loadings in several stages, such as a
1333
+ pressure held while a shear grows. ``forces``: nodal forces (3 x nodes, dead loads)
1334
+ grown with them, or a function of the load factor returning them. ``viscosity``:
1335
+ the ``ζ`` of the viscous regularization (in units of the load factor; 0: none). The
1336
+ load factor is the time of the viscous behaviours of the bulk, or the loading lasts
1337
+ ``duration``.
1338
+
1339
+ ``initial``: a displacement (nodes x 3) at the load factor ``start``, from which the
1340
+ loading resumes, the internal variables of the bulk as they are (those of an earlier
1341
+ run, or a state transferred from another mesh: :func:`morphogen.fracture.ductile.
1342
+ transfer_state`); ``equilibrate``: first bring it to equilibrium at that load, over
1343
+ a vanishing time (no viscous flow), the plastic correction of the points included
1344
+ but dissipating nothing (the bulk keeps the dissipated part of its work density, its
1345
+ free energy that of the equilibrium; ``result.equilibration``: the Newton
1346
+ iterations).
1347
+
1348
+ ``history``: that of the interface points at the start (one value per element, or
1349
+ elements x points): a damage of 1 for the part of a bilinear interface that is
1350
+ already broken, a negative value for the bonded points of a :class:`Contact`."""
1351
+ t0 = time.perf_counter()
1352
+ n = self.n_dofs
1353
+ dofs, values, sets = [], [], []
1354
+ for nodes, comps, value in prescribed:
1355
+ nodes = np.atleast_1d(np.asarray(nodes, dtype=np.int64))
1356
+ comps = np.atleast_1d(np.asarray(comps, dtype=np.int64))
1357
+ d = (3 * nodes[:, None] + comps[None, :]).ravel()
1358
+ dofs.append(d)
1359
+ shape = (len(nodes), len(comps))
1360
+ if callable(value): # a function of the load factor
1361
+
1362
+ def course(t, value=value, shape=shape):
1363
+ return np.broadcast_to(np.asarray(value(t), dtype=float), shape).ravel()
1364
+
1365
+ else:
1366
+ amplitude = np.broadcast_to(np.asarray(value, dtype=float), shape).ravel()
1367
+
1368
+ def course(t, amplitude=amplitude):
1369
+ return t * amplitude
1370
+
1371
+ values.append(course)
1372
+ sets.append(d)
1373
+ dofs = np.concatenate(dofs)
1374
+ if len(np.unique(dofs)) != len(dofs):
1375
+ raise ValueError("prescribed: a degree of freedom is given twice")
1376
+
1377
+ def values_at(t: float) -> np.ndarray:
1378
+ """The prescribed displacements at the load factor ``t``."""
1379
+ return np.concatenate([course(t) for course in values])
1380
+
1381
+ if callable(forces):
1382
+
1383
+ def external_at(t: float) -> np.ndarray:
1384
+ out = np.asarray(forces(t), dtype=float).ravel()
1385
+ if out.shape != (n,):
1386
+ raise ValueError(f"forces: one per degree of freedom ({n})")
1387
+ return out
1388
+
1389
+ else:
1390
+ external = np.zeros(n) if forces is None else np.asarray(forces, dtype=float).ravel()
1391
+ if external.shape != (n,):
1392
+ raise ValueError(f"forces: one per degree of freedom ({n})")
1393
+
1394
+ def external_at(t: float) -> np.ndarray:
1395
+ return t * external
1396
+
1397
+ free = np.setdiff1d(np.arange(n), dofs)
1398
+ hist = self._new_state()
1399
+ if history is not None:
1400
+ history = np.asarray(history, dtype=float)
1401
+ if history.shape[:1] != hist.shape[:1] or history.shape not in (
1402
+ hist.shape[:1],
1403
+ hist.shape[:2],
1404
+ ):
1405
+ raise ValueError(
1406
+ "history: one value per interface element, or one per point "
1407
+ f"({hist.shape[0]} x {hist.shape[1]})"
1408
+ )
1409
+ hist[..., 0] = history if history.ndim == 2 else history[:, None]
1410
+ rubs = self.par[8] > 0.0 # a law with friction
1411
+ if initial is None:
1412
+ u, lam = np.zeros(n), 0.0
1413
+ if self.bulk is not None:
1414
+ self.bulk.reset()
1415
+ else:
1416
+ u = np.array(initial, dtype=float).ravel()
1417
+ if u.shape != (n,):
1418
+ raise ValueError(f"initial: a displacement of the {n // 3} nodes")
1419
+ lam = float(start)
1420
+ u[dofs] = values_at(lam)
1421
+ clock = 1.0 if duration is None else float(duration) / float(load)
1422
+ names = self._part_names()
1423
+ parts = tuple(np.zeros(n) for _ in names) # the forces of the parts at the last step
1424
+ applied_last = np.zeros(n)
1425
+ equilibration = 0
1426
+ self._begin(u, lam)
1427
+ if initial is not None and equilibrate:
1428
+ self._attempt(lam)
1429
+ self._dt = 1e-9 * clock * max(abs(load - lam), abs(load), 1e-30) / steps
1430
+ ok, equilibration, u, f, hist, load_now = self._newton(
1431
+ u, hist, dofs, free, external_at(lam)[free], 0.0, tol, max_newton
1432
+ )
1433
+ if not ok:
1434
+ raise RuntimeError(f"cohesive problem: no equilibrium of the state at load {lam:g}")
1435
+ if self.bulk is not None: # dissipating nothing: the dissipated energy kept
1436
+ dissipated = self.bulk.work - self.bulk.free_energy()
1437
+ self.bulk.commit()
1438
+ psi = self.bulk.free_energy()
1439
+ self.bulk.work[...] = np.where(np.isfinite(psi), dissipated + psi, self.bulk.work)
1440
+ parts = tuple(part.copy() for part in self._parts)
1441
+ applied_last[dofs] = f[dofs]
1442
+ applied_last[free] = load_now
1443
+ work = {"external": [0.0], "bulk": [0.0], "interfaces": [0.0]}
1444
+ work.update({name: [0.0] for name in names if name not in work})
1445
+ if rubs:
1446
+ work["friction"] = [0.0]
1447
+ loads, reactions, cracked, dmax, its, snaps = [lam], [], [0.0], [0.0], [equilibration], []
1448
+ reactions.append(
1449
+ np.array([[applied_last[s[s % 3 == c]].sum() for c in range(3)] for s in sets])
1450
+ )
1451
+ if fields:
1452
+ snaps.append(u.reshape(-1, 3).copy())
1453
+ span = (load - lam) / steps
1454
+ step = span
1455
+ cuts = 0
1456
+ while lam < load * (1 - 1e-12):
1457
+ step = min(step, load - lam)
1458
+ target = lam + step
1459
+ u_try = u.copy()
1460
+ u_try[dofs] = values_at(target)
1461
+ self._dt = step * clock
1462
+ rate = step / viscosity if viscosity > 0 else 0.0
1463
+ self._attempt(target)
1464
+ ok, iterations, u_try, f, hist_try, load_now = self._newton(
1465
+ u_try, hist, dofs, free, external_at(target)[free], rate, tol, max_newton
1466
+ )
1467
+ while ok and self._augment(): # solved again (the multipliers of a contact)
1468
+ ok, more, u_try, f, hist_try, load_now = self._newton(
1469
+ u_try, hist, dofs, free, external_at(target)[free], rate, tol, max_newton
1470
+ )
1471
+ iterations += more
1472
+ if not ok:
1473
+ cuts += 1
1474
+ if cuts > max_cuts:
1475
+ raise RuntimeError(f"cohesive problem: no convergence at load {target:g}")
1476
+ step *= 0.5
1477
+ continue
1478
+ du_step = u_try - u
1479
+ applied = np.zeros(n) # the reactions and the dead loads
1480
+ applied[dofs] = f[dofs]
1481
+ applied[free] = load_now
1482
+ work["external"].append(work["external"][-1] + 0.5 * (applied_last + applied) @ du_step)
1483
+ for name, now, before in zip(names, self._parts, parts, strict=True):
1484
+ work[name].append(work[name][-1] + 0.5 * (before + now) @ du_step)
1485
+ parts = tuple(part.copy() for part in self._parts)
1486
+ applied_last = applied
1487
+ if self.bulk is not None:
1488
+ self.bulk.commit()
1489
+ self._accept(u_try)
1490
+ u, hist, lam = u_try, hist_try, target
1491
+ if rubs:
1492
+ work["friction"].append(self._rubbed(hist))
1493
+ cuts = 0 # the divisions of one step only
1494
+ loads.append(lam)
1495
+ reactions.append(np.array([[f[s[s % 3 == c]].sum() for c in range(3)] for s in sets]))
1496
+ area, damage = self._cracked(hist)
1497
+ cracked.append(area)
1498
+ dmax.append(damage)
1499
+ its.append(iterations)
1500
+ if fields:
1501
+ snaps.append(u.reshape(-1, 3).copy())
1502
+ if iterations <= 4:
1503
+ step = min(step * 1.5, span)
1504
+ result = CohesiveResult(
1505
+ np.array(loads),
1506
+ np.array(reactions),
1507
+ np.array(cracked),
1508
+ np.array(dmax),
1509
+ np.array(its),
1510
+ hist[..., 0].copy(),
1511
+ self._damage_of(hist),
1512
+ u.reshape(-1, 3),
1513
+ snaps,
1514
+ time.perf_counter() - t0,
1515
+ {name: np.array(values) for name, values in work.items()},
1516
+ hist[..., 1:3].copy(),
1517
+ hist[..., 3].copy(),
1518
+ )
1519
+ result.equilibration = equilibration
1520
+ return result
1521
+
1522
+ def write(self, path, result: CohesiveResult, step: int = -1):
1523
+ """The bulk (``<path>.vtu``: the displacement of ``step`` with ``fields``, else the
1524
+ final one) and the interfaces (``<path>_interfaces.vtu``: wedges of six nodes with
1525
+ the damage of their points and its mean, and with a law that rubs the mean slip of
1526
+ their points and the energy that friction dissipated per unit area); returns both
1527
+ paths."""
1528
+ from pathlib import Path
1529
+
1530
+ from morphogen.io.meshes import write_vtu_tet
1531
+ from morphogen.io.vtk import write_vtu
1532
+
1533
+ path = Path(path)
1534
+ u = result.fields[step] if result.fields else result.displacement
1535
+ bulk = write_vtu_tet(path.with_suffix(".vtu"), self.mesh, point_data={"displacement": u})
1536
+ # wedges of the corners (the mid-edge nodes of faces of six nodes are left out)
1537
+ cells = np.hstack([self.interfaces.minus[:, :3], self.interfaces.plus[:, :3]])
1538
+ data = {"damage": result.damage @ self.interfaces.weights, "damage_points": result.damage}
1539
+ if self.par[8] > 0.0 and result.slip is not None: # the mean slip of the points
1540
+ data["slip"] = np.linalg.norm(result.slip, axis=2) @ self.interfaces.weights
1541
+ data["friction"] = result.friction @ self.interfaces.weights
1542
+ wedges = write_vtu(
1543
+ path.with_name(path.stem + "_interfaces.vtu"), self.mesh.nodes + u, cells, 13, data
1544
+ )
1545
+ return bulk, wedges
1546
+
1547
+
1548
+ # -- calibration and the double cantilever beam -------------------------------------------------
1549
+
1550
+
1551
+ def cohesive_zone_length(
1552
+ young: float, energy: float, strength: float, factor: float = 1.0
1553
+ ) -> float:
1554
+ """``l_cz = M E G / T²`` (``factor`` M: 1 after Hillerborg, 9π/32 after Rice for a
1555
+ bilinear law in mode I, 0.21 after Falk; Turon et al. 2007)."""
1556
+ return factor * young * energy / strength**2
1557
+
1558
+
1559
+ def turon_strength(young: float, energy: float, element_size: float, elements: int = 3) -> float:
1560
+ """The cohesive strength that keeps ``elements`` elements of size ``element_size`` in
1561
+ the cohesive zone (Turon, Dávila, Camanho & Costa 2007): ``sqrt(9π E G / (32 N_e
1562
+ l_e))``."""
1563
+ return math.sqrt(9 * math.pi * young * energy / (32 * elements * element_size))
1564
+
1565
+
1566
+ def dcb_beam_theory(
1567
+ young: float, poisson: float, width: float, arm: float, precrack: float, energy: float, opening
1568
+ ):
1569
+ """The corrected beam theory of the double cantilever beam (Williams 1989; Reeder et
1570
+ al.; Linke & Lammering 2023, eqs. 2 to 6): the load and the crack length against the
1571
+ opening ``opening`` of the loading line, for arms of thickness ``arm`` and ``width``
1572
+ of an isotropic material, a precrack ``precrack`` and the mode I fracture energy:
1573
+ ``P = 3 E I d / (2 (a + χ h)³)`` with ``a = a0`` until the crack grows, then ``a = (9 d² E
1574
+ I / (4 w G))^(1/4) - χ h``; ``χ = sqrt(E / (11 S) (3 - 2 (Γ / (1 + Γ))²))``, ``Γ = 1.18 E /
1575
+ S``."""
1576
+ d = np.asarray(opening, dtype=float)
1577
+ shear = young / (2 * (1 + poisson))
1578
+ gamma = 1.18 * young / shear
1579
+ chi = math.sqrt(young / (11 * shear) * (3 - 2 * (gamma / (1 + gamma)) ** 2))
1580
+ inertia = width * arm**3 / 12
1581
+ grown = (9 * d**2 * young * inertia / (4 * width * energy)) ** 0.25 - chi * arm
1582
+ crack = np.maximum(precrack, grown)
1583
+ load = 3 * young * inertia * d / (2 * (crack + chi * arm) ** 3)
1584
+ return load, crack
1585
+
1586
+
1587
+ def dcb_specimen(
1588
+ length: float, width: float, arm: float, precrack: float, size: float, order: int = 1
1589
+ ):
1590
+ """A double cantilever beam of two arms of thickness ``arm`` (``length`` x ``width``),
1591
+ meshed by six tetrahedra per voxel of edge ``size`` (of 4 nodes, or of 10 with ``order``
1592
+ 2), opened along its mid-plane: the mesh, the interface elements of the bonded part
1593
+ (beyond the precrack) and the node sets of the loading lines (``"top"``, ``"bottom"``:
1594
+ the nodes at ``x = 0`` on the mid-plane of each arm)."""
1595
+ from morphogen.homogenization.bloch import voxel_tet_mesh
1596
+ from morphogen.image import VoxelImage
1597
+
1598
+ shape = (round(length / size), max(1, round(width / size)), 2 * round(arm / size))
1599
+ if shape[2] % 4:
1600
+ raise ValueError("dcb_specimen: an even number of voxels across each arm")
1601
+ image = VoxelImage(np.zeros(shape, np.uint8), spacing=(size,) * 3, periodic=False)
1602
+ mesh = voxel_tet_mesh(image)
1603
+ if order == 2:
1604
+ mesh = mesh.quadratic()
1605
+ elif order != 1:
1606
+ raise ValueError("dcb_specimen: order 1 or 2")
1607
+ plane = shape[2] // 2 * size
1608
+ opened, interfaces = insert_interfaces(mesh, lambda c: np.abs(c[:, 2] - plane) < 1e-6 * size)
1609
+ bonded = interfaces.subset(interfaces.centroids(opened)[:, 0] > precrack)
1610
+ x = opened.nodes
1611
+ at_end = np.abs(x[:, 0]) < 1e-9 * size
1612
+ top = np.flatnonzero(at_end & (np.abs(x[:, 2] - 1.5 * plane) < 1e-6 * size))
1613
+ bottom = np.flatnonzero(at_end & (np.abs(x[:, 2] - 0.5 * plane) < 1e-6 * size))
1614
+ return opened, bonded, {"top": top, "bottom": bottom}