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,1016 @@
1
+ """Extended finite elements for homogenization: the interfaces of a morphology cut the
2
+ elements of a regular grid instead of being meshed or drawn as stairs of voxels.
3
+
4
+ A two-phase morphology is given by its level set ``phi`` at the nodes of a regular grid
5
+ of the periodic box (:class:`LevelSetSample`; negative in the phase 1). The grid is cut
6
+ into six linear tetrahedra per cell, in which the level set is interpolated linearly: the
7
+ interface is a plane within each element. Following Moës, Cloirec, Cartraud & Remacle
8
+ (2003), the displacement (or the potential of a transport problem) is enriched where an
9
+ interface between two materials cuts the elements::
10
+
11
+ u(x) = sum_i N_i(x) u_i + sum_(j enriched) N_j(x) psi(x) a_j,
12
+ psi(x) = sum_i N_i(x) |phi_i| - |sum_i N_i(x) phi_i|,
13
+
14
+ the ridge function ``psi`` continuous, with a kink on the interface (the jump of the
15
+ normal strain that the continuity of the tractions asks for) and zero in the elements
16
+ that the interface does not cut: no blending elements. The elements cut are integrated on
17
+ the sub-tetrahedra of their two sides, each with its material (four Gauss points each:
18
+ the stiffness is integrated exactly). Where one side is a void or an inert phase, the
19
+ elements are not enriched and only their solid part is integrated (Sukumar et al. 2001);
20
+ the nodes without any solid around them are left out.
21
+
22
+ The discretization keeps the convergence of conforming meshes without a mesher: a plane
23
+ interface of any orientation is represented exactly (laminates oblique to the grid are
24
+ solved to round-off, where voxels draw stairs), and curved interfaces to second order in
25
+ the size of the elements. The level set is moved away from the nodes it passes too close
26
+ to (``snap``, a fraction of the edge of the cells), which bounds the conditioning.
27
+
28
+ The problems are those of the periodic element (:class:`XFEMElasticProblem`,
29
+ :class:`XFEMThermalProblem`; the thermal one for every transport phenomenon): the
30
+ unknowns are the periodic fluctuations, standard and enriched, on the torus of the grid;
31
+ :func:`~morphogen.homogenization.apparent.homogenize` takes a :class:`LevelSetSample`
32
+ as it takes a mesh or an image. Loading paths with the nonlinear behaviours of the
33
+ phases are followed on the same discretization, in small or finite strains
34
+ (:class:`NonlinearXFEMProblem`): the integration points of the cut elements are those of
35
+ their sub-tetrahedra, each with the behaviour of its side; in finite strains the
36
+ formulation is the total Lagrangian one of the finite elements, the level set cutting the
37
+ reference configuration. Linear tetrahedra lock under
38
+ isochoric plastic flow: for plasticity prefer conforming quadratic meshes or the voxels
39
+ of the FFT solver (B-bar); damage, viscoelasticity and compressible behaviours do not
40
+ suffer from it.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import logging
46
+ import time
47
+ from dataclasses import dataclass
48
+
49
+ import numpy as np
50
+ import scipy.sparse as sp
51
+
52
+ from morphogen.homogenization.core import (
53
+ Loading,
54
+ MacroscopicLoadings,
55
+ PhaseStatistics,
56
+ Solution,
57
+ boundary_condition,
58
+ )
59
+ from morphogen.homogenization.elements import tensor_to_voigt, voigt_to_tensor
60
+ from morphogen.homogenization.materials import Material, transport_physics
61
+ from morphogen.homogenization.nonlinear import _PathSolver
62
+ from morphogen.homogenization.solvers import NEGLIGIBLE, LinearSolver, SolveInfo
63
+ from morphogen.mesh.tetra import TetMesh
64
+
65
+ log = logging.getLogger("morphogen")
66
+
67
+ #: Barycentric coordinates of the four Gauss points of a tetrahedron (degree 2)
68
+ _A, _B = 0.5854101966249685, 0.1381966011250105
69
+ _Q4 = np.array([[_A, _B, _B, _B], [_B, _A, _B, _B], [_B, _B, _A, _B], [_B, _B, _B, _A]])
70
+ #: Elements whose matrices are built at once (the memory of their strain operators)
71
+ _CHUNK = 2048
72
+ #: Voigt rows of the strain of a displacement component with a gradient: (row, component
73
+ #: of the displacement, component of the gradient)
74
+ _STRAIN = ((0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 1, 2), (3, 2, 1), (4, 0, 2), (4, 2, 0),
75
+ (5, 0, 1), (5, 1, 0)) # fmt: skip
76
+
77
+
78
+ @dataclass
79
+ class LevelSetSample:
80
+ """A two-phase morphology on the nodes of a regular grid of a periodic box: ``values``
81
+ (nx x ny x nz), its level set at the nodes ``lower + (i, j, k) h`` (negative in the
82
+ phase ``inside``, positive in the phase ``outside``; the node of index ``n`` along an
83
+ axis is that of index 0, one period further)."""
84
+
85
+ values: np.ndarray
86
+ lower: tuple = (0.0, 0.0, 0.0)
87
+ upper: tuple = (1.0, 1.0, 1.0)
88
+ inside: int = 1
89
+ outside: int = 0
90
+
91
+ def __post_init__(self) -> None:
92
+ self.values = np.ascontiguousarray(self.values, dtype=float)
93
+ if self.values.ndim != 3 or min(self.values.shape) < 1:
94
+ raise ValueError("LevelSetSample: the level set at the nodes of a grid (nx, ny, nz)")
95
+ if not np.all(np.isfinite(self.values)):
96
+ raise ValueError("LevelSetSample: finite values of the level set")
97
+ self.lower = tuple(float(v) for v in self.lower)
98
+ self.upper = tuple(float(v) for v in self.upper)
99
+ if not all(b > a for a, b in zip(self.lower, self.upper, strict=True)):
100
+ raise ValueError("LevelSetSample: a box with positive edges")
101
+ if self.inside == self.outside:
102
+ raise ValueError("LevelSetSample: two different phases")
103
+
104
+ @classmethod
105
+ def of(cls, micro, shape=None, *, spacing: float | None = None) -> LevelSetSample:
106
+ """The sample of a periodic microstructure with a level set (a model realization,
107
+ an :class:`~morphogen.mesh.conforming.ImplicitBody`): ``shape`` cells along the
108
+ longest edge of its box (or a shape per axis), or cells of edge ``spacing``."""
109
+ from morphogen.domain import Domain, Grid
110
+
111
+ domain: Domain = micro.domain
112
+ if not domain.periodic:
113
+ raise ValueError(
114
+ "XFEM homogenization is periodic: a periodic microstructure (its level set "
115
+ "on the torus of the grid)"
116
+ )
117
+ lengths = np.asarray(domain.lengths, dtype=float)
118
+ if (shape is None) == (spacing is None):
119
+ raise ValueError("LevelSetSample.of: give the shape of the grid or its spacing")
120
+ if spacing is not None:
121
+ n = np.maximum(1, np.rint(lengths / float(spacing))).astype(int)
122
+ elif np.ndim(shape) == 0:
123
+ n = np.maximum(1, np.rint(lengths / lengths.max() * int(shape))).astype(int)
124
+ else:
125
+ n = np.asarray(shape, dtype=int)
126
+ h = lengths / n
127
+ lower = np.asarray(domain.lower, dtype=float)
128
+ sampling = Domain(size=tuple(lengths), origin=tuple(lower - h / 2), periodic=True)
129
+ try:
130
+ field = micro.level_set(grid=Grid(sampling, tuple(int(k) for k in n)))
131
+ except NotImplementedError:
132
+ raise ValueError(
133
+ f"{type(micro).__name__}: no level-set function (tessellations are meshed "
134
+ "grain by grain or solved on voxels)"
135
+ ) from None
136
+ return cls(np.asarray(field.data, dtype=float), tuple(lower), tuple(lower + lengths))
137
+
138
+ @property
139
+ def shape(self) -> tuple[int, int, int]:
140
+ return self.values.shape
141
+
142
+ def phase_fractions(self, snap: float = 1e-3) -> dict[int, float]:
143
+ """The volume fractions of the two phases: those of the elements and of the parts
144
+ of the elements that the interface cuts (the geometry that the problems solve)."""
145
+ from morphogen.mesh.conforming import background_mesh
146
+
147
+ n = np.asarray(self.shape)
148
+ nodes, tets, _, _ = background_mesh(n, self.lower, self.upper)
149
+ ijk = np.stack(np.unravel_index(np.arange(len(nodes)), n + 1), axis=1)
150
+ wrap = ((ijk[:, 0] % n[0]) * n[1] + ijk[:, 1] % n[1]) * n[2] + ijk[:, 2] % n[2]
151
+ limit = snap * float(self.spacing.min())
152
+ phi = self.values.ravel()
153
+ phi = np.where(np.abs(phi) < limit, np.where(phi < 0, -limit, limit), phi)
154
+ x, pe = nodes[tets], phi[wrap[tets]]
155
+ neg = (pe < 0).sum(axis=1)
156
+ inside = float(_gradients(x[neg == 4])[1].sum())
157
+ cut = neg % 4 != 0
158
+ if cut.any():
159
+ verts, side = subtetrahedra(x[cut], pe[cut])
160
+ vol = np.abs(np.linalg.det(verts[:, :, 1:] - verts[:, :, :1])) / 6.0
161
+ inside += float(vol[side < 0].sum())
162
+ fraction = inside / self.volume
163
+ return dict(sorted({self.inside: fraction, self.outside: 1.0 - fraction}.items()))
164
+
165
+ @property
166
+ def spacing(self) -> np.ndarray:
167
+ return (np.asarray(self.upper) - np.asarray(self.lower)) / np.asarray(self.shape)
168
+
169
+ @property
170
+ def volume(self) -> float:
171
+ return float(np.prod(np.asarray(self.upper) - np.asarray(self.lower)))
172
+
173
+
174
+ # -- geometry of the cut elements ------------------------------------------------------------
175
+
176
+
177
+ def _gradients(x: np.ndarray):
178
+ """Gradients of the shape functions (m x 4 x 3) and volumes of linear tetrahedra of
179
+ corners ``x`` (m x 4 x 3)."""
180
+ dm = np.stack([x[:, 1] - x[:, 0], x[:, 2] - x[:, 0], x[:, 3] - x[:, 0]], axis=2)
181
+ inv = np.linalg.inv(dm)
182
+ grads = np.concatenate([-inv.sum(axis=1, keepdims=True), inv], axis=1)
183
+ return grads, np.abs(np.linalg.det(dm)) / 6.0
184
+
185
+
186
+ def subtetrahedra(x: np.ndarray, phi: np.ndarray):
187
+ """The tetrahedra of corners ``x`` (m x 4 x 3) cut by the zero of the linear
188
+ interpolant of their nodal values ``phi`` (m x 4, none zero, of both signs): the
189
+ corners of their sub-tetrahedra (m x 6 x 4 x 3) and the sign of ``phi`` in each (m x
190
+ 6; 0 for the two unused ones of an element cut with one node alone on its side, which
191
+ has a tetrahedron and a prism of three)."""
192
+ m = len(x)
193
+ neg = phi < 0
194
+ count = neg.sum(axis=1)
195
+ if np.any((count == 0) | (count == 4)):
196
+ raise ValueError("subtetrahedra: elements whose nodal values have both signs")
197
+ verts = np.zeros((m, 6, 4, 3))
198
+ side = np.zeros((m, 6))
199
+
200
+ def ordered(sel, first):
201
+ order = np.argsort(~first, axis=1, kind="stable")
202
+ return (np.take_along_axis(x[sel], order[:, :, None], axis=1),
203
+ np.take_along_axis(phi[sel], order, axis=1)) # fmt: skip
204
+
205
+ for alone, lone_side in ((1, -1.0), (3, 1.0)): # one node alone on the side lone_side
206
+ sel = np.flatnonzero(count == alone)
207
+ if not sel.size:
208
+ continue
209
+ xs, ps = ordered(sel, neg[sel] if lone_side < 0 else ~neg[sel])
210
+ t = ps[:, :1] / (ps[:, :1] - ps[:, 1:])
211
+ p = xs[:, :1] + t[:, :, None] * (xs[:, 1:] - xs[:, :1])
212
+ o = xs[:, 1:]
213
+ verts[sel, 0] = np.stack([xs[:, 0], p[:, 0], p[:, 1], p[:, 2]], axis=1)
214
+ verts[sel, 1] = np.stack([o[:, 0], o[:, 1], o[:, 2], p[:, 0]], axis=1)
215
+ verts[sel, 2] = np.stack([o[:, 1], o[:, 2], p[:, 0], p[:, 1]], axis=1)
216
+ verts[sel, 3] = np.stack([o[:, 2], p[:, 0], p[:, 1], p[:, 2]], axis=1)
217
+ side[sel, 0] = lone_side
218
+ side[sel, 1:4] = -lone_side
219
+ sel = np.flatnonzero(count == 2)
220
+ if sel.size:
221
+ xs, ps = ordered(sel, ~neg[sel]) # a, b positive, then c, d negative
222
+
223
+ def cut(i, j):
224
+ t = ps[:, i] / (ps[:, i] - ps[:, j])
225
+ return xs[:, i] + t[:, None] * (xs[:, j] - xs[:, i])
226
+
227
+ a, b, c, d = (xs[:, k] for k in range(4))
228
+ pac, pad, pbc, pbd = cut(0, 2), cut(0, 3), cut(1, 2), cut(1, 3)
229
+ pieces = ((a, pac, pad, b), (pac, pad, b, pbc), (pad, b, pbc, pbd),
230
+ (c, pac, pbc, d), (pac, pbc, d, pad), (pbc, d, pad, pbd)) # fmt: skip
231
+ for k, piece in enumerate(pieces):
232
+ verts[sel, k] = np.stack(piece, axis=1)
233
+ side[sel, :3] = 1.0
234
+ side[sel, 3:] = -1.0
235
+ return verts, side
236
+
237
+
238
+ class _Cut:
239
+ """The elements cut by the interface: their corners ``x`` (m x 4 x 3), nodal level
240
+ sets ``phi``, gradients ``grads`` and, at their 24 integration points (four per
241
+ sub-tetrahedron; zero weights for the unused ones), the weights ``w``, the sides
242
+ ``side`` (the sign of the level set), the shape functions ``n`` (m x 24 x 4) and the
243
+ ridge function ``psi``; ``gpsi`` (m x 2 x 3): the gradient of the ridge on the sides
244
+ +1 and -1."""
245
+
246
+ def __init__(self, x: np.ndarray, phi: np.ndarray):
247
+ m = len(x)
248
+ self.x, self.phi = x, phi
249
+ self.grads, self.volume = _gradients(x)
250
+ verts, side = subtetrahedra(x, phi)
251
+ edges = verts[:, :, 1:] - verts[:, :, :1]
252
+ vol = np.abs(np.linalg.det(edges)) / 6.0
253
+ pts = np.einsum("qv,msvd->msqd", _Q4, verts).reshape(m, 24, 3)
254
+ self.w = np.repeat(vol / 4.0, 4, axis=1)
255
+ self.side = np.repeat(side, 4, axis=1)
256
+ lam = np.einsum("mad,mqd->mqa", self.grads[:, 1:], pts - x[:, None, 0])
257
+ self.n = np.concatenate([1.0 - lam.sum(axis=2, keepdims=True), lam], axis=2)
258
+ # |phi_a| - s phi_a on the side s: the nodal values of the ridge on that side
259
+ coef = np.stack([np.abs(phi) - phi, np.abs(phi) + phi], axis=1) # sides +1, -1
260
+ self.gpsi = np.einsum("msa,mad->msd", coef, self.grads)
261
+ which = (self.side < 0).astype(int) # 0 on the side +1 (and unused), 1 on the side -1
262
+ self.psi = np.einsum("mqa,mqa->mq", self.n, np.take_along_axis(
263
+ coef, which[:, :, None].repeat(4, axis=2), axis=1)) # fmt: skip
264
+ self.which = which
265
+
266
+ def __len__(self) -> int:
267
+ return len(self.x)
268
+
269
+ def functions(self, sl: slice, enriched: bool) -> np.ndarray:
270
+ """The gradients (m x 24 x functions x 3) of the functions of the elements ``sl``
271
+ at their points: the four shape functions, then (``enriched``) their products by
272
+ the ridge."""
273
+ g = self.grads[sl]
274
+ std = np.broadcast_to(g[:, None], (g.shape[0], 24, 4, 3))
275
+ if not enriched:
276
+ return std
277
+ gpsi = np.take_along_axis(self.gpsi[sl], self.which[sl][:, :, None].repeat(3, axis=2),
278
+ axis=1) # fmt: skip
279
+ enr = (
280
+ self.psi[sl][:, :, None, None] * g[:, None]
281
+ + self.n[sl][:, :, :, None] * gpsi[:, :, None, :]
282
+ )
283
+ return np.concatenate([std, enr], axis=2)
284
+
285
+
286
+ def _operator(g: np.ndarray, nd: int) -> np.ndarray:
287
+ """The strain operators (..., 6, 3 functions) of displacements, or the gradient
288
+ operators (..., 3, functions) of a potential, from the gradients ``g`` (..., functions,
289
+ 3) of their functions; the unknowns of a function are consecutive."""
290
+ if nd == 1:
291
+ return np.swapaxes(g, -1, -2)
292
+ nf = g.shape[-2]
293
+ b = np.zeros((*g.shape[:-2], 6, 3 * nf))
294
+ for row, comp, axis in _STRAIN:
295
+ b[..., row, comp::3] = g[..., axis]
296
+ return b
297
+
298
+
299
+ def _gradient_operator(g: np.ndarray) -> np.ndarray:
300
+ """The operators (..., 9, 3 functions) of the displacement gradients ``H_iJ`` (stored
301
+ row by row, as :mod:`morphogen.homogenization.finite`) of displacements, from the
302
+ gradients ``g`` (..., functions, 3) of their functions."""
303
+ nf = g.shape[-2]
304
+ b = np.zeros((*g.shape[:-2], 9, 3 * nf))
305
+ for i in range(3):
306
+ for j in range(3):
307
+ b[..., 3 * i + j, i::3] = g[..., j]
308
+ return b
309
+
310
+
311
+ # -- problems ----------------------------------------------------------------------------------
312
+
313
+
314
+ class _XFEMProblem(MacroscopicLoadings):
315
+ """The periodic problem of a :class:`LevelSetSample` (see the module); ``snap``: the
316
+ level set is moved to this fraction of the edge of the cells from the nodes it passes
317
+ closer to; ``solver``: the linear solver (:mod:`morphogen.homogenization.solvers`)."""
318
+
319
+ physics = ""
320
+ nd = 0
321
+ bc = "periodic"
322
+
323
+ def __init__(self, sample: LevelSetSample, materials: dict[int, Material],
324
+ bc: str = "periodic", *, solver: str = "auto", tol: float = 1e-8,
325
+ maxiter: int | None = None, snap: float = 1e-3,
326
+ physics: str | None = None): # fmt: skip
327
+ if not isinstance(sample, LevelSetSample):
328
+ raise TypeError("the XFEM solver needs a LevelSetSample (LevelSetSample.of)")
329
+ if boundary_condition(bc) != "periodic":
330
+ raise ValueError(
331
+ "the XFEM solver of level sets uses periodic boundary conditions; for kubc, "
332
+ "mixed or subc conditions, mesh the microstructure (morphogen.mesh.conforming)"
333
+ )
334
+ if physics is not None:
335
+ if transport_physics(physics) != (self.nd == 1):
336
+ kind = "a transport phenomenon" if self.nd == 1 else "'elastic'"
337
+ raise ValueError(f"{type(self).__name__}: physics {kind}, got {physics!r}")
338
+ self.physics = physics
339
+ if not 0.0 < snap < 0.5:
340
+ raise ValueError("snap: a fraction of the edge of the cells in (0, 0.5)")
341
+ missing = [p for p in (sample.inside, sample.outside) if p not in materials]
342
+ if missing:
343
+ raise ValueError(f"no material for phase(s) {missing}")
344
+ self.sample = sample
345
+ self.materials = materials
346
+ self.box_volume = sample.volume
347
+ self.tol, self.maxiter, self.solver_method = float(tol), maxiter, solver
348
+ self.nc = 6 if self.nd == 3 else 3
349
+ self._units: dict = {}
350
+ self._solver = None
351
+ self._build(float(snap))
352
+
353
+ # -- set-up ------------------------------------------------------------------------
354
+
355
+ def _law(self, material: Material):
356
+ """The matrix (stiffness or conductivity) and the thermal strain of a phase; None
357
+ for a phase that carries nothing."""
358
+ if material.inert(self.physics):
359
+ return None
360
+ if not material.has(self.physics):
361
+ raise ValueError(f"a phase has no parameters for the physics {self.physics!r}")
362
+ d = np.asarray(material.matrix(self.physics), dtype=float)
363
+ eigen = np.zeros(self.nc)
364
+ if self.nd == 3:
365
+ eigen = tensor_to_voigt(material.expansion_tensor(), strain=True)
366
+ return d, eigen
367
+
368
+ def _build(self, snap: float) -> None:
369
+ from morphogen.mesh.conforming import background_mesh
370
+
371
+ s = self.sample
372
+ n = np.asarray(s.shape)
373
+ h = s.spacing
374
+ nodes, tets, _, _ = background_mesh(n, s.lower, s.upper)
375
+ g = n + 1
376
+ ijk = np.stack(np.unravel_index(np.arange(len(nodes)), g), axis=1)
377
+ wrap = ((ijk[:, 0] % n[0]) * n[1] + ijk[:, 1] % n[1]) * n[2] + ijk[:, 2] % n[2]
378
+ self.n_nodes = int(np.prod(n))
379
+ phi = s.values.ravel().copy()
380
+ limit = snap * float(h.min())
381
+ phi = np.where(np.abs(phi) < limit, np.where(phi < 0, -limit, limit), phi)
382
+ self.phi = phi
383
+ x = nodes[tets]
384
+ torus = wrap[tets]
385
+ pe = phi[torus]
386
+ neg = (pe < 0).sum(axis=1)
387
+ laws = {1.0: self._law(self.materials[s.outside]),
388
+ -1.0: self._law(self.materials[s.inside])} # fmt: skip
389
+ self.laws = laws
390
+ self.empty = all(law is None for law in laws.values())
391
+ whole = neg % 4 == 0
392
+ cut = np.flatnonzero(~whole)
393
+ both = laws[1.0] is not None and laws[-1.0] is not None
394
+ #: the uncut elements that carry a material: corners, nodes on the torus, side
395
+ side = np.where(neg[whole] == 4, -1.0, 1.0)
396
+ keep = np.where(side < 0, laws[-1.0] is not None, laws[1.0] is not None)
397
+ self.el_x, self.el_nodes, self.el_side = x[whole][keep], torus[whole][keep], side[keep]
398
+ self.el_grads, self.el_volume = _gradients(self.el_x)
399
+ #: the cut elements: enriched between two materials, their solid part otherwise
400
+ self.cut = _Cut(x[cut], pe[cut]) if cut.size and not self.empty else None
401
+ self.cut_nodes = torus[cut]
402
+ self.enriched = bool(both and cut.size)
403
+ self.enr_index = np.full(self.n_nodes, -1, dtype=np.int64)
404
+ if self.enriched:
405
+ ids = np.unique(self.cut_nodes)
406
+ self.enr_index[ids] = np.arange(ids.size)
407
+ self.n_enriched = int((self.enr_index >= 0).sum())
408
+ self.n_dofs = self.nd * (self.n_nodes + self.n_enriched)
409
+ # the background mesh of the fields: each element in the phase of most of its volume
410
+ phase = np.where(neg >= 2, s.inside, s.outside)
411
+ self.mesh = TetMesh(nodes, tets, phase, np.asarray(s.lower), np.asarray(s.upper),
412
+ periodic=True) # fmt: skip
413
+ self._wrap, self._whole, self._keep, self._cut_ids = wrap, whole, keep, cut
414
+ if not self.empty:
415
+ self._assemble()
416
+
417
+ def _element_dofs(self, nodes: np.ndarray, enriched: bool) -> np.ndarray:
418
+ """The unknowns of elements of nodes ``nodes`` (m x 4): those of their four
419
+ standard functions, then of the enriched ones."""
420
+ nd = self.nd
421
+ comp = np.arange(nd)
422
+ std = (nd * nodes[:, :, None] + comp).reshape(len(nodes), -1)
423
+ if not enriched:
424
+ return std
425
+ enr = (nd * (self.n_nodes + self.enr_index[nodes])[:, :, None] + comp).reshape(
426
+ len(nodes), -1
427
+ )
428
+ return np.concatenate([std, enr], axis=1)
429
+
430
+ def _cut_weights(self, sl: slice) -> dict:
431
+ """The weights of the points of the cut elements ``sl`` on each side that carries a
432
+ material."""
433
+ c = self.cut
434
+ return {v: np.where(c.side[sl] == v, c.w[sl], 0.0) for v, law in self.laws.items()
435
+ if law is not None} # fmt: skip
436
+
437
+ def _assemble(self) -> None:
438
+ nd = self.nd
439
+ n = self.n_dofs
440
+ rows, cols, vals = [], [], []
441
+ # the uncut elements: constant strains
442
+ b = _operator(self.el_grads, nd)
443
+ for v, law in self.laws.items():
444
+ sel = np.flatnonzero(self.el_side == v)
445
+ if law is None or not sel.size:
446
+ continue
447
+ for lo in range(0, sel.size, 16 * _CHUNK):
448
+ part = sel[lo : lo + 16 * _CHUNK]
449
+ bt = np.swapaxes(b[part], 1, 2)
450
+ ke = self.el_volume[part, None, None] * (bt @ (law[0] @ b[part]))
451
+ dofs = self._element_dofs(self.el_nodes[part], False)
452
+ rows.append(np.repeat(dofs, dofs.shape[1], axis=1).ravel())
453
+ cols.append(np.tile(dofs, (1, dofs.shape[1])).ravel())
454
+ vals.append(ke.ravel())
455
+ if self.cut is not None:
456
+ for lo in range(0, len(self.cut), _CHUNK):
457
+ sl = slice(lo, lo + _CHUNK)
458
+ bq = _operator(self.cut.functions(sl, self.enriched), nd)
459
+ ke = 0.0
460
+ m, nf = bq.shape[0], bq.shape[-1]
461
+ for v, w in self._cut_weights(sl).items():
462
+ # sum_q w_q B_q^T D B_q, the points of each element stacked
463
+ db = (self.laws[v][0] @ bq) * w[:, :, None, None]
464
+ ke = ke + np.swapaxes(bq.reshape(m, -1, nf), 1, 2) @ db.reshape(m, -1, nf)
465
+ dofs = self._element_dofs(self.cut_nodes[sl], self.enriched)
466
+ rows.append(np.repeat(dofs, dofs.shape[1], axis=1).ravel())
467
+ cols.append(np.tile(dofs, (1, dofs.shape[1])).ravel())
468
+ vals.append(ke.ravel())
469
+ k = sp.coo_matrix(
470
+ (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)
471
+ ).tocsr()
472
+ self.matrix = (0.5 * (k + k.T)).tocsr()
473
+ diag = self.matrix.diagonal()
474
+ # the unknowns that carry something: not those of the nodes in the voids
475
+ active = diag > 1e-14 * diag.max()
476
+ self._regularization = 0.0
477
+ if any(law is None for law in self.laws.values()):
478
+ # parts of the solid that nothing holds (cut off by the voids) move freely: a
479
+ # small stiffness keeps the system definite without loading the others
480
+ self._regularization = 1e-10 * float(diag.mean())
481
+ shift = sp.diags(np.where(active, self._regularization, 0.0))
482
+ self.matrix = (self.matrix + shift).tocsr()
483
+ #: one node held against the translations of the periodic fluctuation
484
+ held = int(np.flatnonzero(active[: nd * self.n_nodes : nd])[0])
485
+ active[nd * held : nd * held + nd] = False
486
+ self.free = np.flatnonzero(active)
487
+ volume = float(self.el_volume.sum())
488
+ if self.cut is not None:
489
+ volume += float(sum(w.sum() for w in self._cut_weights(slice(None)).values()))
490
+ self.material_fraction = volume / self.box_volume
491
+
492
+ def _linear_solver(self) -> LinearSolver:
493
+ if self._solver is None:
494
+ reduced = self.matrix[self.free][:, self.free].tocsr()
495
+ near_null = None
496
+ if self.nd == 3 and reduced.shape[0] > 0:
497
+ near_null = self._rigid_modes()[self.free]
498
+ self._solver = LinearSolver(reduced, method=self.solver_method, tol=self.tol,
499
+ maxiter=self.maxiter, near_null=near_null) # fmt: skip
500
+ return self._solver
501
+
502
+ def _rigid_modes(self) -> np.ndarray:
503
+ """Translations and rotations of the standard unknowns (zero on the enriched): the
504
+ near-null space of the multigrid."""
505
+ nd, nn = self.nd, self.n_nodes
506
+ x = np.zeros((nn, 3))
507
+ x[self._wrap] = self.mesh.nodes
508
+ x = x - x.mean(axis=0)
509
+ modes = np.zeros((self.n_dofs, 6))
510
+ for c in range(3):
511
+ modes[c : nd * nn : nd, c] = 1.0
512
+ modes[1 : nd * nn : nd, 3], modes[2 : nd * nn : nd, 3] = -x[:, 2], x[:, 1]
513
+ modes[2 : nd * nn : nd, 4], modes[0 : nd * nn : nd, 4] = -x[:, 0], x[:, 2]
514
+ modes[0 : nd * nn : nd, 5], modes[1 : nd * nn : nd, 5] = -x[:, 1], x[:, 0]
515
+ return modes
516
+
517
+ # -- loads and averages --------------------------------------------------------------
518
+
519
+ def _affine(self, x: np.ndarray, corners: np.ndarray) -> np.ndarray:
520
+ """The values (m x 4 nd) of the affine field of the macroscopic strain (gradient)
521
+ ``x`` at the corners of elements."""
522
+ if self.nd == 1:
523
+ return corners @ x
524
+ e = voigt_to_tensor(x, strain=True)
525
+ return (corners @ e.T).reshape(len(corners), -1)
526
+
527
+ def _generalized(self, q: np.ndarray, x: np.ndarray):
528
+ """The strains (gradients) of the uncut elements (m x nc) and of the points of the
529
+ cut ones (m x 24 x nc), for the fluctuation ``q`` and the macroscopic ``x``."""
530
+ nd = self.nd
531
+ b = _operator(self.el_grads, nd)
532
+ ue = q[self._element_dofs(self.el_nodes, False)]
533
+ whole = np.einsum("mra,ma->mr", b, ue) + x
534
+ cut = None
535
+ if self.cut is not None:
536
+ cut = np.empty((len(self.cut), 24, self.nc))
537
+ for lo in range(0, len(self.cut), _CHUNK):
538
+ sl = slice(lo, lo + _CHUNK)
539
+ bq = _operator(self.cut.functions(sl, self.enriched), nd)
540
+ ue = q[self._element_dofs(self.cut_nodes[sl], self.enriched)]
541
+ cut[sl] = np.einsum("mqra,ma->mqr", bq, ue) + x
542
+ return whole, cut
543
+
544
+ def _load(self, stress_of) -> tuple[np.ndarray, float]:
545
+ """The right-hand side ``-int B^T s`` of the stresses ``s = stress_of(law)`` of
546
+ the phases (uniform in each: those of a macroscopic strain or of a change of
547
+ temperature), and its scale without the cancellations between elements."""
548
+ nd = self.nd
549
+ f = np.zeros(self.n_dofs)
550
+ scale = 0.0
551
+ b = _operator(self.el_grads, nd)
552
+ for v, law in self.laws.items():
553
+ sel = np.flatnonzero(self.el_side == v)
554
+ if law is None:
555
+ continue
556
+ s = stress_of(law)
557
+ if sel.size:
558
+ fe = self.el_volume[sel, None] * np.einsum("mra,r->ma", b[sel], s)
559
+ np.add.at(f, self._element_dofs(self.el_nodes[sel], False), -fe)
560
+ scale += float(np.sum(fe * fe))
561
+ if self.cut is not None:
562
+ for lo in range(0, len(self.cut), _CHUNK):
563
+ sl = slice(lo, lo + _CHUNK)
564
+ bq = _operator(self.cut.functions(sl, self.enriched), nd)
565
+ w = self._cut_weights(sl)[v]
566
+ fe = np.einsum("mq,mqra,r->ma", w, bq, s)
567
+ np.add.at(f, self._element_dofs(self.cut_nodes[sl], self.enriched), -fe)
568
+ scale += float(np.sum(fe * fe))
569
+ return f, float(np.sqrt(scale))
570
+
571
+ def _solve(self, rhs: np.ndarray, scale: float):
572
+ q = np.zeros(self.n_dofs)
573
+ if float(np.linalg.norm(rhs[self.free])) <= NEGLIGIBLE * scale:
574
+ return q, SolveInfo("xfem", self.free.size, 0, 0.0, 0.0, 0.0)
575
+ solver = self._linear_solver()
576
+ q[self.free], info = solver.solve(rhs[self.free])
577
+ info.method = f"xfem-{info.method}"
578
+ return q, info
579
+
580
+ def _sign(self) -> float:
581
+ """The flux of a transport is ``-K grad``; a stress ``D eps``."""
582
+ return 1.0 if self.nd == 3 else -1.0
583
+
584
+ def _field(self, x: np.ndarray, dt: float = 0.0):
585
+ """The periodic fluctuation (standard and enriched unknowns) of the macroscopic
586
+ strain (gradient) ``x`` and the change of temperature ``dt``."""
587
+ x = np.asarray(x, dtype=float)
588
+ rhs, scale = self._load(lambda law: law[0] @ (x - dt * law[1]))
589
+ return self._solve(rhs, scale)
590
+
591
+ def _integrals(self, q: np.ndarray, x: np.ndarray, dt: float):
592
+ """Per side: the volume, the integrals of the strains, stresses and energy
593
+ density, and of their squares."""
594
+ whole, cut = self._generalized(q, x)
595
+ out = {}
596
+ for v, law in self.laws.items():
597
+ if law is None:
598
+ continue
599
+ d, eigen = law
600
+ sel = self.el_side == v
601
+ eps = [whole[sel]]
602
+ wts = [self.el_volume[sel]]
603
+ if cut is not None:
604
+ w = self._cut_weights(slice(None))[v]
605
+ on = w > 0
606
+ eps.append(cut[on])
607
+ wts.append(w[on])
608
+ eps, wts = np.concatenate(eps), np.concatenate(wts)
609
+ sig = self._sign() * (eps - dt * eigen) @ d
610
+ energy = np.einsum("pi,pi->p", sig, eps - dt * eigen) * self._sign()
611
+ out[v] = (wts, eps, sig, energy)
612
+ return out
613
+
614
+ def _dual(self, q, x, dt=0.0) -> np.ndarray:
615
+ total = np.zeros(self.nc)
616
+ for wts, _, sig, _ in self._integrals(q, np.asarray(x, dtype=float), dt).values():
617
+ total += wts @ sig
618
+ return total / self.box_volume
619
+
620
+ def _evaluate(self, loading, q, x, dt, info, fields, t0) -> Solution:
621
+ elastic = self.nd == 3
622
+ x = np.asarray(x, dtype=float)
623
+ parts = self._integrals(q, x, dt)
624
+ total, energy, phases = np.zeros(self.nc), 0.0, []
625
+ names = ("strain", "stress", "energy") if elastic else ("gradient", "flux", "dissipation")
626
+ half = np.array([1.0, 1.0, 1.0, 0.5, 0.5, 0.5]) if elastic else 1.0
627
+ for v, (wts, eps, sig, dens) in parts.items():
628
+ vol = wts.sum()
629
+ total += wts @ sig
630
+ energy += wts @ dens
631
+ values = (eps * half, sig, dens[:, None])
632
+ mean = {n: wts @ a / vol for n, a in zip(names, values, strict=True)}
633
+ std = {n: np.sqrt(np.maximum(wts @ (a * a) / vol - mean[n] ** 2, 0.0))
634
+ for n, a in zip(names, values, strict=True)} # fmt: skip
635
+ phase = self.sample.inside if v < 0 else self.sample.outside
636
+ phases.append(PhaseStatistics(phase, float(vol / self.box_volume), mean, std))
637
+ fld = self._fields(q, x, dt) if fields else None
638
+ info.solve_s = time.perf_counter() - t0
639
+ mean_stress = total / self.box_volume
640
+ return Solution(
641
+ physics=self.physics,
642
+ bc=self.bc,
643
+ loading=loading,
644
+ strain=voigt_to_tensor(x, strain=True) if elastic else x.copy(),
645
+ stress=voigt_to_tensor(mean_stress, strain=False) if elastic else mean_stress,
646
+ energy=float(energy / self.box_volume),
647
+ material_fraction=self.material_fraction,
648
+ phases=sorted(phases, key=lambda p: p.phase),
649
+ info=info,
650
+ fields=fld,
651
+ support=self.mesh if fields else None,
652
+ )
653
+
654
+ def _fields(self, q, x, dt) -> dict:
655
+ """The means over the elements of the background mesh of the strains, stresses
656
+ and energy (zero in the voids), and the nodal displacement (the affine field and
657
+ the standard fluctuation: the enrichment vanishes at the nodes)."""
658
+ elastic = self.nd == 3
659
+ whole, cut = self._generalized(q, x)
660
+ m = self.mesh.n_elements
661
+ eps, sig, dens = np.zeros((m, self.nc)), np.zeros((m, self.nc)), np.zeros(m)
662
+ ids = np.flatnonzero(self._whole)[self._keep]
663
+ for v, law in self.laws.items():
664
+ if law is None:
665
+ continue
666
+ d, eigen = law
667
+ sel = self.el_side == v
668
+ eps[ids[sel]] = whole[sel]
669
+ sig[ids[sel]] = self._sign() * (whole[sel] - dt * eigen) @ d
670
+ if cut is not None:
671
+ w = self._cut_weights(slice(None))[v]
672
+ s = self._sign() * (cut - dt * eigen) @ d
673
+ eps[self._cut_ids] += np.einsum("mq,mqr->mr", w, cut) / self.cut.volume[:, None]
674
+ sig[self._cut_ids] += np.einsum("mq,mqr->mr", w, s) / self.cut.volume[:, None]
675
+ dens = np.einsum("mi,mi->m", sig, eps) * self._sign()
676
+ nd, nn = self.nd, self.n_nodes
677
+ nodal = q[: nd * nn].reshape(nn, nd)[self._wrap]
678
+ if elastic:
679
+ nodal = nodal + self.mesh.nodes @ voigt_to_tensor(x, strain=True).T
680
+ return {"strain": eps, "stress": sig, "energy": dens, "displacement": nodal}
681
+ nodal = nodal[:, 0] + self.mesh.nodes @ x
682
+ return {"gradient": eps, "flux": sig, "dissipation": dens, "temperature": nodal}
683
+
684
+ def _empty_solution(self, loading: Loading, t0: float) -> Solution:
685
+ elastic = self.nd == 3
686
+ values = np.where(loading.strain_controlled, loading.array, 0.0)
687
+ return Solution(
688
+ physics=self.physics,
689
+ bc=self.bc,
690
+ loading=loading,
691
+ strain=voigt_to_tensor(values, strain=True) if elastic else values,
692
+ stress=np.zeros((3, 3)) if elastic else np.zeros(3),
693
+ energy=0.0,
694
+ material_fraction=0.0,
695
+ phases=[],
696
+ info=SolveInfo("none", 0, 0, 0.0, 0.0, time.perf_counter() - t0),
697
+ )
698
+
699
+ def summary(self) -> dict:
700
+ """The sizes of the discretization: elements, those cut, nodes, enriched nodes and
701
+ unknowns."""
702
+ return {
703
+ "elements": int(self.mesh.n_elements),
704
+ "cut": 0 if self.cut is None else len(self.cut),
705
+ "nodes": self.n_nodes,
706
+ "enriched": self.n_enriched,
707
+ "unknowns": int(self.free.size) if not self.empty else 0,
708
+ }
709
+
710
+
711
+ class XFEMElasticProblem(_XFEMProblem):
712
+ """Periodic linear (thermo-)elasticity of a :class:`LevelSetSample` by extended finite
713
+ elements (see the module)."""
714
+
715
+ physics = "elastic"
716
+ nd = 3
717
+
718
+
719
+ class XFEMThermalProblem(_XFEMProblem):
720
+ """Periodic steady conduction of a :class:`LevelSetSample` by extended finite
721
+ elements, or with ``physics`` any other transport phenomenon of a scalar potential
722
+ (:data:`~morphogen.homogenization.materials.TRANSPORT`)."""
723
+
724
+ physics = "thermal"
725
+ nd = 1
726
+
727
+
728
+ # -- loading paths -------------------------------------------------------------------------------
729
+
730
+
731
+ class _XFEMPaths:
732
+ """Discretization of the loading paths by extended finite elements (see
733
+ :class:`~morphogen.homogenization.nonlinear._PathSolver`): the integration points are
734
+ those of the uncut elements (one each), then those of the sub-tetrahedra of the cut
735
+ elements on the sides that carry a material; the tangent is assembled at each
736
+ iteration and solved as that of the finite elements. In finite strains (total
737
+ Lagrangian: the level set cuts the elements of the reference configuration, and the
738
+ enrichment functions are those of its points) the measures are the displacement
739
+ gradients, of nine components, their conjugates the first Piola-Kirchhoff stresses,
740
+ and the macroscopic gradient is upper triangular
741
+ (:mod:`morphogen.homogenization.finite`)."""
742
+
743
+ def __init__(self, problem):
744
+ from morphogen.homogenization.solvers import choose_method
745
+
746
+ self.problem = problem
747
+ p = problem
748
+ self.finite = bool(p.finite)
749
+ self.n_q = p.free.size
750
+ self.n_whole = len(p.el_volume)
751
+ self.b_whole = self._operator(p.el_grads)
752
+ self.dofs_whole = p._element_dofs(p.el_nodes, False)
753
+ self.solver = None
754
+ self.iterative = choose_method(p.solver_method, self.n_q) != "direct"
755
+
756
+ # -- the arrays of the points and their behaviours: those of the CPU -----------------
757
+
758
+ def arrays(self, n_pts: int, nc: int, width: int) -> tuple:
759
+ from morphogen.homogenization.nonlinear import _PointArrays
760
+
761
+ return _PointArrays.arrays(self, n_pts, nc, width)
762
+
763
+ def integrate(self, *args) -> int:
764
+ from morphogen.homogenization.nonlinear import _PointArrays
765
+
766
+ return _PointArrays.integrate(self, *args)
767
+
768
+ def stress_scale(self, sigma, wts) -> float:
769
+ return float(np.sum(np.abs(wts) * np.sqrt(np.einsum("ij,ij->i", sigma, sigma))))
770
+
771
+ def asymmetry(self, tangent, wts) -> float:
772
+ from morphogen.homogenization.nonlinear import asymmetry
773
+
774
+ return asymmetry(tangent, wts, self.problem.point_group)
775
+
776
+ def symmetrize(self, tangent) -> None:
777
+ tangent[...] = 0.5 * (tangent + np.swapaxes(tangent, 1, 2))
778
+
779
+ def host(self, *arrays) -> tuple:
780
+ return arrays
781
+
782
+ # -- kinematics, forces and tangents --------------------------------------------------
783
+
784
+ def _full(self, q) -> np.ndarray:
785
+ out = np.zeros(self.problem.n_dofs)
786
+ out[self.problem.free] = q
787
+ return out
788
+
789
+ def _operator(self, g: np.ndarray) -> np.ndarray:
790
+ """The operators of the measures of strain of displacements (the strains, or the
791
+ displacement gradients in finite strains) from the gradients of their functions."""
792
+ return _gradient_operator(g) if self.finite else _operator(g, 3)
793
+
794
+ def _macro(self, e) -> np.ndarray:
795
+ """The measure of strain of the macroscopic components ``e`` (6)."""
796
+ from morphogen.homogenization import finite as fin
797
+
798
+ e = np.asarray(e, dtype=float)
799
+ return fin.gradient_of(e) if self.finite else e
800
+
801
+ def _measures(self, q_full, e):
802
+ """The measures of strain of the uncut elements and of the points of the cut
803
+ ones (m x 24 x components) for the fluctuation ``q_full`` and the macroscopic
804
+ components ``e``."""
805
+ p = self.problem
806
+ x = self._macro(e)
807
+ ue = q_full[self.dofs_whole]
808
+ whole = np.einsum("mra,ma->mr", self.b_whole, ue) + x
809
+ cut = None
810
+ if p.cut is not None:
811
+ cut = np.empty((len(p.cut), 24, len(x)))
812
+ for lo in range(0, len(p.cut), _CHUNK):
813
+ sl = slice(lo, lo + _CHUNK)
814
+ bq = self._operator(p.cut.functions(sl, p.enriched))
815
+ ue = q_full[p._element_dofs(p.cut_nodes[sl], p.enriched)]
816
+ cut[sl] = np.einsum("mqra,ma->mqr", bq, ue) + x
817
+ return whole, cut
818
+
819
+ def displacement(self, q, e) -> np.ndarray:
820
+ p = self.problem
821
+ nodal = self._full(q)[: 3 * p.n_nodes].reshape(-1, 3)[p._wrap]
822
+ if self.finite:
823
+ gradient = self._macro(e).reshape(3, 3)
824
+ else:
825
+ gradient = voigt_to_tensor(e, strain=True)
826
+ return (nodal + p.mesh.nodes @ gradient.T).ravel()
827
+
828
+ def measures(self, q, e, grads, wts) -> None:
829
+ p = self.problem
830
+ whole, cut = self._measures(self._full(q), e)
831
+ grads[: self.n_whole] = whole
832
+ wts[: self.n_whole] = p.el_volume
833
+ if cut is not None:
834
+ grads[self.n_whole :] = cut[p.cut_points]
835
+ wts[self.n_whole :] = p.cut.w[p.cut_points]
836
+
837
+ def _cut_arrays(self, values, sl: slice):
838
+ """The values of the points of the cut elements ``sl`` (m x 24 x ...), zero at
839
+ the points that carry nothing."""
840
+ p = self.problem
841
+ lo, hi, _ = sl.indices(len(p.cut))
842
+ mask = p.cut_points[lo:hi]
843
+ start = self.n_whole + int(p.cut_points[:lo].sum())
844
+ out = np.zeros((hi - lo, 24, *values.shape[1:]))
845
+ out[mask] = values[start : start + int(mask.sum())]
846
+ return out, np.where(mask, p.cut.w[lo:hi], 0.0)
847
+
848
+ def forces(self, sigma, wts):
849
+ p = self.problem
850
+ f = np.zeros(p.n_dofs)
851
+ fe = p.el_volume[:, None] * np.einsum("mra,mr->ma", self.b_whole, sigma[: self.n_whole])
852
+ np.add.at(f, self.dofs_whole, fe)
853
+ scale = float(np.sum(fe * fe))
854
+ if p.cut is not None:
855
+ for lo in range(0, len(p.cut), _CHUNK):
856
+ sl = slice(lo, lo + _CHUNK)
857
+ bq = self._operator(p.cut.functions(sl, p.enriched))
858
+ s, w = self._cut_arrays(sigma, sl)
859
+ fe = np.einsum("mq,mqra,mqr->ma", w, bq, s)
860
+ np.add.at(f, p._element_dofs(p.cut_nodes[sl], p.enriched), fe)
861
+ scale += float(np.sum(fe * fe))
862
+ total = np.einsum("p,pi->i", wts, sigma)
863
+ return f[p.free], total, float(np.sqrt(scale))
864
+
865
+ def _tangent(self, tangent, wts) -> sp.csr_matrix:
866
+ """The tangent stiffness of all the unknowns, ``sum int B^T C B``."""
867
+ p = self.problem
868
+ rows, cols, vals = [], [], []
869
+ b = self.b_whole
870
+ ke = p.el_volume[:, None, None] * (np.swapaxes(b, 1, 2) @ (tangent[: self.n_whole] @ b))
871
+ dofs = self.dofs_whole
872
+ rows.append(np.repeat(dofs, 12, axis=1).ravel())
873
+ cols.append(np.tile(dofs, (1, 12)).ravel())
874
+ vals.append(ke.ravel())
875
+ if p.cut is not None:
876
+ for lo in range(0, len(p.cut), _CHUNK):
877
+ sl = slice(lo, lo + _CHUNK)
878
+ bq = self._operator(p.cut.functions(sl, p.enriched))
879
+ c, w = self._cut_arrays(tangent, sl)
880
+ m, nf = bq.shape[0], bq.shape[-1]
881
+ cb = (c @ bq) * w[:, :, None, None]
882
+ ke = np.swapaxes(bq.reshape(m, -1, nf), 1, 2) @ cb.reshape(m, -1, nf)
883
+ dofs = p._element_dofs(p.cut_nodes[sl], p.enriched)
884
+ rows.append(np.repeat(dofs, nf, axis=1).ravel())
885
+ cols.append(np.tile(dofs, (1, nf)).ravel())
886
+ vals.append(ke.ravel())
887
+ n = p.n_dofs
888
+ return sp.coo_matrix(
889
+ (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)
890
+ ).tocsr()
891
+
892
+ def full_tangent(self, tangent, wts) -> sp.csr_matrix:
893
+ return self._tangent(tangent, wts)
894
+
895
+ def linearize(self, tangent, wts, first: bool, symmetric: bool | None = None):
896
+ p = self.problem
897
+ k = self._tangent(tangent, wts)
898
+ kqq = k[p.free][:, p.free].tocsr()
899
+ if p._regularization:
900
+ kqq = (kqq + p._regularization * sp.identity(kqq.shape[0])).tocsr()
901
+ symmetric = p.symmetrize if symmetric is None else symmetric
902
+ if first or self.solver is None:
903
+ near_null = p._rigid_modes()[p.free]
904
+ self.solver = LinearSolver(kqq, method=p.solver_method, tol=p.tol, maxiter=p.maxiter,
905
+ near_null=near_null, symmetric=symmetric) # fmt: skip
906
+ else:
907
+ self.solver = self.solver.updated(kqq, symmetric)
908
+ return self.solver
909
+
910
+ def macro_columns(self, tangent, wts) -> tuple[np.ndarray, np.ndarray]:
911
+ """``int B^T C`` on all the unknowns (n x 6) and ``int C`` (6 x 6), for the six
912
+ macroscopic components (in finite strains: those of the upper triangular
913
+ gradient among the nine)."""
914
+ p = self.problem
915
+ if self.finite:
916
+ from morphogen.homogenization.finite import MACRO
917
+
918
+ macro = list(MACRO)
919
+ tangent = tangent[:, :, macro]
920
+ columns = np.zeros((p.n_dofs, 6))
921
+ bt = np.swapaxes(self.b_whole, 1, 2)
922
+ fe = p.el_volume[:, None, None] * (bt @ tangent[: self.n_whole])
923
+ np.add.at(columns, self.dofs_whole, fe)
924
+ if p.cut is not None:
925
+ for lo in range(0, len(p.cut), _CHUNK):
926
+ sl = slice(lo, lo + _CHUNK)
927
+ bq = self._operator(p.cut.functions(sl, p.enriched))
928
+ c, w = self._cut_arrays(tangent, sl)
929
+ fe = np.einsum("mq,mqra,mqrs->mas", w, bq, c)
930
+ np.add.at(columns, p._element_dofs(p.cut_nodes[sl], p.enriched), fe)
931
+ kee = np.einsum("p,pij->ij", wts, tangent)
932
+ return columns, kee[macro] if self.finite else kee
933
+
934
+ def coupling(self, tangent, wts, unknown):
935
+ columns, kee = self.macro_columns(tangent, wts)
936
+ return columns[self.problem.free][:, unknown], kee
937
+
938
+ def macro_response(self, tangent, wts, v) -> np.ndarray:
939
+ """``K_Ew v``: the integral of the stress increments of the fluctuation ``v``."""
940
+ p = self.problem
941
+ whole, cut = self._measures(self._full(v), np.zeros(6))
942
+ eps = whole if cut is None else np.concatenate([whole, cut[p.cut_points]])
943
+ out = np.einsum("p,pij,pj->i", wts, tangent, eps)
944
+ if self.finite:
945
+ from morphogen.homogenization.finite import macro_part
946
+
947
+ out = macro_part(out)
948
+ return out
949
+
950
+
951
+ class NonlinearXFEMProblem(_PathSolver, _XFEMProblem):
952
+ """Loading paths of a :class:`LevelSetSample` with the nonlinear behaviours of its
953
+ phases, by extended finite elements in small or finite strains (``kinematics``; see
954
+ the module and :class:`~morphogen.homogenization.nonlinear.NonlinearFEProblem` for
955
+ the options of the iterations): :meth:`run` follows a
956
+ :class:`~morphogen.homogenization.paths.LoadingPath`. The linear problems of the
957
+ sample are those of :class:`XFEMElasticProblem`."""
958
+
959
+ physics = "elastic"
960
+ nd = 3
961
+
962
+ def __init__(self, sample: LevelSetSample, materials: dict[int, Material],
963
+ bc: str = "periodic", *, solver: str = "auto", tol: float = 1e-8,
964
+ maxiter: int | None = None, snap: float = 1e-3, newton_tol: float = 1e-6,
965
+ max_newton: int = 25, max_cuts: int = 10, kinematics: str = "small",
966
+ tangent: str = "auto"): # fmt: skip
967
+ from morphogen.homogenization.materials import material_table
968
+ from morphogen.homogenization.nonlinear import behaviour_table
969
+
970
+ super().__init__(sample, materials, bc, solver=solver, tol=tol, maxiter=maxiter, snap=snap)
971
+ self._path_options(newton_tol, max_newton, max_cuts, kinematics, tangent)
972
+ if self.empty:
973
+ return
974
+ s = self.sample
975
+ phase = np.where(self.el_side < 0, s.inside, s.outside)
976
+ self.cut_points = np.zeros((0, 24), dtype=bool)
977
+ if self.cut is not None:
978
+ carried = np.zeros(self.cut.w.shape, dtype=bool)
979
+ for v, law in self.laws.items():
980
+ if law is not None:
981
+ carried |= (self.cut.side == v) & (self.cut.w > 0)
982
+ self.cut_points = carried
983
+ phase = np.concatenate([phase, np.where(self.cut.side[carried] < 0, s.inside,
984
+ s.outside)]) # fmt: skip
985
+ self.table = material_table(phase, materials, "elastic")
986
+ self.groups = self.table.phases
987
+ beh = behaviour_table(phase, materials, self.table, finite=self.finite)
988
+ self._point_behaviours(beh, self.table.mat, self.table.stat, 1)
989
+ if beh.nonlinear:
990
+ log.info(
991
+ "XFEM loading paths: linear tetrahedra lock under isochoric plastic flow "
992
+ "(prefer conforming quadratic meshes or voxels for plasticity)"
993
+ )
994
+
995
+ def _discretization(self) -> _XFEMPaths:
996
+ return _XFEMPaths(self)
997
+
998
+ def _support(self):
999
+ return self.mesh
1000
+
1001
+ def _element_mean(self, values) -> np.ndarray:
1002
+ """The means of the values of the points over the elements of the background
1003
+ mesh (zero in the voids): those of the points of the sub-tetrahedra of the cut
1004
+ elements, weighted."""
1005
+ n_whole = len(self.el_volume)
1006
+ out = np.zeros((self.mesh.n_elements, *values.shape[1:]))
1007
+ out[np.flatnonzero(self._whole)[self._keep]] = values[:n_whole]
1008
+ if self.cut is not None:
1009
+ rows = np.nonzero(self.cut_points)[0]
1010
+ w = self.cut.w[self.cut_points]
1011
+ total = np.bincount(rows, w, minlength=len(self.cut))
1012
+ share = w / total[rows]
1013
+ part = np.zeros((len(self.cut), *values.shape[1:]))
1014
+ np.add.at(part, rows, share.reshape(-1, *[1] * (values.ndim - 1)) * values[n_whole:])
1015
+ out[self._cut_ids] = part
1016
+ return out