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,1739 @@
1
+ """Finite elements on conforming tetrahedral meshes (4-node and 10-node tetrahedra).
2
+
3
+ The unknown is the fluctuation ``w`` of ``u = E x + w`` (``T = G . x + w`` in
4
+ conduction), constrained by the boundary conditions of :mod:`morphogen.homogenization.core`:
5
+
6
+ ``kubc``
7
+ ``w = 0`` at the nodes of the faces of the box;
8
+ ``mixed``
9
+ the normal (or the prescribed shear) components of ``w`` vanish on the faces
10
+ concerned (Dirrenberger et al. 2014);
11
+ ``subc``
12
+ tractions ``Sigma n`` (heat flux ``Q . n``) on the faces of the box, rigid motions
13
+ removed by 3-2-1 supports;
14
+ ``periodic``
15
+ ``w`` takes the same value at a node of an upper face and at its image on the
16
+ lower face. :func:`morphogen.mesh.conforming.conforming_mesh` gives opposite faces
17
+ matching nodes for periodic microstructures, and the conditions are then exact. On
18
+ meshes with non-matching faces, the image value is interpolated with the shape
19
+ functions of the face element that contains it: an approximation (the patch test is
20
+ not passed exactly), reported in the log. On porous meshes whose opposite faces
21
+ differ (voxel meshes of a pore phase), a node whose image falls in a pore of the
22
+ opposite face lies on a free surface, and stays free.
23
+
24
+ Meshes of whole periodic cells (polycrystals, ``mesh.whole``) are bounded by pairs of
25
+ translated facets instead of the faces of the box: ``w`` takes the same value at the
26
+ translates of a node (``mesh.periodic_links()``), and the kinematic and static
27
+ conditions apply on that boundary (``mesh.outer_faces()``, with their own normals);
28
+ mixed conditions, defined on the faces of the box, need a mesh of the box.
29
+
30
+ Porous media are meshed without their pores (or their pore elements are discarded when
31
+ the pore phase is a void): averages are taken over the box with zero stress in the
32
+ pores, as for the FFT solver. Elements are integrated exactly: one point for 4-node
33
+ elements, four points for 10-node elements with straight edges.
34
+
35
+ The 10-node elements are isoparametric: a mid-edge node may leave the middle of its
36
+ edge (:func:`morphogen.mesh.curved.curved_mesh` puts those of the interfaces on the
37
+ implicit surfaces of the phases). Such an element is its straight tetrahedron moved by
38
+ ``sum_k N_k d_k``, with ``N_k`` the function of a mid-edge node and ``d_k`` its
39
+ departure from the middle of its edge: at an integration point, the gradients of the
40
+ shape functions are those of the straight element times the inverse of ``F = I + sum_k
41
+ d_k (x) grad N_k``, and the volume element is multiplied by ``det F``. Linear fields are
42
+ in the space of the elements whatever the departures (the elements pass the patch test
43
+ up to the four-point rule, exact for straight elements only).
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import logging
49
+ import time
50
+
51
+ import numpy as np
52
+ import scipy.sparse as sp
53
+ from numba import njit, prange
54
+ from scipy.spatial import cKDTree
55
+
56
+ from morphogen.homogenization.core import (
57
+ Loading,
58
+ MacroscopicLoadings,
59
+ PhaseStatistics,
60
+ Solution,
61
+ boundary_condition,
62
+ )
63
+ from morphogen.homogenization.elements import VOIGT, voigt_to_tensor
64
+ from morphogen.homogenization.materials import Material, material_table, transport_physics
65
+ from morphogen.homogenization.solvers import (
66
+ NEGLIGIBLE,
67
+ LinearSolver,
68
+ SolveInfo,
69
+ choose_method,
70
+ norm,
71
+ times,
72
+ )
73
+ from morphogen.mesh.tetra import TET_EDGES, TetMesh
74
+
75
+ log = logging.getLogger("morphogen")
76
+
77
+ _A, _B = 0.5854101966249685, 0.1381966011250105
78
+ GAUSS = {
79
+ 1: (np.array([[0.25, 0.25, 0.25, 0.25]]), np.array([1.0])),
80
+ 2: (
81
+ np.array([[_A, _B, _B, _B], [_B, _A, _B, _B], [_B, _B, _A, _B], [_B, _B, _B, _A]]),
82
+ np.full(4, 0.25),
83
+ ),
84
+ }
85
+ EDGES = np.ascontiguousarray(TET_EDGES, dtype=np.int64)
86
+ #: The integrations of the elastic problems: every point, or the volume change of each
87
+ #: element as its mean (10-node tetrahedra; :mod:`morphogen.homogenization.dilatation`)
88
+ INTEGRATIONS = ("full", "bbar")
89
+ #: Poisson's ratio from which a phase is nearly incompressible (a warning with ``full``)
90
+ NEARLY_INCOMPRESSIBLE = 0.49
91
+
92
+
93
+ def integration_of(value) -> str:
94
+ """The name of an integration: ``"full"``, or ``"bbar"`` (also written ``"reduced"``,
95
+ ``"selective"``, ``"b-bar"``, ``"f-bar"``)."""
96
+ name = "full" if value is None else str(value).lower().replace("-", "").replace("_", "")
97
+ name = {"reduced": "bbar", "selective": "bbar", "fbar": "bbar"}.get(name, name)
98
+ if name not in INTEGRATIONS:
99
+ raise ValueError(
100
+ "integration: 'full' or 'bbar' (the volume change of each element as its mean: "
101
+ f"selective reduced integration), got {value!r}"
102
+ )
103
+ return name
104
+
105
+
106
+ def nearly_incompressible(materials, phases, limit: float = NEARLY_INCOMPRESSIBLE) -> list[int]:
107
+ """The phases whose Poisson's ratio is at least ``limit`` (isotropic elastic
108
+ materials): those that lock the elements integrated at every point."""
109
+ out = []
110
+ for p in phases:
111
+ material = materials.get(int(p))
112
+ poisson = getattr(material, "poisson", None)
113
+ if material is not None and not material.void and poisson is not None:
114
+ if float(poisson) >= limit:
115
+ out.append(int(p))
116
+ return out
117
+
118
+
119
+ @njit(cache=True, inline="always")
120
+ def _corner_gradients(x, g):
121
+ """Gradients of the barycentric coordinates (4 x 3) and the volume of a tetrahedron."""
122
+ a00 = x[1, 0] - x[0, 0]
123
+ a01 = x[2, 0] - x[0, 0]
124
+ a02 = x[3, 0] - x[0, 0]
125
+ a10 = x[1, 1] - x[0, 1]
126
+ a11 = x[2, 1] - x[0, 1]
127
+ a12 = x[3, 1] - x[0, 1]
128
+ a20 = x[1, 2] - x[0, 2]
129
+ a21 = x[2, 2] - x[0, 2]
130
+ a22 = x[3, 2] - x[0, 2]
131
+ det = (
132
+ a00 * (a11 * a22 - a12 * a21)
133
+ - a01 * (a10 * a22 - a12 * a20)
134
+ + a02 * (a10 * a21 - a11 * a20)
135
+ )
136
+ inv = 1.0 / det
137
+ # rows of A^-1 are the gradients of L1, L2, L3
138
+ g[1, 0] = (a11 * a22 - a12 * a21) * inv
139
+ g[1, 1] = (a02 * a21 - a01 * a22) * inv
140
+ g[1, 2] = (a01 * a12 - a02 * a11) * inv
141
+ g[2, 0] = (a12 * a20 - a10 * a22) * inv
142
+ g[2, 1] = (a00 * a22 - a02 * a20) * inv
143
+ g[2, 2] = (a02 * a10 - a00 * a12) * inv
144
+ g[3, 0] = (a10 * a21 - a11 * a20) * inv
145
+ g[3, 1] = (a01 * a20 - a00 * a21) * inv
146
+ g[3, 2] = (a00 * a11 - a01 * a10) * inv
147
+ for d in range(3):
148
+ g[0, d] = -(g[1, d] + g[2, d] + g[3, d])
149
+ return det / 6.0
150
+
151
+
152
+ @njit(cache=True, inline="always")
153
+ def _shape_gradients(order, gl, bary, out):
154
+ """Gradients (n x 3) of the shape functions at a point of barycentric coordinates."""
155
+ if order == 1:
156
+ for a in range(4):
157
+ for d in range(3):
158
+ out[a, d] = gl[a, d]
159
+ return
160
+ for a in range(4):
161
+ f = 4.0 * bary[a] - 1.0
162
+ for d in range(3):
163
+ out[a, d] = f * gl[a, d]
164
+ for k in range(6):
165
+ i = EDGES[k, 0]
166
+ j = EDGES[k, 1]
167
+ for d in range(3):
168
+ out[4 + k, d] = 4.0 * (bary[i] * gl[j, d] + bary[j] * gl[i, d])
169
+
170
+
171
+ @njit(cache=True, inline="always")
172
+ def _geometry(nodes, elements, e, x, gl, dev):
173
+ """The corners ``x`` of element ``e``, the gradients ``gl`` of their barycentric
174
+ coordinates and, for a 10-node element, the departures ``dev`` (6 x 3) of its mid-edge
175
+ nodes from the middles of its straight edges. Returns the volume of the straight
176
+ tetrahedron and whether the element is curved (a departure beyond the round-off of
177
+ coordinates read from a file)."""
178
+ for a in range(4):
179
+ for d in range(3):
180
+ x[a, d] = nodes[elements[e, a], d]
181
+ vol = _corner_gradients(x, gl)
182
+ curved = False
183
+ if elements.shape[1] == 10:
184
+ for k in range(6):
185
+ i = EDGES[k, 0]
186
+ j = EDGES[k, 1]
187
+ m = elements[e, 4 + k]
188
+ length2 = 0.0
189
+ dev2 = 0.0
190
+ for d in range(3):
191
+ dv = nodes[m, d] - 0.5 * (x[i, d] + x[j, d])
192
+ dev[k, d] = dv
193
+ dev2 += dv * dv
194
+ length2 += (x[j, d] - x[i, d]) ** 2
195
+ if dev2 > 1e-20 * length2:
196
+ curved = True
197
+ return vol, curved
198
+
199
+
200
+ @njit(cache=True, inline="always")
201
+ def _point_gradients(order, curved, gl, dev, bary, out):
202
+ """Gradients (n x 3) of the shape functions of an element at a point of barycentric
203
+ coordinates, and the ratio of its volume element to that of its straight tetrahedron
204
+ (1 for a straight element). A curved 10-node element is the straight one moved by
205
+ ``sum_k N_k d_k`` (``N_k`` the function of a mid-edge node, ``d_k`` its departure):
206
+ with ``F = I + sum_k d_k (x) grad N_k``, the gradients are those of the straight
207
+ element times ``F^-1`` and the ratio is ``det F``."""
208
+ _shape_gradients(order, gl, bary, out)
209
+ if not curved:
210
+ return 1.0
211
+ f00 = 1.0
212
+ f01 = 0.0
213
+ f02 = 0.0
214
+ f10 = 0.0
215
+ f11 = 1.0
216
+ f12 = 0.0
217
+ f20 = 0.0
218
+ f21 = 0.0
219
+ f22 = 1.0
220
+ for k in range(6):
221
+ g0 = out[4 + k, 0]
222
+ g1 = out[4 + k, 1]
223
+ g2 = out[4 + k, 2]
224
+ f00 += dev[k, 0] * g0
225
+ f01 += dev[k, 0] * g1
226
+ f02 += dev[k, 0] * g2
227
+ f10 += dev[k, 1] * g0
228
+ f11 += dev[k, 1] * g1
229
+ f12 += dev[k, 1] * g2
230
+ f20 += dev[k, 2] * g0
231
+ f21 += dev[k, 2] * g1
232
+ f22 += dev[k, 2] * g2
233
+ c00 = f11 * f22 - f12 * f21
234
+ c01 = f02 * f21 - f01 * f22
235
+ c02 = f01 * f12 - f02 * f11
236
+ det = f00 * c00 + f10 * c01 + f20 * c02
237
+ inv = 1.0 / det
238
+ i00 = c00 * inv
239
+ i01 = c01 * inv
240
+ i02 = c02 * inv
241
+ i10 = (f12 * f20 - f10 * f22) * inv
242
+ i11 = (f00 * f22 - f02 * f20) * inv
243
+ i12 = (f02 * f10 - f00 * f12) * inv
244
+ i20 = (f10 * f21 - f11 * f20) * inv
245
+ i21 = (f01 * f20 - f00 * f21) * inv
246
+ i22 = (f00 * f11 - f01 * f10) * inv
247
+ for a in range(10):
248
+ g0 = out[a, 0]
249
+ g1 = out[a, 1]
250
+ g2 = out[a, 2]
251
+ out[a, 0] = g0 * i00 + g1 * i10 + g2 * i20
252
+ out[a, 1] = g0 * i01 + g1 * i11 + g2 * i21
253
+ out[a, 2] = g0 * i02 + g1 * i12 + g2 * i22
254
+ return det
255
+
256
+
257
+ @njit(cache=True, inline="always")
258
+ def _element_matrix(order, curved, gl, dev, vol, nd, d, gp, gw, grad, db, ke):
259
+ """Element matrix of a tetrahedron: conductivity tensor or elasticity matrix ``d``."""
260
+ nn = grad.shape[0]
261
+ ke[:, :] = 0.0
262
+ for g in range(gp.shape[0]):
263
+ w = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
264
+ if nd == 1:
265
+ for b in range(nn):
266
+ for i in range(3):
267
+ db[b, i, 0] = d[i, 0] * grad[b, 0] + d[i, 1] * grad[b, 1] + d[i, 2] * grad[b, 2]
268
+ for a in range(nn):
269
+ for b in range(nn):
270
+ ke[a, b] += w * (
271
+ grad[a, 0] * db[b, 0, 0]
272
+ + grad[a, 1] * db[b, 1, 0]
273
+ + grad[a, 2] * db[b, 2, 0]
274
+ )
275
+ continue
276
+ # D B_b (6 x 3) for each node, B_a^T (D B_b) for each pair
277
+ for b in range(nn):
278
+ gx, gy, gz = grad[b, 0], grad[b, 1], grad[b, 2]
279
+ for r in range(6):
280
+ db[b, r, 0] = d[r, 0] * gx + d[r, 4] * gz + d[r, 5] * gy
281
+ db[b, r, 1] = d[r, 1] * gy + d[r, 3] * gz + d[r, 5] * gx
282
+ db[b, r, 2] = d[r, 2] * gz + d[r, 3] * gy + d[r, 4] * gx
283
+ for a in range(nn):
284
+ gx, gy, gz = grad[a, 0], grad[a, 1], grad[a, 2]
285
+ for b in range(nn):
286
+ for c2 in range(3):
287
+ ke[3 * a, 3 * b + c2] += w * (
288
+ gx * db[b, 0, c2] + gz * db[b, 4, c2] + gy * db[b, 5, c2]
289
+ )
290
+ ke[3 * a + 1, 3 * b + c2] += w * (
291
+ gy * db[b, 1, c2] + gz * db[b, 3, c2] + gx * db[b, 5, c2]
292
+ )
293
+ ke[3 * a + 2, 3 * b + c2] += w * (
294
+ gz * db[b, 2, c2] + gy * db[b, 3, c2] + gx * db[b, 4, c2]
295
+ )
296
+
297
+
298
+ @njit(cache=True)
299
+ def _mean_dilatation_matrix(order, curved, gl, dev, vol, d, gp, gw, grad, db, ke, dp, c, q):
300
+ """Elasticity matrix of a tetrahedron whose volume change is its mean (``B``-bar: see
301
+ :mod:`morphogen.homogenization.dilatation`): with ``P = I - 1 (x) 1 / 3`` and the mean
302
+ ``c`` of the divergence operator over the element, ``sum_g w_g B_g^T (P D P) B_g + q_L
303
+ c^T + c q_R^T + k V c c^T / 9``, ``q = V B(c)^T (D 1 - k 1 / 3) / 3``, ``k = 1 . D
304
+ 1``."""
305
+ nn = grad.shape[0]
306
+ cm = np.empty(6)
307
+ mc = np.empty(6)
308
+ for r in range(6):
309
+ cm[r] = d[r, 0] + d[r, 1] + d[r, 2]
310
+ mc[r] = d[0, r] + d[1, r] + d[2, r]
311
+ k = cm[0] + cm[1] + cm[2]
312
+ for r in range(6):
313
+ mr = 1.0 if r < 3 else 0.0
314
+ for s in range(6):
315
+ ms = 1.0 if s < 3 else 0.0
316
+ dp[r, s] = d[r, s] - (cm[r] * ms + mr * mc[s]) / 3.0 + k * mr * ms / 9.0
317
+ _element_matrix(order, curved, gl, dev, vol, 3, dp, gp, gw, grad, db, ke)
318
+ total = 0.0
319
+ for b in range(nn):
320
+ for i in range(3):
321
+ c[3 * b + i] = 0.0
322
+ for g in range(gp.shape[0]):
323
+ w = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
324
+ total += w
325
+ for b in range(nn):
326
+ for i in range(3):
327
+ c[3 * b + i] += w * grad[b, i]
328
+ for r in range(6):
329
+ mr = 1.0 if r < 3 else 0.0
330
+ cm[r] = (cm[r] - k * mr / 3.0) / 3.0
331
+ mc[r] = (mc[r] - k * mr / 3.0) / 3.0
332
+ for b in range(nn):
333
+ gx, gy, gz = c[3 * b] / total, c[3 * b + 1] / total, c[3 * b + 2] / total
334
+ c[3 * b], c[3 * b + 1], c[3 * b + 2] = gx, gy, gz
335
+ # q_L = V B(c)^T v_L (the first three), q_R = V B(c)^T v_R (the last three)
336
+ q[3 * b] = total * (gx * cm[0] + gz * cm[4] + gy * cm[5])
337
+ q[3 * b + 1] = total * (gy * cm[1] + gz * cm[3] + gx * cm[5])
338
+ q[3 * b + 2] = total * (gz * cm[2] + gy * cm[3] + gx * cm[4])
339
+ q[3 * (nn + b)] = total * (gx * mc[0] + gz * mc[4] + gy * mc[5])
340
+ q[3 * (nn + b) + 1] = total * (gy * mc[1] + gz * mc[3] + gx * mc[5])
341
+ q[3 * (nn + b) + 2] = total * (gz * mc[2] + gy * mc[3] + gx * mc[4])
342
+ for a in range(3 * nn):
343
+ for b in range(3 * nn):
344
+ ke[a, b] += q[a] * c[b] + c[a] * q[3 * nn + b] + k * total * c[a] * c[b] / 9.0
345
+
346
+
347
+ @njit(cache=True)
348
+ def _fill(nodes, elements, order, nd, mat, matrices, gp, gw, indptr_n, indices_n, data, bbar):
349
+ """Add the element matrices into the CSR values (serial: elements share rows);
350
+ ``bbar``: those of the mean dilatation (elasticity)."""
351
+ n_el, nn = elements.shape
352
+ x = np.empty((4, 3))
353
+ gl = np.empty((4, 3))
354
+ dev = np.empty((6, 3))
355
+ grad = np.empty((nn, 3))
356
+ db = np.empty((nn, 6, 3))
357
+ ke = np.empty((nn * nd, nn * nd))
358
+ pos = np.empty((nn, nn), dtype=np.int64)
359
+ dp = np.empty((6, 6))
360
+ mean = np.empty(3 * nn) # of the divergence operator
361
+ rank = np.empty(6 * nn) # the vectors of the term of rank two
362
+ for e in range(n_el):
363
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
364
+ if bbar:
365
+ _mean_dilatation_matrix(
366
+ order, curved, gl, dev, vol, matrices[mat[e]], gp, gw, grad, db, ke, dp, mean, rank
367
+ )
368
+ else:
369
+ _element_matrix(order, curved, gl, dev, vol, nd, matrices[mat[e]], gp, gw, grad, db, ke)
370
+ for a in range(nn):
371
+ na = elements[e, a]
372
+ lo = indptr_n[na]
373
+ hi = indptr_n[na + 1]
374
+ for b in range(nn):
375
+ nb = elements[e, b]
376
+ # binary search of nb in the sorted neighbours of na
377
+ left, right = lo, hi
378
+ while left < right:
379
+ mid = (left + right) // 2
380
+ if indices_n[mid] < nb:
381
+ left = mid + 1
382
+ else:
383
+ right = mid
384
+ pos[a, b] = left - lo
385
+ for a in range(nn):
386
+ na = elements[e, a]
387
+ length = indptr_n[na + 1] - indptr_n[na]
388
+ for c in range(nd):
389
+ start = nd * nd * indptr_n[na] + c * nd * length
390
+ for b in range(nn):
391
+ p = pos[a, b]
392
+ for c2 in range(nd):
393
+ data[start + p * nd + c2] += ke[nd * a + c, nd * b + c2]
394
+
395
+
396
+ @njit(parallel=True, cache=True)
397
+ def _expand_columns(indptr_n, indices_n, nd):
398
+ """Dof-level column indices of the node-level pattern."""
399
+ n = indptr_n.size - 1
400
+ out = np.empty(nd * nd * indptr_n[-1], dtype=np.int64)
401
+ for na in prange(n):
402
+ length = indptr_n[na + 1] - indptr_n[na]
403
+ for c in range(nd):
404
+ start = nd * nd * indptr_n[na] + c * nd * length
405
+ for j in range(length):
406
+ nb = indices_n[indptr_n[na] + j]
407
+ for c2 in range(nd):
408
+ out[start + j * nd + c2] = nb * nd + c2
409
+ return out
410
+
411
+
412
+ N_ELASTIC = 27
413
+ N_THERMAL = 15
414
+
415
+
416
+ @njit(cache=True, inline="always")
417
+ def _strain(order, gl, bary, elements, e, u, grad, eps):
418
+ """Strain (engineering shears) at a point of the straight element ``e``."""
419
+ _shape_gradients(order, gl, bary, grad)
420
+ _strain_of(grad, elements, e, u, eps)
421
+
422
+
423
+ @njit(cache=True, inline="always")
424
+ def _strain_of(grad, elements, e, u, eps):
425
+ """Strain (engineering shears) of element ``e`` from the gradients of its shape
426
+ functions at a point."""
427
+ nn = elements.shape[1]
428
+ eps[:] = 0.0
429
+ for a in range(nn):
430
+ k = elements[e, a]
431
+ ux, uy, uz = u[3 * k], u[3 * k + 1], u[3 * k + 2]
432
+ gx, gy, gz = grad[a, 0], grad[a, 1], grad[a, 2]
433
+ eps[0] += gx * ux
434
+ eps[1] += gy * uy
435
+ eps[2] += gz * uz
436
+ eps[3] += gz * uy + gy * uz
437
+ eps[4] += gz * ux + gx * uz
438
+ eps[5] += gy * ux + gx * uy
439
+
440
+
441
+ @njit(cache=True, inline="always")
442
+ def _gradient_of(grad, elements, e, t, gt):
443
+ """Gradient of the potential in element ``e`` from the gradients of its shape
444
+ functions at a point."""
445
+ nn = elements.shape[1]
446
+ gt[:] = 0.0
447
+ for a in range(nn):
448
+ k = elements[e, a]
449
+ for d in range(3):
450
+ gt[d] += grad[a, d] * t[k]
451
+
452
+
453
+ @njit(cache=True, inline="always")
454
+ def _product(m, v, out):
455
+ n = v.shape[0]
456
+ for r in range(n):
457
+ s = 0.0
458
+ for c in range(n):
459
+ s += m[r, c] * v[c]
460
+ out[r] = s
461
+
462
+
463
+ N_ELASTIC = 27
464
+ N_THERMAL = 15
465
+
466
+
467
+ @njit(parallel=True, cache=True)
468
+ def _elastic_sums(nodes, elements, order, group, n_groups, mat, matrices, eigen, dt, u, gp, gw):
469
+ """Integrals over each group of the strain (tensor components), the stress
470
+ ``D (eps - dt alpha)``, the energy density ``sigma : (eps - dt alpha)`` and their
471
+ squares (``eigen[mat_e]``: the thermal strain of a unit change of temperature)."""
472
+ n_el, nn = elements.shape
473
+ n_chunks = min(max(n_el, 1), 256)
474
+ partial = np.zeros((n_chunks, n_groups, N_ELASTIC))
475
+ for ch in prange(n_chunks):
476
+ x = np.empty((4, 3))
477
+ gl = np.empty((4, 3))
478
+ dev = np.empty((6, 3))
479
+ grad = np.empty((nn, 3))
480
+ eps = np.empty(6)
481
+ mech = np.empty(6)
482
+ sig = np.empty(6)
483
+ for e in range(ch * n_el // n_chunks, (ch + 1) * n_el // n_chunks):
484
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
485
+ acc = partial[ch, group[e]]
486
+ dm = matrices[mat[e]]
487
+ for g in range(gp.shape[0]):
488
+ w = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
489
+ _strain_of(grad, elements, e, u, eps)
490
+ for r in range(6):
491
+ mech[r] = eps[r] - dt * eigen[mat[e], r]
492
+ _product(dm, mech, sig)
493
+ dens = 0.0
494
+ for r in range(6):
495
+ dens += sig[r] * mech[r]
496
+ for r in range(6):
497
+ et = eps[r] if r < 3 else 0.5 * eps[r]
498
+ acc[r] += w * et
499
+ acc[6 + r] += w * sig[r]
500
+ acc[13 + r] += w * et * et
501
+ acc[19 + r] += w * sig[r] * sig[r]
502
+ acc[12] += w * dens
503
+ acc[25] += w * dens * dens
504
+ acc[26] += w
505
+ return partial.sum(axis=0)
506
+
507
+
508
+ @njit(parallel=True, cache=True)
509
+ def _thermal_sums(nodes, elements, order, group, n_groups, mat, matrices, t, gp, gw):
510
+ n_el, nn = elements.shape
511
+ n_chunks = min(max(n_el, 1), 256)
512
+ partial = np.zeros((n_chunks, n_groups, N_THERMAL))
513
+ for ch in prange(n_chunks):
514
+ x = np.empty((4, 3))
515
+ gl = np.empty((4, 3))
516
+ dev = np.empty((6, 3))
517
+ grad = np.empty((nn, 3))
518
+ gt = np.empty(3)
519
+ q = np.empty(3)
520
+ for e in range(ch * n_el // n_chunks, (ch + 1) * n_el // n_chunks):
521
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
522
+ acc = partial[ch, group[e]]
523
+ km = matrices[mat[e]]
524
+ for g in range(gp.shape[0]):
525
+ w = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
526
+ _gradient_of(grad, elements, e, t, gt)
527
+ _product(km, gt, q)
528
+ dens = q[0] * gt[0] + q[1] * gt[1] + q[2] * gt[2]
529
+ for d in range(3):
530
+ flux = -q[d]
531
+ acc[d] += w * gt[d]
532
+ acc[3 + d] += w * flux
533
+ acc[7 + d] += w * gt[d] * gt[d]
534
+ acc[10 + d] += w * flux * flux
535
+ acc[6] += w * dens
536
+ acc[13] += w * dens * dens
537
+ acc[14] += w
538
+ return partial.sum(axis=0)
539
+
540
+
541
+ @njit(parallel=True, cache=True)
542
+ def _elastic_fields(nodes, elements, order, mat, matrices, eigen, dt, u, gp, gw):
543
+ """Element means of strain (tensor components), stress and energy density."""
544
+ n_el, nn = elements.shape
545
+ strain = np.zeros((n_el, 6))
546
+ stress = np.zeros((n_el, 6))
547
+ energy = np.zeros(n_el)
548
+ for e in prange(n_el):
549
+ x = np.empty((4, 3))
550
+ gl = np.empty((4, 3))
551
+ dev = np.empty((6, 3))
552
+ grad = np.empty((nn, 3))
553
+ eps = np.empty(6)
554
+ mech = np.empty(6)
555
+ sig = np.empty(6)
556
+ _, curved = _geometry(nodes, elements, e, x, gl, dev)
557
+ dm = matrices[mat[e]]
558
+ total = 0.0
559
+ for g in range(gp.shape[0]):
560
+ w = gw[g] * _point_gradients(order, curved, gl, dev, gp[g], grad)
561
+ _strain_of(grad, elements, e, u, eps)
562
+ for r in range(6):
563
+ mech[r] = eps[r] - dt * eigen[mat[e], r]
564
+ _product(dm, mech, sig)
565
+ total += w
566
+ for r in range(6):
567
+ strain[e, r] += w * (eps[r] if r < 3 else 0.5 * eps[r])
568
+ stress[e, r] += w * sig[r]
569
+ energy[e] += w * sig[r] * mech[r]
570
+ for r in range(6):
571
+ strain[e, r] /= total
572
+ stress[e, r] /= total
573
+ energy[e] /= total
574
+ return strain, stress, energy
575
+
576
+
577
+ @njit(cache=True)
578
+ def _thermal_forces(nodes, elements, order, mat, matrices, eigen, gp, gw):
579
+ """Nodal forces of a unit change of temperature, ``sum_e int B^T D alpha dV``, and
580
+ the norm of the element contributions (before they cancel between elements)."""
581
+ n_el, nn = elements.shape
582
+ out = np.zeros(3 * nodes.shape[0])
583
+ norm2 = 0.0
584
+ x = np.empty((4, 3))
585
+ gl = np.empty((4, 3))
586
+ dev = np.empty((6, 3))
587
+ grad = np.empty((nn, 3))
588
+ sig = np.empty(6)
589
+ for e in range(n_el):
590
+ a = eigen[mat[e]]
591
+ if a[0] == 0.0 and a[1] == 0.0 and a[2] == 0.0 and a[3] == 0.0 and a[4] == 0.0:
592
+ if a[5] == 0.0:
593
+ continue
594
+ vol, curved = _geometry(nodes, elements, e, x, gl, dev)
595
+ _product(matrices[mat[e]], a, sig)
596
+ for g in range(gp.shape[0]):
597
+ w = gw[g] * vol * _point_gradients(order, curved, gl, dev, gp[g], grad)
598
+ for b in range(nn):
599
+ k = elements[e, b]
600
+ gx, gy, gz = grad[b, 0], grad[b, 1], grad[b, 2]
601
+ fx = w * (gx * sig[0] + gz * sig[4] + gy * sig[5])
602
+ fy = w * (gy * sig[1] + gz * sig[3] + gx * sig[5])
603
+ fz = w * (gz * sig[2] + gy * sig[3] + gx * sig[4])
604
+ out[3 * k] += fx
605
+ out[3 * k + 1] += fy
606
+ out[3 * k + 2] += fz
607
+ norm2 += fx * fx + fy * fy + fz * fz
608
+ return out, np.sqrt(norm2)
609
+
610
+
611
+ @njit(parallel=True, cache=True)
612
+ def _thermal_fields(nodes, elements, order, mat, matrices, t, gp, gw):
613
+ """Element means of the temperature gradient, heat flux and dissipation density."""
614
+ n_el, nn = elements.shape
615
+ grad = np.zeros((n_el, 3))
616
+ flux = np.zeros((n_el, 3))
617
+ dissipation = np.zeros(n_el)
618
+ for e in prange(n_el):
619
+ x = np.empty((4, 3))
620
+ gl = np.empty((4, 3))
621
+ dev = np.empty((6, 3))
622
+ shape_grad = np.empty((nn, 3))
623
+ gt = np.empty(3)
624
+ q = np.empty(3)
625
+ _, curved = _geometry(nodes, elements, e, x, gl, dev)
626
+ km = matrices[mat[e]]
627
+ total = 0.0
628
+ for g in range(gp.shape[0]):
629
+ w = gw[g] * _point_gradients(order, curved, gl, dev, gp[g], shape_grad)
630
+ _gradient_of(shape_grad, elements, e, t, gt)
631
+ _product(km, gt, q)
632
+ total += w
633
+ for d in range(3):
634
+ grad[e, d] += w * gt[d]
635
+ flux[e, d] -= w * q[d]
636
+ dissipation[e] += w * q[d] * gt[d]
637
+ for d in range(3):
638
+ grad[e, d] /= total
639
+ flux[e, d] /= total
640
+ dissipation[e] /= total
641
+ return grad, flux, dissipation
642
+
643
+
644
+ @njit(cache=True)
645
+ def _node_elements(elements, n_nodes):
646
+ """Elements around each node (CSR: pointers, element indices)."""
647
+ n_el, nn = elements.shape
648
+ ptr = np.zeros(n_nodes + 1, dtype=np.int64)
649
+ for e in range(n_el):
650
+ for a in range(nn):
651
+ ptr[elements[e, a] + 1] += 1
652
+ for i in range(n_nodes):
653
+ ptr[i + 1] += ptr[i]
654
+ fill = ptr[:-1].copy()
655
+ idx = np.empty(ptr[-1], dtype=np.int64)
656
+ for e in range(n_el):
657
+ for a in range(nn):
658
+ node = elements[e, a]
659
+ idx[fill[node]] = e
660
+ fill[node] += 1
661
+ return ptr, idx
662
+
663
+
664
+ @njit(cache=True, inline="always")
665
+ def _neighbours(elements, ptr, idx, i, buf):
666
+ """Sorted distinct nodes of the elements around node ``i`` (in ``buf``); count."""
667
+ nn = elements.shape[1]
668
+ c = 0
669
+ for q in range(ptr[i], ptr[i + 1]):
670
+ e = idx[q]
671
+ for a in range(nn):
672
+ buf[c] = elements[e, a]
673
+ c += 1
674
+ view = buf[:c]
675
+ view.sort()
676
+ u = 0
677
+ for j in range(c):
678
+ if j == 0 or view[j] != view[j - 1]:
679
+ buf[u] = view[j]
680
+ u += 1
681
+ return u
682
+
683
+
684
+ @njit(parallel=True, cache=True)
685
+ def _pattern(elements, ptr, idx, n_nodes):
686
+ nn = elements.shape[1]
687
+ lengths = np.zeros(n_nodes, dtype=np.int64)
688
+ for i in prange(n_nodes):
689
+ buf = np.empty((ptr[i + 1] - ptr[i]) * nn, dtype=np.int64)
690
+ lengths[i] = _neighbours(elements, ptr, idx, i, buf)
691
+ indptr = np.zeros(n_nodes + 1, dtype=np.int64)
692
+ for i in range(n_nodes):
693
+ indptr[i + 1] = indptr[i] + lengths[i]
694
+ indices = np.empty(indptr[-1], dtype=np.int64)
695
+ for i in prange(n_nodes):
696
+ buf = np.empty((ptr[i + 1] - ptr[i]) * nn, dtype=np.int64)
697
+ u = _neighbours(elements, ptr, idx, i, buf)
698
+ indices[indptr[i] : indptr[i] + u] = buf[:u]
699
+ return indptr, indices
700
+
701
+
702
+ def node_pattern(elements: np.ndarray, n_nodes: int) -> tuple[np.ndarray, np.ndarray]:
703
+ """Node-level CSR pattern (row pointers, sorted column indices) of a mesh."""
704
+ elements = np.ascontiguousarray(elements, dtype=np.int64)
705
+ ptr, idx = _node_elements(elements, n_nodes)
706
+ return _pattern(elements, ptr, idx, n_nodes)
707
+
708
+
709
+ #: The elements of a colour are shared between the threads by chunks: this many at most
710
+ #: (their work arrays are allocated once for each, before the loops)
711
+ CHUNKS = 64
712
+
713
+
714
+ @njit(cache=True)
715
+ def _element_colours(elements, ptr, idx):
716
+ """Greedy colouring of the elements (``ptr``, ``idx``: those around each node): each
717
+ takes the smallest colour that the elements before it with a node of its own do not
718
+ have. Returns the elements sorted by colour (in their order within a colour) and
719
+ the offsets of the colours in that list."""
720
+ n_el, nn = elements.shape
721
+ colour = np.full(n_el, -1, dtype=np.int64)
722
+ most = 0
723
+ for i in range(ptr.size - 1):
724
+ most = max(most, ptr[i + 1] - ptr[i])
725
+ taken = np.full(nn * most + 2, -1, dtype=np.int64) # the element that last met a colour
726
+ count = 0
727
+ for e in range(n_el):
728
+ for a in range(nn):
729
+ node = elements[e, a]
730
+ for q in range(ptr[node], ptr[node + 1]):
731
+ c = colour[idx[q]]
732
+ if c >= 0:
733
+ taken[c] = e
734
+ c = 0
735
+ while taken[c] == e:
736
+ c += 1
737
+ colour[e] = c
738
+ count = max(count, c + 1)
739
+ starts = np.zeros(count + 1, dtype=np.int64)
740
+ for e in range(n_el):
741
+ starts[colour[e] + 1] += 1
742
+ for c in range(count):
743
+ starts[c + 1] += starts[c]
744
+ order = np.empty(n_el, dtype=np.int64)
745
+ place = starts[:count].copy()
746
+ for e in range(n_el):
747
+ order[place[colour[e]]] = e
748
+ place[colour[e]] += 1
749
+ return order, starts
750
+
751
+
752
+ @njit(cache=True)
753
+ def chunk_slots(colours):
754
+ """The offsets of the chunks of each colour (:data:`CHUNKS` at most, one element at
755
+ least) in the list of all the chunks: the place of the sums of each chunk, added in
756
+ this order whatever the number of threads."""
757
+ slots = np.zeros(colours.size, dtype=np.int64)
758
+ for c in range(colours.size - 1):
759
+ slots[c + 1] = slots[c] + min(colours[c + 1] - colours[c], CHUNKS)
760
+ return slots
761
+
762
+
763
+ def element_colours(elements: np.ndarray, n_nodes: int) -> tuple[np.ndarray, np.ndarray]:
764
+ """The elements of a mesh sorted by colour, and the offsets of the colours in that
765
+ list: two elements of a colour have no node in common. The loops that add the
766
+ contributions of the elements at their nodes (a stiffness, nodal forces) take the
767
+ elements of a colour in parallel, without two threads writing at one place, and
768
+ each place receives the contributions of its elements colour by colour: the same
769
+ sums for any number of threads."""
770
+ elements = np.ascontiguousarray(elements, dtype=np.int64)
771
+ ptr, idx = _node_elements(elements, n_nodes)
772
+ return _element_colours(elements, ptr, idx)
773
+
774
+
775
+ def assemble(mesh: TetMesh, nd: int, mat, matrices, integration: str = "full") -> sp.csr_matrix:
776
+ """Global matrix (all nodes and components) of a tetrahedral mesh: element ``e``
777
+ has the elasticity matrix (``nd = 3``) or conductivity tensor (``nd = 1``)
778
+ ``matrices[mat[e]]``. ``integration``: ``"bbar"`` takes the volume change of each
779
+ 10-node tetrahedron as its mean (elasticity; :data:`INTEGRATIONS`)."""
780
+ bbar = integration_of(integration) == "bbar" and nd == 3 and mesh.order == 2
781
+ indptr_n, indices_n = node_pattern(mesh.elements, mesh.n_nodes)
782
+ gp, gw = GAUSS[mesh.order]
783
+ data = np.zeros(nd * nd * indptr_n[-1])
784
+ _fill(
785
+ mesh.nodes,
786
+ mesh.elements,
787
+ mesh.order,
788
+ nd,
789
+ np.ascontiguousarray(mat, dtype=np.int64),
790
+ np.ascontiguousarray(matrices, dtype=float),
791
+ gp,
792
+ gw,
793
+ indptr_n,
794
+ indices_n,
795
+ data,
796
+ bbar,
797
+ )
798
+ indices = _expand_columns(indptr_n, indices_n, nd)
799
+ lengths = np.repeat(np.diff(indptr_n) * nd, nd)
800
+ indptr = np.zeros(nd * mesh.n_nodes + 1, dtype=np.int64)
801
+ np.cumsum(lengths, out=indptr[1:])
802
+ if indptr[-1] < 2**31 - 1:
803
+ indices, indptr = indices.astype(np.int32), indptr.astype(np.int32)
804
+ n = nd * mesh.n_nodes
805
+ return sp.csr_matrix((data, indices, indptr), shape=(n, n))
806
+
807
+
808
+ def _face_weights(order: int, bary: np.ndarray) -> np.ndarray:
809
+ """Shape functions of a 3- or 6-node triangle at barycentric coordinates (k x 3)."""
810
+ if order == 1:
811
+ return bary
812
+ l0, l1, l2 = bary[:, 0], bary[:, 1], bary[:, 2]
813
+ return np.stack(
814
+ [
815
+ l0 * (2 * l0 - 1),
816
+ l1 * (2 * l1 - 1),
817
+ l2 * (2 * l2 - 1),
818
+ 4 * l0 * l1,
819
+ 4 * l1 * l2,
820
+ 4 * l2 * l0,
821
+ ],
822
+ axis=1,
823
+ )
824
+
825
+
826
+ @njit(parallel=True, cache=True)
827
+ def _places(indptr, indices, column, r_indptr, r_indices, place):
828
+ """The place in a reduced matrix (CSR pattern ``r_indptr``, ``r_indices``, its rows
829
+ sorted) of each stored value of a matrix (``indptr``, ``indices``): row and column
830
+ are those of the reduced unknowns ``column`` of its own (-1: none, no place)."""
831
+ for i in prange(indptr.size - 1):
832
+ a = column[i]
833
+ for k in range(indptr[i], indptr[i + 1]):
834
+ b = column[indices[k]]
835
+ found = -1
836
+ if a >= 0 and b >= 0:
837
+ lo, hi = r_indptr[a], r_indptr[a + 1]
838
+ while lo < hi:
839
+ mid = (lo + hi) // 2
840
+ if r_indices[mid] < b:
841
+ lo = mid + 1
842
+ else:
843
+ hi = mid
844
+ found = lo
845
+ place[k] = found
846
+
847
+
848
+ @njit(cache=True)
849
+ def _sources(indptr, indices, place, weight, weighted, n_out):
850
+ """The stored values of ``K`` that go to each place of the reduced matrix (their
851
+ indices, in their order, and the offsets of the places in that list), with the
852
+ product of the values of ``T`` of their row and of their column when these are not
853
+ all ones (``weighted``)."""
854
+ offsets = np.zeros(n_out + 1, dtype=np.int64)
855
+ for k in range(place.size):
856
+ if place[k] >= 0:
857
+ offsets[place[k] + 1] += 1
858
+ for p in range(n_out):
859
+ offsets[p + 1] += offsets[p]
860
+ sources = np.empty(offsets[n_out], dtype=place.dtype)
861
+ factors = np.empty(offsets[n_out] if weighted else 1)
862
+ fill = offsets[:n_out].copy()
863
+ for i in range(indptr.size - 1):
864
+ for k in range(indptr[i], indptr[i + 1]):
865
+ p = place[k]
866
+ if p >= 0:
867
+ sources[fill[p]] = k
868
+ if weighted:
869
+ factors[fill[p]] = weight[i] * weight[indices[k]]
870
+ fill[p] += 1
871
+ return offsets, sources, factors
872
+
873
+
874
+ @njit(parallel=True, cache=True)
875
+ def _gather(offsets, sources, factors, weighted, data, out):
876
+ """``out = T^T K T``: at each place of the reduced matrix, the sum of the stored
877
+ values of ``K`` (``data``) that go there, in their order (:func:`_sources`); the
878
+ places are shared between the threads."""
879
+ for p in prange(out.size):
880
+ s = 0.0
881
+ for q in range(offsets[p], offsets[p + 1]):
882
+ if weighted:
883
+ s += factors[q] * data[sources[q]]
884
+ else:
885
+ s += data[sources[q]]
886
+ out[p] = s
887
+
888
+
889
+ class Reduction:
890
+ """The reduced matrices ``T^T K T`` of the matrices ``K`` of one pattern, for a
891
+ reduction ``T`` that has one stored value per row at most (periodic faces that match,
892
+ kinematic conditions): each stored value of ``K`` goes to one place of the reduced
893
+ matrix, found once (:func:`_places`), and each place sums the values that go there
894
+ (:func:`_gather`, on several threads). The tangent of a loading path is reduced at
895
+ each linearization; the two products of sparse matrices and their conversions take
896
+ much longer. The reduced matrices share the arrays of their pattern. :meth:`of`
897
+ returns none for a ``T`` whose rows interpolate several unknowns (periodic faces
898
+ that do not match)."""
899
+
900
+ def __init__(self, t: sp.csr_matrix, indptr: np.ndarray, indices: np.ndarray):
901
+ n_rows, n_red = t.shape
902
+ has = np.diff(t.indptr) == 1
903
+ column = np.full(n_rows, -1, dtype=np.int64)
904
+ column[has] = t.indices
905
+ self.weight = np.zeros(n_rows)
906
+ self.weight[has] = t.data
907
+ self.weighted = bool(np.any(t.data != 1.0))
908
+ # the pattern of the reduced matrix: that of the product for a K of ones
909
+ ones = sp.csr_matrix((np.ones(indices.size), indices, indptr), shape=(n_rows, n_rows))
910
+ pattern = (t.T @ ones @ t).tocsr()
911
+ pattern.sum_duplicates()
912
+ pattern.sort_indices()
913
+ self.shape = (n_red, n_red)
914
+ self.indptr, self.indices = pattern.indptr, pattern.indices
915
+ small = max(pattern.nnz, indices.size) < 2**31 - 1
916
+ place = np.empty(indices.size, dtype=np.int32 if small else np.int64)
917
+ _places(indptr, indices, column, self.indptr, self.indices, place)
918
+ self._sources = _sources(indptr, indices, place, self.weight, self.weighted, pattern.nnz)
919
+
920
+ @classmethod
921
+ def of(cls, t, indptr, indices) -> Reduction | None:
922
+ t = sp.csr_matrix(t)
923
+ t.sum_duplicates()
924
+ if t.nnz and int(np.diff(t.indptr).max()) > 1:
925
+ return None
926
+ return cls(t, indptr, indices)
927
+
928
+ def __call__(self, data: np.ndarray) -> sp.csr_matrix:
929
+ """``T^T K T`` for the stored values ``data`` of ``K``."""
930
+ out = np.empty(self.indices.size)
931
+ _gather(*self._sources, self.weighted, np.ascontiguousarray(data, dtype=float), out)
932
+ reduced = sp.csr_matrix((out, self.indices, self.indptr), shape=self.shape)
933
+ reduced.has_sorted_indices = True
934
+ return reduced
935
+
936
+
937
+ def periodic_map(mesh: TetMesh) -> tuple[sp.csr_matrix, np.ndarray, dict]:
938
+ """Matrix T (nodes x masters) with ``w = T w_masters`` for periodic fluctuations.
939
+
940
+ Nodes of the upper faces are slaves. A slave with an image node on the lower face
941
+ takes its value; the others are interpolated in the lower face element containing
942
+ their image. A node whose image lies off the elements of the lower face, farther than
943
+ a quarter of the longest edge of the nearest of them, is on a free surface: the
944
+ material of the cell meets a pore of the next one there (porous voxel meshes whose
945
+ opposite faces differ), and it stays free, unless another node lies at its place
946
+ modulo the periods (an image through an edge or a corner of the box), whose class it
947
+ joins. Returns T, the master nodes and the counts ``matched`` and ``interpolated`` of
948
+ slave nodes, ``outside``: interpolated nodes found just outside the lower face (the
949
+ nearest element is used), and ``free``: the nodes of the upper faces left free. Whole
950
+ periodic cells: the translates of a node take its value.
951
+ """
952
+ n = mesh.n_nodes
953
+ if mesh.whole: # translates of the nodes of the boundary: their first node
954
+ slave, master, _ = mesh.periodic_links()
955
+ target = np.arange(n)
956
+ target[slave] = master
957
+ masters = np.flatnonzero(target == np.arange(n))
958
+ position = np.full(n, -1)
959
+ position[masters] = np.arange(masters.size)
960
+ t = sp.csr_matrix((np.ones(n), (np.arange(n), position[target])), shape=(n, masters.size))
961
+ counts = {"matched": int(slave.size), "interpolated": 0, "outside": 0, "free": 0}
962
+ return t, masters, counts
963
+ rows, cols, vals = [], [], []
964
+ slave_of = np.full(n, -1)
965
+ freed = np.zeros(n, dtype=bool)
966
+ outside = 0
967
+ n_matched = 0
968
+ n_interpolated = 0
969
+ for axis in range(3):
970
+ upper = mesh.face_nodes(axis, 1)
971
+ faces = mesh.boundary_faces(axis, 0)
972
+ if upper.size == 0:
973
+ continue
974
+ if faces.size == 0:
975
+ raise ValueError(
976
+ f"periodic conditions: the lower face normal to axis {axis} carries no "
977
+ "element while the upper one does"
978
+ )
979
+ keep = slave_of[upper] < 0 # each node is the slave of its first upper face
980
+ upper = upper[keep]
981
+ slave_of[upper] = axis
982
+ freed[upper] = False
983
+ others = [d for d in range(3) if d != axis]
984
+ # nodes with an image node on the lower face (matching meshes): weight 1
985
+ lower = np.unique(faces)
986
+ dist, near = cKDTree(mesh.nodes[lower][:, others]).query(mesh.nodes[upper][:, others])
987
+ matched = dist <= 1e-7 * float(np.max(mesh.size))
988
+ rows.append(upper[matched])
989
+ cols.append(lower[near[matched]])
990
+ vals.append(np.ones(int(matched.sum())))
991
+ n_matched += int(matched.sum())
992
+ upper = upper[~matched]
993
+ if upper.size == 0:
994
+ continue
995
+ corners = mesh.nodes[faces[:, :3]][:, :, others] # (k, 3, 2)
996
+ tree = cKDTree(corners.mean(axis=1))
997
+ pts = mesh.nodes[upper][:, others]
998
+ k = min(12, len(faces))
999
+ _, cand = tree.query(pts, k=k)
1000
+ cand = cand.reshape(len(pts), k)
1001
+ # off the lower face (a pore of the next cell there): free nodes of a free surface
1002
+ gap, edge = _distance_to_triangles(pts, corners[cand])
1003
+ loose = gap > 0.25 * edge
1004
+ slave_of[upper[loose]] = -1
1005
+ freed[upper[loose]] = True
1006
+ upper, pts, cand = upper[~loose], pts[~loose], cand[~loose]
1007
+ n_interpolated += upper.size
1008
+ if upper.size == 0:
1009
+ continue
1010
+ a, b, c = corners[cand, 0], corners[cand, 1], corners[cand, 2]
1011
+ v0, v1, v2 = b - a, c - a, pts[:, None, :] - a
1012
+ d00 = (v0 * v0).sum(-1)
1013
+ d01 = (v0 * v1).sum(-1)
1014
+ d11 = (v1 * v1).sum(-1)
1015
+ d20 = (v2 * v0).sum(-1)
1016
+ d21 = (v2 * v1).sum(-1)
1017
+ den = d00 * d11 - d01 * d01
1018
+ l1 = (d11 * d20 - d01 * d21) / den
1019
+ l2 = (d00 * d21 - d01 * d20) / den
1020
+ bary = np.stack([1 - l1 - l2, l1, l2], axis=-1)
1021
+ score = bary.min(axis=-1)
1022
+ best = np.argmax(score, axis=1)
1023
+ idx = np.arange(len(pts))
1024
+ chosen = cand[idx, best]
1025
+ lam = bary[idx, best]
1026
+ bad = score[idx, best] < -1e-6
1027
+ outside += int(bad.sum())
1028
+ lam = np.clip(lam, 0.0, None)
1029
+ lam /= lam.sum(axis=1, keepdims=True)
1030
+ w = _face_weights(mesh.order, lam)
1031
+ masters = faces[chosen]
1032
+ rows.append(np.repeat(upper, w.shape[1]))
1033
+ cols.append(masters.ravel())
1034
+ vals.append(w.ravel())
1035
+ if freed.any(): # the free nodes at the place of others modulo the periods (diagonally)
1036
+ joined = _free_classes(mesh, np.flatnonzero(freed), slave_of)
1037
+ for node, master in joined:
1038
+ rows.append(np.array([node]))
1039
+ cols.append(np.array([master]))
1040
+ vals.append(np.ones(1))
1041
+ slave_of[node], freed[node] = 0, False
1042
+ n_free = int(freed.sum())
1043
+ free = np.flatnonzero(slave_of < 0)
1044
+ rows.append(free)
1045
+ cols.append(free)
1046
+ vals.append(np.ones(free.size))
1047
+ p = sp.csr_matrix(
1048
+ (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)
1049
+ )
1050
+ p.eliminate_zeros()
1051
+ t = p.copy()
1052
+ for _ in range(4): # resolve the slaves whose masters are slaves (edges, corners)
1053
+ support = np.unique(t.indices)
1054
+ if not np.any(slave_of[support] >= 0):
1055
+ break
1056
+ t = t @ p
1057
+ t.data[np.abs(t.data) < 1e-14] = 0.0
1058
+ t.eliminate_zeros()
1059
+ masters = np.flatnonzero(slave_of < 0)
1060
+ used = np.unique(t.indices)
1061
+ if np.any(slave_of[used] >= 0):
1062
+ raise RuntimeError("periodic conditions: could not resolve the slave nodes")
1063
+ position = np.full(n, -1)
1064
+ position[masters] = np.arange(masters.size)
1065
+ t = sp.csr_matrix((t.data, position[t.indices], t.indptr), shape=(n, masters.size))
1066
+ counts = {"matched": n_matched, "interpolated": n_interpolated, "outside": outside}
1067
+ return t, masters, {**counts, "free": n_free}
1068
+
1069
+
1070
+ def _free_classes(mesh: TetMesh, loose: np.ndarray, slave_of: np.ndarray) -> list:
1071
+ """The free nodes of the upper faces (``loose``) at the place of other nodes modulo the
1072
+ periods of the box (their images through an edge or a corner, along a diagonal): one
1073
+ master for each class of them, the node of the class that is a master already, else its
1074
+ first free node; returns the pairs (free node, its master) of the others."""
1075
+ size = np.asarray(mesh.size, dtype=float)
1076
+ tol = 1e-7 * float(size.max())
1077
+ on = mesh.boundary_nodes()
1078
+ wrapped = np.mod(mesh.nodes[on] - mesh.lower, size)
1079
+ wrapped[np.abs(wrapped - size) <= tol] = 0.0
1080
+ tree = cKDTree(wrapped, boxsize=size)
1081
+ index = np.full(mesh.n_nodes, -1)
1082
+ index[on] = np.arange(on.size)
1083
+ free = set(int(p) for p in loose)
1084
+ out, done = [], set()
1085
+ for p, near in zip(loose, tree.query_ball_point(wrapped[index[loose]], tol), strict=True):
1086
+ if int(p) in done:
1087
+ continue
1088
+ members = on[np.asarray(near, dtype=np.int64)]
1089
+ masters = [int(m) for m in members if slave_of[m] < 0 and int(m) not in free]
1090
+ own = sorted(int(m) for m in members if int(m) in free)
1091
+ master = masters[0] if masters else own[0]
1092
+ out += [(m, master) for m in own if m != master]
1093
+ done.update(own)
1094
+ return out
1095
+
1096
+
1097
+ def _distance_to_triangles(points: np.ndarray, triangles: np.ndarray):
1098
+ """The distance from each point (m x 2) to the nearest of its candidate triangles
1099
+ (m x k x 3 x 2: zero inside one) and the longest edge of that triangle."""
1100
+ p = points[:, None, :]
1101
+ gaps, sides = [], []
1102
+ for i in range(3): # the distance to each edge, and the side of the point
1103
+ a, d = triangles[:, :, i], triangles[:, :, (i + 1) % 3] - triangles[:, :, i]
1104
+ s = np.clip(((p - a) * d).sum(-1) / np.maximum((d * d).sum(-1), 1e-300), 0.0, 1.0)
1105
+ gaps.append(np.linalg.norm(p - a - s[..., None] * d, axis=-1))
1106
+ sides.append(d[..., 0] * (p - a)[..., 1] - d[..., 1] * (p - a)[..., 0])
1107
+ sides = np.array(sides)
1108
+ inside = np.all(sides >= 0, axis=0) | np.all(sides <= 0, axis=0)
1109
+ gap = np.where(inside, 0.0, np.min(gaps, axis=0))
1110
+ nearest = np.argmin(gap, axis=1)
1111
+ idx = np.arange(len(points))
1112
+ tri = triangles[idx, nearest]
1113
+ edges = np.linalg.norm(tri - np.roll(tri, 1, axis=1), axis=-1).max(axis=1)
1114
+ return gap[idx, nearest], edges
1115
+
1116
+
1117
+ def _outer_normals(mesh: TetMesh) -> tuple[np.ndarray, np.ndarray]:
1118
+ """Faces bounding the volume element and their outward normals times their areas."""
1119
+ faces = mesh.outer_faces()
1120
+ p = mesh.nodes[faces[:, :3]]
1121
+ return faces, 0.5 * np.cross(p[:, 1] - p[:, 0], p[:, 2] - p[:, 0]).reshape(-1, 3)
1122
+
1123
+
1124
+ #: A rule of the triangle exact to degree 4 (Dunavant): area coordinates and weights
1125
+ _T1, _T2 = (0.445948490915965, 0.108103018168070), (0.091576213509771, 0.816847572980459)
1126
+ _TRIANGLE = (
1127
+ np.array(
1128
+ [
1129
+ [_T1[0], _T1[0], _T1[1]],
1130
+ [_T1[0], _T1[1], _T1[0]],
1131
+ [_T1[1], _T1[0], _T1[0]],
1132
+ [_T2[0], _T2[0], _T2[1]],
1133
+ [_T2[0], _T2[1], _T2[0]],
1134
+ [_T2[1], _T2[0], _T2[0]],
1135
+ ]
1136
+ ),
1137
+ np.array([0.223381589678011] * 3 + [0.109951743655322] * 3),
1138
+ )
1139
+
1140
+
1141
+ def _face_loads(mesh: TetMesh) -> tuple[np.ndarray, np.ndarray]:
1142
+ """The faces bounding the volume element and, for each of their nodes, the integral
1143
+ over the face of its shape function times the outward normal (faces x nodes x 3):
1144
+ the consistent nodal loads of a uniform traction (flux) are their products by the
1145
+ stress (flux). Straight faces: a third of the area vector at the corners (3 nodes) or
1146
+ at the mid-edge nodes (6 nodes); faces with curved edges (the nodes of an interface
1147
+ moved within a face of the box): the six nodes, integrated on the curved triangle."""
1148
+ faces, normal = _outer_normals(mesh)
1149
+ loads = np.zeros((len(faces), faces.shape[1], 3))
1150
+ if mesh.order == 1:
1151
+ loads[:] = normal[:, None, :] / 3.0
1152
+ return faces, loads
1153
+ loads[:, 3:] = normal[:, None, :] / 3.0
1154
+ if not mesh.curved:
1155
+ return faces, loads
1156
+ x = mesh.nodes[faces] # (faces, 6, 3)
1157
+ ends = x[:, [0, 1, 2]], x[:, [1, 2, 0]]
1158
+ bent = np.flatnonzero(np.abs(x[:, 3:] - 0.5 * (ends[0] + ends[1])).max(axis=(1, 2)) > 0.0)
1159
+ if not bent.size:
1160
+ return faces, loads
1161
+ points, weights = _TRIANGLE
1162
+ shape = _face_weights(2, points) # (points, 6)
1163
+ l0, l1, l2 = points[:, 0], points[:, 1], points[:, 2]
1164
+ zero = np.zeros_like(l0)
1165
+ # derivatives of the six functions along the two edges from the first corner
1166
+ d1 = np.stack([1 - 4 * l0, 4 * l1 - 1, zero, 4 * (l0 - l1), 4 * l2, -4 * l2], axis=1)
1167
+ d2 = np.stack([1 - 4 * l0, zero, 4 * l2 - 1, -4 * l1, 4 * l1, 4 * (l0 - l2)], axis=1)
1168
+ t1 = np.einsum("qa,fad->fqd", d1, x[bent])
1169
+ t2 = np.einsum("qa,fad->fqd", d2, x[bent])
1170
+ area = np.cross(t1, t2) # (faces, points, 3): the area vector per unit reference area
1171
+ loads[bent] = 0.5 * np.einsum("q,qa,fqd->fad", weights, shape, area)
1172
+ return faces, loads
1173
+
1174
+
1175
+ def linear_interpolation(mesh: TetMesh) -> tuple[sp.csr_matrix, np.ndarray]:
1176
+ """Interpolation (nodes x corner nodes) of the 4-node element functions of a
1177
+ 10-node mesh into its 10-node functions, and the corner nodes."""
1178
+ corners = np.unique(mesh.elements[:, :4])
1179
+ index = np.full(mesh.n_nodes, -1)
1180
+ index[corners] = np.arange(corners.size)
1181
+ if mesh.order == 1:
1182
+ return sp.identity(mesh.n_nodes, format="csr"), corners
1183
+ mids, first = np.unique(mesh.elements[:, 4:].ravel(), return_index=True)
1184
+ ends = mesh.elements[:, TET_EDGES].reshape(-1, 2)[first]
1185
+ rows = np.concatenate([corners, mids, mids])
1186
+ cols = np.concatenate([np.arange(corners.size), index[ends[:, 0]], index[ends[:, 1]]])
1187
+ vals = np.concatenate([np.ones(corners.size), np.full(2 * mids.size, 0.5)])
1188
+ p = sp.csr_matrix((vals, (rows, cols)), shape=(mesh.n_nodes, corners.size))
1189
+ return p, corners
1190
+
1191
+
1192
+ class _FEProblem(MacroscopicLoadings):
1193
+ physics = ""
1194
+ nd = 0
1195
+
1196
+ def __init__(
1197
+ self,
1198
+ mesh: TetMesh,
1199
+ materials: dict[int, Material],
1200
+ bc: str = "kubc",
1201
+ *,
1202
+ solver: str = "auto",
1203
+ tol: float = 1e-8,
1204
+ maxiter: int | None = None,
1205
+ regularization: float = 1e-12,
1206
+ physics: str | None = None,
1207
+ integration: str = "full",
1208
+ ):
1209
+ if not isinstance(mesh, TetMesh):
1210
+ raise TypeError("the FE solver needs a TetMesh (see morphogen.mesh.conforming)")
1211
+ #: ``"full"``, or ``"bbar"``: the volume change of each 10-node tetrahedron as its
1212
+ #: mean (elastic problems; :mod:`morphogen.homogenization.dilatation`)
1213
+ self.integration = integration_of(integration)
1214
+ if physics is not None:
1215
+ if transport_physics(physics) != (self.nd == 1):
1216
+ kind = "a transport phenomenon" if self.nd == 1 else "'elastic'"
1217
+ raise ValueError(f"{type(self).__name__}: physics {kind}, got {physics!r}")
1218
+ self.physics = physics
1219
+ self.bc = boundary_condition(bc)
1220
+ if self.bc == "mixed" and mesh.whole:
1221
+ raise ValueError(
1222
+ "mixed boundary conditions are defined on the faces of the box: mesh the "
1223
+ "polycrystal with cells='box'"
1224
+ )
1225
+ self.box_volume = mesh.box_volume
1226
+ phases = [int(p) for p in np.unique(mesh.phase)]
1227
+ missing = [p for p in phases if p not in materials]
1228
+ if missing:
1229
+ raise ValueError(f"no material for phase(s) {missing}; phases present: {phases}")
1230
+ # the phases inert for the physics: voids, and the insulators of a transport
1231
+ voids = [p for p in phases if materials[p].inert(self.physics)]
1232
+ solid_phases = [p for p in phases if p not in voids]
1233
+ # pores: void phases, or parts of the box left out of the mesh
1234
+ covered = float(np.abs(mesh.volumes()).sum()) / mesh.box_volume
1235
+ self.has_voids = bool(voids) or covered < 1.0 - 1e-9
1236
+ if self.bc == "subc" and self.has_voids:
1237
+ raise ValueError(
1238
+ "static uniform (Neumann) boundary conditions cannot be applied to porous "
1239
+ "media (Dirrenberger et al. 2014, sec. 3.4.2); use 'mixed' instead"
1240
+ )
1241
+ if voids:
1242
+ mesh = mesh.subset(solid_phases) if solid_phases else None
1243
+ self.floating_fraction = 0.0
1244
+ if mesh is not None and self.has_voids and mesh.n_elements:
1245
+ mesh = self._drop_floating(mesh)
1246
+ self.empty = mesh is None or mesh.n_elements == 0
1247
+ if self.empty:
1248
+ log.warning("no load-carrying material in the sample: its apparent properties are zero")
1249
+ self.mesh = mesh
1250
+ self.solver_method = solver
1251
+ self.tol = tol
1252
+ self.maxiter = maxiter
1253
+ self.regularization = float(regularization) if self.has_voids else 0.0
1254
+ self.groups = tuple(solid_phases)
1255
+ if not self.empty:
1256
+ # material matrix of every element (one per grain of an oriented crystal)
1257
+ self.table = material_table(
1258
+ mesh.phase,
1259
+ materials,
1260
+ self.physics,
1261
+ grains=mesh.cell,
1262
+ orientations=mesh.orientations,
1263
+ )
1264
+ self.groups = self.table.phases
1265
+ self.group = np.ascontiguousarray(self.table.stat)
1266
+ self.mat = np.ascontiguousarray(self.table.mat)
1267
+ locking = nearly_incompressible(materials, solid_phases) if self.nd == 3 else []
1268
+ if locking and (self.integration == "full" or mesh.order == 1):
1269
+ log.warning(
1270
+ "phase(s) %s nearly incompressible (Poisson's ratio of %.2f or more): "
1271
+ "elements integrated at every point lock; take 10-node elements with "
1272
+ "integration='bbar' (the volume change of each element as its mean)",
1273
+ locking,
1274
+ NEARLY_INCOMPRESSIBLE,
1275
+ )
1276
+ self._systems: dict = {}
1277
+ self._matrix = None
1278
+ self._units: dict = {}
1279
+ self._forces = None
1280
+
1281
+ def _drop_floating(self, mesh: TetMesh) -> TetMesh:
1282
+ """Remove the clusters of elements that touch no face of the box (they carry no
1283
+ load); ``floating_fraction`` is their share of the meshed volume."""
1284
+ labels, n_comp = mesh.components()
1285
+ if n_comp == 1 and mesh.boundary_nodes().size:
1286
+ return mesh
1287
+ on_boundary = np.zeros(mesh.n_nodes, dtype=bool)
1288
+ on_boundary[mesh.boundary_nodes()] = True
1289
+ touching = np.zeros(n_comp, dtype=bool)
1290
+ hit = on_boundary[mesh.elements].any(axis=1)
1291
+ touching[np.unique(labels[hit])] = True
1292
+ keep = touching[labels]
1293
+ if keep.all():
1294
+ return mesh
1295
+ vol = np.abs(mesh.volumes())
1296
+ self.floating_fraction = float(vol[~keep].sum() / vol.sum())
1297
+ sub = mesh._derived(mesh.nodes, mesh.elements[keep], keep)
1298
+ return sub.subset(np.unique(sub.phase)) if sub.n_elements else sub
1299
+
1300
+ # -- constraints ------------------------------------------------------------------
1301
+ def _face_mask(self, axis: int) -> np.ndarray:
1302
+ on = np.zeros(self.mesh.n_nodes, dtype=bool)
1303
+ on[self.mesh.face_nodes(axis, 0)] = True
1304
+ on[self.mesh.face_nodes(axis, 1)] = True
1305
+ return on
1306
+
1307
+ def _support_nodes(self) -> list[int]:
1308
+ """3-2-1 supports: nodes nearest to three corners of the box."""
1309
+ m = self.mesh
1310
+ lo, hi = m.lower, m.upper
1311
+ targets = [lo, np.array([hi[0], lo[1], lo[2]]), np.array([lo[0], hi[1], lo[2]])]
1312
+ tree = cKDTree(m.nodes)
1313
+ return [int(tree.query(t)[1]) for t in targets]
1314
+
1315
+ def _stiffness(self) -> sp.csr_matrix:
1316
+ if self._matrix is None:
1317
+ self._matrix = assemble(
1318
+ self.mesh, self.nd, self.mat, self.table.matrices, self.integration
1319
+ )
1320
+ return self._matrix
1321
+
1322
+ def _reduction(self, key):
1323
+ """Reduced unknowns of a constraint key: the matrix ``T`` of ``w = T x`` and the
1324
+ dof that each reduced unknown represents."""
1325
+ nd = self.nd
1326
+ n = self.mesh.n_nodes
1327
+ if key[0] == "periodic":
1328
+ t_nodes, masters, counts = periodic_map(self.mesh)
1329
+ if counts["interpolated"]:
1330
+ log.warning(
1331
+ "periodic conditions on non-matching faces: %d of %d nodes interpolated "
1332
+ "(%d outside the opposite face); the results are approximate. Mesh "
1333
+ "periodic microstructures with conforming_mesh(..., periodic=True).",
1334
+ counts["interpolated"],
1335
+ counts["interpolated"] + counts["matched"],
1336
+ counts["outside"],
1337
+ )
1338
+ t = sp.kron(t_nodes, sp.identity(nd), format="csr") if nd > 1 else t_nodes
1339
+ # each reduced unknown is the value of a master dof
1340
+ rep = (masters[:, None] * nd + np.arange(nd)).ravel()
1341
+ fixed = np.zeros(t.shape[1], dtype=bool)
1342
+ if not self.has_voids:
1343
+ fixed[:nd] = True # translations: fluctuation zero at one master node
1344
+ keep = np.flatnonzero(~fixed)
1345
+ return t[:, keep].tocsr(), rep[keep]
1346
+ rep = np.flatnonzero(~self._constraints(key))
1347
+ t = sp.csr_matrix((np.ones(rep.size), (rep, np.arange(rep.size))), shape=(n * nd, rep.size))
1348
+ return t, rep
1349
+
1350
+ def _reduce(self, key, k, t, rep) -> sp.csr_matrix:
1351
+ """Reduced matrix ``T^T K T`` (regularized for porous media)."""
1352
+ reduced = (t.T @ k @ t).tocsr() if key[0] == "periodic" else k[rep][:, rep].tocsr()
1353
+ return self._regularized(reduced)
1354
+
1355
+ def _regularized(self, reduced: sp.csr_matrix) -> sp.csr_matrix:
1356
+ """A reduced matrix with the shift of its diagonal that regularizes porous media."""
1357
+ if self.regularization > 0 and reduced.shape[0]:
1358
+ diag = reduced.diagonal()
1359
+ shift = self.regularization * float(np.mean(diag))
1360
+ reduced = (reduced + sp.diags(np.full(diag.size, shift))).tocsr()
1361
+ return reduced
1362
+
1363
+ def _linear_solver(self, reduced, t, rep, symmetric: bool = True) -> LinearSolver:
1364
+ """The solver of a reduced matrix (``symmetric``: false for the tangent of
1365
+ nonsymmetric consistent tangents, see :class:`LinearSolver`)."""
1366
+ method = choose_method(self.solver_method, reduced.shape[0])
1367
+ near_null = self._near_null(t)
1368
+ coarse = None
1369
+ if method == "amg" and self.mesh.order == 2:
1370
+ coarse = self._coarse_space(t, rep, near_null)
1371
+ return LinearSolver(
1372
+ reduced,
1373
+ method=method,
1374
+ tol=self.tol,
1375
+ maxiter=self.maxiter,
1376
+ near_null=near_null,
1377
+ coarse=coarse,
1378
+ symmetric=symmetric,
1379
+ dofs=rep if self.nd == 3 else None,
1380
+ )
1381
+
1382
+ def _system(self, key):
1383
+ """Reduced system of a constraint key: ``w = T x`` and the solver of
1384
+ ``T^T K T x = T^T f``."""
1385
+ if key in self._systems:
1386
+ return self._systems[key]
1387
+ t, rep = self._reduction(key)
1388
+ reduced = self._reduce(key, self._stiffness(), t, rep)
1389
+ self._systems[key] = (t, self._linear_solver(reduced, t, rep))
1390
+ return self._systems[key]
1391
+
1392
+ def _coarse_space(self, t, rep, near_null):
1393
+ """Interpolation of the reduced unknowns of the linear elements (corner nodes)
1394
+ into those of the quadratic elements, the near-null modes of the former and the
1395
+ degrees of freedom that they stand for (displacements; none otherwise).
1396
+
1397
+ ``rep`` is the dof represented by each reduced unknown: the coarse unknowns are
1398
+ those carried by corner nodes; the values of the other corner dofs follow from
1399
+ the constraints (``T``), and the mid-edge values from linear interpolation.
1400
+ """
1401
+ nd = self.nd
1402
+ p_nodes, corners = linear_interpolation(self.mesh)
1403
+ p_full = sp.kron(p_nodes, sp.identity(nd), format="csr") if nd > 1 else p_nodes
1404
+ corner_dofs = (corners[:, None] * nd + np.arange(nd)).ravel()
1405
+ on_corner = np.zeros(t.shape[0], dtype=bool)
1406
+ on_corner[corner_dofs] = True
1407
+ cols = np.flatnonzero(on_corner[rep])
1408
+ p = (p_full[rep] @ t[corner_dofs][:, cols]).tocsr()
1409
+ p.eliminate_zeros()
1410
+ return p, near_null[cols], rep[cols] if nd == 3 else None
1411
+
1412
+ def _solve(self, key, rhs_full, scale=None):
1413
+ """Fluctuation solving the reduced system; a load below ``NEGLIGIBLE`` times
1414
+ ``scale`` (the size of its parts before they cancel) is only round-off: the
1415
+ fluctuation is zero (the affine field is the solution)."""
1416
+ t, solver = self._system(key)
1417
+ b = t.T @ rhs_full
1418
+ if scale is not None and norm(b) <= NEGLIGIBLE * scale:
1419
+ info = SolveInfo(solver.method, b.size, 0, 0.0, solver.setup_s, 0.0)
1420
+ return np.zeros(t.shape[0]), info
1421
+ x, info = solver.solve(b)
1422
+ return t @ x, info
1423
+
1424
+ def _phase_statistics(self, sums, n_mean, names, sizes) -> list[PhaseStatistics]:
1425
+ out = []
1426
+ vol_index = sums.shape[1] - 1
1427
+ for g, phase in enumerate(self.groups):
1428
+ vol = sums[g, vol_index]
1429
+ if vol <= 0:
1430
+ continue
1431
+ mean, std, pos = {}, {}, 0
1432
+ for name, size in zip(names, sizes, strict=True):
1433
+ m = sums[g, pos : pos + size] / vol
1434
+ sq = sums[g, n_mean + pos : n_mean + pos + size] / vol
1435
+ mean[name] = m
1436
+ std[name] = np.sqrt(np.maximum(sq - m * m, 0.0))
1437
+ pos += size
1438
+ out.append(PhaseStatistics(phase, float(vol / self.box_volume), mean, std))
1439
+ return out
1440
+
1441
+ def _empty_solution(self, loading: Loading, t0: float) -> Solution:
1442
+ elastic = self.physics == "elastic"
1443
+ values = np.where(loading.strain_controlled, loading.array, 0.0)
1444
+ strain = voigt_to_tensor(values, strain=True) if elastic else values
1445
+ return Solution(
1446
+ physics=self.physics,
1447
+ bc=self.bc,
1448
+ loading=loading,
1449
+ strain=strain,
1450
+ stress=np.zeros((3, 3)) if elastic else np.zeros(3),
1451
+ energy=0.0,
1452
+ material_fraction=0.0,
1453
+ phases=[],
1454
+ info=SolveInfo("none", 0, 0, 0.0, 0.0, time.perf_counter() - t0),
1455
+ )
1456
+
1457
+
1458
+ class FEElasticProblem(_FEProblem):
1459
+ """Linear (thermo-)elasticity on a tetrahedral mesh (small strains); crystals are
1460
+ turned by the orientations of the grains of polycrystal meshes."""
1461
+
1462
+ physics = "elastic"
1463
+ nd = 3
1464
+
1465
+ def _key(self, x: np.ndarray):
1466
+ """Constraint key of a native loading (strain components, or stresses)."""
1467
+ if self.bc != "mixed":
1468
+ return (self.bc,)
1469
+ shear = np.flatnonzero(x[3:] != 0)
1470
+ if shear.size == 0:
1471
+ return ("mixed", "normal")
1472
+ if shear.size == 1 and np.all(x[:3] == 0):
1473
+ a, b = VOIGT[3 + shear[0]]
1474
+ return ("mixed", "shear", min(a, b), max(a, b))
1475
+ raise ValueError(
1476
+ "mixed boundary conditions are defined for diagonal (triaxial) strains and for "
1477
+ "a single shear component (Dirrenberger et al. 2014, sec. 3.4.3)"
1478
+ )
1479
+
1480
+ def _constraints(self, key) -> np.ndarray:
1481
+ n = self.mesh.n_nodes
1482
+ con = np.zeros((n, 3), dtype=bool)
1483
+ if key[0] == "kubc":
1484
+ con[self.mesh.boundary_nodes(), :] = True
1485
+ elif key[0] == "subc":
1486
+ a, b, c = self._support_nodes()
1487
+ con[a, :] = True
1488
+ con[b, 1:] = True
1489
+ con[c, 2] = True
1490
+ elif key[1] == "normal":
1491
+ for d in range(3):
1492
+ con[self._face_mask(d), d] = True
1493
+ else:
1494
+ a, b = key[2], key[3]
1495
+ con[self._face_mask(a), b] = True
1496
+ con[self._face_mask(b), a] = True
1497
+ if not self.has_voids:
1498
+ third = 3 - a - b
1499
+ con[self._support_nodes()[0], third] = True
1500
+ return con.ravel()
1501
+
1502
+ def _near_null(self, t):
1503
+ x = self.mesh.nodes - self.mesh.nodes.mean(axis=0)
1504
+ n = self.mesh.n_nodes
1505
+ modes = []
1506
+ for c in range(3):
1507
+ m = np.zeros((n, 3))
1508
+ m[:, c] = 1.0
1509
+ modes.append(m)
1510
+ if self.bc != "periodic":
1511
+ for a, b in ((0, 1), (1, 2), (2, 0)):
1512
+ r = np.zeros((n, 3))
1513
+ r[:, a] = -x[:, b]
1514
+ r[:, b] = x[:, a]
1515
+ modes.append(r)
1516
+ full = np.stack([m.ravel() for m in modes], axis=1)
1517
+ # least-squares representation of the modes in the reduced unknowns
1518
+ tt = (t.T @ t).diagonal()
1519
+ return (t.T @ full) / np.where(tt > 0, tt, 1.0)[:, None]
1520
+
1521
+ def _thermal_forces(self) -> tuple[np.ndarray, float]:
1522
+ """Nodal forces of a unit change of temperature and their scale."""
1523
+ if self._forces is None:
1524
+ gp, gw = GAUSS[self.mesh.order]
1525
+ self._forces = _thermal_forces(
1526
+ self.mesh.nodes,
1527
+ self.mesh.elements,
1528
+ self.mesh.order,
1529
+ self.mat,
1530
+ self.table.matrices,
1531
+ self.table.eigen,
1532
+ gp,
1533
+ gw,
1534
+ )
1535
+ return self._forces
1536
+
1537
+ def _field(self, x: np.ndarray, dt: float):
1538
+ """Displacement for the native loading ``x`` (strain, or stress for ``subc``,
1539
+ Voigt order) and the change of temperature ``dt``."""
1540
+ key = self._key(x)
1541
+ m = self.mesh
1542
+ if self.native == "strain":
1543
+ e = voigt_to_tensor(x, strain=True)
1544
+ u_aff = times(m.nodes, e.T).ravel()
1545
+ rhs = -(self._stiffness() @ u_aff)
1546
+ scale = norm(self._stiffness().diagonal() * u_aff)
1547
+ else:
1548
+ u_aff = np.zeros(3 * m.n_nodes)
1549
+ rhs = self._traction_load(voigt_to_tensor(x, strain=False))
1550
+ scale = None
1551
+ if dt:
1552
+ forces, size = self._thermal_forces()
1553
+ rhs = rhs + dt * forces
1554
+ scale = None if scale is None else float(np.hypot(scale, abs(dt) * size))
1555
+ w, info = self._solve(key, rhs, scale)
1556
+ return u_aff + w, info
1557
+
1558
+ def _sums(self, u: np.ndarray, dt: float) -> np.ndarray:
1559
+ m = self.mesh
1560
+ gp, gw = GAUSS[m.order]
1561
+ return _elastic_sums(
1562
+ m.nodes,
1563
+ m.elements,
1564
+ m.order,
1565
+ self.group,
1566
+ len(self.groups),
1567
+ self.mat,
1568
+ self.table.matrices,
1569
+ self.table.eigen,
1570
+ float(dt),
1571
+ u,
1572
+ gp,
1573
+ gw,
1574
+ )
1575
+
1576
+ def _dual(self, u: np.ndarray, x: np.ndarray, dt: float) -> np.ndarray:
1577
+ """Average stress (strain loadings) or strain (stress loadings, engineering
1578
+ shears) of a displacement, in the Voigt order."""
1579
+ total = self._sums(u, dt).sum(axis=0) / self.box_volume
1580
+ if self.native == "strain":
1581
+ return total[6:12].copy()
1582
+ return total[0:6] * np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0])
1583
+
1584
+ def _evaluate(self, loading, u, x, dt, info, fields, t0) -> Solution:
1585
+ m = self.mesh
1586
+ sums = self._sums(u, dt)
1587
+ total = sums.sum(axis=0)
1588
+ stress = voigt_to_tensor(total[6:12] / self.box_volume, strain=False)
1589
+ if self.native == "strain":
1590
+ strain = voigt_to_tensor(x, strain=True)
1591
+ else:
1592
+ strain = voigt_to_tensor(total[0:6] / self.box_volume, strain=False)
1593
+ fld = None
1594
+ if fields:
1595
+ gp, gw = GAUSS[m.order]
1596
+ es, ss, en = _elastic_fields(
1597
+ m.nodes,
1598
+ m.elements,
1599
+ m.order,
1600
+ self.mat,
1601
+ self.table.matrices,
1602
+ self.table.eigen,
1603
+ float(dt),
1604
+ u,
1605
+ gp,
1606
+ gw,
1607
+ )
1608
+ fld = {"strain": es, "stress": ss, "energy": en, "displacement": u.reshape(-1, 3)}
1609
+ info.solve_s = time.perf_counter() - t0
1610
+ return Solution(
1611
+ physics="elastic",
1612
+ bc=self.bc,
1613
+ loading=loading,
1614
+ strain=strain,
1615
+ stress=stress,
1616
+ energy=float(total[12] / self.box_volume),
1617
+ material_fraction=float(total[26] / self.box_volume),
1618
+ phases=self._phase_statistics(sums, 13, ("strain", "stress", "energy"), (6, 6, 1)),
1619
+ info=info,
1620
+ fields=fld,
1621
+ support=m if fields else None,
1622
+ )
1623
+
1624
+ def _traction_load(self, sigma: np.ndarray) -> np.ndarray:
1625
+ m = self.mesh
1626
+ load = np.zeros((m.n_nodes, 3))
1627
+ # consistent loads: corners A/3 (3-node), mid-edge nodes A/3 (6-node, straight)
1628
+ faces, loads = _face_loads(m)
1629
+ np.add.at(load, faces, loads @ sigma.T)
1630
+ return load.ravel()
1631
+
1632
+
1633
+ class FEThermalProblem(_FEProblem):
1634
+ """Steady linear heat conduction on a tetrahedral mesh, or with ``physics`` any other
1635
+ transport phenomenon of a scalar potential (:data:`~morphogen.homogenization.
1636
+ materials.TRANSPORT`: ``"electrical"``, ``"dielectric"``, ``"magnetic"``,
1637
+ ``"diffusion"``), with the coefficient of the materials for it; the phases whose
1638
+ coefficient is zero (insulators) are left out as pores."""
1639
+
1640
+ physics = "thermal"
1641
+ nd = 1
1642
+
1643
+ def _key(self, x: np.ndarray):
1644
+ if self.bc != "mixed":
1645
+ return (self.bc,)
1646
+ nonzero = np.flatnonzero(x != 0)
1647
+ if nonzero.size > 1:
1648
+ raise ValueError(
1649
+ "mixed thermal boundary conditions (MTBC) need a gradient along one axis"
1650
+ )
1651
+ return ("mixed", int(nonzero[0]) if nonzero.size else 0)
1652
+
1653
+ def _constraints(self, key) -> np.ndarray:
1654
+ con = np.zeros(self.mesh.n_nodes, dtype=bool)
1655
+ if key[0] == "kubc":
1656
+ con[self.mesh.boundary_nodes()] = True
1657
+ elif key[0] == "subc":
1658
+ con[self._support_nodes()[0]] = True
1659
+ else:
1660
+ con |= self._face_mask(key[1])
1661
+ return con
1662
+
1663
+ def _near_null(self, t):
1664
+ ones = np.ones((self.mesh.n_nodes, 1))
1665
+ tt = (t.T @ t).diagonal()
1666
+ return (t.T @ ones) / np.where(tt > 0, tt, 1.0)[:, None]
1667
+
1668
+ def _field(self, x: np.ndarray, dt: float = 0.0):
1669
+ """Temperature for the native loading ``x`` (gradient, or flux for ``subc``)."""
1670
+ key = self._key(x)
1671
+ m = self.mesh
1672
+ if self.native == "gradient":
1673
+ t_aff = times(m.nodes, x)
1674
+ rhs = -(self._stiffness() @ t_aff)
1675
+ scale = norm(self._stiffness().diagonal() * t_aff)
1676
+ else:
1677
+ t_aff = np.zeros(m.n_nodes)
1678
+ rhs = self._flux_load(x)
1679
+ scale = None
1680
+ w, info = self._solve(key, rhs, scale)
1681
+ return t_aff + w, info
1682
+
1683
+ def _sums(self, temp: np.ndarray) -> np.ndarray:
1684
+ m = self.mesh
1685
+ gp, gw = GAUSS[m.order]
1686
+ return _thermal_sums(
1687
+ m.nodes,
1688
+ m.elements,
1689
+ m.order,
1690
+ self.group,
1691
+ len(self.groups),
1692
+ self.mat,
1693
+ self.table.matrices,
1694
+ temp,
1695
+ gp,
1696
+ gw,
1697
+ )
1698
+
1699
+ def _dual(self, temp: np.ndarray, x: np.ndarray, dt: float = 0.0) -> np.ndarray:
1700
+ """Average flux (gradient loadings) or gradient (flux loadings)."""
1701
+ total = self._sums(temp).sum(axis=0) / self.box_volume
1702
+ return (total[3:6] if self.native == "gradient" else total[0:3]).copy()
1703
+
1704
+ def _evaluate(self, loading, temp, x, dt, info, fields, t0) -> Solution:
1705
+ m = self.mesh
1706
+ sums = self._sums(temp)
1707
+ total = sums.sum(axis=0)
1708
+ if self.native == "gradient":
1709
+ grad = np.array(x, dtype=float)
1710
+ else:
1711
+ grad = total[0:3] / self.box_volume
1712
+ fld = None
1713
+ if fields:
1714
+ gp, gw = GAUSS[m.order]
1715
+ eg, ef, ed = _thermal_fields(
1716
+ m.nodes, m.elements, m.order, self.mat, self.table.matrices, temp, gp, gw
1717
+ )
1718
+ fld = {"gradient": eg, "flux": ef, "dissipation": ed, "temperature": temp}
1719
+ info.solve_s = time.perf_counter() - t0
1720
+ return Solution(
1721
+ physics=self.physics,
1722
+ bc=self.bc,
1723
+ loading=loading,
1724
+ strain=grad,
1725
+ stress=total[3:6] / self.box_volume,
1726
+ energy=float(total[6] / self.box_volume),
1727
+ material_fraction=float(total[14] / self.box_volume),
1728
+ phases=self._phase_statistics(sums, 7, ("gradient", "flux", "dissipation"), (3, 3, 1)),
1729
+ info=info,
1730
+ fields=fld,
1731
+ support=m if fields else None,
1732
+ )
1733
+
1734
+ def _flux_load(self, flux: np.ndarray) -> np.ndarray:
1735
+ m = self.mesh
1736
+ load = np.zeros(m.n_nodes)
1737
+ faces, loads = _face_loads(m)
1738
+ np.add.at(load, faces, -(loads @ flux))
1739
+ return load