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,467 @@
1
+ """Electromagnetic Bloch waves of three-dimensional photonic crystals, by plane waves.
2
+
3
+ In a periodic medium of permittivity ``ε(x)`` and permeability ``μ(x)``, a harmonic field
4
+ without sources obeys ``curl(ε⁻¹ curl H) = ω² B`` with ``B = μ H`` and ``div B = 0``. At
5
+ the wave vector ``k`` the induction of a Bloch wave is a sum of plane waves over the
6
+ reciprocal vectors ``G`` of the cell,
7
+
8
+ B(x) = Σ_G (b¹_G e¹_G + b²_G e²_G) exp(i (k + G)·x),
9
+
10
+ with two amplitudes per plane wave on the unit vectors ``e¹, e²`` normal to ``q = k + G``
11
+ (``(e¹, e², q/|q|)`` direct): the fields are divergence-free by construction, and the
12
+ gradients, which the curl ignores and which clutter the spectrum of the nodal
13
+ discretizations with zero frequencies, are left out (Ho, Chan & Soukoulis 1990; Johnson &
14
+ Joannopoulos 2001). The frequencies are those of the Hermitian problem
15
+
16
+ Pᴴ μ⁻¹ C ε⁻¹ C μ⁻¹ P b = ω² Pᴴ μ⁻¹ P b, C = i q ×,
17
+
18
+ ``P`` the map of the amplitudes to the plane waves. The curls are taken on the plane
19
+ waves and the products by ``ε⁻¹`` and ``μ⁻¹`` on the grid of the cell, a pair of fast
20
+ Fourier transforms apart, so that the matrices are never formed: the lowest frequencies
21
+ are found by a block Davidson method (the Rayleigh-Ritz values of a subspace that the
22
+ preconditioned residuals of its lowest waves extend, restarted from them and from those
23
+ of the step before), from the waves of the previous wave vector; small cells are
24
+ diagonalized. The preconditioner is the operator of the inverse medium, ``Pᴴ μ C⁻¹ ε C⁻¹
25
+ μ P`` with ``C⁻¹ = i q × / |q|²`` on the transverse waves (Johnson & Joannopoulos 2001):
26
+ the inverse of the operator but for the projections, whatever the contrast of the
27
+ phases. A uniform permeability leaves the standard problem ``Pᴴ C ε⁻¹ C P h = ω² μ h`` of
28
+ the dielectric crystals. The Galerkin projection on the transverse waves is exact: the
29
+ residual of an eigenvector is transverse and orthogonal to the transverse waves in the
30
+ product of ``μ⁻¹``.
31
+
32
+ The grid of the plane waves is that of the voxels, or one ``coarsen`` times coarser
33
+ whose cells hold several voxels. A cell that an interface cuts then takes the tensor of
34
+ Meade et al. (1993), as averaged by Johnson & Joannopoulos (2001),
35
+
36
+ ε̃⁻¹ = <ε⁻¹> n ⊗ n + <ε>⁻¹ (1 - n ⊗ n),
37
+
38
+ the harmonic mean for the field normal to the interface and the arithmetic mean along
39
+ it (the effective tensor of the layers that the interface draws in the cell), ``n`` the
40
+ sum of the gradients of the permittivity over the voxels of the cell. The stairs of the
41
+ voxels cost the frequencies an error of first order in the size of the cells; this
42
+ average brings it back to the second order: voxelize three or four times finer than
43
+ the plane waves.
44
+
45
+ With relative permittivities and permeabilities the frequencies are in units of the
46
+ speed of light over the unit of length (``ω a / 2π c``: :meth:`~morphogen.homogenization.
47
+ bloch.BandStructure.normalized`). A cell one voxel thick is a crystal invariant along
48
+ that axis: its waves in the plane are the two polarizations ``"tm"`` and ``"te"`` of
49
+ :func:`~morphogen.homogenization.bloch.scalar_band_structure` together, and those that
50
+ leave the plane (a wave vector with a component along the axis) are found here only.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import logging
56
+
57
+ import numpy as np
58
+ from scipy import fft as sfft
59
+ from scipy.linalg import eigh
60
+
61
+ from morphogen import settings
62
+ from morphogen.image import VoxelImage
63
+
64
+ log = logging.getLogger(__name__)
65
+
66
+ #: Up to this number of unknowns (two per plane wave) the matrices are formed and
67
+ #: diagonalized
68
+ DENSE_LIMIT = 1800
69
+
70
+ #: The amplitudes of a block handled at once (bounds the memory of the transforms)
71
+ BLOCK_VALUES = 6_000_000
72
+
73
+ #: The subspace of the Davidson method, in blocks of the waves sought, before a restart
74
+ SUBSPACE = 5
75
+
76
+ _AXES = (-3, -2, -1)
77
+
78
+
79
+ def _tensor_field(values: dict, data: np.ndarray, name: str):
80
+ """The field of a coefficient of the phases on the voxels: an array of the shape of
81
+ the image (isotropic phases) or ``(3, 3) + shape`` (a tensor in one phase at least)."""
82
+ phases = np.unique(data)
83
+ missing = [int(p) for p in phases if int(p) not in values]
84
+ if missing:
85
+ raise ValueError(f"electromagnetic waves: no {name} for phase(s) {missing}")
86
+ tensors = {}
87
+ for p in phases:
88
+ v = np.asarray(values[int(p)], dtype=float)
89
+ if v.shape == (3,):
90
+ v = np.diag(v)
91
+ if v.shape not in ((), (3, 3)) or not np.all(np.isfinite(v)):
92
+ raise ValueError(f"electromagnetic waves: a {name} or a 3 x 3 tensor (phase {int(p)})")
93
+ low = float(v) if v.ndim == 0 else float(np.linalg.eigvalsh(0.5 * (v + v.T)).min())
94
+ if not low > 0.0:
95
+ raise ValueError(
96
+ f"electromagnetic waves: a positive {name} (phase {int(p)}; 1 for the vacuum: "
97
+ "perfect conductors and absorbing phases are not covered)"
98
+ )
99
+ tensors[int(p)] = v
100
+ if all(v.ndim == 0 for v in tensors.values()):
101
+ lookup = np.zeros(int(phases.max()) + 1)
102
+ for p, v in tensors.items():
103
+ lookup[p] = float(v)
104
+ return lookup[data]
105
+ lookup = np.zeros((int(phases.max()) + 1, 3, 3))
106
+ for p, v in tensors.items():
107
+ lookup[p] = v * np.eye(3) if v.ndim == 0 else 0.5 * (v + v.T)
108
+ return np.moveaxis(lookup[data], (-2, -1), (0, 1))
109
+
110
+
111
+ def _invert(field: np.ndarray) -> np.ndarray:
112
+ if field.ndim == 3:
113
+ return 1.0 / field
114
+ return np.moveaxis(np.linalg.inv(np.moveaxis(field, (0, 1), (-2, -1))), (-2, -1), (0, 1))
115
+
116
+
117
+ def _blocks(field: np.ndarray, factors) -> np.ndarray:
118
+ """The mean of a field of the voxels over the cells of ``factors`` voxels per axis."""
119
+ n = field.shape
120
+ shape = (n[0] // factors[0], factors[0], n[1] // factors[1], factors[1], n[2] // factors[2])
121
+ return field.reshape(*shape, factors[2]).mean(axis=(1, 3, 5))
122
+
123
+
124
+ def smoothed_inverse(field: np.ndarray, coarsen: int = 1) -> np.ndarray:
125
+ """The inverse of an isotropic coefficient of the voxels (``field``: the permittivity)
126
+ on a grid ``coarsen`` times coarser along each axis (the axes of one voxel are kept):
127
+ ``1 / field`` on the voxels themselves, else the tensor ``<1/ε> n ⊗ n + (1 - n ⊗ n) /
128
+ <ε>`` of each cell (``(3, 3) + shape``; see the module). The normal ``n`` is the sum
129
+ of the gradients of the field over the voxels of the cell (central differences: the
130
+ normal of a plane that cuts the cell, whatever its stairs), or, where they cancel (a
131
+ layer thinner than the cell, with its two faces), their principal direction; the
132
+ cells that hold one value keep it."""
133
+ field = np.asarray(field, dtype=float)
134
+ s = int(coarsen)
135
+ if s < 1:
136
+ raise ValueError("coarsen: a positive integer")
137
+ if s == 1:
138
+ return 1.0 / field
139
+ factors = tuple(1 if n == 1 else s for n in field.shape)
140
+ if any(n % f for n, f in zip(field.shape, factors, strict=True)):
141
+ raise ValueError(f"coarsen: {s} does not divide the voxels {field.shape} of the cell")
142
+ mean = _blocks(field, factors)
143
+ harmonic = _blocks(1.0 / field, factors)
144
+ gradient = [
145
+ np.zeros_like(field)
146
+ if field.shape[a] == 1
147
+ else 0.5 * (np.roll(field, -1, axis=a) - np.roll(field, 1, axis=a))
148
+ for a in range(3)
149
+ ]
150
+ total = np.stack([_blocks(g, factors) for g in gradient])
151
+ length = np.sqrt((total**2).sum(axis=0))
152
+ spread = _blocks(np.sqrt(sum(g * g for g in gradient)), factors) # the mean norm
153
+ structure = np.zeros((3, 3, *mean.shape))
154
+ for i in range(3):
155
+ for j in range(i, 3):
156
+ structure[i, j] = structure[j, i] = _blocks(gradient[i] * gradient[j], factors)
157
+ _, vectors = np.linalg.eigh(np.moveaxis(structure, (0, 1), (-2, -1)))
158
+ normal = np.moveaxis(vectors[..., -1], -1, 0) # that of the largest eigenvalue
159
+ single = length > 0.3 * spread # one interface: its gradients add up
160
+ normal = np.where(single, total / np.where(length > 0.0, length, 1.0), normal)
161
+ projector = normal[:, None] * normal[None, :]
162
+ inverse = (harmonic - 1.0 / mean) * projector
163
+ for i in range(3):
164
+ inverse[i, i] += 1.0 / mean
165
+ return inverse
166
+
167
+
168
+ def _multiply(tensor: np.ndarray, field: np.ndarray) -> np.ndarray:
169
+ """A coefficient of the grid (isotropic, or ``(3, 3) + shape``) times fields ``(p, 3)
170
+ + shape``."""
171
+ if tensor.ndim == 3:
172
+ return tensor * field
173
+ return np.einsum("ijxyz,pjxyz->pixyz", tensor, field)
174
+
175
+
176
+ class PlaneWaves:
177
+ """The plane waves of a periodic cell of edges ``size`` on the grid of the inverse
178
+ coefficients ``inverse_permittivity`` and ``inverse_permeability`` (arrays of the
179
+ shape of the grid, or ``(3, 3) + shape``; the permeability a number when uniform),
180
+ and the Maxwell operators at a wave vector (:meth:`at`)."""
181
+
182
+ def __init__(self, inverse_permittivity, size, inverse_permeability=1.0) -> None:
183
+ self.inverse_permittivity = np.asarray(inverse_permittivity, dtype=float)
184
+ self.permittivity = _invert(self.inverse_permittivity)
185
+ self.shape = self.inverse_permittivity.shape[-3:]
186
+ self.size = np.asarray(size, dtype=float)
187
+ mu = np.asarray(inverse_permeability, dtype=float)
188
+ self.uniform = mu.ndim == 0
189
+ self.inverse_permeability = float(mu) if self.uniform else mu
190
+ self.permeability = 1.0 / float(mu) if self.uniform else _invert(mu)
191
+ self.g = np.stack(
192
+ np.meshgrid(
193
+ *[
194
+ 2.0 * np.pi * sfft.fftfreq(n, d=length / n)
195
+ for n, length in zip(self.shape, self.size, strict=True)
196
+ ],
197
+ indexing="ij",
198
+ )
199
+ )
200
+ #: the unit of the eigenvalues: the square of the first reciprocal vector
201
+ self.scale = float((self.size.max() / (2.0 * np.pi)) ** 2)
202
+ self.count = int(np.prod(self.shape))
203
+
204
+ @property
205
+ def unknowns(self) -> int:
206
+ return 2 * self.count
207
+
208
+ def at(self, wavevector) -> PlaneWaves:
209
+ """Set the wave vector: the vectors ``q = k + G``, their norms and their
210
+ transverse unit vectors ``e1`` and ``e2``."""
211
+ k = np.asarray(wavevector, dtype=float).reshape(3, 1, 1, 1)
212
+ self.q = self.g + k
213
+ norm = np.sqrt((self.q**2).sum(axis=0))
214
+ zero = norm == 0.0
215
+ u = self.q / np.where(zero, 1.0, norm)
216
+ e1 = np.stack([-u[1], u[0], np.zeros_like(norm)]) # z × u
217
+ length = np.sqrt((e1**2).sum(axis=0))
218
+ along = length < 1e-6 # u along z (or zero): x, less its part along u
219
+ if np.any(along):
220
+ e1[:, along] = np.array([1.0, 0.0, 0.0])[:, None] - u[0][along] * u[:, along]
221
+ length[along] = np.sqrt((e1[:, along] ** 2).sum(axis=0))
222
+ e1 /= length
223
+ e2 = np.cross(u, e1, axis=0)
224
+ e2[:, zero] = np.array([0.0, 1.0, 0.0])[:, None]
225
+ self.norm, self.e1, self.e2 = norm, e1, e2
226
+ self.inverse_norm = np.where(zero, 0.0, 1.0 / np.where(zero, 1.0, norm))
227
+ return self
228
+
229
+ # -- the maps between amplitudes, plane waves and the grid ----------------------------
230
+
231
+ def _fields(self, c: np.ndarray) -> np.ndarray:
232
+ return c[:, 0, None] * self.e1 + c[:, 1, None] * self.e2
233
+
234
+ def _project(self, f: np.ndarray) -> np.ndarray:
235
+ return np.stack([(f * self.e1).sum(axis=1), (f * self.e2).sum(axis=1)], axis=1)
236
+
237
+ def _on_grid(self, tensor, f: np.ndarray) -> np.ndarray:
238
+ if np.ndim(tensor) == 0:
239
+ return tensor * f
240
+ workers = settings.workers()
241
+ f = sfft.ifftn(f, axes=_AXES, workers=workers)
242
+ return sfft.fftn(_multiply(tensor, f), axes=_AXES, workers=workers)
243
+
244
+ def _curl(self, f: np.ndarray) -> np.ndarray:
245
+ q = self.q
246
+ return 1j * np.stack(
247
+ [
248
+ q[1] * f[:, 2] - q[2] * f[:, 1],
249
+ q[2] * f[:, 0] - q[0] * f[:, 2],
250
+ q[0] * f[:, 1] - q[1] * f[:, 0],
251
+ ],
252
+ axis=1,
253
+ )
254
+
255
+ def _stiffness(self, c: np.ndarray) -> np.ndarray:
256
+ if self.uniform: # the curl of a transverse wave: i |q| (c1 e2 - c2 e1)
257
+ d = self.norm * (c[:, 0, None] * self.e2 - c[:, 1, None] * self.e1)
258
+ e = self._on_grid(self.inverse_permittivity, d)
259
+ out = np.stack([(e * self.e2).sum(axis=1), -(e * self.e1).sum(axis=1)], axis=1)
260
+ return (self.scale * self.inverse_permeability) * self.norm * out
261
+ h = self._on_grid(self.inverse_permeability, self._fields(c))
262
+ e = self._on_grid(self.inverse_permittivity, self._curl(h))
263
+ return self.scale * self._project(self._on_grid(self.inverse_permeability, self._curl(e)))
264
+
265
+ def _mass(self, c: np.ndarray) -> np.ndarray:
266
+ return self._project(self._on_grid(self.inverse_permeability, self._fields(c)))
267
+
268
+ def _precondition(self, c: np.ndarray) -> np.ndarray:
269
+ inverse = self.inverse_norm
270
+ if self.uniform: # the inverse curls of the transverse waves, as the curls above
271
+ f = inverse * (c[:, 0, None] * self.e2 - c[:, 1, None] * self.e1)
272
+ f = self._on_grid(self.permittivity, f)
273
+ out = np.stack([(f * self.e2).sum(axis=1), -(f * self.e1).sum(axis=1)], axis=1)
274
+ return (self.permeability / self.scale) * inverse * out
275
+ f = self._curl(self._on_grid(self.permeability, self._fields(c))) * inverse**2
276
+ f = self._curl(self._on_grid(self.permittivity, f)) * inverse**2
277
+ return self._project(self._on_grid(self.permeability, f)) / self.scale
278
+
279
+ def _blockwise(self, function, x: np.ndarray) -> np.ndarray:
280
+ """``function`` of the columns of ``x`` (unknowns x p), a few at a time."""
281
+ x = np.asarray(x, dtype=complex)
282
+ single = x.ndim == 1
283
+ columns = x.reshape(self.unknowns, -1).T.reshape(-1, 2, *self.shape)
284
+ step = max(1, BLOCK_VALUES // (3 * self.count))
285
+ out = np.concatenate(
286
+ [function(columns[i : i + step]) for i in range(0, len(columns), step)]
287
+ )
288
+ out = out.reshape(len(columns), self.unknowns).T
289
+ return out[:, 0] if single else out
290
+
291
+ def stiffness(self, x: np.ndarray) -> np.ndarray:
292
+ """``Pᴴ μ⁻¹ C ε⁻¹ C μ⁻¹ P`` times the amplitudes ``x`` (unknowns, or unknowns x p),
293
+ in units of the square of the first reciprocal vector."""
294
+ return self._blockwise(self._stiffness, x)
295
+
296
+ def mass(self, x: np.ndarray) -> np.ndarray:
297
+ """``Pᴴ μ⁻¹ P`` times the amplitudes (the identity for a uniform permeability,
298
+ which the stiffness then carries)."""
299
+ return np.asarray(x, dtype=complex) if self.uniform else self._blockwise(self._mass, x)
300
+
301
+ def precondition(self, x: np.ndarray) -> np.ndarray:
302
+ """The operator of the inverse medium, ``Pᴴ μ C⁻¹ ε C⁻¹ μ P``, times the amplitudes:
303
+ the inverse of the stiffness but for the projections on the transverse waves."""
304
+ return self._blockwise(self._precondition, x)
305
+
306
+ # -- the frequencies -------------------------------------------------------------------
307
+
308
+ def _orthonormal(self, x: np.ndarray, mx: np.ndarray):
309
+ """The columns of ``x`` made orthonormal in the product of the mass (``mx``: the
310
+ mass times them), those that depend on the others left out."""
311
+ gram = x.conj().T @ mx
312
+ values, vectors = eigh(0.5 * (gram + gram.conj().T))
313
+ keep = values > 1e-12 * values[-1]
314
+ t = vectors[:, keep] / np.sqrt(values[keep])
315
+ return x @ t, mx @ t
316
+
317
+ def _davidson(self, x: np.ndarray, bands: int, tol: float, maxiter: int):
318
+ """The lowest waves of the pencil of the stiffness and the mass from the block
319
+ ``x``: the Rayleigh-Ritz values of a subspace that grows by the preconditioned
320
+ residuals of the waves not yet within ``tol`` (those asked for: the first
321
+ ``bands``), restarted from the waves and from those of the step before."""
322
+ block = x.shape[1]
323
+ v, mv = self._orthonormal(x, self.mass(x))
324
+ kv = self.stiffness(v)
325
+ before = None # the waves of the step before, in the basis
326
+ for iteration in range(1, maxiter + 1):
327
+ h = v.conj().T @ kv
328
+ values, c = eigh(0.5 * (h + h.conj().T))
329
+ values, c = values[:block], c[:, :block]
330
+ x, kx, mx = v @ c, kv @ c, mv @ c
331
+ norms = np.sqrt((np.abs(kx - mx * values) ** 2).sum(axis=0))
332
+ worst = float(norms[:bands].max())
333
+ active = norms > tol
334
+ if worst <= tol or iteration == maxiter or not np.any(active):
335
+ break
336
+ w = self.precondition((kx - mx * values)[:, active])
337
+ if v.shape[1] + w.shape[1] > SUBSPACE * block: # restart
338
+ both = c if before is None else np.hstack([c, before])
339
+ t, _ = np.linalg.qr(both)
340
+ v, kv, mv = v @ t, kv @ t, mv @ t
341
+ c = t.conj().T @ c
342
+ before = np.vstack([c, np.zeros((w.shape[1], c.shape[1]), dtype=c.dtype)])
343
+ for _ in range(2): # against the subspace, twice (Gram-Schmidt)
344
+ w -= v @ (mv.conj().T @ w)
345
+ w, mw = self._orthonormal(w, self.mass(w))
346
+ if w.shape[1] == 0:
347
+ break
348
+ if w.shape[1] < before.shape[0] - c.shape[0]:
349
+ before = before[: c.shape[0] + w.shape[1]]
350
+ v, mv = np.hstack([v, w]), np.hstack([mv, mw])
351
+ kv = np.hstack([kv, self.stiffness(w)])
352
+ return values, x, worst, iteration
353
+
354
+ def frequencies(self, wavevector, bands: int, *, guess=None, tol: float = 1e-4,
355
+ maxiter: int = 300): # fmt: skip
356
+ """The lowest ``bands`` angular frequencies at a wave vector and their amplitudes
357
+ (unknowns x block; a ``guess`` for them: those of a neighbouring wave vector)."""
358
+ self.at(wavevector)
359
+ n = self.unknowns
360
+ if not 0 < bands <= n:
361
+ raise ValueError(f"bands: between 1 and {n} (two per plane wave), got {bands}")
362
+ if n <= DENSE_LIMIT or bands > n // 8:
363
+ identity = np.eye(n, dtype=complex)
364
+ k = self.stiffness(identity)
365
+ m = None if self.uniform else self.mass(identity)
366
+ values, vectors = eigh(
367
+ 0.5 * (k + k.conj().T), None if m is None else 0.5 * (m + m.conj().T)
368
+ )
369
+ return self._frequency(values[:bands]), vectors[:, :bands]
370
+ block = bands + max(3, bands // 4)
371
+ rng = np.random.default_rng(0)
372
+ x = rng.standard_normal((n, block)) + 1j * rng.standard_normal((n, block))
373
+ long_waves = 1.0 / (self.norm**2 * self.scale + 1.0)
374
+ x *= np.concatenate([long_waves.ravel(), long_waves.ravel()])[:, None]
375
+ if guess is not None and guess.shape == (n, block):
376
+ # the waves of the neighbouring wave vector, with a part of all the others: a
377
+ # block that misses one of the lowest waves altogether would never find it
378
+ x = guess + 0.1 * x * (np.linalg.norm(guess, axis=0) / np.linalg.norm(x, axis=0))
379
+ values, x, worst, iterations = self._davidson(x, bands, tol, maxiter)
380
+ if worst > tol:
381
+ log.warning(
382
+ "electromagnetic waves: the bands are within %.1e after %d iterations (asked: "
383
+ "%.1e)", worst, iterations, tol,
384
+ ) # fmt: skip
385
+ return self._frequency(values[:bands]), x
386
+
387
+ def _frequency(self, values: np.ndarray) -> np.ndarray:
388
+ return np.sqrt(np.clip(values.real, 0.0, None) / self.scale)
389
+
390
+
391
+ def _crystal(sample, permittivity: dict, permeability, coarsen: int) -> PlaneWaves:
392
+ if not isinstance(sample, VoxelImage):
393
+ raise TypeError(
394
+ "electromagnetic waves: a voxel image (the plane waves are those of its grid; "
395
+ "voxelize a morphology, rather than mesh it)"
396
+ )
397
+ if not sample.periodic:
398
+ log.info("electromagnetic waves: the image is taken as the cell of a periodic medium")
399
+ data = np.asarray(sample.data)
400
+ if data.dtype.kind not in "iu":
401
+ raise ValueError("electromagnetic waves: an image of phases (integers)")
402
+ eps = _tensor_field(permittivity, data, "permittivity")
403
+ if eps.ndim == 3:
404
+ inverse = smoothed_inverse(eps, coarsen)
405
+ elif int(coarsen) != 1:
406
+ raise ValueError(
407
+ "coarsen: the average of the cells that the interfaces cut is that of isotropic "
408
+ "phases; with a tensor of permittivity the plane waves are those of the voxels"
409
+ )
410
+ else:
411
+ inverse = _invert(eps)
412
+ if isinstance(permeability, dict):
413
+ present = [permeability.get(int(p)) for p in np.unique(data)]
414
+ if all(v is not None and np.ndim(v) == 0 for v in present) and len(set(present)) == 1:
415
+ permeability = float(present[0]) # the same in every phase
416
+ if isinstance(permeability, dict):
417
+ mu = _tensor_field(permeability, data, "permeability")
418
+ if mu.ndim == 3:
419
+ inverse_mu = smoothed_inverse(mu, coarsen)
420
+ elif int(coarsen) != 1:
421
+ raise ValueError("coarsen: isotropic phases (see the permittivity)")
422
+ else:
423
+ inverse_mu = _invert(mu)
424
+ else:
425
+ if not float(permeability) > 0.0:
426
+ raise ValueError("electromagnetic waves: a positive permeability")
427
+ inverse_mu = 1.0 / float(permeability)
428
+ return PlaneWaves(inverse, sample.size, inverse_mu)
429
+
430
+
431
+ def electromagnetic_band_structure(
432
+ sample,
433
+ permittivity: dict,
434
+ path=("G", "X", "M", "G", "R"),
435
+ *,
436
+ permeability=1.0,
437
+ bands: int = 8,
438
+ points: int = 12,
439
+ coarsen: int = 1,
440
+ tol: float = 1e-4,
441
+ ):
442
+ """The lowest ``bands`` frequencies of the electromagnetic Bloch waves of a periodic
443
+ cell (a :class:`~morphogen.image.VoxelImage` of phases) along ``path`` (corners of
444
+ the Brillouin zone, ``points`` per segment; or an array of wave vectors), by plane
445
+ waves (see the module): ``permittivity``, that of each phase (a number, three
446
+ principal values or a 3 x 3 tensor in the axes of the cell), and ``permeability`` (a
447
+ number for the whole cell, or those of the phases likewise). ``coarsen``: the plane
448
+ waves on a grid that many times coarser than the voxels, whose cells cut by the
449
+ interfaces take the averaged tensor of Meade et al. (isotropic phases). ``tol``: the
450
+ residual of the bands, in units of the square of the first reciprocal vector (the
451
+ squares of the frequencies are then within about its square). Returns a
452
+ :class:`~morphogen.homogenization.bloch.BandStructure`; at the centre of the zone the
453
+ first two frequencies are zero (the uniform fields)."""
454
+ from morphogen.homogenization.bloch import BandStructure, brillouin_path
455
+
456
+ crystal = _crystal(sample, permittivity, permeability, coarsen)
457
+ if isinstance(path, np.ndarray) and path.ndim == 2:
458
+ ks = np.asarray(path, dtype=float)
459
+ dist = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(ks, axis=0), axis=1))])
460
+ labels = []
461
+ else:
462
+ ks, dist, labels = brillouin_path(crystal.size, path, points)
463
+ freqs = np.zeros((len(ks), int(bands)))
464
+ guess = None
465
+ for i, k in enumerate(ks):
466
+ freqs[i], guess = crystal.frequencies(k, int(bands), guess=guess, tol=tol)
467
+ return BandStructure(ks, dist, freqs, labels)
@@ -0,0 +1,212 @@
1
+ """Weak couplings of elasticity with a scalar field that loads the phases: the pressure of
2
+ the fluid of the pores (the poroelasticity of Biot) and the content of a species that the
3
+ phases absorb (hygroscopic and chemical swelling).
4
+
5
+ Both are eigenstrain problems of the elastic solvers (FFT on voxel images, finite elements
6
+ on conforming meshes, extended finite elements on level sets), as the thermal expansion is.
7
+
8
+ **Swelling.** A phase that absorbs a species (moisture in a polymer or in wood, a solvent
9
+ in a gel, lithium in an electrode) strains by ``beta c`` for a content ``c``:
10
+ ``sigma = C : (eps - beta c)``. With the ``swelling`` of the materials, the strain of
11
+ each phase for a unit of the quantity that drives the sorption (a content, a relative
12
+ humidity, an activity: the coefficient of a phase is then its strain at equilibrium with a
13
+ unit of that quantity, the product of its coefficient of expansion and of its
14
+ solubility), :func:`swelling_tensor` gives the macroscopic strain of the stress-free
15
+ volume element, ``E = S : Sigma + B c``; Levin's relation holds, ``B = <beta : C : A> :
16
+ C*^-1``.
17
+
18
+ **Poroelasticity.** In a porous solid whose pores hold a fluid at the pressure ``p``,
19
+
20
+ ``Sigma = C_d : E - b p``, ``phi - phi_0 = b : E + p / N``
21
+
22
+ with the drained stiffness ``C_d`` (that of the solid with empty pores), the tensor of
23
+ Biot ``b`` and the modulus of Biot ``N`` of the solid (Biot 1941; Coussy 2004). The
24
+ pressure on the walls of the pores is, in the solid, the uniform stress ``-p 1`` and the
25
+ eigenstrain ``-p S_s : 1`` of each solid phase: one more solution of the elastic
26
+ problem, at zero macroscopic strain, gives ``b = 1 - Sigma'`` (``Sigma'``: the mean stress
27
+ of that problem for a unit pressure) and ``1 / N = -(1 - phi_0) <tr eps>_s``, the volume
28
+ the pores gain. A homogeneous solid recovers ``b = 1 - C_d : S_s : 1`` and ``1 / N = (b -
29
+ phi_0 1) : S_s : 1`` (``b = 1 - K_d / K_s``, ``1 / N = (b - phi_0) / K_s`` when isotropic);
30
+ the solid may as well be heterogeneous (several phases, crystals), where these formulae do
31
+ not hold. A fluid of bulk modulus ``K_f`` that cannot drain stiffens the medium (Gassmann
32
+ 1951): ``1 / M = 1 / N + phi_0 / K_f``, ``C_u = C_d + M b (x) b``, and a stress raises its
33
+ pressure by ``p = -B : Sigma / 3`` with the tensor of Skempton ``B = 3 M S_u : b``.
34
+
35
+ References: M. A. Biot, J. Appl. Phys. 12 (1941) 155; F. Gassmann, Vierteljahrsschr.
36
+ Naturforsch. Ges. Zürich 96 (1951) 1; O. Coussy, Poromechanics, Wiley (2004); L. Dormieux,
37
+ D. Kondo, F.-J. Ulm, Microporomechanics, Wiley (2006); V. M. Levin, Mekh. Tverd. Tela 2
38
+ (1967) 88.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import dataclasses
44
+
45
+ import numpy as np
46
+
47
+ from morphogen.homogenization.core import VOIGT_NAMES, Loading
48
+ from morphogen.homogenization.elements import VOIGT, voigt_to_tensor
49
+ from morphogen.homogenization.materials import Material
50
+
51
+ __all__ = [
52
+ "POROELASTIC_ENTRIES",
53
+ "UNDRAINED_ENTRIES",
54
+ "poroelastic_tensors",
55
+ "pressure_materials",
56
+ "swelling_materials",
57
+ "swelling_tensor",
58
+ "undrained",
59
+ ]
60
+
61
+ #: The scalar results of :func:`poroelastic_tensors` (columns of the tables of results and
62
+ #: quantities of the statistics of RVE studies)
63
+ POROELASTIC_ENTRIES = (
64
+ "porosity",
65
+ "biot_coefficient",
66
+ "biot_modulus",
67
+ "bulk_modulus",
68
+ *(f"b{name}" for name in VOIGT_NAMES),
69
+ )
70
+ #: Those of a fluid that cannot drain (with its bulk modulus)
71
+ UNDRAINED_ENTRIES = (
72
+ "storage_modulus",
73
+ "undrained_bulk_modulus",
74
+ "skempton_coefficient",
75
+ *(f"B{name}" for name in VOIGT_NAMES),
76
+ )
77
+
78
+
79
+ def _hydrostatic_strain(material: Material):
80
+ """The strain of a material under a unit hydrostatic tension, ``S : 1``: one
81
+ coefficient (isotropic) or a 3 x 3 tensor in the axes of the crystal."""
82
+ if material.stiffness is None:
83
+ return (1.0 - 2.0 * material.poisson) / material.young # 1 / (3 K)
84
+ compliance = np.linalg.inv(np.array(material.stiffness))
85
+ return voigt_to_tensor(compliance[:, :3].sum(axis=1), strain=True)
86
+
87
+
88
+ def pressure_materials(materials: dict[int, Material]) -> dict[int, Material]:
89
+ """The materials of the problem of a unit pressure in the pores: each solid phase
90
+ with the eigenstrain ``-S : 1`` (as a thermal expansion: the temperature of the
91
+ elastic problems is then the pressure), the voids as they are."""
92
+ out = {}
93
+ for phase, m in materials.items():
94
+ if m.void:
95
+ out[phase] = m
96
+ continue
97
+ if m.young is None and m.stiffness is None:
98
+ raise ValueError(f"poroelasticity: the material of phase {phase} is not elastic")
99
+ out[phase] = dataclasses.replace(m, expansion=-_hydrostatic_strain(m))
100
+ return out
101
+
102
+
103
+ def swelling_materials(materials: dict[int, Material]) -> dict[int, Material]:
104
+ """The materials of the problem of a unit content of the absorbed species: each phase
105
+ with its ``swelling`` as a thermal expansion (none: a phase that does not swell)."""
106
+ if not any(m.swelling is not None for m in materials.values()):
107
+ raise ValueError("swelling: no material swells (Material(swelling=...))")
108
+ return {
109
+ phase: m if m.void else dataclasses.replace(m, expansion=m.swelling)
110
+ for phase, m in materials.items()
111
+ }
112
+
113
+
114
+ def _problem(sample, materials, bc, options):
115
+ from morphogen.homogenization.apparent import make_problem
116
+
117
+ return make_problem(sample, materials, "elastic", bc, **options)
118
+
119
+
120
+ def swelling_tensor(sample, materials: dict[int, Material], bc: str = "periodic", **options):
121
+ """Apparent swelling tensor (3 x 3) of a sample and the solution that gives it: the
122
+ macroscopic strain of a unit content of the absorbed species under zero macroscopic
123
+ stress, with the ``swelling`` of the materials (``E = S : Sigma + B c``). ``options``:
124
+ those of :func:`~morphogen.homogenization.apparent.make_problem` (``solver``, ``tol``,
125
+ ``maxiter``, ``grains``, ``orientations``, ``device``)."""
126
+ from morphogen.homogenization.apparent import thermal_expansion
127
+
128
+ return thermal_expansion(_problem(sample, swelling_materials(materials), bc, options))
129
+
130
+
131
+ def undrained(stiffness, biot, biot_modulus: float, porosity: float, fluid_bulk: float) -> dict:
132
+ """The response of a saturated porous medium whose fluid, of bulk modulus
133
+ ``fluid_bulk``, cannot drain (Gassmann): ``storage_modulus`` ``M`` (``1 / M = 1 / N +
134
+ phi_0 / K_f``), ``undrained_stiffness`` ``C_u = C_d + M b (x) b`` (Voigt),
135
+ ``undrained_bulk_modulus`` (``1 / (1 : S_u : 1)``), ``skempton`` (the 3 x 3 tensor ``B
136
+ = 3 M S_u : b``: a macroscopic stress raises the pressure by ``-B : Sigma / 3``) and
137
+ ``skempton_coefficient`` (its mean), from the drained ``stiffness`` (6 x 6), the tensor
138
+ (3 x 3) and the modulus of Biot and the porosity."""
139
+ if not fluid_bulk > 0.0:
140
+ raise ValueError("fluid_bulk: a positive bulk modulus")
141
+ c = np.asarray(stiffness, dtype=float)
142
+ b = np.asarray(biot, dtype=float)
143
+ vec = np.array([b[i, j] for i, j in VOIGT]) # as a stress: no factor on the shears
144
+ inverse = (1.0 / biot_modulus if np.isfinite(biot_modulus) else 0.0) + porosity / fluid_bulk
145
+ storage = 1.0 / inverse if inverse > 0.0 else float("inf")
146
+ if not np.isfinite(storage): # no pore, a rigid solid: nothing to store
147
+ cu = c.copy()
148
+ skempton = np.zeros((3, 3))
149
+ else:
150
+ cu = c + storage * np.outer(vec, vec)
151
+ skempton = 3.0 * storage * voigt_to_tensor(np.linalg.solve(cu, vec), strain=True)
152
+ out = {
153
+ "storage_modulus": float(storage),
154
+ "undrained_stiffness": cu,
155
+ "undrained_bulk_modulus": float(1.0 / np.linalg.inv(cu)[:3, :3].sum()),
156
+ "skempton": skempton,
157
+ "skempton_coefficient": float(np.trace(skempton) / 3.0),
158
+ }
159
+ out.update(
160
+ {f"B{n}": float(skempton[i, j]) for (i, j), n in zip(VOIGT, VOIGT_NAMES, strict=True)}
161
+ )
162
+ return out
163
+
164
+
165
+ def poroelastic_tensors(sample, materials: dict[int, Material], bc: str = "periodic", *,
166
+ fluid_bulk: float | None = None, **options) -> dict: # fmt: skip
167
+ """The poroelastic law of a porous sample (voxel image, conforming mesh or level set;
168
+ its pores: the void phases), under periodic or kinematic uniform (``kubc``) conditions.
169
+
170
+ Returns the drained stiffness (``"tensor"``, Voigt 6 x 6, with its ``"compliance"``),
171
+ the tensor of Biot (``"biot"``, 3 x 3; its entries ``b11`` ... ``b12`` and its mean
172
+ ``"biot_coefficient"``), the modulus of Biot of the solid (``"biot_modulus"``; infinite
173
+ for a rigid solid), the ``"porosity"`` and the drained ``"bulk_modulus"`` (``1 / (1 :
174
+ S_d : 1)``); with the bulk modulus of the fluid ``fluid_bulk``, also the undrained
175
+ response of :func:`undrained`. The solid may hold several phases and crystals
176
+ (``grains``, ``orientations``). ``options``: those of :func:`~morphogen.homogenization.
177
+ apparent.make_problem` (``solver``, ``tol``, ``maxiter``, ``grains``, ``orientations``,
178
+ ``device``)."""
179
+ from morphogen.homogenization.apparent import stiffness_tensor
180
+
181
+ if bc not in ("periodic", "kubc"):
182
+ raise ValueError(
183
+ "poroelasticity: periodic or kinematic uniform (kubc) conditions (the macroscopic "
184
+ f"strain is prescribed), not {bc!r}"
185
+ )
186
+ if not any(m.void for m in materials.values()):
187
+ raise ValueError("poroelasticity: no pore (a void phase) in the materials")
188
+ problem = _problem(sample, pressure_materials(materials), bc, options)
189
+ drained, _ = stiffness_tensor(problem)
190
+ # a unit pressure at zero macroscopic strain: the stress -p 1 everywhere, and that of
191
+ # the eigenstrains -p S_s : 1 of the solid phases
192
+ sol = problem.solve(Loading.strain(np.zeros(6), temperature=1.0))
193
+ biot = np.eye(3) - 0.5 * (sol.stress + sol.stress.T)
194
+ porosity = 1.0 - float(sol.material_fraction)
195
+ if not porosity > 0.0:
196
+ raise ValueError("poroelasticity: the sample has no pore")
197
+ # the volume gained by the pores is that lost by the solid (no macroscopic strain)
198
+ gained = -sum(p.fraction * float(np.sum(p.mean["strain"][:3])) for p in sol.phases)
199
+ compliance = np.linalg.inv(drained)
200
+ out = {
201
+ "tensor": drained,
202
+ "compliance": compliance,
203
+ "biot": biot,
204
+ "porosity": porosity,
205
+ "biot_coefficient": float(np.trace(biot) / 3.0),
206
+ "biot_modulus": float(1.0 / gained) if gained > 0.0 else float("inf"),
207
+ "bulk_modulus": float(1.0 / compliance[:3, :3].sum()),
208
+ }
209
+ out.update({f"b{n}": float(biot[i, j]) for (i, j), n in zip(VOIGT, VOIGT_NAMES, strict=True)})
210
+ if fluid_bulk is not None:
211
+ out.update(undrained(drained, biot, out["biot_modulus"], porosity, float(fluid_bulk)))
212
+ return out