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,226 @@
1
+ """Bounds on the effective properties of multiphase media and polycrystals.
2
+
3
+ Isotropic phases: Voigt and Reuss bounds, and the Hashin-Shtrikman bounds in Walpole's
4
+ form (valid for any number of isotropic phases); for conduction, the Wiener and
5
+ Hashin-Shtrikman bounds, which hold alike for every transport phenomenon of a scalar
6
+ potential (:data:`~morphogen.homogenization.materials.TRANSPORT`: the electrical
7
+ conductivity, the permittivity, the permeability, the diffusivity). Voids have zero moduli
8
+ and conductivity, as the insulators of a transport: every lower bound is then zero.
9
+
10
+ Thermal expansion: the expansion of phases expanding alike is exact; for two isotropic
11
+ phases, Levin's exact relation (Levin 1967) maps the bulk modulus onto the expansion of a
12
+ statistically isotropic composite, and the Hashin-Shtrikman bounds of the former give
13
+ those of the latter (Schapery 1968).
14
+
15
+ Crystals (statistically isotropic aggregates, uniform orientations): the Voigt and
16
+ Reuss averages of each phase bound the moduli; for a polycrystal of one cubic phase, the
17
+ Hashin-Shtrikman bounds of the shear modulus (Hashin & Shtrikman 1962, J. Mech. Phys.
18
+ Solids 10, 343-352), its bulk modulus being exactly ``(C11 + 2 C12) / 3``; for
19
+ conduction, the Hashin-Shtrikman bounds of a polycrystal are those of a mixture of its
20
+ principal conductivities in equal fractions.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import numpy as np
26
+
27
+ from morphogen.homogenization.materials import TRANSPORT, Material
28
+
29
+
30
+ def _check(fractions, values):
31
+ f = np.asarray(fractions, dtype=float)
32
+ v = np.asarray(values, dtype=float)
33
+ if f.shape != v.shape or f.ndim != 1 or f.size == 0:
34
+ raise ValueError("give one fraction per phase")
35
+ if np.any(f < 0) or not np.isclose(f.sum(), 1.0, atol=1e-9):
36
+ raise ValueError(f"phase fractions must be non-negative and sum to 1, got {f.sum()}")
37
+ if np.any(v < 0):
38
+ raise ValueError("moduli and conductivities must be non-negative")
39
+ return f, v
40
+
41
+
42
+ def voigt(fractions, values) -> float:
43
+ """The Voigt bound (arithmetic mean) of the properties of phases in their volume fractions."""
44
+ f, v = _check(fractions, values)
45
+ return float(np.sum(f * v))
46
+
47
+
48
+ def reuss(fractions, values) -> float:
49
+ """The Reuss bound (harmonic mean) of the properties of phases in their volume fractions; zero
50
+ when a phase of nonzero fraction has a zero property."""
51
+ f, v = _check(fractions, values)
52
+ if np.any((v == 0) & (f > 0)):
53
+ return 0.0
54
+ return float(1.0 / np.sum(f / np.where(v > 0, v, np.inf)))
55
+
56
+
57
+ def _shifted_harmonic(f, v, shift) -> float:
58
+ """[sum f_i / (v_i + s)]^-1 - s (zero when s = 0 and a phase has v_i = 0)."""
59
+ den = v + shift
60
+ if np.any((den == 0) & (f > 0)):
61
+ return 0.0
62
+ return float(1.0 / np.sum(f / np.where(den > 0, den, np.inf)) - shift)
63
+
64
+
65
+ def hashin_shtrikman_bulk(fractions, bulk, shear) -> tuple[float, float]:
66
+ """(lower, upper) Hashin-Shtrikman bounds of the bulk modulus."""
67
+ f, k = _check(fractions, bulk)
68
+ _, mu = _check(fractions, shear)
69
+ return (
70
+ _shifted_harmonic(f, k, 4.0 * mu.min() / 3.0),
71
+ _shifted_harmonic(f, k, 4.0 * mu.max() / 3.0),
72
+ )
73
+
74
+
75
+ def _zeta(k: float, mu: float) -> float:
76
+ return mu / 6.0 * (9.0 * k + 8.0 * mu) / (k + 2.0 * mu) if (k + 2.0 * mu) > 0 else 0.0
77
+
78
+
79
+ def hashin_shtrikman_shear(fractions, bulk, shear) -> tuple[float, float]:
80
+ """(lower, upper) Hashin-Shtrikman bounds of the shear modulus (Walpole 1966)."""
81
+ f, k = _check(fractions, bulk)
82
+ _, mu = _check(fractions, shear)
83
+ return (
84
+ _shifted_harmonic(f, mu, _zeta(k.min(), mu.min())),
85
+ _shifted_harmonic(f, mu, _zeta(k.max(), mu.max())),
86
+ )
87
+
88
+
89
+ def hashin_shtrikman_conductivity(fractions, conductivity) -> tuple[float, float]:
90
+ """(lower, upper) Hashin-Shtrikman bounds of the conductivity (3D)."""
91
+ f, c = _check(fractions, conductivity)
92
+ return _shifted_harmonic(f, c, 2.0 * c.min()), _shifted_harmonic(f, c, 2.0 * c.max())
93
+
94
+
95
+ def cubic_shear_bounds(c11: float, c12: float, c44: float) -> tuple[float, float]:
96
+ """(lower, upper) Hashin-Shtrikman bounds of the shear modulus of a statistically
97
+ isotropic polycrystal of a cubic crystal (Hashin & Shtrikman 1962)."""
98
+ k = (c11 + 2.0 * c12) / 3.0
99
+ mu1, mu2 = 0.5 * (c11 - c12), c44
100
+ if np.isclose(mu1, mu2):
101
+ return mu1, mu1
102
+ beta1 = -3.0 * (k + 2.0 * mu1) / (5.0 * mu1 * (3.0 * k + 4.0 * mu1))
103
+ beta2 = -3.0 * (k + 2.0 * mu2) / (5.0 * mu2 * (3.0 * k + 4.0 * mu2))
104
+ g1 = mu1 + 3.0 / (5.0 / (mu2 - mu1) - 4.0 * beta1)
105
+ g2 = mu2 + 2.0 / (5.0 / (mu1 - mu2) - 6.0 * beta2)
106
+ return float(min(g1, g2)), float(max(g1, g2))
107
+
108
+
109
+ def levin_expansion(fractions, materials, bulk: float) -> float:
110
+ """Thermal expansion of a statistically isotropic composite of two isotropic phases
111
+ of effective bulk modulus ``bulk`` (Levin 1967): ``alpha = <alpha> + (alpha_1 -
112
+ alpha_2) / (1/k_1 - 1/k_2) (1/k - <1/k>)``."""
113
+ f = np.asarray(fractions, dtype=float)
114
+ (m1, m2) = materials
115
+ a = np.array([float(m1.expansion or 0.0), float(m2.expansion or 0.0)])
116
+ k = np.array([m1.bulk, m2.bulk])
117
+ if np.isclose(k[0], k[1]):
118
+ return float(f @ a)
119
+ return float(f @ a + (a[0] - a[1]) / (1.0 / k[0] - 1.0 / k[1]) * (1.0 / bulk - f @ (1.0 / k)))
120
+
121
+
122
+ def _expansion_bounds(f, mats) -> dict | None:
123
+ solid = [(fi, m) for fi, m in zip(f, mats, strict=True) if not m.void and fi > 0]
124
+ if not solid or not all(m.elastic for _, m in solid):
125
+ return None
126
+ if any(isinstance(m.expansion, tuple) for _, m in solid):
127
+ return None
128
+ alphas = {float(m.expansion or 0.0) for _, m in solid}
129
+ if len(alphas) == 1: # a uniform thermal strain is free of stress
130
+ a = alphas.pop()
131
+ return {"hs_lower": a, "hs_upper": a}
132
+ if len(solid) != 2 or len(mats) != 2 or not all(m.isotropic for _, m in solid):
133
+ return None
134
+ fr = np.array([fi for fi, _ in solid])
135
+ k = np.array([m.bulk for _, m in solid])
136
+ mu = np.array([m.shear for _, m in solid])
137
+ two = [m for _, m in solid]
138
+ ends = [levin_expansion(fr, two, kb) for kb in hashin_shtrikman_bulk(fr, k, mu)]
139
+ return {"hs_lower": min(ends), "hs_upper": max(ends)}
140
+
141
+
142
+ def _crystal_bounds(f, mats) -> dict[str, dict]:
143
+ """Voigt and Reuss bounds with the orientation averages of each phase, and the
144
+ Hashin-Shtrikman bounds of one-phase polycrystals."""
145
+ out: dict[str, dict] = {}
146
+ solid = [m for m in mats if not m.void]
147
+ single = len(mats) == 1 and not mats[0].void
148
+ if all(m.void or m.elastic for m in mats):
149
+ kv = np.array([0.0 if m.void else m.moduli("voigt")[0] for m in mats])
150
+ gv = np.array([0.0 if m.void else m.moduli("voigt")[1] for m in mats])
151
+ kr = np.array([0.0 if m.void else m.moduli("reuss")[0] for m in mats])
152
+ gr = np.array([0.0 if m.void else m.moduli("reuss")[1] for m in mats])
153
+ out["bulk_modulus"] = {"voigt": voigt(f, kv), "reuss": reuss(f, kr)}
154
+ out["shear_modulus"] = {"voigt": voigt(f, gv), "reuss": reuss(f, gr)}
155
+ if single and solid[0].symmetry == "cubic":
156
+ d = np.array(solid[0].stiffness)
157
+ k = float((d[0, 0] + 2.0 * d[0, 1]) / 3.0)
158
+ out["bulk_modulus"].update(hs_lower=k, hs_upper=k)
159
+ lo, hi = cubic_shear_bounds(d[0, 0], d[0, 1], d[3, 3])
160
+ out["shear_modulus"].update(hs_lower=lo, hs_upper=hi)
161
+ for physics, name in TRANSPORT.items():
162
+ if not all(m.void or m.has(physics) for m in mats):
163
+ continue
164
+ inert = [m.inert(physics) for m in mats]
165
+ cv = np.array([0.0 if i else m.mean_conductivity("voigt", physics)
166
+ for m, i in zip(mats, inert, strict=True)]) # fmt: skip
167
+ cr = np.array([0.0 if i else m.mean_conductivity("reuss", physics)
168
+ for m, i in zip(mats, inert, strict=True)]) # fmt: skip
169
+ out[name] = {"voigt": voigt(f, cv), "reuss": reuss(f, cr)}
170
+ if single and not inert[0]:
171
+ k = np.linalg.eigvalsh(solid[0].matrix(physics))
172
+ lo, hi = hashin_shtrikman_conductivity(np.full(3, 1.0 / 3.0), k)
173
+ out[name].update(hs_lower=lo, hs_upper=hi)
174
+ return out
175
+
176
+
177
+ def bounds(fractions: dict[int, float], materials: dict[int, Material]) -> dict[str, dict]:
178
+ """All bounds for the phases present, keyed by property then bound name.
179
+
180
+ ``fractions`` maps phase -> volume fraction (e.g. from
181
+ :func:`morphogen.analysis.phase_fractions`). With crystals (anisotropic materials),
182
+ the bounds are those of statistically isotropic aggregates (uniform orientations).
183
+ """
184
+ phases = [p for p, v in fractions.items() if v > 0]
185
+ f = np.array([fractions[p] for p in phases], dtype=float)
186
+ f = f / f.sum()
187
+ mats = [materials[p] for p in phases]
188
+ expansion = _expansion_bounds(f, mats)
189
+ if not all(m.void or m.isotropic for m in mats):
190
+ out = _crystal_bounds(f, mats)
191
+ if expansion is not None and any(m.expansion is not None for m in mats):
192
+ out["thermal_expansion"] = expansion
193
+ return out
194
+ out: dict[str, dict] = {}
195
+ if expansion is not None and any(m.expansion is not None for m in mats):
196
+ out["thermal_expansion"] = expansion
197
+ if all(m.void or m.elastic for m in mats):
198
+ k = np.array([0.0 if m.void else m.bulk for m in mats])
199
+ mu = np.array([0.0 if m.void else m.shear for m in mats])
200
+ k_hs = hashin_shtrikman_bulk(f, k, mu)
201
+ mu_hs = hashin_shtrikman_shear(f, k, mu)
202
+ out["bulk_modulus"] = {
203
+ "voigt": voigt(f, k),
204
+ "reuss": reuss(f, k),
205
+ "hs_lower": k_hs[0],
206
+ "hs_upper": k_hs[1],
207
+ }
208
+ out["shear_modulus"] = {
209
+ "voigt": voigt(f, mu),
210
+ "reuss": reuss(f, mu),
211
+ "hs_lower": mu_hs[0],
212
+ "hs_upper": mu_hs[1],
213
+ }
214
+ for physics, name in TRANSPORT.items():
215
+ if not all(m.void or m.has(physics) for m in mats):
216
+ continue
217
+ c = np.array([0.0 if m.inert(physics) else m.mean_conductivity("voigt", physics)
218
+ for m in mats]) # fmt: skip
219
+ c_hs = hashin_shtrikman_conductivity(f, c)
220
+ out[name] = {
221
+ "voigt": voigt(f, c),
222
+ "reuss": reuss(f, c),
223
+ "hs_lower": c_hs[0],
224
+ "hs_upper": c_hs[1],
225
+ }
226
+ return out
@@ -0,0 +1,458 @@
1
+ """Types shared by the solvers: boundary conditions, loadings, solutions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import time
7
+ from dataclasses import dataclass, field
8
+
9
+ import numpy as np
10
+
11
+ from morphogen.homogenization.elements import tensor_to_voigt
12
+ from morphogen.homogenization.materials import TRANSPORT
13
+ from morphogen.homogenization.solvers import SolveInfo
14
+
15
+ BOUNDARY_CONDITIONS = ("kubc", "subc", "mixed", "periodic")
16
+ _ALIASES = {
17
+ "kubc": "kubc",
18
+ "dirichlet": "kubc",
19
+ "kinematic": "kubc",
20
+ "utg": "kubc",
21
+ "subc": "subc",
22
+ "neumann": "subc",
23
+ "static": "subc",
24
+ "uhf": "subc",
25
+ "mixed": "mixed",
26
+ "mbc": "mixed",
27
+ "mtbc": "mixed",
28
+ "periodic": "periodic",
29
+ "pbc": "periodic",
30
+ }
31
+
32
+
33
+ def boundary_condition(name: str) -> str:
34
+ """Canonical name of a boundary condition (accepts aliases such as 'pbc', 'utg')."""
35
+ key = str(name).strip().lower()
36
+ if key not in _ALIASES:
37
+ raise ValueError(
38
+ f"unknown boundary condition {name!r}; use one of {BOUNDARY_CONDITIONS} "
39
+ "(aliases: dirichlet, utg, neumann, uhf, mbc, mtbc, pbc)"
40
+ )
41
+ return _ALIASES[key]
42
+
43
+
44
+ #: Names of the Voigt components (elasticity) and of the vector components (conduction).
45
+ VOIGT_NAMES = ("11", "22", "33", "23", "31", "12")
46
+ VECTOR_NAMES = ("1", "2", "3")
47
+ _ALIASES_VOIGT = {"32": "23", "13": "31", "21": "12"}
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Loading:
52
+ """Macroscopic loading.
53
+
54
+ ``kind`` is ``strain`` or ``stress`` (6 Voigt components, order 11 22 33 23 31 12,
55
+ engineering shear strains) for elasticity, ``gradient`` or ``flux`` (3 components)
56
+ for the transport phenomena of a scalar potential (heat or electrical conduction,
57
+ dielectric or magnetic polarization, diffusion), or ``mixed``: component ``i`` is a
58
+ strain (gradient) where ``controls[i]`` is true, a stress (flux) where it is false.
59
+ The components of the macroscopic strain are then unknowns of the problem, dual to
60
+ those of the macroscopic stress (their reactions are ``V Sigma``), as the degrees of
61
+ freedom of the periodic element of Z-set (see :func:`superpose`). ``temperature`` is a
62
+ uniform change of temperature from the stress-free state (elasticity: thermal strains
63
+ of the materials that expand). ``physics``: ``"elastic"`` for the loadings of 6
64
+ components; for those of 3, the transport phenomenon they load
65
+ (:data:`~morphogen.homogenization.materials.TRANSPORT`, ``"thermal"`` by default): a
66
+ problem takes the gradients and fluxes of any of them, and :func:`~morphogen.
67
+ homogenization.apparent.homogenize` solves each named loading with the problem of its
68
+ physics.
69
+ """
70
+
71
+ kind: str
72
+ value: tuple[float, ...]
73
+ controls: tuple[bool, ...] | None = None
74
+ temperature: float = 0.0
75
+ physics: str | None = None
76
+
77
+ def __post_init__(self) -> None:
78
+ sizes = {"strain": 6, "stress": 6, "gradient": 3, "flux": 3, "mixed": (3, 6)}
79
+ if self.kind not in sizes:
80
+ raise ValueError(f"loading kind: one of {tuple(sizes)}, got {self.kind!r}")
81
+ v = tuple(float(x) for x in np.asarray(self.value, dtype=float).ravel())
82
+ n = sizes[self.kind]
83
+ if (len(v) not in n) if isinstance(n, tuple) else len(v) != n:
84
+ raise ValueError(f"a {self.kind} loading has {n} components")
85
+ if not all(np.isfinite(v)):
86
+ raise ValueError("loading values must be finite")
87
+ object.__setattr__(self, "value", v)
88
+ if self.kind == "mixed":
89
+ if self.controls is None or len(self.controls) != len(v):
90
+ raise ValueError("a mixed loading tells which component is a strain (controls)")
91
+ object.__setattr__(self, "controls", tuple(bool(c) for c in self.controls))
92
+ elif self.controls is not None:
93
+ raise ValueError("controls: mixed loadings only")
94
+ elastic = len(v) == 6
95
+ if self.physics is None:
96
+ object.__setattr__(self, "physics", "elastic" if elastic else "thermal")
97
+ elif self.physics not in (("elastic",) if elastic else tuple(TRANSPORT)):
98
+ allowed = "'elastic'" if elastic else f"one of {tuple(TRANSPORT)}"
99
+ raise ValueError(
100
+ f"physics of a loading of {len(v)} components: {allowed}, got {self.physics!r}"
101
+ )
102
+ t = float(self.temperature)
103
+ if not np.isfinite(t):
104
+ raise ValueError("temperature: a finite change of temperature")
105
+ if t and not elastic:
106
+ raise ValueError("temperature: a change of temperature loads elastic problems")
107
+ object.__setattr__(self, "temperature", t)
108
+
109
+ @classmethod
110
+ def strain(cls, value, *, temperature: float = 0.0) -> Loading:
111
+ """Imposed strain: a 3 x 3 tensor or 6 Voigt components (engineering shears)."""
112
+ v = np.asarray(value, dtype=float)
113
+ v = tensor_to_voigt(v, strain=True) if v.shape == (3, 3) else v
114
+ return cls("strain", v, temperature=temperature)
115
+
116
+ @classmethod
117
+ def stress(cls, value, *, temperature: float = 0.0) -> Loading:
118
+ v = np.asarray(value, dtype=float)
119
+ v = tensor_to_voigt(v, strain=False) if v.shape == (3, 3) else v
120
+ return cls("stress", v, temperature=temperature)
121
+
122
+ @classmethod
123
+ def gradient(cls, value, *, physics: str = "thermal") -> Loading:
124
+ """Imposed gradient of the potential of a transport phenomenon (3 components)."""
125
+ return cls("gradient", value, physics=physics)
126
+
127
+ @classmethod
128
+ def flux(cls, value, *, physics: str = "thermal") -> Loading:
129
+ """Imposed flux of a transport phenomenon (3 components; ``flux = -K gradient``)."""
130
+ return cls("flux", value, physics=physics)
131
+
132
+ @classmethod
133
+ def mixed(
134
+ cls,
135
+ strain=None,
136
+ stress=None,
137
+ *,
138
+ gradient=None,
139
+ flux=None,
140
+ temperature: float = 0.0,
141
+ physics: str | None = None,
142
+ ) -> Loading:
143
+ """Strain prescribed on some components, stress on the others (or gradient and
144
+ flux): each as a mapping (``{"11": 0.01, "23": 0}``; conduction ``{"1": ...}``)
145
+ or a sequence with ``None`` where the other one is prescribed. Every component
146
+ must be prescribed exactly once. Example, uniaxial tension along 1 with free
147
+ lateral contraction: ``Loading.mixed(strain={"11": 0.01}, stress={"22": 0, "33":
148
+ 0, "23": 0, "31": 0, "12": 0})``."""
149
+ elastic = gradient is None and flux is None
150
+ if not elastic and (strain is not None or stress is not None):
151
+ raise ValueError("a mixed loading: strain and stress, or gradient and flux")
152
+ names = VOIGT_NAMES if elastic else VECTOR_NAMES
153
+ first, second = (strain, stress) if elastic else (gradient, flux)
154
+ a, b = _components(first, names), _components(second, names)
155
+ both = [n for n, x, y in zip(names, a, b, strict=True) if x is not None and y is not None]
156
+ neither = [n for n, x, y in zip(names, a, b, strict=True) if x is None and y is None]
157
+ if both or neither:
158
+ raise ValueError(
159
+ f"mixed loading: components {both} prescribed twice, {neither} not prescribed"
160
+ )
161
+ values = [x if x is not None else y for x, y in zip(a, b, strict=True)]
162
+ controls = [x is not None for x in a]
163
+ return cls(
164
+ "mixed", values, controls=tuple(controls), temperature=temperature, physics=physics
165
+ )
166
+
167
+ @classmethod
168
+ def uniaxial(cls, axis: int, *, strain=None, stress=None, temperature: float = 0.0):
169
+ """Tension along ``axis``: its strain (or stress) prescribed, the other stress
170
+ components zero (free lateral contraction)."""
171
+ if (strain is None) == (stress is None):
172
+ raise ValueError("uniaxial loading: give the strain or the stress along the axis")
173
+ name = VOIGT_NAMES[int(axis)]
174
+ free = {n: 0.0 for n in VOIGT_NAMES if n != name}
175
+ if strain is not None:
176
+ return cls.mixed(strain={name: strain}, stress=free, temperature=temperature)
177
+ values = [stress if n == name else 0.0 for n in VOIGT_NAMES]
178
+ return cls.stress(values, temperature=temperature)
179
+
180
+ @classmethod
181
+ def from_spec(cls, spec) -> Loading:
182
+ """Loading of a configuration mapping: ``strain`` and/or ``stress`` (elasticity)
183
+ or ``gradient`` and/or ``flux`` (a transport phenomenon: ``physics``, thermal by
184
+ default), each a mapping of components or a full list, and ``temperature``.
185
+ Components not given are free: zero stress (flux). ``{"strain": {"11": 0.01}}`` is
186
+ a uniaxial tension, ``{"temperature": 1}`` a free thermal expansion, ``{"physics":
187
+ "electrical", "gradient": {"1": 1}}`` a potential gradient along x, the currents
188
+ across it free."""
189
+ if isinstance(spec, Loading):
190
+ return spec
191
+ if not isinstance(spec, dict):
192
+ raise ValueError(f"a loading is a mapping, got {spec!r}")
193
+ unknown = set(spec) - {"strain", "stress", "gradient", "flux", "temperature", "physics"}
194
+ if unknown:
195
+ raise ValueError(f"loading: unknown keys {sorted(unknown)}")
196
+ physics = spec.get("physics")
197
+ elastic = not ({"gradient", "flux"} & set(spec)) and physics in (None, "elastic")
198
+ if not elastic and ({"strain", "stress"} & set(spec)):
199
+ raise ValueError("a loading: strain and stress, or gradient and flux")
200
+ names = VOIGT_NAMES if elastic else VECTOR_NAMES
201
+ first = _components(spec.get("strain" if elastic else "gradient"), names)
202
+ second = _components(spec.get("stress" if elastic else "flux"), names)
203
+ values, controls = [], []
204
+ for name, a, b in zip(names, first, second, strict=True):
205
+ if a is not None and b is not None:
206
+ raise ValueError(f"loading: component {name} prescribed twice")
207
+ values.append(a if a is not None else (b or 0.0))
208
+ controls.append(a is not None)
209
+ temperature = float(spec.get("temperature", 0.0))
210
+ if all(controls):
211
+ kind = "strain" if elastic else "gradient"
212
+ elif not any(controls):
213
+ kind = "stress" if elastic else "flux"
214
+ else:
215
+ kind = "mixed"
216
+ return cls(
217
+ kind,
218
+ values,
219
+ controls=tuple(controls) if kind == "mixed" else None,
220
+ temperature=temperature,
221
+ physics=physics,
222
+ )
223
+
224
+ @classmethod
225
+ def parse(cls, text: str) -> Loading:
226
+ """Loading of a compact text: ``E11=0.01 S22=0 dT=10`` (strain ``E``, stress
227
+ ``S``), ``G1=1 Q2=0`` (gradient, flux; of the transport phenomenon
228
+ ``physics=electrical``, thermal by default); components not given are free."""
229
+ spec: dict = {}
230
+ keys = {"E": "strain", "S": "stress", "G": "gradient", "Q": "flux"}
231
+ for item in text.replace(",", " ").split():
232
+ name, _, value = item.partition("=")
233
+ if not value:
234
+ raise ValueError(f"loading: expected NAME=VALUE, got {item!r}")
235
+ if name.lower() == "physics":
236
+ spec["physics"] = value
237
+ elif name.lower() in ("dt", "temperature"):
238
+ spec["temperature"] = float(value)
239
+ elif name[:1].upper() in keys and name[1:]:
240
+ spec.setdefault(keys[name[:1].upper()], {})[name[1:]] = float(value)
241
+ else:
242
+ raise ValueError(f"loading: unknown component {name!r} (E11, S12, G1, Q3, dT)")
243
+ return cls.from_spec(spec)
244
+
245
+ @property
246
+ def array(self) -> np.ndarray:
247
+ return np.array(self.value)
248
+
249
+ @property
250
+ def strain_controlled(self) -> np.ndarray:
251
+ """Components prescribed as strains (gradients); the others are stresses (fluxes)."""
252
+ if self.kind == "mixed":
253
+ return np.array(self.controls)
254
+ return np.full(len(self.value), self.kind in ("strain", "gradient"))
255
+
256
+ def to_dict(self) -> dict:
257
+ out = {"kind": self.kind, "value": list(self.value)}
258
+ if self.controls is not None:
259
+ out["controls"] = list(self.controls)
260
+ if self.temperature:
261
+ out["temperature"] = self.temperature
262
+ if self.physics not in ("elastic", "thermal"):
263
+ out["physics"] = self.physics
264
+ return out
265
+
266
+
267
+ def _components(spec, names) -> list:
268
+ """Values of the named components (None where not given)."""
269
+ out = [None] * len(names)
270
+ if spec is None:
271
+ return out
272
+ if isinstance(spec, dict):
273
+ for key, value in spec.items():
274
+ name = _ALIASES_VOIGT.get(str(key), str(key))
275
+ if name not in names:
276
+ raise ValueError(f"unknown component {key!r}; use {list(names)}")
277
+ out[names.index(name)] = None if value is None else float(value)
278
+ return out
279
+ values = list(spec)
280
+ if len(values) != len(names):
281
+ raise ValueError(f"expected {len(names)} components (None where not prescribed)")
282
+ return [None if v is None else float(v) for v in values]
283
+
284
+
285
+ def superpose(problem, loading: Loading) -> tuple[np.ndarray, np.ndarray, SolveInfo]:
286
+ """Solution of a loading that mixes the components a boundary condition prescribes
287
+ (``problem.native``: strains, or stresses for static conditions) with their duals.
288
+
289
+ The macroscopic native components are the extra unknowns of the problem, dual to the
290
+ others: their reactions are the volume times the averages of the dual field, ``R =
291
+ V Sigma`` for strain components. A linear problem condenses them exactly: the
292
+ responses to unit native loadings (``problem._unit(j)``, cached) and to a unit change
293
+ of temperature give the matrix ``M`` (the apparent stiffness, or compliance) and the
294
+ vector ``r`` of ``dual = M x + r dT``; the unknown components of ``x`` solve the
295
+ prescribed rows, and the field is the sum of the unit fields. Returns ``x``, the field
296
+ and the work done."""
297
+ n = len(loading.value)
298
+ native = problem.native_mask(loading)
299
+ values = loading.array
300
+ dt = loading.temperature
301
+ x = np.where(native, values, 0.0)
302
+ unknown = ~native
303
+ need = np.flatnonzero(unknown | (x != 0))
304
+ units = {int(j): problem._unit(int(j)) for j in need}
305
+ m = np.zeros((n, n))
306
+ for j, (_, response, _) in units.items():
307
+ m[:, j] = response
308
+ r = np.zeros(n)
309
+ thermal = problem._unit(-1) if dt else None
310
+ if thermal is not None:
311
+ r = thermal[1]
312
+ if unknown.any():
313
+ rhs = values[unknown] - m[np.ix_(unknown, native)] @ x[native] - r[unknown] * dt
314
+ x[unknown] = np.linalg.solve(m[np.ix_(unknown, unknown)], rhs)
315
+ parts = [(x[j], units[j][0]) for j in units if x[j] != 0]
316
+ if thermal is not None:
317
+ parts.append((dt, thermal[0]))
318
+ state = sum((c * f for c, f in parts[1:]), parts[0][0] * parts[0][1]) if parts else None
319
+ infos = [u[2] for u in units.values()] + ([thermal[2]] if thermal is not None else [])
320
+ info = SolveInfo(
321
+ infos[0].method if infos else "none",
322
+ infos[0].n_dofs if infos else 0,
323
+ sum(i.iterations for i in infos),
324
+ max((i.residual for i in infos), default=0.0),
325
+ sum(i.setup_s for i in infos),
326
+ 0.0,
327
+ )
328
+ return x, state, info
329
+
330
+
331
+ @dataclass
332
+ class PhaseStatistics:
333
+ """Volume fraction, means and standard deviations of the fields in one phase."""
334
+
335
+ phase: int
336
+ fraction: float
337
+ mean: dict[str, np.ndarray]
338
+ std: dict[str, np.ndarray]
339
+
340
+ def to_dict(self) -> dict:
341
+ return {
342
+ "phase": self.phase,
343
+ "fraction": self.fraction,
344
+ "mean": {k: np.asarray(v).tolist() for k, v in self.mean.items()},
345
+ "std": {k: np.asarray(v).tolist() for k, v in self.std.items()},
346
+ }
347
+
348
+
349
+ @dataclass
350
+ class Solution:
351
+ """Volume averages over the box of one solved problem.
352
+
353
+ Elasticity: ``strain`` is the macroscopic strain ``E`` (imposed, or the average
354
+ strain under SUBC), ``stress`` the average stress ``Sigma`` (voids count as zero),
355
+ both 3 x 3 tensors, and ``energy`` the average of ``sigma : eps`` (twice the
356
+ elastic energy density). Conduction, and every transport phenomenon of a scalar
357
+ potential (``physics``: :data:`~morphogen.homogenization.materials.TRANSPORT`):
358
+ ``strain`` is the macroscopic gradient ``G``, ``stress`` the average flux ``Q``
359
+ (``q = -k grad T``) and ``energy`` the average of ``k grad T . grad T``.
360
+ """
361
+
362
+ physics: str
363
+ bc: str
364
+ loading: Loading
365
+ strain: np.ndarray
366
+ stress: np.ndarray
367
+ energy: float
368
+ material_fraction: float
369
+ phases: list[PhaseStatistics]
370
+ info: SolveInfo
371
+ #: local fields (with ``fields=True``): element means of strain and stress (or
372
+ #: gradient and flux) and energy density, plus the nodal displacement (temperature)
373
+ #: of finite element solutions
374
+ fields: dict[str, np.ndarray] | None = field(default=None, repr=False)
375
+ #: the mesh (TetMesh, porous phases removed) or image (VoxelImage) of the fields
376
+ support: object | None = field(default=None, repr=False)
377
+
378
+ def to_dict(self) -> dict:
379
+ return {
380
+ "physics": self.physics,
381
+ "bc": self.bc,
382
+ "loading": self.loading.to_dict(),
383
+ "strain": self.strain.tolist(),
384
+ "stress": self.stress.tolist(),
385
+ "energy": self.energy,
386
+ "material_fraction": self.material_fraction,
387
+ "phases": [p.to_dict() for p in self.phases],
388
+ "info": self.info.to_dict(),
389
+ }
390
+
391
+
392
+ class MacroscopicLoadings:
393
+ """Solution of macroscopic loadings by a problem that solves for the components its
394
+ boundary condition prescribes (``_field(x, dt)``) and evaluates the averages of a
395
+ field (``_dual``, ``_evaluate``); other components are condensed by
396
+ :func:`superpose`."""
397
+
398
+ physics = ""
399
+ bc = ""
400
+
401
+ @property
402
+ def native(self) -> str:
403
+ """What the boundary condition prescribes: strains (gradients), or stresses
404
+ (fluxes) for static conditions."""
405
+ if self.bc == "subc":
406
+ return "stress" if self.physics == "elastic" else "flux"
407
+ return "strain" if self.physics == "elastic" else "gradient"
408
+
409
+ def native_mask(self, loading: Loading) -> np.ndarray:
410
+ """Components of a loading that the boundary condition prescribes directly."""
411
+ if (loading.physics == "elastic") != (self.physics == "elastic"):
412
+ raise ValueError(f"the loading is {loading.physics}, the problem {self.physics}")
413
+ strain = loading.strain_controlled
414
+ return strain if self.native in ("strain", "gradient") else ~strain
415
+
416
+ def _unit(self, j: int):
417
+ """Field, dual response and work of the unit native loading ``j`` (``-1``: a
418
+ unit change of temperature), cached."""
419
+ if j not in self._units:
420
+ x = np.zeros(6 if self.physics == "elastic" else 3)
421
+ dt = 0.0
422
+ if j >= 0:
423
+ x[j] = 1.0
424
+ else:
425
+ dt = 1.0
426
+ state, info = self._field(x, dt)
427
+ self._units[j] = (state, self._dual(state, x, dt), info)
428
+ return self._units[j]
429
+
430
+ def solve(self, loading: Loading, *, fields: bool = False) -> Solution:
431
+ """Solve for a macroscopic loading: what the boundary condition prescribes
432
+ (strains, or stresses under ``subc``), or any mix of strain and stress components
433
+ under ``kubc``, ``periodic`` and ``subc``, by condensation of the macroscopic
434
+ unknowns (:func:`superpose`)."""
435
+ t0 = time.perf_counter()
436
+ native = self.native_mask(loading)
437
+ if self.empty:
438
+ return self._empty_solution(loading, t0)
439
+ dt = loading.temperature
440
+ if native.all():
441
+ x = loading.array
442
+ unit = np.flatnonzero(x)
443
+ if dt == 0.0 and unit.size == 1 and x[unit[0]] == 1.0: # e.g. tensors: cached
444
+ state, _, info = self._unit(int(unit[0]))
445
+ info = dataclasses.replace(info)
446
+ elif dt == 1.0 and not x.any():
447
+ state, _, info = self._unit(-1)
448
+ info = dataclasses.replace(info)
449
+ else:
450
+ state, info = self._field(x, dt)
451
+ else:
452
+ if self.bc == "mixed":
453
+ raise ValueError(
454
+ "mixed boundary conditions prescribe a strain (gradient): stress or mixed "
455
+ "loadings need kubc, periodic or subc conditions"
456
+ )
457
+ x, state, info = superpose(self, loading)
458
+ return self._evaluate(loading, state, x, dt, info, fields, t0)