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,566 @@
1
+ """The toughness of the phases of a morphology and of the interfaces between them, and the
2
+ direction of each advance of a crack through them: the kink of the bulk against the
3
+ deflection along an interface ahead of the front (He & Hutchinson 1989), which turns cracks
4
+ along the weak interfaces of architectured materials (the brick-and-mortar of nacre, the
5
+ plies of Bouligand structures) and holds them back at tough phases.
6
+
7
+ *Toughness* (:class:`Toughness`): a critical energy release rate ``Γ`` (in the units of
8
+ ``G``) for each phase, that of its material, and for the interfaces between two phases (a
9
+ value per pair, or one for all; none: no interface criterion).
10
+
11
+ *Kinked factors* (Cotterell & Rice 1980): a kink of infinitesimal length at the angle ``θ``
12
+ (from the direction of propagation towards the normal of the crack) has to first order the
13
+ factors ``k_I(θ) = cos³(θ/2) K_I - 3 sin(θ/2) cos²(θ/2) K_II`` and ``k_II(θ) = sin(θ/2)
14
+ cos²(θ/2) K_I + cos(θ/2) (1 - 3 sin²(θ/2)) K_II``, the hoop and shear stresses of the
15
+ asymptotic field on the ray ``θ`` (:func:`kinked_factors`), and the energy release rate
16
+ ``G(θ) = (k_I² + k_II²) / E' + K_III² / 2μ`` (:func:`kinked_release_rate`; a kink whose
17
+ ``k_I`` would be negative is closed, its mode I releasing nothing; the tearing mode is
18
+ kept). ``k_II`` vanishes in the direction of the largest hoop stress (Erdogan & Sih), where
19
+ ``k_I`` is largest. A crack normal to an interface in pure mode I has ``G(±90°) = G(0) / 4``.
20
+
21
+ *Candidates* (:func:`advance_candidates`), in the plane of growth through the middle of the
22
+ front (straight fronts of :class:`~morphogen.fracture.mixed.KinkedCrack`):
23
+
24
+ * the bulk: the kink of the largest hoop stress (straight ahead with ``kink=False``), by one
25
+ increment; its toughness is that of the toughest solid phase met along it, the phase at the
26
+ front or a tougher one that the advance enters;
27
+ * the interfaces (:func:`interface_paths`), when the toughness has interfaces: where the front
28
+ lies on an interface (two of its phases within a quarter of an element of the front, ahead
29
+ of it) or meets one straight ahead within an increment, the chords of one increment from
30
+ that point along the interfaces running from it (to the transitions of the phases on the
31
+ circle of one increment around it, the phases on the two sides of the chord those of the
32
+ interface along it), in the senses within 90° of the direction of the crack: the crack
33
+ goes on to the interface and turns along it, and follows a curved interface by chords. A
34
+ chord along which the pair of phases changes, at a junction of interfaces (a head joint
35
+ meeting the interface between two layers of a brick-and-mortar), stops there, or, within
36
+ half an increment, the branches of the junction are the advances. Their toughness is that
37
+ of the interface.
38
+
39
+ The phases at points are those of the ``morphology`` of the toughness (exact for a
40
+ morphology of point queries), or those of the elements of the crack mesh containing them
41
+ (the interfaces of conforming meshes, or the staircases of the others). The bulk takes the
42
+ driving force of the crack (``G`` of the G-θ method, ``J_tip`` of an inelastic bulk), the
43
+ interfaces that driving force in the proportion of their first-order ``G(θ)`` to that of
44
+ the kink of the bulk, so that the choice between them is that of the first-order kinked
45
+ factors and the bulk alone is the growth without interfaces. The advance is the candidate of
46
+ the largest ratio ``G(θ) / Γ(θ)`` (:func:`choose_advance`; the bulk on a tie): an elastic
47
+ body grows at the load factor ``sqrt(Γ / G)`` of that candidate, an inelastic one once its
48
+ ratio reaches 1 (the driving force at the tip against the toughness of the phase at the
49
+ front, unless an interface ahead or a tougher phase within the increment rules the
50
+ advance).
51
+
52
+ *Deflection or penetration* (He & Hutchinson 1989): a crack normal to the interface of two
53
+ identical materials deflects into it, at ±90°, when ``Γ_interface / Γ_bulk`` is below
54
+ ``G(90°) / G(0) = 1/4`` (0.26 for the kinks of He & Hutchinson, α = β = 0), and goes through
55
+ it above. Once along an interface the crack follows it while that stays the most favourable:
56
+ along an interface parallel to the remote tension, in pure mode II, rather than kink back
57
+ into the bulk while ``Γ_interface / Γ_bulk < G(0) / G(-70.5°) = 3/4``.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import math
63
+ from dataclasses import dataclass, field
64
+ from typing import Any
65
+
66
+ import numpy as np
67
+
68
+ #: The senses of an interface kept: within 90° of the direction of the crack (and 5°)
69
+ _AHEAD = -math.sin(math.radians(5.0))
70
+ #: Points of the circles of the transitions of the phases (1.5°)
71
+ _CIRCLE = 240
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Toughness:
76
+ """The toughness of the phases and of their interfaces (see the module): ``phases`` one
77
+ value for every phase or a dict of the phases (``default``: that of the phases not in
78
+ it); ``interfaces`` None (no interface criterion), one value for every interface between
79
+ two solid phases, or a dict of pairs of phases (in either order; the pairs not in it: no
80
+ criterion); ``morphology``: the phases at points whose interfaces the advances follow (a
81
+ function of points, or a microstructure: :func:`~morphogen.fracture.lefm.phases_at`; by
82
+ default the phases of the elements of the crack meshes of a morphology)."""
83
+
84
+ phases: Any = 1.0
85
+ interfaces: Any = None
86
+ default: float | None = None
87
+ morphology: Any = field(default=None, compare=False, repr=False)
88
+
89
+ def __post_init__(self) -> None:
90
+ def positive(value, what: str) -> float:
91
+ value = float(value)
92
+ if not value > 0:
93
+ raise ValueError(f"Toughness: a positive toughness of {what}")
94
+ return value
95
+
96
+ if isinstance(self.phases, dict):
97
+ phases = {int(p): positive(v, f"the phase {p}") for p, v in self.phases.items()}
98
+ else:
99
+ phases = positive(self.phases, "the phases")
100
+ object.__setattr__(self, "phases", phases)
101
+ if self.default is not None:
102
+ object.__setattr__(self, "default", positive(self.default, "the other phases"))
103
+ interfaces = self.interfaces
104
+ if isinstance(interfaces, dict):
105
+ pairs = {}
106
+ for pair, value in interfaces.items():
107
+ a, b = (int(p) for p in pair)
108
+ if a == b:
109
+ raise ValueError("Toughness: an interface between two phases")
110
+ pairs[(min(a, b), max(a, b))] = positive(value, f"the interface {a}/{b}")
111
+ interfaces = pairs
112
+ elif interfaces is not None:
113
+ interfaces = positive(interfaces, "the interfaces")
114
+ object.__setattr__(self, "interfaces", interfaces)
115
+
116
+ @classmethod
117
+ def of(cls, value) -> Toughness | None:
118
+ """A toughness from None, a :class:`Toughness`, one value for all the phases or a
119
+ dict of the phases."""
120
+ if value is None or isinstance(value, Toughness):
121
+ return value
122
+ if isinstance(value, dict):
123
+ return cls(dict(value))
124
+ return cls(float(value))
125
+
126
+ @property
127
+ def uniform(self) -> bool:
128
+ """Whether it is one value for all the phases without interfaces: the toughness of
129
+ a homogeneous body, the growth without interfaces."""
130
+ if self.interfaces is not None:
131
+ return False
132
+ if not isinstance(self.phases, dict):
133
+ return True
134
+ values = set(self.phases.values()) | ({self.default} - {None})
135
+ return len(values) == 1
136
+
137
+ @property
138
+ def value(self) -> float:
139
+ """The toughness of a uniform toughness (:attr:`uniform`)."""
140
+ if not self.uniform:
141
+ raise ValueError("Toughness: not one value for all the phases")
142
+ if isinstance(self.phases, dict):
143
+ return next(iter(set(self.phases.values()) | ({self.default} - {None})))
144
+ return self.phases
145
+
146
+ def of_phase(self, phase: int) -> float:
147
+ """The toughness of a phase."""
148
+ if not isinstance(self.phases, dict):
149
+ return self.phases
150
+ if int(phase) in self.phases:
151
+ return self.phases[int(phase)]
152
+ if self.default is not None:
153
+ return self.default
154
+ raise KeyError(f"Toughness: none for the phase {phase} (a default)")
155
+
156
+ def of_interface(self, a: int, b: int) -> float | None:
157
+ """The toughness of the interface between two phases (None: no criterion)."""
158
+ if self.interfaces is None or int(a) == int(b):
159
+ return None
160
+ if not isinstance(self.interfaces, dict):
161
+ return self.interfaces
162
+ return self.interfaces.get((min(int(a), int(b)), max(int(a), int(b))))
163
+
164
+ def phases_at(self, points) -> np.ndarray:
165
+ """The phases of the ``morphology`` at points (rows): its point queries, or a voxel
166
+ image of it made once (:func:`~morphogen.fracture.lefm.phases_at`)."""
167
+ if self.morphology is None:
168
+ raise ValueError("Toughness: no morphology")
169
+ lookup = self.__dict__.get("_lookup")
170
+ if lookup is None:
171
+ lookup = _phase_function(self.morphology)
172
+ object.__setattr__(self, "_lookup", lookup)
173
+ return np.asarray(lookup(np.atleast_2d(np.asarray(points, dtype=float))), dtype=np.int64)
174
+
175
+
176
+ def _phase_function(morphology):
177
+ """The phases of a morphology at points: a function of points, the point queries of a
178
+ two-phase microstructure, or a voxel image of another made once (as
179
+ :func:`~morphogen.fracture.lefm.phases_at`)."""
180
+ from morphogen.fracture.lefm import phases_at
181
+
182
+ if callable(morphology) and not hasattr(morphology, "domain"):
183
+ return morphology
184
+ names = getattr(morphology, "phase_names", None) or {0: "0", 1: "1"}
185
+ if set(names) <= {0, 1}:
186
+ try:
187
+ morphology.contains(np.asarray(morphology.domain.lower, dtype=float)[None])
188
+ return lambda points: phases_at(morphology, points)
189
+ except NotImplementedError:
190
+ pass
191
+ lengths = np.asarray(morphology.domain.lengths, dtype=float)
192
+ image = morphology.voxelize(voxel_size=float(lengths.max()) / 128.0)
193
+ data = np.asarray(image.data)
194
+ if data.dtype.kind not in "iub":
195
+ raise ValueError("Toughness: the morphology gives no phase image")
196
+ origin = np.asarray(image.origin, dtype=float)
197
+ steps = np.asarray(image.spacing, dtype=float)
198
+ shape = np.asarray(data.shape)
199
+
200
+ def lookup(points):
201
+ index = np.clip(np.floor((points - origin) / steps).astype(np.int64), 0, shape - 1)
202
+ return data[index[:, 0], index[:, 1], index[:, 2]]
203
+
204
+ return lookup
205
+
206
+
207
+ def kinked_factors(k1, k2, angle):
208
+ """The stress intensity factors ``(k_I, k_II)`` of a kink of infinitesimal length at
209
+ ``angle`` (radians, from the direction of propagation towards the normal of the crack)
210
+ from a front of factors ``k1``, ``k2`` (Cotterell & Rice 1980, to first order)."""
211
+ half = 0.5 * np.asarray(angle, dtype=float)
212
+ c, s = np.cos(half), np.sin(half)
213
+ return c**3 * k1 - 3.0 * s * c**2 * k2, s * c**2 * k1 + c * (1.0 - 3.0 * s**2) * k2
214
+
215
+
216
+ def kinked_release_rate(k1, k2, k3, angle, e_prime: float, mu: float):
217
+ """The energy release rate ``G(θ) = (k_I² + k_II²) / E' + K_III² / 2μ`` of the kink at
218
+ ``angle`` (:func:`kinked_factors`; a negative ``k_I``, a closed kink, counts nothing)."""
219
+ a, b = kinked_factors(k1, k2, angle)
220
+ return (np.maximum(a, 0.0) ** 2 + b**2) / e_prime + k3**2 / (2.0 * mu)
221
+
222
+
223
+ @dataclass(frozen=True)
224
+ class Advance:
225
+ """A candidate advance of a crack (see the module): ``kind`` ``"bulk"`` or
226
+ ``"interface"``, the ``angle`` of its last segment from the last segment of the crack
227
+ (radians, towards its normal), the ``crack`` after it, the energy release rate ``G(θ)``
228
+ of its direction (``release_rate``), the toughness ``Γ(θ)`` it meets and what it meets
229
+ (``met``: the phase whose toughness it is, or the pair of phases of the interface)."""
230
+
231
+ kind: str
232
+ angle: float
233
+ crack: Any = field(repr=False)
234
+ release_rate: float
235
+ toughness: float
236
+ met: Any
237
+
238
+ @property
239
+ def ratio(self) -> float:
240
+ """``G(θ) / Γ(θ)``: the advance happens once it reaches 1."""
241
+ return self.release_rate / self.toughness
242
+
243
+ @property
244
+ def label(self) -> str:
245
+ """What the advance meets: a phase, or the interface ``p/q``."""
246
+ if self.kind == "interface":
247
+ return "/".join(str(p) for p in self.met)
248
+ return str(self.met)
249
+
250
+
251
+ # -- the phases in the plane of growth ------------------------------------------------------
252
+
253
+
254
+ class _Phases:
255
+ """The solid phase at points of a solved body (``-1``: a void phase, or outside the
256
+ body): that of the morphology of a ``toughness``, or of the element of the crack mesh
257
+ containing each point."""
258
+
259
+ def __init__(self, solution, toughness: Toughness):
260
+ mesh = solution.mesh
261
+ self.mesh = mesh
262
+ self.toughness = toughness if toughness.morphology is not None else None
263
+ self.voids = [int(p) for p, m in solution.materials.items() if getattr(m, "void", False)]
264
+ self.lower, self.upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
265
+ self._tree = None
266
+
267
+ def __call__(self, points) -> np.ndarray:
268
+ points = np.atleast_2d(np.asarray(points, dtype=float))
269
+ if self.toughness is not None:
270
+ labels = self.toughness.phases_at(points)
271
+ tol = 1e-9 * float(np.max(self.upper - self.lower))
272
+ inside = np.all((points >= self.lower - tol) & (points <= self.upper + tol), axis=1)
273
+ labels = np.where(inside, labels, -1)
274
+ else:
275
+ element = self._containing(points)
276
+ labels = np.where(element >= 0, self.mesh.phase[np.maximum(element, 0)], -1)
277
+ if self.voids:
278
+ labels = np.where(np.isin(labels, self.voids), -1, labels)
279
+ return labels
280
+
281
+ def _containing(self, points, tol: float = 1e-9) -> np.ndarray:
282
+ """The element containing each point (-1: none), among the elements of the nearest
283
+ centroids, 24 of them, then more for the points not found (the flat elements of a
284
+ crack along an interface have far centroids)."""
285
+ from scipy.spatial import cKDTree
286
+
287
+ x = self.mesh.nodes[self.mesh.elements[:, :4]]
288
+ if self._tree is None:
289
+ self._tree = cKDTree(x.mean(axis=1))
290
+ out = np.full(len(points), -1, dtype=np.int64)
291
+ todo = np.arange(len(points))
292
+ for k in (24, 128, 512):
293
+ count = min(k, self.mesh.n_elements)
294
+ _, near = self._tree.query(points[todo], k=count)
295
+ near = near.reshape(len(todo), count)
296
+ origin = x[near, 0]
297
+ edges = np.stack([x[near, 1] - origin, x[near, 2] - origin, x[near, 3] - origin],
298
+ axis=-1) # fmt: skip
299
+ local = np.linalg.solve(edges, (points[todo, None, :] - origin)[..., None])[..., 0]
300
+ smallest = np.minimum(local.min(axis=2), 1.0 - local.sum(axis=2))
301
+ best = np.argmax(smallest, axis=1)
302
+ rows = np.arange(len(todo))
303
+ found = smallest[rows, best] >= -tol
304
+ out[todo[found]] = near[rows, best][found]
305
+ todo = todo[~found]
306
+ if not len(todo) or count == self.mesh.n_elements:
307
+ break
308
+ return out
309
+
310
+
311
+ def _plane(crack, mesh):
312
+ """The point of the front in the middle of the body, the direction ``e`` of the last
313
+ segment and its normal ``n``: the plane of growth."""
314
+ lower, upper = mesh.nodes.min(axis=0), mesh.nodes.max(axis=0)
315
+ points, _ = crack.front(lower, upper, 64)
316
+ origin = points.mean(axis=0) if len(points) else np.asarray(crack.tip, dtype=float)
317
+ _, n, d, _, _ = crack.frame(origin[None])
318
+ return origin, d[0], n[0]
319
+
320
+
321
+ def _toughest_along(phases, toughness: Toughness, origin, direction, length: float, step: float):
322
+ """The toughest solid phase met along the segment from ``origin`` (left out) over
323
+ ``length`` in ``direction`` and its toughness (None, None: no solid phase)."""
324
+ s = np.arange(step, length + 0.5 * step, step)
325
+ labels = phases(origin + s[:, None] * direction)
326
+ met = np.unique(labels[labels >= 0])
327
+ if not len(met):
328
+ return None, None
329
+ values = [toughness.of_phase(int(p)) for p in met]
330
+ k = int(np.argmax(values))
331
+ return int(met[k]), float(values[k])
332
+
333
+
334
+ def _interface(toughness: Toughness, a, b) -> np.ndarray:
335
+ """Whether the phases ``a`` and ``b`` (arrays) are the two sides of an interface with a
336
+ toughness."""
337
+ out = (a != b) & (a >= 0) & (b >= 0)
338
+ for i in np.flatnonzero(out):
339
+ out[i] = toughness.of_interface(int(a[i]), int(b[i])) is not None
340
+ return out
341
+
342
+
343
+ def _bisect(phases, start, end, label, iterations: int = 14):
344
+ """The points between ``start`` (the phase ``label``) and ``end`` (another) where the
345
+ phase changes (rows), by bisection."""
346
+ lo, hi = np.array(start, dtype=float), np.array(end, dtype=float)
347
+ for _ in range(iterations):
348
+ mid = 0.5 * (lo + hi)
349
+ same = phases(mid) == label
350
+ lo = np.where(same[:, None], mid, lo)
351
+ hi = np.where(same[:, None], hi, mid)
352
+ return 0.5 * (lo + hi)
353
+
354
+
355
+ def _near(phases, toughness: Toughness, origin, e, n, radius: float) -> bool:
356
+ """Whether an interface with a toughness passes within ``radius`` of ``origin`` ahead
357
+ (within 90° of ``e``): two of its phases on a small circle around it."""
358
+ a = np.linspace(0.0, 2.0 * np.pi, 72, endpoint=False)
359
+ a = a[np.cos(a) >= _AHEAD]
360
+ points = origin + radius * (np.outer(np.cos(a), e) + np.outer(np.sin(a), n))
361
+ labels = np.unique(np.concatenate([phases(origin[None]), phases(points)]))
362
+ labels = [int(p) for p in labels if p >= 0]
363
+ return any(toughness.of_interface(p, q) is not None
364
+ for i, p in enumerate(labels) for q in labels[i + 1 :]) # fmt: skip
365
+
366
+
367
+ def _crossing(phases, toughness: Toughness, origin, e, n, reach: float, step: float, offsets):
368
+ """The distance along ``e`` (from ``origin`` displaced by each of ``offsets`` along
369
+ ``n``) of the first change of phase within ``reach`` between the two sides of an
370
+ interface with a toughness (None: none, or another change first)."""
371
+ s = np.arange(step, reach + 0.5 * step, step)
372
+ best = None
373
+ for b in offsets:
374
+ start = origin + b * n
375
+ labels = phases(start + s[:, None] * e)
376
+ change = np.flatnonzero(labels != labels[0])
377
+ if not len(change) or labels[0] < 0:
378
+ continue
379
+ k = int(change[0])
380
+ if not _interface(toughness, labels[k - 1 : k], labels[k : k + 1])[0]:
381
+ continue
382
+ point = _bisect(phases, (start + s[k - 1] * e)[None], (start + s[k] * e)[None],
383
+ labels[k - 1])[0] # fmt: skip
384
+ distance = float((point - origin) @ e)
385
+ best = distance if best is None else min(best, distance)
386
+ return best
387
+
388
+
389
+ def _sides(phases, toughness: Toughness, centre, u, across, distances, width: float):
390
+ """Along the chord from ``centre`` in the direction ``u``, at ``distances``: whether the
391
+ phases ``width`` apart on its two sides are those of an interface with a toughness, and
392
+ their pair (the smaller phase, the larger)."""
393
+ points = centre + np.outer(distances, u)
394
+ left, right = phases(points + width * across), phases(points - width * across)
395
+ return _interface(toughness, left, right), np.minimum(left, right), np.maximum(left, right)
396
+
397
+
398
+ def _branches(phases, toughness: Toughness, centre, e, n, radius: float, width: float):
399
+ """The interfaces running from ``centre`` (see the module): for each transition of the
400
+ phases on the circle of ``radius`` around it between the two sides of an interface with
401
+ a toughness, the unit direction ``u`` of the chord to it, the pair of phases of the
402
+ interface along the chord from ``centre`` (the phases ``width`` apart on its two sides),
403
+ the length of the advance along it and whether it ends at a junction: the chord, or its
404
+ part up to where that pair changes (another interface meets it, or it curves away)."""
405
+ a = np.linspace(0.0, 2.0 * np.pi, _CIRCLE, endpoint=False)
406
+ points = centre + radius * (np.outer(np.cos(a), e) + np.outer(np.sin(a), n))
407
+ labels = phases(points)
408
+ k = np.flatnonzero(_interface(toughness, labels, np.roll(labels, -1)))
409
+ if not len(k):
410
+ return []
411
+ ends = _bisect(phases, points[k], np.roll(points, -1, axis=0)[k], labels[k])
412
+ axis = np.cross(e, n)
413
+ t = np.arange(1, 17) / 16.0
414
+ out = []
415
+ for y in ends:
416
+ u = (y - centre) / np.linalg.norm(y - centre)
417
+ across = np.cross(axis, u) # the normal of the chord in the plane
418
+ valid, lo, hi = _sides(phases, toughness, centre, u, across, t * radius, width)
419
+ good = np.flatnonzero(valid & (t >= 0.1))
420
+ if not len(good) or good[0] > 2: # the chord does not start along an interface
421
+ continue
422
+ first = int(good[0])
423
+ pair = (int(lo[first]), int(hi[first]))
424
+ same = valid & (lo == pair[0]) & (hi == pair[1])
425
+ same[:first] = True
426
+ if same.all():
427
+ out.append((u, pair, radius, False))
428
+ continue
429
+ stop = int(np.argmin(same))
430
+ s0, s1 = t[stop - 1] * radius, t[stop] * radius
431
+ for _ in range(12): # where the pair changes
432
+ mid = 0.5 * (s0 + s1)
433
+ v, low, high = _sides(phases, toughness, centre, u, across, [mid], width)
434
+ if v[0] and (int(low[0]), int(high[0])) == pair:
435
+ s0 = mid
436
+ else:
437
+ s1 = mid
438
+ length = 0.5 * (s0 + s1)
439
+ if length >= 0.25 * radius:
440
+ out.append((u, pair, length, True))
441
+ return out
442
+
443
+
444
+ def _extended(crack, points):
445
+ """The crack grown through the points (in the plane of growth), a segment each."""
446
+ for p in points:
447
+ _, n, d, _, _ = crack.frame(crack.tip[None])
448
+ v = np.asarray(p, dtype=float) - crack.tip
449
+ a, b = float(v @ d[0]), float(v @ n[0])
450
+ length = math.hypot(a, b)
451
+ if length > 1e-9:
452
+ angle = math.atan2(b, a)
453
+ crack = crack.grown(length, angle if abs(angle) > 1e-12 else 0.0)
454
+ return crack
455
+
456
+
457
+ def interface_paths(solution, toughness, increment: float) -> list:
458
+ """The advances of the crack of a solved body along the interfaces within an
459
+ ``increment`` ahead of its front (see the module): ``(angle, crack, pair)`` for each, the
460
+ angle of its last segment from the last segment of the crack, the crack after it and the
461
+ pair of phases of the interface (none without interfaces in the toughness)."""
462
+ rule = Toughness.of(toughness)
463
+ if rule is None or rule.interfaces is None:
464
+ return []
465
+ crack, mesh = solution.crack, solution.mesh
466
+ if not hasattr(crack, "points"):
467
+ raise ValueError("interfaces: a straight front (a KinkedCrack)")
468
+ if rule.morphology is None and mesh.side is None:
469
+ raise ValueError("interfaces: a crack mesh of a morphology, or the morphology")
470
+ phases = _Phases(solution, rule)
471
+ origin, e, n = _plane(crack, mesh)
472
+ h = solution.element_size()
473
+ increment = float(increment)
474
+ on = 0.25 * min(h, increment)
475
+ step = min(h, increment) / 8.0
476
+ exact = rule.morphology is not None or "multi-material" in str(mesh.metadata.get("mesher"))
477
+ width = 0.15 * increment if exact else max(0.15 * increment, 0.5 * h) # staircases
478
+ # where the crack meets an interface: on it at the front, or straight ahead (a path to it)
479
+ starts = []
480
+ near = _near(phases, rule, origin, e, n, on)
481
+ if near:
482
+ starts.append((origin, (), e))
483
+ meet = _crossing(phases, rule, origin, e, n, increment, step, (on, -on) if near else (0.0,))
484
+ if meet is not None and meet > on:
485
+ starts.append((origin + meet * e, (origin + meet * e,), e))
486
+ out: list = []
487
+ while starts:
488
+ centre, approach, arrival = starts.pop(0)
489
+ for u, pair, length, junction in _branches(phases, rule, centre, e, n, increment, width):
490
+ if u @ arrival < _AHEAD: # within 90° of the direction of the crack
491
+ continue
492
+ end = centre + length * u
493
+ if junction and length < 0.5 * increment and len(approach) < 2:
494
+ starts.append((end, (*approach, end), u)) # a junction close ahead: its branches
495
+ continue
496
+ angle = math.atan2(float(u @ n), float(u @ e))
497
+ if any(p == pair and abs(math.remainder(angle - a, 2 * math.pi)) < math.radians(5.0)
498
+ for a, _, p in out): # fmt: skip
499
+ continue
500
+ grown = _extended(crack, (*approach, end))
501
+ # the lips are the faces behind the plane of the front: no path turned back on itself
502
+ if np.any(grown.psi(np.asarray(grown.points[:-1])) > 0.05 * step):
503
+ continue
504
+ out.append((angle, grown, pair))
505
+ return out
506
+
507
+
508
+ def advance_candidates(solution, toughness, increment: float, *, modes=None, driving=None,
509
+ kink: bool = True, paths=None) -> list[Advance]: # fmt: skip
510
+ """The candidate advances of the crack of a solved body by ``increment`` (see the
511
+ module): the bulk, and along the interfaces ahead (``paths``: those of
512
+ :func:`interface_paths`, computed by default). ``modes``: those of
513
+ :meth:`~morphogen.fracture.mixed.CrackSolution.modes` (computed by default); ``driving``:
514
+ the driving force of the bulk (by default ``G`` of the modes; ``J_tip`` of an inelastic
515
+ bulk); ``kink``: the bulk in the direction of the largest hoop stress, else straight."""
516
+ from morphogen.fracture.mixed import _isotropic_moduli
517
+
518
+ rule = Toughness.of(toughness)
519
+ if rule is None:
520
+ raise ValueError("advance_candidates: a toughness")
521
+ crack = solution.crack
522
+ if modes is None:
523
+ modes = solution.modes()
524
+ k = np.array([modes["K_I"], modes["K_II"], modes["K_III"]], dtype=float)
525
+ finite = bool(np.all(np.isfinite(k)))
526
+ angle = float(modes["angle"]) if kink and finite else 0.0
527
+ driving = float(modes["G"] if driving is None else driving)
528
+ grown = crack.grown(increment, angle)
529
+ if rule.uniform:
530
+ return [Advance("bulk", angle, grown, driving, rule.value, solution.front_phase())]
531
+ if rule.morphology is None and solution.mesh.side is None:
532
+ raise ValueError("a toughness per phase or of interfaces: a crack mesh of a morphology, "
533
+ "or the morphology") # fmt: skip
534
+ phases = _Phases(solution, rule)
535
+ origin, e, n = _plane(crack, solution.mesh)
536
+ h = solution.element_size()
537
+ step = min(h, float(increment)) / 8.0
538
+ direction = math.cos(angle) * e + math.sin(angle) * n
539
+ met, gamma = _toughest_along(phases, rule, origin, direction, float(increment), step)
540
+ if met is None: # nothing solid ahead (a pore): the phase at the front
541
+ met = solution.front_phase()
542
+ gamma = rule.of_phase(met)
543
+ out = [Advance("bulk", angle, grown, driving, gamma, met)]
544
+ if rule.interfaces is None or not finite:
545
+ return out
546
+ young, nu = _isotropic_moduli(solution.materials[solution.front_phase()])
547
+ e_prime, mu = young / (1.0 - nu**2), young / (2.0 * (1.0 + nu))
548
+ reference = float(kinked_release_rate(*k, angle, e_prime, mu))
549
+ if paths is None:
550
+ paths = interface_paths(solution, rule, increment)
551
+ for theta, path, pair in paths:
552
+ rate = float(kinked_release_rate(*k, theta, e_prime, mu))
553
+ rate = driving * rate / reference if reference > 0 else 0.0
554
+ out.append(Advance("interface", theta, path, rate, rule.of_interface(*pair), pair))
555
+ return out
556
+
557
+
558
+ def choose_advance(candidates) -> Advance:
559
+ """The candidate of the largest ratio ``G(θ) / Γ(θ)`` (the first, the bulk, on a tie)."""
560
+ best = None
561
+ for c in candidates:
562
+ if best is None or c.ratio > best.ratio * (1.0 + 1e-12):
563
+ best = c
564
+ if best is None:
565
+ raise ValueError("choose_advance: no candidate")
566
+ return best
morphogen/gpu.py ADDED
@@ -0,0 +1,108 @@
1
+ """Optional GPU backend (NVIDIA GPUs, through CuPy): the choice of the device.
2
+
3
+ The FFT solvers of voxel images run their conjugate gradients on the GPU with
4
+ ``device="gpu"`` (or ``"auto"``: the GPU when there is one): the stiffness operators of
5
+ the voxels, applied matrix-free, become CUDA kernels and the Fourier preconditioner cuFFT
6
+ transforms (:mod:`morphogen.homogenization.gpu`). Along loading paths the integration
7
+ points stay on the GPU, where their behaviours are integrated; the Newton iterations of
8
+ the periodic element stay on the CPU. CuPy and the CUDA libraries it needs (the runtime,
9
+ NVRTC and cuFFT, about 270 MB; no CUDA toolkit is needed) are optional::
10
+
11
+ pip install cupy-cuda13x "cuda-toolkit[cudart,nvrtc,cufft]==13.*"
12
+
13
+ (``cupy-cuda12x`` and ``cuda-toolkit[...]==12.*`` for drivers older than CUDA 13).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ from functools import lru_cache
21
+
22
+ DEVICES = ("cpu", "gpu", "auto")
23
+ INSTALL = 'pip install cupy-cuda13x "cuda-toolkit[cudart,nvrtc,cufft]==13.*"'
24
+
25
+ #: The libraries kept loaded for the life of the process (see :func:`_keep_nvrtc_builtins`)
26
+ _KEPT: list = []
27
+
28
+
29
+ @lru_cache(maxsize=1)
30
+ def _probe() -> tuple[bool, str]:
31
+ """Whether a CUDA device can be used through CuPy, and why not otherwise."""
32
+ try:
33
+ import cupy
34
+ except ImportError:
35
+ return False, f"CuPy is not installed ({INSTALL})"
36
+ try:
37
+ if cupy.cuda.runtime.getDeviceCount() < 1:
38
+ return False, "no CUDA device"
39
+ cupy.zeros(1).sum() # the runtime and the kernels work
40
+ except Exception as exc: # the driver, the runtime or NVRTC is missing
41
+ return False, f"CUDA is not usable: {exc}"
42
+ _keep_nvrtc_builtins(cupy)
43
+ return True, ""
44
+
45
+
46
+ def _keep_nvrtc_builtins(cupy) -> None:
47
+ """NVRTC's library of builtins kept loaded (Windows). NVRTC opens it by its name at
48
+ each compilation and closes it after; once another library of the process has narrowed
49
+ the search path of the DLLs (Gmsh's does, when it opens a file), the next compilation
50
+ fails ("failed to open nvrtc-builtins64_134.dll"), unless the library is already
51
+ loaded. It lies next to NVRTC's own, which CuPy has loaded."""
52
+ if sys.platform != "win32":
53
+ return
54
+ import ctypes
55
+ from ctypes import wintypes
56
+
57
+ try:
58
+ major, minor = cupy.cuda.nvrtc.getVersion()
59
+ except Exception: # an NVRTC that CuPy cannot reach: nothing to keep
60
+ return
61
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
62
+ kernel32.GetModuleHandleW.restype = wintypes.HMODULE
63
+ kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
64
+ kernel32.GetModuleFileNameW.argtypes = [wintypes.HMODULE, wintypes.LPWSTR, wintypes.DWORD]
65
+ nvrtc = kernel32.GetModuleHandleW(f"nvrtc64_{major}0_0.dll")
66
+ if not nvrtc:
67
+ return
68
+ name = ctypes.create_unicode_buffer(32768)
69
+ if not kernel32.GetModuleFileNameW(nvrtc, name, len(name)):
70
+ return
71
+ builtins = os.path.join(os.path.dirname(name.value), f"nvrtc-builtins64_{major}{minor}.dll")
72
+ if os.path.isfile(builtins):
73
+ _KEPT.append(ctypes.WinDLL(builtins))
74
+
75
+
76
+ def available() -> bool:
77
+ """Whether the GPU backend can run (CuPy, a CUDA device and its runtime)."""
78
+ return _probe()[0]
79
+
80
+
81
+ def device_of(name) -> str:
82
+ """The device that a choice ``"cpu"``, ``"gpu"`` or ``"auto"`` designates: ``"auto"``
83
+ is the GPU when it is available; ``"gpu"`` without one is an error."""
84
+ if name not in DEVICES:
85
+ raise ValueError(f"device: one of {DEVICES}, got {name!r}")
86
+ if name == "auto":
87
+ return "gpu" if available() else "cpu"
88
+ if name == "gpu" and not available():
89
+ raise RuntimeError(f"device 'gpu': {_probe()[1]}")
90
+ return name
91
+
92
+
93
+ def info() -> dict:
94
+ """The GPU and CuPy, or why the backend is not available."""
95
+ ok, why = _probe()
96
+ if not ok:
97
+ return {"gpu": None, "reason": why}
98
+ import cupy
99
+
100
+ props = cupy.cuda.runtime.getDeviceProperties(0)
101
+ name = props["name"]
102
+ return {
103
+ "gpu": name.decode() if isinstance(name, bytes) else str(name),
104
+ "memory_gb": round(props["totalGlobalMem"] / 2**30, 2),
105
+ "compute_capability": f"{props['major']}.{props['minor']}",
106
+ "cupy": cupy.__version__,
107
+ "cuda_runtime": cupy.cuda.runtime.runtimeGetVersion(),
108
+ }
@@ -0,0 +1,8 @@
1
+ """Graphical interface in the web browser (``morphogen gui``), served locally with the
2
+ standard library: generate realizations of any model from forms built on the
3
+ parameters' metadata, watch automata and growth processes form structures, optimize
4
+ periodic cells live, and explore the design space of tile assemblies."""
5
+
6
+ from morphogen.gui.server import serve
7
+
8
+ __all__ = ["serve"]