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,499 @@
1
+ """FFT-based homogenization of periodic voxel images.
2
+
3
+ Each voxel is a trilinear hexahedron and the fluctuation ``w`` of ``u = E x + w``
4
+ (``T = G . x + w``) is periodic on the grid. The equilibrium equations ``K w = f`` are
5
+ solved by conjugate gradients without assembling ``K`` (each product loops over the
6
+ voxels), preconditioned by the inverse of the stiffness ``K0`` of a homogeneous
7
+ reference medium. ``K0`` is a circulant operator: it is diagonal (3 x 3 blocks in
8
+ elasticity) in Fourier space, and its inverse costs a few FFTs (Schneider, Merkert &
9
+ Kabel 2017, "FFT-based homogenization for microstructures discretized by linear
10
+ hexahedral elements", Int. J. Numer. Meth. Engng 109, 1461-1489). This is a
11
+ Lippmann-Schwinger scheme whose discrete Green operator is that of trilinear elements:
12
+ the fields have no ringing artefacts, and pores (zero stiffness) are handled without an
13
+ ersatz material.
14
+
15
+ The number of iterations grows with the contrast between the phases (as its square
16
+ root, at worst); the memory is a few vectors of the size of the grid. With
17
+ ``device="gpu"`` the conjugate gradients run on the GPU (:mod:`morphogen.homogenization.
18
+ gpu`); the solutions are those of the CPU to the tolerance of the iterations.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import time
25
+
26
+ import numpy as np
27
+ from numba import njit, prange
28
+ from scipy import fft as sfft
29
+
30
+ from morphogen import gpu, settings
31
+ from morphogen.homogenization import kernels
32
+ from morphogen.homogenization.core import (
33
+ Loading,
34
+ MacroscopicLoadings,
35
+ PhaseStatistics,
36
+ Solution,
37
+ boundary_condition,
38
+ )
39
+ from morphogen.homogenization.elements import hex_element, voigt_to_tensor
40
+ from morphogen.homogenization.materials import Material, material_table, transport_physics
41
+ from morphogen.homogenization.solvers import NEGLIGIBLE, SolveInfo, conjugate_gradient, norm
42
+ from morphogen.image import VoxelImage
43
+
44
+ log = logging.getLogger("morphogen")
45
+
46
+
47
+ @njit(parallel=True, cache=True)
48
+ def apply_operator(nx, ny, nz, nd, group, mats, w, out):
49
+ """out = K w on the periodic grid; ``mats[g]`` is the element matrix of material
50
+ ``g`` of the voxels with ``group`` g (-1: no stiffness). Loops over nodes, so no
51
+ atomics are needed."""
52
+ corners = kernels.CORNERS
53
+ size = 8 * nd
54
+ for n in prange(nx * ny * nz):
55
+ k = n % nz
56
+ j = (n // nz) % ny
57
+ i = n // (ny * nz)
58
+ acc = np.zeros(3)
59
+ we = np.empty(size)
60
+ for a in range(2):
61
+ ei = i - a if i - a >= 0 else nx - 1
62
+ for b in range(2):
63
+ ej = j - b if j - b >= 0 else ny - 1
64
+ for c in range(2):
65
+ ek = k - c if k - c >= 0 else nz - 1
66
+ g = group[(ei * ny + ej) * nz + ek]
67
+ if g < 0:
68
+ continue
69
+ ln = kernels.CORNER_INDEX[a, b, c]
70
+ for q in range(8):
71
+ qi = ei + corners[q, 0]
72
+ qj = ej + corners[q, 1]
73
+ qk = ek + corners[q, 2]
74
+ if qi == nx:
75
+ qi = 0
76
+ if qj == ny:
77
+ qj = 0
78
+ if qk == nz:
79
+ qk = 0
80
+ m = (qi * ny + qj) * nz + qk
81
+ for c2 in range(nd):
82
+ we[q * nd + c2] = w[m * nd + c2]
83
+ mat = mats[g]
84
+ for r in range(nd):
85
+ row = ln * nd + r
86
+ s = 0.0
87
+ for col in range(size):
88
+ s += mat[row, col] * we[col]
89
+ acc[r] += s
90
+ for r in range(nd):
91
+ out[n * nd + r] = acc[r]
92
+
93
+
94
+ def _stencil(k: np.ndarray, nd: int) -> np.ndarray:
95
+ """Blocks (3, 3, 3, nd, nd) of the homogeneous operator of element matrix ``k`` for
96
+ node offsets -1, 0, 1."""
97
+ blocks = np.zeros((3, 3, 3, nd, nd))
98
+ corners = kernels.CORNERS
99
+ for ln in range(8):
100
+ for q in range(8):
101
+ off = corners[q] - corners[ln] + 1
102
+ rows = slice(ln * nd, ln * nd + nd)
103
+ cols = slice(q * nd, q * nd + nd)
104
+ blocks[off[0], off[1], off[2]] += k[rows, cols]
105
+ return blocks
106
+
107
+
108
+ class FourierPreconditioner:
109
+ """Inverse of a homogeneous reference operator, applied in Fourier space: the
110
+ element matrix ``coef_a * ka + coef_b * kb`` (see :meth:`from_element`)."""
111
+
112
+ def __init__(self, shape, ka, kb, coef_a: float, coef_b: float, nd: int):
113
+ self._build(shape, coef_a * np.asarray(ka) + coef_b * np.asarray(kb), nd)
114
+
115
+ @classmethod
116
+ def from_element(cls, shape, k_ref, nd: int) -> FourierPreconditioner:
117
+ """Preconditioner of the homogeneous medium of element matrix ``k_ref``."""
118
+ self = cls.__new__(cls)
119
+ self._build(shape, np.asarray(k_ref, dtype=float), nd)
120
+ return self
121
+
122
+ def _build(self, shape, k, nd: int) -> None:
123
+ self.shape = tuple(int(s) for s in shape)
124
+ self.nd = nd
125
+ self.blocks = np.ascontiguousarray(_stencil(k, nd))
126
+ nx, ny, nz = self.shape
127
+ # the mean of the fluctuation is set to zero: the inverse is zero at frequency 0
128
+ self.inverse = np.empty((nx, ny, nz // 2 + 1, nd, nd), dtype=np.complex128)
129
+ kernels.fourier_inverse(nx, ny, nz, self.blocks, self.inverse)
130
+
131
+ def __call__(self, r: np.ndarray) -> np.ndarray:
132
+ nd, shape = self.nd, self.shape
133
+ field = r.reshape(*shape, nd)
134
+ workers = settings.workers()
135
+ hat = sfft.rfftn(field, axes=(0, 1, 2), workers=workers)
136
+ hat = np.einsum("...ij,...j->...i", self.inverse, hat)
137
+ return sfft.irfftn(hat, s=shape, axes=(0, 1, 2), workers=workers).reshape(-1)
138
+
139
+
140
+ class _FFTProblem(MacroscopicLoadings):
141
+ physics = ""
142
+ nd = 0
143
+
144
+ def __init__(
145
+ self,
146
+ image: VoxelImage,
147
+ materials: dict[int, Material],
148
+ bc: str = "periodic",
149
+ *,
150
+ tol: float = 1e-8,
151
+ maxiter: int | None = None,
152
+ reference: tuple[float, float] | None = None,
153
+ grains=None,
154
+ orientations=None,
155
+ device: str = "cpu",
156
+ physics: str | None = None,
157
+ ):
158
+ if not isinstance(image, VoxelImage):
159
+ raise TypeError("the FFT solver needs a VoxelImage")
160
+ if physics is not None:
161
+ self._set_physics(physics)
162
+ self.device = gpu.device_of(device)
163
+ if boundary_condition(bc) != "periodic":
164
+ raise ValueError(
165
+ "the FFT solver of voxel images uses periodic boundary conditions; for "
166
+ "kubc, mixed or subc conditions, mesh the microstructure (finite elements, "
167
+ "see morphogen.mesh.conforming)"
168
+ )
169
+ if image.data.dtype.kind not in "iub":
170
+ raise ValueError("homogenization needs an integer phase image")
171
+ if not image.periodic:
172
+ log.info("FFT solver: the image is treated as the cell of a periodic medium")
173
+ if grains is not None:
174
+ grains = np.asarray(grains.data if isinstance(grains, VoxelImage) else grains)
175
+ if grains.shape != image.shape:
176
+ raise ValueError("grains: one grain label per voxel of the image")
177
+ self.bc = "periodic"
178
+ self.image = image
179
+ self.shape = image.shape
180
+ self.box_volume = float(image.volume)
181
+ self.table = material_table(
182
+ image.data, materials, self.physics, grains=grains, orientations=orientations
183
+ )
184
+ # material of every voxel (-1: void), phase of every voxel (statistics)
185
+ self.mat = np.ascontiguousarray(self.table.mat)
186
+ self.stat = np.ascontiguousarray(self.table.stat)
187
+ self.active = self.mat >= 0
188
+ self.empty = not np.any(self.active) or not np.any(self.table.matrices)
189
+ if self.empty:
190
+ log.warning("no load-carrying material in the sample: its apparent properties are zero")
191
+ self.element = hex_element(tuple(image.spacing))
192
+ self.element_matrices = self._element_matrices(self.table.matrices)
193
+ self.counts = np.bincount(self.mat[self.active], minlength=len(self.table.matrices))
194
+ self.tol = float(tol)
195
+ self.maxiter = maxiter
196
+ self.reference = reference
197
+ self._preconditioner = None
198
+ self._units: dict = {}
199
+
200
+ def _set_physics(self, physics: str) -> None:
201
+ """The physics of the problem, among those its class solves (elasticity; any of
202
+ the transport phenomena of a scalar potential for the thermal problems)."""
203
+ if transport_physics(physics) != (self.nd == 1):
204
+ kind = "a transport phenomenon" if self.nd == 1 else "'elastic'"
205
+ raise ValueError(f"{type(self).__name__}: physics {kind}, got {physics!r}")
206
+ self.physics = physics
207
+
208
+ def _element_matrices(self, matrices) -> np.ndarray:
209
+ raise NotImplementedError
210
+
211
+ def _reference_element(self) -> np.ndarray:
212
+ raise NotImplementedError
213
+
214
+ def _load_scale(self, loads) -> float:
215
+ """Norm of the element loads (without cancellation between elements)."""
216
+ return float(np.sqrt(np.sum(self.counts * np.sum(loads * loads, axis=1))))
217
+
218
+ def _solve(self, rhs, scale: float):
219
+ nx, ny, nz = self.shape
220
+ nd = self.nd
221
+ if norm(np.ravel(rhs)) <= NEGLIGIBLE * scale:
222
+ return np.zeros_like(rhs), SolveInfo("fft", rhs.size, 0, 0.0, 0.0, 0.0)
223
+ if self._preconditioner is None and self.device != "gpu":
224
+ self._preconditioner = FourierPreconditioner.from_element(
225
+ self.shape, self._reference_element(), nd
226
+ )
227
+ mats = self.element_matrices
228
+
229
+ def apply(v):
230
+ out = np.empty_like(v)
231
+ apply_operator(nx, ny, nz, nd, self.mat, mats, v, out)
232
+ return out
233
+
234
+ maxiter = self.maxiter or 20 * int(max(self.shape)) + 1000
235
+ t0 = time.perf_counter()
236
+ if self.device == "gpu":
237
+ from morphogen.homogenization import gpu as gpu_solver
238
+
239
+ x, it, res = gpu_solver.solve_linear(self, rhs, self.tol, maxiter)
240
+ else:
241
+ x, it, res = conjugate_gradient(apply, self._preconditioner, rhs, self.tol, maxiter)
242
+ if res > self.tol:
243
+ log.warning("FFT solver stopped at relative residual %.2e after %d iterations", res, it)
244
+ method = "fft-gpu" if self.device == "gpu" else "fft"
245
+ return x, SolveInfo(method, rhs.size, it, res, 0.0, time.perf_counter() - t0)
246
+
247
+ def _phase_statistics(self, sums, n_mean, names, sizes) -> list[PhaseStatistics]:
248
+ out = []
249
+ vol_index = sums.shape[1] - 1
250
+ for g, phase in enumerate(self.table.phases):
251
+ vol = sums[g, vol_index]
252
+ if vol <= 0:
253
+ continue
254
+ mean, std, pos = {}, {}, 0
255
+ for name, size in zip(names, sizes, strict=True):
256
+ m = sums[g, pos : pos + size] / vol
257
+ sq = sums[g, n_mean + pos : n_mean + pos + size] / vol
258
+ mean[name] = m
259
+ std[name] = np.sqrt(np.maximum(sq - m * m, 0.0))
260
+ pos += size
261
+ out.append(PhaseStatistics(phase, float(vol / self.box_volume), mean, std))
262
+ return out
263
+
264
+ def _empty_solution(self, loading: Loading, t0: float) -> Solution:
265
+ elastic = self.physics == "elastic"
266
+ values = np.where(loading.strain_controlled, loading.array, 0.0)
267
+ # the phases inert for the physics (voids, insulators) fill the image
268
+ strain = voigt_to_tensor(values, strain=True) if elastic else values
269
+ return Solution(
270
+ physics=self.physics,
271
+ bc=self.bc,
272
+ loading=loading,
273
+ strain=strain,
274
+ stress=np.zeros((3, 3)) if elastic else np.zeros(3),
275
+ energy=0.0,
276
+ material_fraction=0.0,
277
+ phases=[],
278
+ info=SolveInfo("none", 0, 0, 0.0, 0.0, time.perf_counter() - t0),
279
+ )
280
+
281
+
282
+ #: Mandel weights: sqrt(2) on the shear components
283
+ _MANDEL = np.array([1.0, 1.0, 1.0, np.sqrt(2.0), np.sqrt(2.0), np.sqrt(2.0)])
284
+
285
+
286
+ def reference_moduli(matrices, isotropic: bool) -> tuple[float, float]:
287
+ """Lame coefficients of the isotropic reference medium of the FFT preconditioner:
288
+ the mean of the extreme moduli of the materials (bulk moduli and shear stiffnesses
289
+ of the crystals)."""
290
+ d = np.asarray(matrices, dtype=float)
291
+ if isotropic:
292
+ lam, mu = d[:, 0, 1], d[:, 3, 3]
293
+ return 0.5 * (lam.min() + lam.max()), 0.5 * (mu.min() + mu.max())
294
+ m = d * _MANDEL[None, :, None] * _MANDEL[None, None, :]
295
+ n = np.array([1.0, 1.0, 1.0, 0.0, 0.0, 0.0]) / np.sqrt(3.0)
296
+ bulk = np.einsum("i,mij,j->m", n, m, n) / 3.0
297
+ proj = np.eye(6) - np.outer(n, n)
298
+ dev = np.linalg.eigvalsh(proj @ m @ proj)[:, 1:] / 2.0 # without the hydrostatic mode
299
+ k0 = 0.5 * (bulk.min() + bulk.max())
300
+ mu0 = 0.5 * (dev.min() + dev.max())
301
+ return k0 - 2.0 * mu0 / 3.0, mu0
302
+
303
+
304
+ class FFTElasticProblem(_FFTProblem):
305
+ """Periodic linear elasticity of a voxel image (FFT-preconditioned CG); crystals are
306
+ turned by the orientations of their grains (``grains``: label image)."""
307
+
308
+ physics = "elastic"
309
+ nd = 3
310
+
311
+ def _element_matrices(self, matrices) -> np.ndarray:
312
+ b = self.element.b_gauss
313
+ k = self.element.weight * np.einsum("gri,mrs,gsj->mij", b, matrices, b, optimize=True)
314
+ return np.ascontiguousarray(0.5 * (k + np.swapaxes(k, 1, 2)))
315
+
316
+ def _reference_element(self) -> np.ndarray:
317
+ if self.reference is not None:
318
+ lam, mu = self.reference
319
+ else:
320
+ used = self.table.matrices[self.counts > 0]
321
+ lam, mu = reference_moduli(used, self.table.isotropic)
322
+ return self.element.stiffness(lam, mu)
323
+
324
+ def _thermal_loads(self) -> np.ndarray:
325
+ """Element load vectors of a unit change of temperature, ``int B^T D alpha``."""
326
+ el = self.element
327
+ sig = np.einsum("mrs,ms->mr", self.table.matrices, self.table.eigen)
328
+ return el.weight * np.einsum("grc,mr->mc", el.b_gauss, sig)
329
+
330
+ def _field(self, x: np.ndarray, dt: float):
331
+ """Periodic fluctuation for the macroscopic strain ``x`` (Voigt order) and the
332
+ change of temperature ``dt``."""
333
+ nx, ny, nz = self.shape
334
+ u_loc = self.element.affine_displacement(x)
335
+ loads = self.element_matrices @ u_loc
336
+ if dt:
337
+ loads = loads - dt * self._thermal_loads()
338
+ loads = np.ascontiguousarray(loads)
339
+ dof = np.arange(3 * nx * ny * nz, dtype=np.int64)
340
+ rhs = kernels.element_load(nx, ny, nz, True, self.mat, dof, 3, loads, dof.size)
341
+ return self._solve(rhs, self._load_scale(loads))
342
+
343
+ def _sums(self, w, x, dt) -> np.ndarray:
344
+ el = self.element
345
+ nx, ny, nz = self.shape
346
+ return kernels.elastic_sums(
347
+ nx,
348
+ ny,
349
+ nz,
350
+ True,
351
+ self.mat,
352
+ self.stat,
353
+ len(self.table.phases),
354
+ self.table.matrices,
355
+ self.table.eigen,
356
+ float(dt),
357
+ w,
358
+ el.affine_displacement(x),
359
+ el.b_gauss,
360
+ el.weight,
361
+ )
362
+
363
+ def _dual(self, w, x, dt) -> np.ndarray:
364
+ return self._sums(w, x, dt).sum(axis=0)[6:12] / self.box_volume
365
+
366
+ def _evaluate(self, loading, w, x, dt, info, fields, t0) -> Solution:
367
+ el = self.element
368
+ nx, ny, nz = self.shape
369
+ sums = self._sums(w, x, dt)
370
+ total = sums.sum(axis=0)
371
+ fld = None
372
+ if fields:
373
+ e_strain, e_stress, e_energy = kernels.elastic_fields(
374
+ nx,
375
+ ny,
376
+ nz,
377
+ True,
378
+ self.mat,
379
+ self.table.matrices,
380
+ self.table.eigen,
381
+ float(dt),
382
+ w,
383
+ el.affine_displacement(x),
384
+ el.b_mean,
385
+ el.b_gauss,
386
+ )
387
+ fld = {
388
+ "strain": e_strain.reshape(*self.shape, 6),
389
+ "stress": e_stress.reshape(*self.shape, 6),
390
+ "energy": e_energy.reshape(self.shape),
391
+ }
392
+ info.solve_s = time.perf_counter() - t0
393
+ return Solution(
394
+ physics="elastic",
395
+ bc=self.bc,
396
+ loading=loading,
397
+ strain=voigt_to_tensor(x, strain=True),
398
+ stress=voigt_to_tensor(total[6:12] / self.box_volume, strain=False),
399
+ energy=float(total[12] / self.box_volume),
400
+ material_fraction=float(total[26] / self.box_volume),
401
+ phases=self._phase_statistics(sums, 13, ("strain", "stress", "energy"), (6, 6, 1)),
402
+ info=info,
403
+ fields=fld,
404
+ support=self.image if fields else None,
405
+ )
406
+
407
+
408
+ class FFTThermalProblem(_FFTProblem):
409
+ """Periodic steady heat conduction of a voxel image (FFT-preconditioned CG), or with
410
+ ``physics`` any other transport phenomenon of a scalar potential
411
+ (:data:`~morphogen.homogenization.materials.TRANSPORT`: ``"electrical"``,
412
+ ``"dielectric"``, ``"magnetic"``, ``"diffusion"``), with the coefficient of the
413
+ materials for it; the phases whose coefficient is zero (insulators) are voids."""
414
+
415
+ physics = "thermal"
416
+ nd = 1
417
+
418
+ def _element_matrices(self, matrices) -> np.ndarray:
419
+ g = self.element.g_gauss
420
+ k = self.element.weight * np.einsum("gdi,mde,gej->mij", g, matrices, g, optimize=True)
421
+ return np.ascontiguousarray(0.5 * (k + np.swapaxes(k, 1, 2)))
422
+
423
+ def _reference_element(self) -> np.ndarray:
424
+ if self.reference is not None:
425
+ k0 = self.reference[0]
426
+ else:
427
+ used = self.table.matrices[self.counts > 0]
428
+ eig = np.linalg.eigvalsh(used)
429
+ k0 = 0.5 * (eig.min() + eig.max())
430
+ return k0 * self.element.k_thermal
431
+
432
+ def _field(self, x: np.ndarray, dt: float = 0.0):
433
+ """Periodic fluctuation of temperature for the macroscopic gradient ``x``."""
434
+ nx, ny, nz = self.shape
435
+ t_loc = self.element.affine_temperature(x)
436
+ loads = np.ascontiguousarray(self.element_matrices @ t_loc)
437
+ dof = np.arange(nx * ny * nz, dtype=np.int64)
438
+ rhs = kernels.element_load(nx, ny, nz, True, self.mat, dof, 1, loads, dof.size)
439
+ return self._solve(rhs, self._load_scale(loads))
440
+
441
+ def _sums(self, t, x) -> np.ndarray:
442
+ el = self.element
443
+ nx, ny, nz = self.shape
444
+ return kernels.thermal_sums(
445
+ nx,
446
+ ny,
447
+ nz,
448
+ True,
449
+ self.mat,
450
+ self.stat,
451
+ len(self.table.phases),
452
+ self.table.matrices,
453
+ t,
454
+ el.affine_temperature(x),
455
+ el.g_gauss,
456
+ el.weight,
457
+ )
458
+
459
+ def _dual(self, t, x, dt=0.0) -> np.ndarray:
460
+ return self._sums(t, x).sum(axis=0)[3:6] / self.box_volume
461
+
462
+ def _evaluate(self, loading, t, x, dt, info, fields, t0) -> Solution:
463
+ el = self.element
464
+ nx, ny, nz = self.shape
465
+ sums = self._sums(t, x)
466
+ total = sums.sum(axis=0)
467
+ fld = None
468
+ if fields:
469
+ e_grad, e_flux, e_diss = kernels.thermal_fields(
470
+ nx,
471
+ ny,
472
+ nz,
473
+ True,
474
+ self.mat,
475
+ self.table.matrices,
476
+ t,
477
+ el.affine_temperature(x),
478
+ el.g_mean,
479
+ el.g_gauss,
480
+ )
481
+ fld = {
482
+ "gradient": e_grad.reshape(*self.shape, 3),
483
+ "flux": e_flux.reshape(*self.shape, 3),
484
+ "dissipation": e_diss.reshape(self.shape),
485
+ }
486
+ info.solve_s = time.perf_counter() - t0
487
+ return Solution(
488
+ physics=self.physics,
489
+ bc=self.bc,
490
+ loading=loading,
491
+ strain=np.array(x, dtype=float),
492
+ stress=total[3:6] / self.box_volume,
493
+ energy=float(total[6] / self.box_volume),
494
+ material_fraction=float(total[14] / self.box_volume),
495
+ phases=self._phase_statistics(sums, 7, ("gradient", "flux", "dissipation"), (3, 3, 1)),
496
+ info=info,
497
+ fields=fld,
498
+ support=self.image if fields else None,
499
+ )