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,1135 @@
1
+ """Strongly coupled linear homogenization on periodic voxel images: several fields
2
+ solved together, each a displacement or a scalar potential, their fluxes tied by one
3
+ symmetric constitutive law.
4
+
5
+ A *layout* lists the fields. A displacement ``u`` has the strain ``eps`` (6 components,
6
+ Voigt order 11 22 33 23 31 12, engineering shears) for its generalized gradient and the
7
+ stress ``sigma`` for its flux; a scalar potential ``phi`` has its gradient ``grad phi``
8
+ (3 components) and a flux vector. The generalized gradient ``Z`` stacks those of the
9
+ fields, the generalized flux ``S`` their fluxes, and the law of each phase is the
10
+ symmetric matrix ``L`` of ``S = L Z``. The couplings of :data:`COUPLINGS`:
11
+
12
+ ``piezoelectric`` (``u``, the electric potential ``phi``; ``E = -grad phi``)
13
+ ``sigma = C eps - e^T E``, ``D = e eps + kappa E``: ``Z = (eps, grad phi)``, ``S =
14
+ (sigma, D)``, ``L = [[C, e^T], [e, -kappa]]`` with the stiffness ``C`` at constant
15
+ electric field, the piezoelectric matrix ``e`` (3 x 6, stress-charge form, C/m^2) and
16
+ the permittivity ``kappa`` at constant strain.
17
+ ``piezomagnetic`` (``u``, the magnetic potential ``psi``; ``H = -grad psi``)
18
+ ``sigma = C eps - q^T H``, ``B = q eps + mu H``: the same with the piezomagnetic
19
+ matrix ``q`` (3 x 6, N/(A m)) and the permeability ``mu``.
20
+ ``magnetoelectroelastic`` (``u``, ``phi``, ``psi``)
21
+ ``sigma = C eps - e^T E - q^T H``, ``D = e eps + kappa E + alpha H``, ``B = q eps +
22
+ alpha^T E + mu H``: ``L = [[C, e^T, q^T], [e, -kappa, -alpha], [q, -alpha^T, -mu]]``
23
+ with the magnetoelectric tensor ``alpha`` (3 x 3). A composite of a piezoelectric
24
+ phase and a piezomagnetic one is magnetoelectric though neither phase is (a product
25
+ property).
26
+ ``magnetoelectric`` (``phi``, ``psi``; rigid phases)
27
+ ``D = kappa E + alpha H``, ``B = alpha^T E + mu H``: ``Z = (grad phi, grad psi)``,
28
+ ``S = -(D, B)``, ``L = [[kappa, alpha], [alpha^T, mu]]``.
29
+ ``thermoelectric`` (the electric potential ``V``, the temperature ``T``, linearized
30
+ about the mean temperature ``T0``)
31
+ ``j = -sigma (grad V + s grad T)`` (the current density; ``s``: the Seebeck
32
+ coefficient) and the entropy flux ``j_s = q / T0 = s j - (k / T0) grad T`` (``k``: the
33
+ thermal conductivity at zero current; Kelvin's relation ``Pi = s T0``): ``Z = (grad V,
34
+ grad T)``, ``S = -(j, j_s)``, ``L = [[sigma, sigma s], [s^T sigma, k / T0 + s^T sigma
35
+ s]]``, symmetric positive definite by Onsager's reciprocity.
36
+
37
+ The energy-conserving laws (the first three) are symmetric but not definite: their
38
+ potentials are saddle points of the electric enthalpy. :class:`CoupledProblem` solves the
39
+ periodic fluctuations of all the fields at once on the trilinear voxels of the FFT solver
40
+ (:mod:`morphogen.homogenization.fft`): the system ``K w = f`` of the element matrices
41
+ ``int B^T L B`` (``B``: the generalized gradients of the shape functions) by MINRES, or by
42
+ conjugate gradients when every block of the law is positive, preconditioned block by
43
+ block by the inverse of a homogeneous reference medium in Fourier space. The unknowns of
44
+ each field are scaled by the square root of its reference so that the blocks have the
45
+ same magnitude whatever the units (stiffnesses of 1e11 Pa beside permittivities of 1e-9
46
+ F/m). The unit loadings of ``Z`` give the effective law ``L*`` (the mean fluxes), which
47
+ :func:`coupled_tensors` splits into the tensors of the coupling, with the constants
48
+ derived from them.
49
+
50
+ Uniform fields that load the phases without a gradient are the weak couplings of the
51
+ same problems: a change of temperature with the thermal stresses ``beta = C alpha`` and
52
+ the pyroelectric coefficients ``p`` of the phases, ``S = L Z - lambda dT``, gives the
53
+ effective ``lambda*`` (:meth:`CoupledProblem.eigen_flux`; the generalized relation of
54
+ Levin).
55
+
56
+ :func:`laminate` is the exact effective law of layers, for any of these laws: the checks
57
+ of the solver.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import logging
63
+ import time
64
+ from dataclasses import dataclass, field
65
+
66
+ import numpy as np
67
+ from numba import njit, prange
68
+
69
+ from morphogen.homogenization import kernels
70
+ from morphogen.homogenization.elements import hex_element
71
+ from morphogen.homogenization.fft import FourierPreconditioner, reference_moduli
72
+ from morphogen.homogenization.materials import Material
73
+ from morphogen.homogenization.solvers import NEGLIGIBLE, SolveInfo, conjugate_gradient, minres
74
+ from morphogen.image import VoxelImage
75
+ from morphogen.stopping import checkpoint
76
+
77
+ log = logging.getLogger("morphogen")
78
+
79
+ #: The notation of the tensors of the coupled laws
80
+ NOTATION = (
81
+ "Voigt order 11 22 33 23 31 12 of strains (engineering shears) and stresses: "
82
+ "sigma = C eps - e^T E - q^T H, D = e eps + kappa E + alpha H, B = q eps + alpha^T E + mu H "
83
+ "(e, q: 3 x 6, rows 1 2 3; d = e C^-1; kappa, mu at constant strain); thermoelectric: "
84
+ "j = -sigma (grad V + s grad T), q = T0 s j - k grad T"
85
+ )
86
+ #: The fields of a layout: the degrees of freedom of a node and the components of the
87
+ #: generalized gradient of each kind
88
+ FIELDS = {"displacement": (3, 6), "potential": (1, 3)}
89
+ #: The couplings and the fields of their layouts
90
+ COUPLINGS = {
91
+ "piezoelectric": ("displacement", "potential"),
92
+ "piezomagnetic": ("displacement", "potential"),
93
+ "magnetoelectroelastic": ("displacement", "potential", "potential"),
94
+ "magnetoelectric": ("potential", "potential"),
95
+ "thermoelectric": ("potential", "potential"),
96
+ }
97
+ #: Voigt indices of the components of a strain normal to the layers of a laminate normal
98
+ #: to x3 (33, 23, 31) and in their plane (11, 22, 12); of a gradient likewise (3; 1, 2)
99
+ _NORMAL = {"displacement": (2, 3, 4), "potential": (2,)}
100
+ _PLANE = {"displacement": (0, 1, 5), "potential": (0, 1)}
101
+
102
+
103
+ def layout_sizes(layout) -> tuple[int, int]:
104
+ """The degrees of freedom of a node and the components of the generalized gradient of
105
+ a layout of fields (:data:`FIELDS`)."""
106
+ unknown = [f for f in layout if f not in FIELDS]
107
+ if unknown or not layout:
108
+ raise ValueError(f"layout: fields among {tuple(FIELDS)}, got {tuple(layout)}")
109
+ return sum(FIELDS[f][0] for f in layout), sum(FIELDS[f][1] for f in layout)
110
+
111
+
112
+ def _slices(layout) -> list[tuple[slice, slice]]:
113
+ """The degrees of freedom of a node and the components of the gradient of each field."""
114
+ out, dof, comp = [], 0, 0
115
+ for f in layout:
116
+ nd, nz = FIELDS[f]
117
+ out.append((slice(dof, dof + nd), slice(comp, comp + nz)))
118
+ dof, comp = dof + nd, comp + nz
119
+ return out
120
+
121
+
122
+ # -- tensors of the couplings --------------------------------------------------------------
123
+
124
+
125
+ def _tensor3(e) -> np.ndarray:
126
+ """The third-order tensor ``e_kij`` (3 x 3 x 3, symmetric in ij) of a piezoelectric
127
+ matrix (3 x 6, Voigt order 11 22 33 23 31 12 of the strains, engineering shears)."""
128
+ from morphogen.homogenization.materials import _VOIGT_INDEX
129
+
130
+ return np.asarray(e, dtype=float)[..., _VOIGT_INDEX]
131
+
132
+
133
+ def rotate_piezo(e, euler) -> np.ndarray:
134
+ """The piezoelectric (or piezomagnetic) matrix of a crystal (3 x 6, in its axes) in
135
+ the axes of the sample, for one orientation (Bunge angles in degrees: shape (3, 6)) or
136
+ several (shape (n, 3, 6)): ``e_kij = g_pk g_qi g_rj e'_pqr`` with ``crystal = g @
137
+ sample``, as :func:`~morphogen.homogenization.materials.rotate_stiffness`."""
138
+ from morphogen.homogenization.materials import _I0, _I1
139
+ from morphogen.orientations import euler_to_matrix
140
+
141
+ g = euler_to_matrix(euler)
142
+ t = np.einsum("npk,nqi,nrj,pqr->nkij", g, g, g, _tensor3(e), optimize=True)
143
+ out = t[:, :, _I0, _I1]
144
+ return out[0] if np.ndim(euler) == 1 else out
145
+
146
+
147
+ def poled_ceramic(e31: float, e33: float, e15: float) -> np.ndarray:
148
+ """The piezoelectric matrix ``e`` (3 x 6) of a ceramic poled along x3 (the symmetry
149
+ 6mm of PZT and BaTiO3; also the piezomagnetic matrix of CoFe2O4 magnetized along x3):
150
+ ``e31 = e32``, ``e33`` and ``e15 = e24`` (Voigt order 11 22 33 23 31 12: ``e15`` is
151
+ the entry (1, 31), ``e24`` the entry (2, 23))."""
152
+ e = np.zeros((3, 6))
153
+ e[2, 0] = e[2, 1] = e31
154
+ e[2, 2] = e33
155
+ e[0, 4] = e[1, 3] = e15
156
+ return e
157
+
158
+
159
+ def _piezo(value, name: str):
160
+ if value is None:
161
+ return None
162
+ e = np.asarray(value, dtype=float)
163
+ if e.shape != (3, 6) or not np.all(np.isfinite(e)):
164
+ raise ValueError(f"{name}: a finite 3 x 6 matrix (Voigt order 11 22 33 23 31 12)")
165
+ return tuple(tuple(float(v) for v in row) for row in e)
166
+
167
+
168
+ def _second_order(value, name: str, *, symmetric: bool):
169
+ """One value, three principal values or a 3 x 3 tensor, as a tuple (None: none)."""
170
+ if value is None:
171
+ return None
172
+ a = np.asarray(value, dtype=float)
173
+ if a.ndim == 0:
174
+ a = float(a) * np.eye(3)
175
+ elif a.shape == (3,):
176
+ a = np.diag(a)
177
+ if a.shape != (3, 3) or not np.all(np.isfinite(a)):
178
+ raise ValueError(f"{name}: one value, three principal values or a 3 x 3 tensor")
179
+ if symmetric and not np.allclose(a, a.T, rtol=1e-10, atol=1e-14 * np.abs(a).max()):
180
+ raise ValueError(f"{name}: a symmetric tensor")
181
+ return tuple(tuple(float(v) for v in row) for row in a)
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class Coupling:
186
+ """The coupling coefficients of a material, in the axes of its crystal (those of the
187
+ sample without an orientation): ``piezoelectric`` (``e``, 3 x 6: ``D = e eps`` at zero
188
+ field, C/m^2), ``piezomagnetic`` (``q``, 3 x 6: ``B = q eps``, N/(A m)),
189
+ ``magnetoelectric`` (``alpha``, 3 x 3 or one value: ``D = alpha H``), ``seebeck``
190
+ (``s``, one value or a 3 x 3 tensor: the field ``E = s grad T`` at zero current, V/K)
191
+ and ``pyroelectric`` (``p``, 3 components: ``D = p dT`` at constant strain and field,
192
+ C/(m^2 K)). Matrices follow morphoGen's Voigt order 11 22 33 23 31 12 with engineering
193
+ shears, which is that of the IEEE standard on piezoelectricity (``e15``: the entry of
194
+ the row 1 and the column 31)."""
195
+
196
+ piezoelectric: tuple | None = None
197
+ piezomagnetic: tuple | None = None
198
+ magnetoelectric: tuple | None = None
199
+ seebeck: tuple | None = None
200
+ pyroelectric: tuple | None = None
201
+
202
+ def __post_init__(self) -> None:
203
+ set_ = object.__setattr__
204
+ set_(self, "piezoelectric", _piezo(self.piezoelectric, "piezoelectric"))
205
+ set_(self, "piezomagnetic", _piezo(self.piezomagnetic, "piezomagnetic"))
206
+ alpha = _second_order(self.magnetoelectric, "magnetoelectric", symmetric=False)
207
+ set_(self, "magnetoelectric", alpha)
208
+ set_(self, "seebeck", _second_order(self.seebeck, "seebeck", symmetric=True))
209
+ if self.pyroelectric is not None:
210
+ p = np.asarray(self.pyroelectric, dtype=float)
211
+ if p.shape != (3,) or not np.all(np.isfinite(p)):
212
+ raise ValueError("pyroelectric: three finite components")
213
+ set_(self, "pyroelectric", tuple(float(v) for v in p))
214
+
215
+ @classmethod
216
+ def from_config(cls, spec) -> Coupling:
217
+ """A mapping of the coefficients (:class:`Coupling`); a poled ceramic gives ``e``
218
+ (or ``q``) by its constants: ``piezoelectric: {e31: .., e33: .., e15: ..}``."""
219
+ if isinstance(spec, Coupling):
220
+ return spec
221
+ if not isinstance(spec, dict):
222
+ raise ValueError("coupling: a mapping of coupling coefficients")
223
+ names = ("piezoelectric", "piezomagnetic", "magnetoelectric", "seebeck", "pyroelectric")
224
+ unknown = sorted(set(spec) - set(names))
225
+ if unknown:
226
+ raise ValueError(f"coupling: unknown keys {unknown}; allowed: {list(names)}")
227
+ values = dict(spec)
228
+ for name in ("piezoelectric", "piezomagnetic"):
229
+ value = values.get(name)
230
+ if isinstance(value, dict):
231
+ prefix = "e" if name == "piezoelectric" else "q"
232
+ keys = {f"{prefix}31", f"{prefix}33", f"{prefix}15"}
233
+ if set(value) != keys:
234
+ raise ValueError(f"coupling.{name}: a 3 x 6 matrix, or {sorted(keys)}")
235
+ values[name] = poled_ceramic(*(float(value[f"{prefix}{k}"]) for k in (31, 33, 15)))
236
+ return cls(**values)
237
+
238
+ def to_config(self) -> dict:
239
+ out = {}
240
+ for name in ("piezoelectric", "piezomagnetic", "magnetoelectric", "seebeck",
241
+ "pyroelectric"): # fmt: skip
242
+ value = getattr(self, name)
243
+ if value is not None:
244
+ out[name] = np.array(value).tolist()
245
+ return out
246
+
247
+ def matrix(self, name: str, euler=None) -> np.ndarray:
248
+ """The tensor ``name`` in the axes of the sample for the orientation ``euler``
249
+ (Bunge angles, degrees), zero without it: 3 x 6 (``piezoelectric``,
250
+ ``piezomagnetic``), 3 x 3 (``magnetoelectric``, ``seebeck``) or 3
251
+ (``pyroelectric``)."""
252
+ from morphogen.orientations import euler_to_matrix
253
+
254
+ value = getattr(self, name)
255
+ shape = {"piezoelectric": (3, 6), "piezomagnetic": (3, 6), "pyroelectric": (3,)}
256
+ if value is None:
257
+ return np.zeros(shape.get(name, (3, 3)))
258
+ a = np.array(value)
259
+ if euler is None:
260
+ return a
261
+ if a.shape == (3, 6):
262
+ return rotate_piezo(a, euler)
263
+ g = euler_to_matrix(euler)[0]
264
+ return g.T @ a if a.shape == (3,) else g.T @ a @ g
265
+
266
+
267
+ def _dielectric(m: Material, physics: str, euler, name: str) -> np.ndarray:
268
+ if not m.has(physics):
269
+ raise ValueError(f"{name}: the material has no {physics} coefficient")
270
+ return m.matrix(physics, euler)
271
+
272
+
273
+ def coupled_law(material: Material, coupling: str, euler=None, *, temperature: float = 300.0):
274
+ """The law ``L`` of a material for a coupling of :data:`COUPLINGS` (see the module)
275
+ in the axes of the sample (``euler``: the orientation of its crystal), and its
276
+ thermal flux ``lambda`` of ``S = L Z - lambda dT`` (the thermal stress ``C alpha`` and
277
+ minus the pyroelectric coefficients; zero for the transport couplings). A material
278
+ without elastic parameters has no stiffness (a pore filled by a dielectric);
279
+ ``temperature``: the mean temperature ``T0`` of the thermoelectric law (K)."""
280
+ if coupling not in COUPLINGS:
281
+ raise ValueError(f"coupling: one of {tuple(COUPLINGS)}, got {coupling!r}")
282
+ c = material.coupling or Coupling()
283
+ _, nz = layout_sizes(COUPLINGS[coupling])
284
+ law, eigen = np.zeros((nz, nz)), np.zeros(nz)
285
+ if coupling == "thermoelectric":
286
+ if not temperature > 0:
287
+ raise ValueError("thermoelectric: a positive mean temperature (K)")
288
+ sigma = _dielectric(material, "electrical", euler, coupling)
289
+ k = _dielectric(material, "thermal", euler, coupling)
290
+ s = c.matrix("seebeck", euler)
291
+ law[:3, :3] = sigma
292
+ law[:3, 3:] = sigma @ s
293
+ law[3:, :3] = (sigma @ s).T
294
+ law[3:, 3:] = k / temperature + s.T @ sigma @ s
295
+ return law, eigen
296
+ if coupling == "magnetoelectric":
297
+ alpha = c.matrix("magnetoelectric", euler)
298
+ law[:3, :3] = _dielectric(material, "dielectric", euler, coupling)
299
+ law[3:, 3:] = _dielectric(material, "magnetic", euler, coupling)
300
+ law[:3, 3:], law[3:, :3] = alpha, alpha.T
301
+ return law, eigen
302
+ if material.elastic:
303
+ from morphogen.homogenization.elements import tensor_to_voigt
304
+
305
+ law[:6, :6] = material.matrix("elastic", euler)
306
+ strain = tensor_to_voigt(material.expansion_tensor(euler), strain=True)
307
+ eigen[:6] = law[:6, :6] @ strain
308
+ if coupling in ("piezoelectric", "magnetoelectroelastic"):
309
+ e = c.matrix("piezoelectric", euler)
310
+ law[6:9, :6], law[:6, 6:9] = e, e.T
311
+ law[6:9, 6:9] = -_dielectric(material, "dielectric", euler, coupling)
312
+ eigen[6:9] = -c.matrix("pyroelectric", euler)
313
+ if coupling in ("piezomagnetic", "magnetoelectroelastic"):
314
+ at = 9 if coupling == "magnetoelectroelastic" else 6
315
+ q = c.matrix("piezomagnetic", euler)
316
+ law[at : at + 3, :6], law[:6, at : at + 3] = q, q.T
317
+ law[at : at + 3, at : at + 3] = -_dielectric(material, "magnetic", euler, coupling)
318
+ if coupling == "magnetoelectroelastic":
319
+ alpha = c.matrix("magnetoelectric", euler)
320
+ law[6:9, 9:12], law[9:12, 6:9] = -alpha, -alpha.T
321
+ return law, eigen
322
+
323
+
324
+ # -- the exact law of a laminate -----------------------------------------------------------
325
+
326
+
327
+ def laminate(laws, fractions, layout, eigen=None):
328
+ """The exact effective law of layers normal to x3 of laws ``laws`` (symmetric
329
+ matrices ``S = L Z`` of a layout of fields) in the volume ``fractions``: the
330
+ components of ``Z`` in the plane of the layers and those of ``S`` across them are
331
+ uniform (the continuity of the tangential gradients and of the normal fluxes), so
332
+ that ``L*_nn = <L_nn^-1>^-1``, ``L*_np = L*_nn <L_nn^-1 L_np>`` and ``L*_pp = <L_pp -
333
+ L_pn L_nn^-1 L_np> + <L_pn L_nn^-1> L*_nn <L_nn^-1 L_np>`` (Backus' averages of a
334
+ stiffness, Maxwell's of a conductivity, and those of every coupled law of the module,
335
+ definite or not; of complex symmetric laws too: those of a harmonic regime,
336
+ :mod:`morphogen.homogenization.harmonic`). With the thermal fluxes ``eigen`` of the
337
+ layers (``S = L Z - lambda dT``), returns the law and the effective ``lambda*``:
338
+ ``lambda*_n = L*_nn <L_nn^-1
339
+ lambda_n>`` and ``lambda*_p = <lambda_p - L_pn L_nn^-1 lambda_n> + <L_pn L_nn^-1>
340
+ lambda*_n``."""
341
+ _, nz = layout_sizes(layout)
342
+ laws = np.asarray(laws)
343
+ laws = laws.astype(complex if np.iscomplexobj(laws) else float) # harmonic laws too
344
+ f = np.asarray(fractions, dtype=float)
345
+ if laws.shape != (f.size, nz, nz):
346
+ raise ValueError(f"laminate: one {nz} x {nz} law per layer")
347
+ if np.any(f < 0) or not np.isclose(f.sum(), 1.0):
348
+ raise ValueError("laminate: fractions that sum to 1")
349
+ n, p = [], []
350
+ for kind, (_, comp) in zip(layout, _slices(layout), strict=True):
351
+ n += [comp.start + i for i in _NORMAL[kind]]
352
+ p += [comp.start + i for i in _PLANE[kind]]
353
+ inv = [np.linalg.inv(m[np.ix_(n, n)]) for m in laws]
354
+ lnn = np.linalg.inv(sum(fi * a for fi, a in zip(f, inv, strict=True)))
355
+ a = sum(fi * i @ m[np.ix_(n, p)] for fi, i, m in zip(f, inv, laws, strict=True))
356
+ lpp = sum(
357
+ fi * (m[np.ix_(p, p)] - m[np.ix_(p, n)] @ i @ m[np.ix_(n, p)])
358
+ for fi, i, m in zip(f, inv, laws, strict=True)
359
+ )
360
+ out = np.zeros((nz, nz), dtype=laws.dtype)
361
+ out[np.ix_(n, n)] = lnn
362
+ out[np.ix_(n, p)] = lnn @ a
363
+ out[np.ix_(p, n)] = (lnn @ a).T
364
+ out[np.ix_(p, p)] = lpp + a.T @ lnn @ a
365
+ if eigen is None:
366
+ return out
367
+ lam = np.asarray(eigen, dtype=float).reshape(f.size, nz)
368
+ star = np.zeros(nz)
369
+ star[n] = lnn @ sum(fi * i @ v[n] for fi, i, v in zip(f, inv, lam, strict=True))
370
+ star[p] = (
371
+ sum(
372
+ fi * (v[p] - m[np.ix_(p, n)] @ i @ v[n])
373
+ for fi, i, m, v in zip(f, inv, laws, lam, strict=True)
374
+ )
375
+ + a.T @ star[n]
376
+ )
377
+ return out, star
378
+
379
+
380
+ # -- kernels -------------------------------------------------------------------------------
381
+
382
+
383
+ @njit(parallel=True, cache=True)
384
+ def _apply(nx, ny, nz, nd, group, mats, w, out):
385
+ """``out = K w`` on the periodic grid of ``nd`` unknowns per node (the kernel of
386
+ :func:`morphogen.homogenization.fft.apply_operator` for any ``nd``)."""
387
+ corners = kernels.CORNERS
388
+ size = 8 * nd
389
+ for n in prange(nx * ny * nz):
390
+ k = n % nz
391
+ j = (n // nz) % ny
392
+ i = n // (ny * nz)
393
+ acc = np.zeros(nd)
394
+ we = np.empty(size)
395
+ for a in range(2):
396
+ ei = i - a if i - a >= 0 else nx - 1
397
+ for b in range(2):
398
+ ej = j - b if j - b >= 0 else ny - 1
399
+ for c in range(2):
400
+ ek = k - c if k - c >= 0 else nz - 1
401
+ g = group[(ei * ny + ej) * nz + ek]
402
+ if g < 0:
403
+ continue
404
+ ln = kernels.CORNER_INDEX[a, b, c]
405
+ for q in range(8):
406
+ qi = ei + corners[q, 0]
407
+ qj = ej + corners[q, 1]
408
+ qk = ek + corners[q, 2]
409
+ if qi == nx:
410
+ qi = 0
411
+ if qj == ny:
412
+ qj = 0
413
+ if qk == nz:
414
+ qk = 0
415
+ m = (qi * ny + qj) * nz + qk
416
+ for c2 in range(nd):
417
+ we[q * nd + c2] = w[m * nd + c2]
418
+ mat = mats[g]
419
+ for r in range(nd):
420
+ row = ln * nd + r
421
+ s = 0.0
422
+ for col in range(size):
423
+ s += mat[row, col] * we[col]
424
+ acc[r] += s
425
+ for r in range(nd):
426
+ out[n * nd + r] = acc[r]
427
+
428
+
429
+ @njit(parallel=True, cache=True)
430
+ def _sums(nx, ny, nz, nd, mat, stat, n_stat, laws, eigen, dt, w, aff, b_gauss, wt):
431
+ """Integrals over each phase (``stat``) of the generalized gradients ``Z``, of the
432
+ fluxes ``S = L Z - dt lambda``, of ``S . Z`` and of the volume: (phases, 2 nz + 2)."""
433
+ n_el = nx * ny * nz
434
+ ncomp = b_gauss.shape[1]
435
+ size = 8 * nd
436
+ n_chunks = min(n_el, 256)
437
+ partial = np.zeros((n_chunks, n_stat, 2 * ncomp + 2))
438
+ for ch in prange(n_chunks):
439
+ nodes = np.empty(8, dtype=np.int64)
440
+ we = np.empty(size)
441
+ z = np.empty(ncomp)
442
+ s = np.empty(ncomp)
443
+ for e in range(ch * n_el // n_chunks, (ch + 1) * n_el // n_chunks):
444
+ m = mat[e]
445
+ if m < 0:
446
+ continue
447
+ kernels._element_nodes(e, nx, ny, nz, True, nodes)
448
+ for q in range(8):
449
+ for c in range(nd):
450
+ we[q * nd + c] = aff[q * nd + c] + w[nodes[q] * nd + c]
451
+ acc = partial[ch, stat[e]]
452
+ for gp in range(8):
453
+ for r in range(ncomp):
454
+ v = 0.0
455
+ for col in range(size):
456
+ v += b_gauss[gp, r, col] * we[col]
457
+ z[r] = v
458
+ dens = 0.0
459
+ for r in range(ncomp):
460
+ v = -dt * eigen[m, r]
461
+ for col in range(ncomp):
462
+ v += laws[m, r, col] * z[col]
463
+ s[r] = v
464
+ dens += v * z[r]
465
+ for r in range(ncomp):
466
+ acc[r] += wt * z[r]
467
+ acc[ncomp + r] += wt * s[r]
468
+ acc[2 * ncomp] += wt * dens
469
+ acc[2 * ncomp + 1] += wt
470
+ return partial.sum(axis=0)
471
+
472
+
473
+ @njit(parallel=True, cache=True)
474
+ def _element_fields(nx, ny, nz, nd, mat, laws, eigen, dt, w, aff, b_gauss):
475
+ """The means over each voxel of the generalized gradients and fluxes (zero in the
476
+ voxels without a law)."""
477
+ n_el = nx * ny * nz
478
+ ncomp = b_gauss.shape[1]
479
+ size = 8 * nd
480
+ grad = np.zeros((n_el, ncomp))
481
+ flux = np.zeros((n_el, ncomp))
482
+ for e in prange(n_el):
483
+ m = mat[e]
484
+ if m < 0:
485
+ continue
486
+ nodes = np.empty(8, dtype=np.int64)
487
+ we = np.empty(size)
488
+ z = np.empty(ncomp)
489
+ kernels._element_nodes(e, nx, ny, nz, True, nodes)
490
+ for q in range(8):
491
+ for c in range(nd):
492
+ we[q * nd + c] = aff[q * nd + c] + w[nodes[q] * nd + c]
493
+ for gp in range(8):
494
+ for r in range(ncomp):
495
+ v = 0.0
496
+ for col in range(size):
497
+ v += b_gauss[gp, r, col] * we[col]
498
+ z[r] = v
499
+ grad[e, r] += 0.125 * v
500
+ for r in range(ncomp):
501
+ v = -dt * eigen[m, r]
502
+ for col in range(ncomp):
503
+ v += laws[m, r, col] * z[col]
504
+ flux[e, r] += 0.125 * v
505
+ return grad, flux
506
+
507
+
508
+ # -- the problem ---------------------------------------------------------------------------
509
+
510
+
511
+ @dataclass
512
+ class CoupledSolution:
513
+ """One solved loading of a :class:`CoupledProblem`: the macroscopic generalized
514
+ gradient ``gradient`` and the mean flux ``flux`` (the components of the layout), the
515
+ mean of ``S . Z``, the change of temperature, the volume fraction that carries a law,
516
+ the solver data and, with ``fields``, the voxel means of the gradients and fluxes
517
+ (``fields["gradient"]``, ``fields["flux"]``: shape + components) and the nodal
518
+ fluctuation of each field (``fields["fluctuation"]``: shape + degrees of freedom)."""
519
+
520
+ gradient: np.ndarray
521
+ flux: np.ndarray
522
+ energy: float
523
+ temperature: float
524
+ material_fraction: float
525
+ info: SolveInfo
526
+ phases: dict = field(default_factory=dict, repr=False)
527
+ fields: dict | None = field(default=None, repr=False)
528
+
529
+
530
+ def conjugate_orthogonal_gradient(apply, precondition, rhs, tol, maxiter, nd: int):
531
+ """The conjugate orthogonal conjugate gradient method (van der Vorst & Melissen 1990)
532
+ for the real form of a complex symmetric system: the unknowns ``[x, y]`` of ``z = x +
533
+ i y`` (``nd`` per node, the first half ``x``) and the operator ``apply([x, y]) =
534
+ [Re(K z), -Im(K z)]`` of a complex symmetric ``K``; ``precondition`` acts alike on the
535
+ two halves (a real symmetric positive operator). Conjugate gradients with the
536
+ unconjugated product ``u^T v``: the iterations of the real problem when the imaginary
537
+ part of ``K`` is small, where MINRES on the indefinite real form needs as many as the
538
+ square of them. Returns (the solution, the iterations, the relative residual); the
539
+ method has no minimization property and may stall (a residual above ``tol`` at the
540
+ end: the caller falls back on MINRES)."""
541
+ half = nd // 2
542
+
543
+ def to_complex(v, sign=1.0):
544
+ f = v.reshape(-1, nd)
545
+ return (f[:, :half] + sign * 1j * f[:, half:]).ravel()
546
+
547
+ def to_real(c, sign=1.0):
548
+ out = np.empty((c.size // half, nd))
549
+ f = c.reshape(-1, half)
550
+ out[:, :half] = f.real
551
+ out[:, half:] = sign * f.imag
552
+ return out.ravel()
553
+
554
+ def operator(p):
555
+ return to_complex(apply(to_real(p)), -1.0)
556
+
557
+ def inverse(r):
558
+ return to_complex(precondition(to_real(r)))
559
+
560
+ c = to_complex(rhs, -1.0)
561
+ norm_c = float(np.linalg.norm(c))
562
+ z = np.zeros_like(c)
563
+ if norm_c == 0.0:
564
+ return to_real(z), 0, 0.0
565
+ r = c.copy()
566
+ s = inverse(r)
567
+ p = s.copy()
568
+ rho = np.dot(r, s) # unconjugated
569
+ res, it = 1.0, 0
570
+ for it in range(1, maxiter + 1): # noqa: B007
571
+ checkpoint()
572
+ q = operator(p)
573
+ curvature = np.dot(p, q)
574
+ if curvature == 0.0 or not np.isfinite(curvature):
575
+ break
576
+ alpha = rho / curvature
577
+ z += alpha * p
578
+ r -= alpha * q
579
+ res = float(np.linalg.norm(r)) / norm_c
580
+ if res <= tol or not np.isfinite(res):
581
+ break
582
+ s = inverse(r)
583
+ rho_new = np.dot(r, s)
584
+ if rho == 0.0:
585
+ break
586
+ p = s + (rho_new / rho) * p
587
+ rho = rho_new
588
+ return to_real(z), it, res if np.isfinite(res) else float("inf")
589
+
590
+
591
+ class CoupledProblem:
592
+ """Periodic problem of the coupled fields of a ``layout`` (:data:`FIELDS`) on a voxel
593
+ image: ``laws[m]`` is the symmetric law ``S = L Z`` of the material ``m`` (the
594
+ components of the layout), ``mat`` the material of each voxel (-1: none, a void) and
595
+ ``eigen[m]`` its flux ``lambda`` per unit change of temperature (``S = L Z - lambda
596
+ dT``; zero if not given). Each diagonal block of the laws must be definite, positive or
597
+ negative, alike in all the materials that have it (a block may vanish in some: the
598
+ stiffness of a pore filled by a dielectric).
599
+
600
+ :meth:`solve` gives the mean flux of a macroscopic gradient ``Z`` (and a change of
601
+ temperature), :meth:`tensor` the effective law ``L*`` (one solve per component, the
602
+ unit solutions cached) and :meth:`eigen_flux` the effective ``lambda*``. ``tol``: the
603
+ relative residual of the Krylov solver (MINRES; conjugate gradients when every block
604
+ is positive); ``stat``: the phase of each voxel for the statistics (``mat`` if not
605
+ given). ``pairs``: the layout is twice the same fields, the real and imaginary parts
606
+ of a complex symmetric law (``[[L', -L''], [-L'', -L']]``: the harmonic problems of
607
+ :mod:`morphogen.homogenization.harmonic`), solved by
608
+ :func:`conjugate_orthogonal_gradient` (MINRES if it stalls)."""
609
+
610
+ def __init__(self, image: VoxelImage, laws, layout, mat, *, eigen=None, stat=None,
611
+ tol: float = 1e-8, maxiter: int | None = None, pairs: bool = False): # fmt: skip
612
+ if not isinstance(image, VoxelImage):
613
+ raise TypeError("the coupled solver needs a VoxelImage")
614
+ self.layout = tuple(layout)
615
+ self.nd, self.nz = layout_sizes(self.layout)
616
+ self.image = image
617
+ self.shape = image.shape
618
+ self.box_volume = float(image.volume)
619
+ laws = np.array(laws, dtype=float).reshape(-1, self.nz, self.nz)
620
+ if not np.allclose(laws, np.swapaxes(laws, 1, 2), rtol=1e-10,
621
+ atol=1e-12 * max(np.abs(laws).max(initial=0.0), 1e-300)): # fmt: skip
622
+ raise ValueError("coupled laws: symmetric matrices S = L Z")
623
+ self.laws = 0.5 * (laws + np.swapaxes(laws, 1, 2))
624
+ self.mat = np.ascontiguousarray(np.asarray(mat).ravel(), dtype=np.int64)
625
+ if self.mat.size != int(np.prod(self.shape)):
626
+ raise ValueError("mat: the material of each voxel of the image")
627
+ if self.mat.max(initial=-1) >= len(self.laws):
628
+ raise ValueError("mat: indices of the laws")
629
+ self.stat = self.mat if stat is None else np.ascontiguousarray(stat, dtype=np.int64)
630
+ self.eigen = (
631
+ np.zeros((len(self.laws), self.nz))
632
+ if eigen is None
633
+ else np.array(eigen, dtype=float).reshape(len(self.laws), self.nz)
634
+ )
635
+ self.tol = float(tol)
636
+ self.maxiter = maxiter
637
+ self.pairs = bool(pairs)
638
+ middle = len(self.layout) // 2
639
+ if self.pairs and self.layout[:middle] != self.layout[middle:]:
640
+ raise ValueError("pairs: a layout of twice the same fields")
641
+ self.counts = np.bincount(self.mat[self.mat >= 0], minlength=len(self.laws))
642
+ self.empty = not np.any(self.counts) or not np.any(self.laws[self.counts > 0])
643
+ self.element = hex_element(tuple(image.spacing))
644
+ self.b_gauss = self._gradients()
645
+ self._references()
646
+ # the scaled problem: unknowns w = scale * w', gradients Z = scale * Z'
647
+ d = self.scale_z
648
+ self._laws = np.ascontiguousarray(self.laws * d[None, :, None] * d[None, None, :])
649
+ self._eigen = np.ascontiguousarray(self.eigen * d[None, :])
650
+ k = self.element.weight * np.einsum(
651
+ "gri,mrs,gsj->mij", self.b_gauss, self._laws, self.b_gauss, optimize=True
652
+ )
653
+ self.element_matrices = np.ascontiguousarray(0.5 * (k + np.swapaxes(k, 1, 2)))
654
+ self._preconditioners = None
655
+ self._units: dict = {}
656
+
657
+ # -- set-up ------------------------------------------------------------------------
658
+
659
+ def _gradients(self) -> np.ndarray:
660
+ """The generalized gradients of the shape functions at the Gauss points: (8, nz, 8
661
+ nd), the unknowns of a voxel ordered corner by corner."""
662
+ el, nd = self.element, self.nd
663
+ b = np.zeros((8, self.nz, 8 * nd))
664
+ for kind, (dof, comp) in zip(self.layout, _slices(self.layout), strict=True):
665
+ for a in range(8):
666
+ if kind == "displacement":
667
+ for c in range(3):
668
+ b[:, comp, a * nd + dof.start + c] = el.b_gauss[:, :, 3 * a + c]
669
+ else:
670
+ b[:, comp, a * nd + dof.start] = el.g_gauss[:, :, a]
671
+ return np.ascontiguousarray(b)
672
+
673
+ def _references(self) -> None:
674
+ """The sign and the homogeneous reference medium of each block, and the scales
675
+ of the fields: the reference of a potential is the mean of the extreme
676
+ eigenvalues of its block over the materials, that of a displacement the isotropic
677
+ medium of :func:`~morphogen.homogenization.fft.reference_moduli`."""
678
+ used = self.laws[self.counts > 0]
679
+ self.signs, self.references = [], []
680
+ scale_w, scale_z = np.ones(self.nd), np.ones(self.nz)
681
+ for kind, (dof, comp) in zip(self.layout, _slices(self.layout), strict=True):
682
+ blocks = used[:, comp, comp]
683
+ blocks = blocks[np.abs(blocks).max(axis=(1, 2), initial=0.0) > 0]
684
+ if not len(blocks): # no material has the block: nothing to solve for it
685
+ self.signs.append(1.0)
686
+ self.references.append(None)
687
+ continue
688
+ eig = np.linalg.eigvalsh(blocks)
689
+ sign = 1.0 if eig.min() > 0 else -1.0
690
+ if not np.all(sign * eig > 0):
691
+ raise ValueError(
692
+ f"coupled laws: the block of the field {kind!r} must be definite, "
693
+ "positive or negative, alike in every material"
694
+ )
695
+ if kind == "displacement":
696
+ lam, mu = reference_moduli(sign * blocks, False)
697
+ ref = (lam, mu)
698
+ size = mu
699
+ else:
700
+ ref = 0.5 * (sign * eig).min() + 0.5 * (sign * eig).max()
701
+ size = ref
702
+ self.signs.append(sign)
703
+ self.references.append(ref)
704
+ scale_w[dof] = scale_z[comp] = 1.0 / np.sqrt(size)
705
+ self.scale_w, self.scale_z = scale_w, scale_z
706
+ self.definite = all(s > 0 for s in self.signs)
707
+
708
+ def _preconditioner(self):
709
+ """The inverse of the homogeneous reference medium of each block (scaled), in
710
+ Fourier space; the identity for a block that no material has."""
711
+ if self._preconditioners is None:
712
+ el, out = self.element, []
713
+ for kind, ref, (dof, _) in zip(self.layout, self.references, _slices(self.layout),
714
+ strict=True): # fmt: skip
715
+ if ref is None:
716
+ out.append(None)
717
+ elif kind == "displacement":
718
+ k = el.stiffness(*ref) * self.scale_w[dof.start] ** 2
719
+ out.append(FourierPreconditioner.from_element(self.shape, k, 3))
720
+ else:
721
+ k = ref * el.k_thermal * self.scale_w[dof.start] ** 2
722
+ out.append(FourierPreconditioner.from_element(self.shape, k, 1))
723
+ self._preconditioners = out
724
+ parts = list(zip(self._preconditioners, _slices(self.layout), strict=True))
725
+ nd = self.nd
726
+
727
+ def precondition(r):
728
+ field_r = r.reshape(-1, nd)
729
+ z = np.empty_like(field_r)
730
+ for p, (dof, _) in parts:
731
+ block = np.ascontiguousarray(field_r[:, dof])
732
+ z[:, dof] = block if p is None else p(block.ravel()).reshape(block.shape)
733
+ return z.ravel()
734
+
735
+ return precondition
736
+
737
+ def _affine(self, gradient) -> np.ndarray:
738
+ """The nodal values (8 nd) of the affine fields of a (scaled) macroscopic
739
+ gradient at the corners of a voxel."""
740
+ el, nd = self.element, self.nd
741
+ out = np.zeros((8, nd))
742
+ for kind, (dof, comp) in zip(self.layout, _slices(self.layout), strict=True):
743
+ if kind == "displacement":
744
+ out[:, dof] = el.affine_displacement(gradient[comp]).reshape(8, 3)
745
+ else:
746
+ out[:, dof.start] = el.affine_temperature(gradient[comp])
747
+ return out.ravel()
748
+
749
+ # -- solution ----------------------------------------------------------------------
750
+
751
+ def _fluctuation(self, z: np.ndarray, dt: float):
752
+ """The (scaled) periodic fluctuation of the scaled macroscopic gradient ``z`` and
753
+ the change of temperature ``dt``."""
754
+ nx, ny, nz = self.shape
755
+ nd = self.nd
756
+ loads = self.element_matrices @ self._affine(z)
757
+ if dt:
758
+ thermal = self.element.weight * np.einsum("grc,mr->mc", self.b_gauss, self._eigen)
759
+ loads = loads - dt * thermal
760
+ loads = np.ascontiguousarray(loads)
761
+ dof = np.arange(nd * nx * ny * nz, dtype=np.int64)
762
+ rhs = kernels.element_load(nx, ny, nz, True, self.mat, dof, nd, loads, dof.size)
763
+ scale = float(np.sqrt(np.sum(self.counts * np.sum(loads * loads, axis=1))))
764
+ if float(np.linalg.norm(rhs)) <= NEGLIGIBLE * scale:
765
+ return np.zeros_like(rhs), SolveInfo("fft", rhs.size, 0, 0.0, 0.0, 0.0)
766
+ mats = self.element_matrices
767
+
768
+ def apply(v):
769
+ out = np.empty_like(v)
770
+ _apply(nx, ny, nz, nd, self.mat, mats, v, out)
771
+ return out
772
+
773
+ maxiter = self.maxiter or 40 * int(max(self.shape)) + 2000
774
+ solve = conjugate_gradient if self.definite else minres
775
+ method = "fft-cg" if self.definite else "fft-minres"
776
+ t0 = time.perf_counter()
777
+ w, it, res = None, 0, float("inf")
778
+ if self.pairs: # a complex symmetric law: conjugate gradients without conjugation
779
+ w, it, res = conjugate_orthogonal_gradient(
780
+ apply, self._preconditioner(), rhs, self.tol, maxiter, nd
781
+ )
782
+ method = "fft-cocg"
783
+ if res > self.tol: # (the method stalled: the real form, by MINRES)
784
+ spent = it
785
+ w, it, res = solve(apply, self._preconditioner(), rhs, self.tol, maxiter)
786
+ it += spent
787
+ method = "fft-cg" if self.definite else "fft-minres"
788
+ if res > self.tol:
789
+ log.warning(
790
+ "coupled solver stopped at relative residual %.2e after %d iterations", res, it
791
+ )
792
+ return w, SolveInfo(method, rhs.size, it, res, 0.0, time.perf_counter() - t0)
793
+
794
+ def _unit(self, j: int):
795
+ """The fluctuation of the unit (scaled) gradient ``j`` (-1: a unit change of
796
+ temperature), cached."""
797
+ if j not in self._units:
798
+ z = np.zeros(self.nz)
799
+ if j >= 0:
800
+ z[j] = 1.0
801
+ self._units[j] = self._fluctuation(z, 1.0 if j < 0 else 0.0)
802
+ return self._units[j]
803
+
804
+ def solve(self, gradient, *, temperature: float = 0.0, fields: bool = False):
805
+ """The solution (:class:`CoupledSolution`) of a macroscopic generalized gradient
806
+ ``Z`` (the components of the layout) and a change of ``temperature``, by
807
+ superposition of the unit solutions."""
808
+ z = np.asarray(gradient, dtype=float).ravel()
809
+ if z.shape != (self.nz,):
810
+ raise ValueError(f"gradient: the {self.nz} components of the layout")
811
+ t0 = time.perf_counter()
812
+ dt = float(temperature)
813
+ if self.empty:
814
+ info = SolveInfo("none", 0, 0, 0.0, 0.0, 0.0)
815
+ return CoupledSolution(z, np.zeros(self.nz), 0.0, dt, 0.0, info)
816
+ zs = z / self.scale_z
817
+ w = np.zeros(self.nd * int(np.prod(self.shape)))
818
+ infos = []
819
+ for j in [*np.flatnonzero(zs), *([-1] if dt else [])]:
820
+ wj, info = self._unit(int(j))
821
+ w += (dt if j < 0 else zs[j]) * wj
822
+ infos.append(info)
823
+ nx, ny, nz = self.shape
824
+ aff = self._affine(zs)
825
+ n_stat = int(self.stat.max(initial=0)) + 1
826
+ sums = _sums(nx, ny, nz, self.nd, self.mat, self.stat, n_stat, self._laws,
827
+ self._eigen, dt, w, aff, self.b_gauss, self.element.weight) # fmt: skip
828
+ total = sums.sum(axis=0)
829
+ ncomp = self.nz
830
+ info = SolveInfo(
831
+ infos[0].method if infos else "none",
832
+ w.size,
833
+ sum(i.iterations for i in infos),
834
+ max((i.residual for i in infos), default=0.0),
835
+ 0.0,
836
+ time.perf_counter() - t0,
837
+ )
838
+ phases = {}
839
+ for g in range(n_stat):
840
+ vol = sums[g, -1]
841
+ if vol > 0:
842
+ phases[g] = {
843
+ "fraction": float(vol / self.box_volume),
844
+ "gradient": sums[g, :ncomp] / vol * self.scale_z,
845
+ "flux": sums[g, ncomp : 2 * ncomp] / vol / self.scale_z,
846
+ }
847
+ out = CoupledSolution(
848
+ gradient=z,
849
+ flux=total[ncomp : 2 * ncomp] / self.box_volume / self.scale_z,
850
+ energy=float(total[2 * ncomp] / self.box_volume),
851
+ temperature=dt,
852
+ material_fraction=float(total[-1] / self.box_volume),
853
+ info=info,
854
+ phases=phases,
855
+ )
856
+ if fields:
857
+ grad, flux = _element_fields(nx, ny, nz, self.nd, self.mat, self._laws,
858
+ self._eigen, dt, w, aff, self.b_gauss) # fmt: skip
859
+ out.fields = {
860
+ "gradient": (grad * self.scale_z).reshape(*self.shape, ncomp),
861
+ "flux": (flux / self.scale_z).reshape(*self.shape, ncomp),
862
+ "fluctuation": (w.reshape(-1, self.nd) * self.scale_w).reshape(
863
+ *self.shape, self.nd
864
+ ),
865
+ }
866
+ return out
867
+
868
+ def tensor(self) -> np.ndarray:
869
+ """The effective law ``L*`` (nz x nz): the mean fluxes of the unit gradients,
870
+ symmetrized (it is symmetric to the tolerance of the solver)."""
871
+ law = np.zeros((self.nz, self.nz))
872
+ for j in range(self.nz):
873
+ unit = np.zeros(self.nz)
874
+ unit[j] = 1.0
875
+ law[:, j] = self.solve(unit).flux
876
+ return 0.5 * (law + law.T)
877
+
878
+ def eigen_flux(self) -> np.ndarray:
879
+ """The effective thermal flux ``lambda*`` of ``S = L* Z - lambda* dT``: minus the
880
+ mean flux of a unit change of temperature without a macroscopic gradient."""
881
+ return -self.solve(np.zeros(self.nz), temperature=1.0).flux
882
+
883
+ @property
884
+ def iterations(self) -> int:
885
+ """The iterations of the unit solutions solved so far."""
886
+ return sum(info.iterations for _, info in self._units.values())
887
+
888
+
889
+ def coupled_problem(image: VoxelImage, materials: dict[int, Material], coupling: str, *,
890
+ grains=None, orientations=None, temperature: float = 300.0,
891
+ tol: float = 1e-8, maxiter: int | None = None) -> CoupledProblem: # fmt: skip
892
+ """The :class:`CoupledProblem` of a voxel image whose phases have the ``materials``,
893
+ for a coupling of :data:`COUPLINGS` (the laws of :func:`coupled_law`). The crystals
894
+ are turned by the orientations of their grains (``grains``: the label of each voxel,
895
+ ``orientations``: their Bunge angles), as in the other problems; ``temperature``: the
896
+ mean temperature of a thermoelectric law (K)."""
897
+ if not isinstance(image, VoxelImage):
898
+ raise TypeError("coupled homogenization: a periodic VoxelImage (the FFT solver)")
899
+ if image.data.dtype.kind not in "iub":
900
+ raise ValueError("homogenization needs an integer phase image")
901
+ phase = np.asarray(image.data).ravel().astype(np.int64)
902
+ present = [int(p) for p in np.unique(phase)]
903
+ missing = [p for p in present if p not in materials]
904
+ if missing:
905
+ raise ValueError(f"no material for phase(s) {missing}; phases present: {present}")
906
+ oriented = grains is not None and orientations is not None
907
+ if oriented:
908
+ grains = np.asarray(grains.data if isinstance(grains, VoxelImage) else grains).ravel()
909
+ if grains.size != phase.size:
910
+ raise ValueError("grains: one grain label per voxel of the image")
911
+ stat = np.searchsorted(present, phase)
912
+ mat = np.full(phase.size, -1, dtype=np.int64)
913
+ laws, eigen = [], []
914
+ for p in present:
915
+ m = materials[p]
916
+ if m.void:
917
+ continue
918
+ sel = np.flatnonzero(phase == p)
919
+ try:
920
+ if oriented and _oriented(m):
921
+ ids, inverse = np.unique(grains[sel], return_inverse=True)
922
+ mat[sel] = len(laws) + inverse
923
+ for g in ids:
924
+ law, lam = coupled_law(m, coupling, np.asarray(orientations, float)[g],
925
+ temperature=temperature) # fmt: skip
926
+ laws.append(law)
927
+ eigen.append(lam)
928
+ continue
929
+ law, lam = coupled_law(m, coupling, temperature=temperature)
930
+ except ValueError as exc:
931
+ raise ValueError(f"phase {p}: {exc}") from None
932
+ mat[sel] = len(laws)
933
+ laws.append(law)
934
+ eigen.append(lam)
935
+ layout = COUPLINGS[coupling]
936
+ nz = layout_sizes(layout)[1]
937
+ problem = CoupledProblem(
938
+ image,
939
+ np.array(laws).reshape(-1, nz, nz),
940
+ layout,
941
+ mat,
942
+ eigen=np.array(eigen).reshape(-1, nz),
943
+ stat=stat,
944
+ tol=tol,
945
+ maxiter=maxiter,
946
+ )
947
+ problem.coupling = coupling
948
+ problem.phases = tuple(present)
949
+ problem.temperature = float(temperature)
950
+ return problem
951
+
952
+
953
+ def _oriented(m: Material) -> bool:
954
+ """Whether a law of the material turns with the orientation of its grain."""
955
+ from morphogen.homogenization.materials import PHYSICS
956
+
957
+ return m.coupling is not None or any(m.has(p) and m.oriented(p) for p in PHYSICS)
958
+
959
+
960
+ # -- the tensors of a coupling ---------------------------------------------------------------
961
+
962
+
963
+ def split_law(law, coupling: str, *, temperature: float = 300.0) -> dict:
964
+ """The tensors of a law ``L`` of a coupling (:data:`COUPLINGS`; see the module), with
965
+ the constants derived from them.
966
+
967
+ ``piezoelectric``: ``stiffness`` (``C^E``, at constant field), ``piezoelectric``
968
+ (``e``, 3 x 6), ``permittivity`` (``kappa^eps``, at constant strain), then
969
+ ``compliance`` (``S^E``), ``d`` (``d = e S^E``, the strain-charge form: 3 x 6, C/N),
970
+ ``permittivity_stress`` (``kappa^sigma = kappa^eps + d e^T``), ``g33`` (``d33 /
971
+ kappa^sigma_33``), the hydrostatic coefficients ``d_h = d31 + d32 + d33`` and ``g_h =
972
+ d_h / kappa^sigma_33``, the coupling factors ``k33`` (``d33 / sqrt(S^E_33
973
+ kappa^sigma_33)``) and ``k_t`` (thickness mode: ``e33 / sqrt(C^D_33 kappa^eps_33)``,
974
+ ``C^D_33 = C^E_33 + e33^2 / kappa^eps_33``), and the entries ``e31``, ``e33``,
975
+ ``e15``, ``d31``, ``d33``, ``d15``. ``piezomagnetic``: the same with
976
+ ``piezomagnetic`` (``q``) and ``permeability``. ``magnetoelectroelastic``: both, and
977
+ ``magnetoelectric`` (``alpha``, 3 x 3) with its entries ``alpha11``, ``alpha33``.
978
+ ``magnetoelectric``: ``permittivity``, ``permeability``, ``magnetoelectric``.
979
+ ``thermoelectric``: ``electrical_conductivity``, ``seebeck`` (``sigma^-1 L_12``),
980
+ ``conductivity`` (thermal, at zero current) and, along each axis, the power factor
981
+ ``sigma s^2`` and the figure of merit ``ZT = sigma s^2 T0 / k`` (``power_factor1``,
982
+ ``zt1``...).
983
+ """
984
+ law = np.asarray(law, dtype=float)
985
+ if coupling not in COUPLINGS:
986
+ raise ValueError(f"coupling: one of {tuple(COUPLINGS)}, got {coupling!r}")
987
+ out: dict = {"tensor": law}
988
+ if coupling == "thermoelectric":
989
+ sigma = law[:3, :3]
990
+ s = np.linalg.solve(sigma, law[:3, 3:])
991
+ k = temperature * (law[3:, 3:] - law[3:, :3] @ s)
992
+ out.update(electrical_conductivity=sigma, seebeck=s, conductivity=0.5 * (k + k.T))
993
+ for i in range(3):
994
+ pf = float(sigma[i, i] * s[i, i] ** 2)
995
+ out[f"power_factor{i + 1}"] = pf
996
+ out[f"zt{i + 1}"] = float(pf * temperature / k[i, i])
997
+ return out
998
+ if coupling == "magnetoelectric":
999
+ out.update(permittivity=law[:3, :3], permeability=law[3:, 3:], magnetoelectric=law[:3, 3:])
1000
+ out.update(alpha11=float(law[0, 3]), alpha33=float(law[2, 5]))
1001
+ return out
1002
+ c = law[:6, :6]
1003
+ out["stiffness"] = c
1004
+ comp = np.linalg.inv(c) if np.linalg.matrix_rank(c) == 6 else None
1005
+ if comp is not None:
1006
+ out["compliance"] = comp
1007
+ blocks = []
1008
+ if coupling in ("piezoelectric", "magnetoelectroelastic"):
1009
+ blocks.append(("piezoelectric", "permittivity", "e", "d", slice(6, 9)))
1010
+ if coupling in ("piezomagnetic", "magnetoelectroelastic"):
1011
+ at = 9 if coupling == "magnetoelectroelastic" else 6
1012
+ blocks.append(("piezomagnetic", "permeability", "q", "dm", slice(at, at + 3)))
1013
+ for name, susceptibility, e_name, d_name, sl in blocks:
1014
+ e = law[sl, :6]
1015
+ kappa = -law[sl, sl]
1016
+ out[name], out[susceptibility] = e, kappa
1017
+ for key, (i, j) in (("31", (2, 0)), ("33", (2, 2)), ("15", (0, 4))):
1018
+ out[f"{e_name}{key}"] = float(e[i, j])
1019
+ if comp is None:
1020
+ continue
1021
+ d = e @ comp
1022
+ stress_free = kappa + d @ e.T
1023
+ out[d_name], out[f"{susceptibility}_stress"] = d, stress_free
1024
+ for key, (i, j) in (("31", (2, 0)), ("33", (2, 2)), ("15", (0, 4))):
1025
+ out[f"{d_name}{key}"] = float(d[i, j])
1026
+ if name == "piezoelectric":
1027
+ dh = float(d[2, 0] + d[2, 1] + d[2, 2])
1028
+ out["d_h"] = dh
1029
+ out["g33"] = float(d[2, 2] / stress_free[2, 2])
1030
+ out["g_h"] = float(dh / stress_free[2, 2])
1031
+ out["k33"] = float(abs(d[2, 2]) / np.sqrt(comp[2, 2] * stress_free[2, 2]))
1032
+ stiffened = c[2, 2] + e[2, 2] ** 2 / kappa[2, 2]
1033
+ out["k_t"] = float(abs(e[2, 2]) / np.sqrt(stiffened * kappa[2, 2]))
1034
+ if coupling == "magnetoelectroelastic":
1035
+ alpha = -law[6:9, 9:12]
1036
+ out["magnetoelectric"] = alpha
1037
+ out.update(alpha11=float(alpha[0, 0]), alpha33=float(alpha[2, 2]))
1038
+ return out
1039
+
1040
+
1041
+ def coupled_tensors(image: VoxelImage, materials: dict[int, Material], coupling: str, *,
1042
+ grains=None, orientations=None, temperature: float = 300.0,
1043
+ tol: float = 1e-8, maxiter: int | None = None,
1044
+ thermal: bool | None = None) -> dict: # fmt: skip
1045
+ """The effective tensors of a coupling (:data:`COUPLINGS`) of a periodic voxel image:
1046
+ those of :func:`split_law` for its effective law (``"tensor"``: the law itself), the
1047
+ iterations and the largest residual of the solver (``"iterations"``, ``"residual"``)
1048
+ and, with ``thermal`` (by default: when a phase expands or is pyroelectric), the
1049
+ effective thermal flux (``"thermal_stress"``: ``beta* = C* alpha*``, Voigt;
1050
+ ``"thermal_expansion"``: ``alpha*`` at constant field, 3 x 3; ``"pyroelectric"``:
1051
+ ``p*`` at constant strain and field). See :func:`coupled_problem` for the options."""
1052
+ problem = coupled_problem(image, materials, coupling, grains=grains,
1053
+ orientations=orientations, temperature=temperature, tol=tol,
1054
+ maxiter=maxiter) # fmt: skip
1055
+ law = problem.tensor()
1056
+ out = split_law(law, coupling, temperature=temperature)
1057
+ if thermal is None:
1058
+ thermal = bool(np.any(problem.eigen))
1059
+ if thermal and COUPLINGS[coupling][0] == "displacement":
1060
+ from morphogen.homogenization.elements import voigt_to_tensor
1061
+
1062
+ lam = problem.eigen_flux()
1063
+ out["thermal_stress"] = lam[:6]
1064
+ if "compliance" in out:
1065
+ out["thermal_expansion"] = voigt_to_tensor(out["compliance"] @ lam[:6], strain=True)
1066
+ if coupling in ("piezoelectric", "magnetoelectroelastic"):
1067
+ out["pyroelectric"] = -lam[6:9]
1068
+ infos = [info for _, info in problem._units.values()]
1069
+ out["iterations"] = int(sum(i.iterations for i in infos))
1070
+ out["residual"] = float(max((i.residual for i in infos), default=0.0))
1071
+ return out
1072
+
1073
+
1074
+ #: The prefix of the entries of each tensor of a coupled law in the tables of results
1075
+ #: (:func:`coupled_entries`), and whether the tensor is symmetric (its upper triangle)
1076
+ ENTRIES = {
1077
+ "stiffness": ("C", True),
1078
+ "piezoelectric": ("e", False),
1079
+ "d": ("d", False),
1080
+ "piezomagnetic": ("q", False),
1081
+ "dm": ("dm", False),
1082
+ "permittivity": ("eps", True),
1083
+ "permittivity_stress": ("eps_s", True),
1084
+ "permeability": ("mu", True),
1085
+ "permeability_stress": ("mu_s", True),
1086
+ "magnetoelectric": ("alpha", False),
1087
+ "electrical_conductivity": ("sigma", True),
1088
+ "seebeck": ("s", False),
1089
+ "conductivity": ("k", True),
1090
+ "thermal_expansion": ("A", True),
1091
+ "thermal_stress": ("beta", False),
1092
+ "pyroelectric": ("p", False),
1093
+ }
1094
+
1095
+
1096
+ def entry_names(coupling: str) -> tuple[str, ...]:
1097
+ """The names of the scalar results of a coupling (:data:`COUPLINGS`) in the tables of
1098
+ results and for the statistics of RVE studies: the entries of its tensors
1099
+ (:func:`coupled_entries`: ``C11``, ``e33``, ``eps11``...), those of its thermal flux
1100
+ with a displacement (``A11``, ``beta1``, ``p3``) and its constants (``d33``, ``k33``,
1101
+ ``zt1``...)."""
1102
+ if coupling not in COUPLINGS:
1103
+ raise ValueError(f"coupling: one of {tuple(COUPLINGS)}, got {coupling!r}")
1104
+ layout = COUPLINGS[coupling]
1105
+ with np.errstate(invalid="ignore", divide="ignore"): # a dummy law: only its names
1106
+ tensors = split_law(np.eye(layout_sizes(layout)[1]), coupling)
1107
+ if layout[0] == "displacement":
1108
+ tensors["thermal_stress"] = np.zeros(6)
1109
+ tensors["thermal_expansion"] = np.zeros((3, 3))
1110
+ if coupling in ("piezoelectric", "magnetoelectroelastic"):
1111
+ tensors["pyroelectric"] = np.zeros(3)
1112
+ constants = [k for k, v in tensors.items() if isinstance(v, float)]
1113
+ return (*coupled_entries(tensors), *constants)
1114
+
1115
+
1116
+ def coupled_entries(tensors: dict) -> dict[str, float]:
1117
+ """The entries of the tensors of a coupled law (:func:`split_law`,
1118
+ :func:`coupled_tensors`) as the columns of a table of results: ``C11`` ... ``C66``,
1119
+ ``e11`` ... ``e36`` (rows 1 2 3, columns in the Voigt order 11 22 33 23 31 12 numbered
1120
+ 1 to 6), ``d11`` ... ``d36``, ``eps11`` ... ``eps33``, ``mu11``, ``alpha11``,
1121
+ ``sigma11``, ``s11``, ``k11``, ``A11``, ``beta1`` ... ``beta6``, ``p1`` ... ``p3``
1122
+ (:data:`ENTRIES`: the upper triangles of the symmetric tensors)."""
1123
+ out: dict[str, float] = {}
1124
+ for name, (prefix, symmetric) in ENTRIES.items():
1125
+ value = tensors.get(name)
1126
+ if value is None:
1127
+ continue
1128
+ a = np.asarray(value, dtype=float)
1129
+ if a.ndim == 1:
1130
+ out.update({f"{prefix}{i + 1}": float(v) for i, v in enumerate(a)})
1131
+ continue
1132
+ for i in range(a.shape[0]):
1133
+ for j in range(i if symmetric else 0, a.shape[1]):
1134
+ out[f"{prefix}{i + 1}{j + 1}"] = float(a[i, j])
1135
+ return out