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,447 @@
1
+ """Thermal oxidation of polymers: the closed-loop mechanistic scheme, homogeneous (thin
2
+ films) or limited by the diffusion of oxygen (thick samples).
3
+
4
+ The scheme of Colin, Verdu and co-workers, with the rate constants that Ernault et al.
5
+ (2019) identified on a DGEBA/IPDA epoxy at 110 °C in air (their Tables 1 and 2):
6
+
7
+ POOH -> 2 P + P=O + V k1 (hydroperoxide decomposition)
8
+ P + O2 -> POO k2
9
+ POO + PH -> POOH + P k3 (propagation, consumes the sites PH)
10
+ P + P -> inactive products k4
11
+ POO + P -> inactive products k5
12
+ POO + POO -> inactive + g6 P=O + O2 k6
13
+
14
+ ``P=O`` (amides here, followed by FTIR) traces the oxidation. In thick samples oxygen
15
+ enters by Fick's law, ``d[O2]/dt = D d2[O2]/dz2 - k2 [P][O2] + k6 [POO]^2``, at the
16
+ concentration ``S p`` (Henry) on the exposed faces: the oxidized layer is a few hundred
17
+ micrometres thick. Concentrations in mol/l, times in seconds, lengths in metres.
18
+
19
+ **In a microstructure** (:func:`oxidation_field`): the same scheme in every voxel of an
20
+ image, each phase with its own constants (a polymer that oxidizes, an inert phase that
21
+ lets oxygen through, an impermeable one: fibres, fillers), oxygen diffusing between the
22
+ voxels from the exposed faces of the image. As in :mod:`morphogen.coupling.diffusion`,
23
+ the activity of oxygen ``u`` (its partial pressure at equilibrium, ``[O2] = S u``) is
24
+ continuous across the interfaces and the flux between two voxels goes through the
25
+ harmonic mean of their permeabilities ``D S``:
26
+
27
+ d[X]/dt = r_X([P], [POO], ..., [O2]) (the five species that do not move)
28
+ S du/dt = div(D S grad u) + r_O2, u = p on the exposed faces.
29
+
30
+ The radicals live for milliseconds and the oxidation for thousands of hours: the system
31
+ is integrated by the implicit one-step method TR-BDF2 (a trapezoidal stage and a
32
+ backward difference, second order, L-stable; Bank et al. 1985) with its embedded error
33
+ estimate for the steps (Hosea & Shampine 1996). Each Newton iteration eliminates the
34
+ five local species voxel by voxel (their 5 x 5 blocks), which leaves one symmetric
35
+ system for the oxygen of all the voxels, ``(diag(V S s) + a K) du = b`` with ``K`` the
36
+ conductances of the faces and ``s`` the local Schur complements, solved by conjugate
37
+ gradients (a sparse factorization for small images): the cost of a step grows as the
38
+ number of voxels, in one, two or three dimensions.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import logging
44
+ from dataclasses import dataclass
45
+
46
+ import numpy as np
47
+ from scipy import sparse
48
+ from scipy.integrate import solve_ivp
49
+ from scipy.sparse import linalg as splinalg
50
+
51
+ log = logging.getLogger(__name__)
52
+
53
+ SPECIES = ("P", "POO", "POOH", "PH", "PO", "O2")
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class ClosedLoopOxidation:
58
+ """Rate constants (s^-1, l mol^-1 s^-1), initial concentrations (mol/l) and oxygen
59
+ transport (solubility mol l^-1 Pa^-1, diffusivity m^2/s, partial pressure Pa) of the
60
+ closed-loop scheme; the defaults are those of Ernault et al. (2019) for DGEBA/IPDA at
61
+ 110 °C in air."""
62
+
63
+ k1: float = 1e-5
64
+ k2: float = 1e6
65
+ k3: float = 2.25
66
+ k4: float = 2.5e10
67
+ k5: float = 2.25e10
68
+ k6: float = 2e3
69
+ gamma6: float = 0.5
70
+ ph0: float = 5.8
71
+ pooh0: float = 1e-3
72
+ solubility: float = 2.3e-7
73
+ diffusivity: float = 7.3e-13
74
+ pressure: float = 0.21 * 101325.0
75
+
76
+ @property
77
+ def surface_oxygen(self) -> float:
78
+ """``[O2] = S p`` at equilibrium with the atmosphere (Henry's law)."""
79
+ return self.solubility * self.pressure
80
+
81
+ def rates(self, y: np.ndarray) -> np.ndarray:
82
+ """Reaction rates of the species ``SPECIES`` (rows of ``y``), oxygen included."""
83
+ p, poo, pooh, ph, _, o2 = y
84
+ r1 = self.k1 * pooh
85
+ r2 = self.k2 * p * o2
86
+ r3 = self.k3 * poo * ph
87
+ r4 = self.k4 * p * p
88
+ r5 = self.k5 * p * poo
89
+ r6 = self.k6 * poo * poo
90
+ return np.array(
91
+ [
92
+ 2.0 * r1 - r2 + r3 - 2.0 * r4 - r5,
93
+ r2 - r3 - r5 - 2.0 * r6,
94
+ -r1 + r3,
95
+ -r3,
96
+ r1 + self.gamma6 * r6,
97
+ -r2 + r6,
98
+ ]
99
+ )
100
+
101
+ def initial(self, n: int = 1, oxygen: float = 0.0) -> np.ndarray:
102
+ y = np.zeros((6, n))
103
+ y[2], y[3], y[5] = self.pooh0, self.ph0, oxygen
104
+ return y
105
+
106
+ def thin_film(self, times) -> dict[str, np.ndarray]:
107
+ """Homogeneous oxidation (oxygen at its surface concentration everywhere):
108
+ concentrations of the species at ``times`` (s)."""
109
+ times = np.asarray(times, dtype=float)
110
+ o2 = self.surface_oxygen
111
+
112
+ def f(_, y):
113
+ z = np.append(y, o2)
114
+ return self.rates(z)[:5]
115
+
116
+ sol = solve_ivp(
117
+ f,
118
+ (0.0, times[-1]),
119
+ self.initial(1)[:5, 0],
120
+ method="Radau",
121
+ t_eval=times,
122
+ rtol=1e-8,
123
+ atol=1e-14,
124
+ )
125
+ if not sol.success:
126
+ raise RuntimeError(f"thin_film: {sol.message}")
127
+ out = dict(zip(SPECIES[:5], sol.y, strict=True))
128
+ out["O2"] = np.full(len(times), o2)
129
+ return out
130
+
131
+ def profile(self, thickness: float, times, *, nodes: int = 61) -> dict[str, np.ndarray]:
132
+ """Diffusion-limited oxidation of a plate of ``thickness`` (m) exposed on both
133
+ faces: ``depth`` (m, from a face to the middle) and the concentrations of the
134
+ species (times x nodes) at ``times`` (s). Method of lines on a uniform grid of
135
+ half the plate (zero flux in the middle), stiff integration (Radau)."""
136
+ times = np.asarray(times, dtype=float)
137
+ h = 0.5 * thickness / (nodes - 1)
138
+ o2s = self.surface_oxygen
139
+ n = nodes - 1 # the nodes below the surface (the surface holds S p)
140
+ lap = sparse.diags([np.ones(n - 1), -2.0 * np.ones(n), np.ones(n - 1)], [-1, 0, 1]).tolil()
141
+ lap[n - 1, n - 2] = 2.0 # symmetry in the middle
142
+ lap = (lap / (h * h)).tocsr()
143
+ source = np.zeros(n)
144
+ source[0] = o2s / (h * h)
145
+ d = self.diffusivity
146
+
147
+ def f(_, y):
148
+ z = y.reshape(6, n)
149
+ dz = self.rates(z)
150
+ dz[5] += d * (lap @ z[5] + source)
151
+ return dz.ravel()
152
+
153
+ block = sparse.identity(n) + abs(lap) # coupling pattern: local species, O2 neighbours
154
+ pattern = sparse.bmat([[sparse.identity(n)] * 6] * 5 + [[sparse.identity(n)] * 5 + [block]])
155
+ sol = solve_ivp(
156
+ f,
157
+ (0.0, times[-1]),
158
+ self.initial(n, oxygen=o2s).ravel(), # stored in air
159
+ method="Radau",
160
+ t_eval=times,
161
+ rtol=1e-6,
162
+ atol=1e-12,
163
+ jac_sparsity=pattern,
164
+ )
165
+ if not sol.success:
166
+ raise RuntimeError(f"profile: {sol.message}")
167
+ y = sol.y.reshape(6, n, -1)
168
+ out = {"depth": np.arange(1, nodes) * h}
169
+ for k, name in enumerate(SPECIES):
170
+ out[name] = y[k].T
171
+ return out
172
+
173
+ def oxidized_layer(self, depth, amide, fraction: float = 0.1) -> float:
174
+ """Thickness of the oxidized layer: the depth where the amide concentration falls
175
+ to ``fraction`` of its value at the surface (linear interpolation)."""
176
+ a = np.asarray(amide, dtype=float)
177
+ target = fraction * a[0]
178
+ below = np.flatnonzero(a < target)
179
+ if below.size == 0:
180
+ return float(depth[-1])
181
+ i = below[0]
182
+ return float(np.interp(target, [a[i], a[i - 1]], [depth[i], depth[i - 1]]))
183
+
184
+
185
+ # -- oxidation in a microstructure ---------------------------------------------------------
186
+
187
+ #: Absolute tolerances of the species (mol/l) in the steps of :func:`oxidation_field`:
188
+ #: the radicals are scarce (1e-11 to 1e-7 mol/l), the others are not
189
+ TOLERANCES = (1e-15, 1e-12, 1e-9, 1e-7, 1e-9, 1e-9)
190
+
191
+ #: Voxels up to which the oxygen of a Newton iteration is solved by a sparse
192
+ #: factorization; preconditioned conjugate gradients beyond
193
+ DIRECT_LIMIT = 512
194
+
195
+ _GAMMA = 2.0 - np.sqrt(2.0) # the trapezoidal stage of TR-BDF2 ends at gamma h
196
+ _D = 0.5 * _GAMMA # the diagonal coefficient of both stages
197
+ _W = 0.25 * np.sqrt(2.0)
198
+
199
+
200
+ @dataclass
201
+ class OxidationField:
202
+ """The oxidation of an image: the concentrations of the species (``fields``: name ->
203
+ array ``(times,) + shape``, mol/l; zero in the phases that hold none) at the
204
+ ``times`` (s), and the number of ``steps`` of the integration."""
205
+
206
+ times: np.ndarray
207
+ fields: dict[str, np.ndarray]
208
+ steps: int
209
+
210
+ def tracer(self, species: str = "PO", time: int = -1) -> np.ndarray:
211
+ """The field of a species at an output time (by default the oxidation products
212
+ at the last one): the tracer of :func:`morphogen.coupling.ageing.
213
+ graded_materials`."""
214
+ return self.fields[species][time]
215
+
216
+
217
+ class _Kinetics:
218
+ """The rates of the scheme in the voxels of an image, each with the constants of its
219
+ phase, and their derivatives."""
220
+
221
+ def __init__(self, schemes: list, index: np.ndarray) -> None:
222
+ def table(name):
223
+ return np.array([getattr(m, name) if m is not None else 0.0 for m in schemes])[index]
224
+
225
+ self.k1, self.k2, self.k3 = table("k1"), table("k2"), table("k3")
226
+ self.k4, self.k5, self.k6 = table("k4"), table("k5"), table("k6")
227
+ self.gamma6 = table("gamma6")
228
+
229
+ def rates(self, y: np.ndarray) -> np.ndarray:
230
+ p, poo, pooh, ph, _, o2 = y
231
+ r1 = self.k1 * pooh
232
+ r2 = self.k2 * p * o2
233
+ r3 = self.k3 * poo * ph
234
+ r4 = self.k4 * p * p
235
+ r5 = self.k5 * p * poo
236
+ r6 = self.k6 * poo * poo
237
+ return np.stack(
238
+ [
239
+ 2.0 * r1 - r2 + r3 - 2.0 * r4 - r5,
240
+ r2 - r3 - r5 - 2.0 * r6,
241
+ -r1 + r3,
242
+ -r3,
243
+ r1 + self.gamma6 * r6,
244
+ -r2 + r6,
245
+ ]
246
+ )
247
+
248
+ def jacobian(self, y: np.ndarray) -> np.ndarray:
249
+ """``d rates_i / d y_j`` (6 x 6 x n)."""
250
+ p, poo, _, ph, _, o2 = y
251
+ k1, k2, k3, k4, k5, k6 = self.k1, self.k2, self.k3, self.k4, self.k5, self.k6
252
+ j = np.zeros((6, 6, p.size))
253
+ j[0, 0] = -k2 * o2 - 4.0 * k4 * p - k5 * poo
254
+ j[0, 1] = k3 * ph - k5 * p
255
+ j[0, 2] = 2.0 * k1
256
+ j[0, 3] = k3 * poo
257
+ j[0, 5] = -k2 * p
258
+ j[1, 0] = k2 * o2 - k5 * poo
259
+ j[1, 1] = -k3 * ph - k5 * p - 4.0 * k6 * poo
260
+ j[1, 3] = -k3 * poo
261
+ j[1, 5] = k2 * p
262
+ j[2, 1] = k3 * ph
263
+ j[2, 2] = -k1
264
+ j[2, 3] = k3 * poo
265
+ j[3, 1] = -k3 * ph
266
+ j[3, 3] = -k3 * poo
267
+ j[4, 1] = 2.0 * self.gamma6 * k6 * poo
268
+ j[4, 2] = k1
269
+ j[5, 0] = -k2 * o2
270
+ j[5, 1] = 2.0 * k6 * poo
271
+ j[5, 5] = -k2 * p
272
+ return j
273
+
274
+
275
+ def oxidation_field(
276
+ image,
277
+ schemes,
278
+ times,
279
+ *,
280
+ exposed=("x-", "x+"),
281
+ pressure: float | None = None,
282
+ unit: float = 1.0,
283
+ periodic=None,
284
+ rtol: float = 1e-4,
285
+ max_steps: int = 20000,
286
+ progress=None,
287
+ ) -> OxidationField:
288
+ """The thermal oxidation of the phases of an image (see the module): the
289
+ concentrations of the species in its voxels at ``times`` (s).
290
+
291
+ ``schemes``: a :class:`ClosedLoopOxidation` for every phase, or a mapping phase ->
292
+ scheme, each with the constants of its polymer and its transport of oxygen; a phase
293
+ without reactive sites (``ph0 = pooh0 = 0``) lets oxygen through and does not
294
+ oxidize, and a phase mapped to None is impermeable and inert (fibres, fillers).
295
+ Oxygen enters through the ``exposed`` faces of the image (``"x-"``, ``"x+"``, ...),
296
+ held at the partial ``pressure`` (Pa; by default that of the schemes, which must then
297
+ agree); the other faces are impermeable, or periodic in a periodic image. The image
298
+ is stored in air: its oxygen starts at equilibrium with the atmosphere. ``unit``:
299
+ the unit of length of the image in metres (``1e-6`` for micrometres). ``rtol``: the
300
+ relative tolerance of the time steps. ``progress``: a function called with the
301
+ fraction of the last time reached, after each step."""
302
+ from morphogen.analysis.basic import as_array
303
+ from morphogen.coupling.diffusion import FACES, _operator
304
+ from morphogen.image import VoxelImage
305
+
306
+ labels = np.asarray(as_array(image)).astype(np.int64)
307
+ spacing = np.asarray(image.spacing if isinstance(image, VoxelImage) else (1.0, 1.0, 1.0), float)
308
+ spacing = spacing * float(unit)
309
+ per = (
310
+ bool(image.periodic)
311
+ if periodic is None and isinstance(image, VoxelImage)
312
+ else bool(periodic)
313
+ )
314
+ exposed = tuple(exposed)
315
+ for face in exposed:
316
+ if face not in FACES:
317
+ raise ValueError(f"exposed: faces among {', '.join(FACES)}")
318
+ phases = [int(q) for q in np.unique(labels)]
319
+ if isinstance(schemes, ClosedLoopOxidation):
320
+ schemes = dict.fromkeys(phases, schemes)
321
+ missing = [q for q in phases if q not in schemes]
322
+ if missing:
323
+ raise ValueError(f"schemes: none for the phases {missing} (None: impermeable and inert)")
324
+ models = [schemes[q] for q in phases]
325
+ if any(m is not None and not isinstance(m, ClosedLoopOxidation) for m in models):
326
+ raise ValueError("schemes: ClosedLoopOxidation, or None for an impermeable phase")
327
+ live = [m for m in models if m is not None]
328
+ if not live:
329
+ raise ValueError("schemes: one phase at least takes oxygen")
330
+ if pressure is None:
331
+ if len({m.pressure for m in live}) > 1:
332
+ raise ValueError("pressure: the schemes differ; give that of the atmosphere")
333
+ pressure = live[0].pressure
334
+ pressure = float(pressure)
335
+ times = np.asarray(times, dtype=float).ravel()
336
+ if times.size == 0 or np.any(np.diff(times) <= 0) or times[0] < 0:
337
+ raise ValueError("times: increasing and non-negative")
338
+
339
+ index = np.searchsorted(phases, labels.ravel())
340
+ n = labels.size
341
+ kinetics = _Kinetics(models, index)
342
+
343
+ def table(name, default=0.0):
344
+ return np.array([getattr(m, name) if m is not None else default for m in models])[index]
345
+
346
+ solubility = table("solubility", 1.0) # (an impermeable voxel: any, it exchanges nothing)
347
+ permeability = (table("diffusivity") * table("solubility")).reshape(labels.shape)
348
+ axes_exposed = {FACES.index(f) // 2 for f in exposed}
349
+ periodic_axes = {a for a in range(3) if per and a not in axes_exposed}
350
+ conductance, faces = _operator(permeability, spacing, periodic_axes, exposed)
351
+ conductance = conductance.tocsr()
352
+ volume = float(np.prod(spacing))
353
+ weights = np.array(TOLERANCES)[:, None]
354
+
355
+ y = np.zeros((6, n))
356
+ y[2], y[3] = table("pooh0"), table("ph0")
357
+ y[5] = np.where(permeability.ravel() > 0.0, solubility * pressure, 0.0)
358
+
359
+ def rhs(state):
360
+ out = kinetics.rates(state)
361
+ flux = faces * pressure - conductance @ (state[5] / solubility)
362
+ out[5] += flux / volume
363
+ return out
364
+
365
+ def scaled(delta, state):
366
+ return float(np.sqrt(np.mean((delta / (weights + rtol * np.abs(state))) ** 2)))
367
+
368
+ def solve(residual, state, a):
369
+ """``(I - a J) delta = residual``: the local species eliminated in each voxel
370
+ (Gauss's elimination of their 5 x 5 blocks, on all the voxels at once: the
371
+ blocks of the kinetics need no pivoting), the oxygen of all the voxels solved
372
+ together."""
373
+ m = -a * kinetics.jacobian(state)
374
+ m[range(6), range(6)] += 1.0
375
+ r = residual.copy()
376
+ for i in range(5):
377
+ for j in range(i + 1, 6):
378
+ factor = m[j, i] / m[i, i]
379
+ m[j, i + 1 :] -= factor * m[i, i + 1 :]
380
+ r[j] -= factor * r[i]
381
+ schur = m[5, 5]
382
+ matrix = (sparse.diags(volume * solubility * schur) + a * conductance).tocsr()
383
+ if n <= DIRECT_LIMIT or np.any(schur <= 0.0):
384
+ du = splinalg.spsolve(matrix.tocsc(), volume * r[5])
385
+ else:
386
+ diagonal = matrix.diagonal()
387
+ jacobi = splinalg.LinearOperator(matrix.shape, matvec=lambda v: v / diagonal)
388
+ du, info = splinalg.cg(matrix, volume * r[5], rtol=1e-10, maxiter=20000, M=jacobi)
389
+ if info:
390
+ raise RuntimeError("oxidation_field: the conjugate gradients did not converge")
391
+ delta = np.empty_like(residual)
392
+ delta[5] = solubility * du
393
+ for i in range(4, -1, -1):
394
+ delta[i] = (r[i] - np.einsum("jn,jn->n", m[i, i + 1 :], delta[i + 1 :])) / m[i, i]
395
+ return delta
396
+
397
+ def stage(guess, constant, a):
398
+ """Newton's method for ``y - a f(y) = constant``; None when it does not converge."""
399
+ state = guess.copy()
400
+ for _ in range(12):
401
+ delta = solve(constant + a * rhs(state) - state, state, a)
402
+ state += delta
403
+ if not np.all(np.isfinite(state)):
404
+ return None
405
+ if scaled(delta, state) < 0.03:
406
+ return state
407
+ return None
408
+
409
+ fields = {name: np.zeros((times.size, *labels.shape)) for name in SPECIES}
410
+ t, h, steps = 0.0, 1e-3, 0
411
+ slope = rhs(y)
412
+ for k, t_out in enumerate(times):
413
+ while t < t_out:
414
+ h = min(h, t_out - t)
415
+ if steps >= max_steps:
416
+ raise RuntimeError(f"oxidation_field: {max_steps} steps before t = {t_out:g} s")
417
+ a = _D * h
418
+ middle = stage(y + _GAMMA * h * slope, y + a * slope, a)
419
+ new = None
420
+ if middle is not None:
421
+ c1 = 1.0 / (_GAMMA * (2.0 - _GAMMA))
422
+ constant = c1 * middle - (1.0 - _GAMMA) ** 2 * c1 * y
423
+ new = stage(middle, constant, a)
424
+ if new is None:
425
+ h *= 0.25
426
+ continue
427
+ slope_middle, slope_new = rhs(middle), rhs(new)
428
+ estimate = h * (
429
+ (_W - (1.0 - _W) / 3.0) * slope
430
+ + (_W - (3.0 * _W + 1.0) / 3.0) * slope_middle
431
+ + (_D - _D / 3.0) * slope_new
432
+ )
433
+ error = scaled(solve(estimate, new, a), new) # (filtered: stiff components)
434
+ steps += 1
435
+ if error > 1.0:
436
+ h *= max(0.2, 0.9 * error ** (-1.0 / 3.0))
437
+ continue
438
+ t += h
439
+ y, slope = np.maximum(new, 0.0), slope_new
440
+ if progress is not None:
441
+ progress(t / float(times[-1]))
442
+ if t < t_out:
443
+ h *= min(5.0, max(0.2, 0.9 * max(error, 1e-10) ** (-1.0 / 3.0)))
444
+ for row, name in enumerate(SPECIES):
445
+ fields[name][k] = y[row].reshape(labels.shape)
446
+ log.info("oxidation_field: %d steps to t = %g s on %d voxels", steps, times[-1], n)
447
+ return OxidationField(times, fields, steps)
@@ -0,0 +1,247 @@
1
+ """Hygromorph plates: multilayers that bend as moisture diffuses through them.
2
+
3
+ Pine cone scales and 4D-printed hygromorphs bend because their layers swell
4
+ differently and because the moisture profile through the thickness evolves (Mou,
5
+ Dirrenberger & Le Duigou 2025). Here a free multilayer plate, each layer isotropic in
6
+ elasticity (plane stress) with orthotropic swelling ``beta_x``, ``beta_y`` (strain per
7
+ unit concentration), a diffusivity and a solubility: moisture enters by Fick's law
8
+ through the thickness (finite volumes, continuity of the activity between layers,
9
+ implicit Euler), the swelling strains ``beta c(z, t)`` are eigenstrains, and the
10
+ classical laminate theory gives the mid-plane strains and curvatures of the free plate
11
+ (``[A B; B D] [eps0; kappa] = [N*; M*]``) at every time: the sequence of bendings along x
12
+ and y. The geometric nonlinearity of large deflections (Föppl–von Kármán, which selects
13
+ cylindrical shapes beyond a critical curvature) is left to finite element models.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+
21
+ import numpy as np
22
+ from scipy.linalg import solve_banded
23
+
24
+ #: Voigt components of the in-plane quantities of a plate normal to each axis.
25
+ _IN_PLANE = {2: ((0, 1), (0, 1, 5)), 0: ((1, 2), (1, 2, 3)), 1: ((2, 0), (2, 0, 4))}
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Layer:
30
+ """A layer of a hygromorph: thickness, Young's modulus and Poisson's ratio (or the
31
+ in-plane ``stiffness``: the 3 x 3 plane-stress matrix of the components ``xx``,
32
+ ``yy``, ``xy``, engineering shear, of an orthotropic or anisotropic layer), swelling
33
+ strains per unit concentration along x and y (and the engineering shear ``beta_xy``),
34
+ the diffusivity through the thickness and the solubility (the concentration at
35
+ equilibrium with the outside activity 1)."""
36
+
37
+ thickness: float
38
+ young: float
39
+ poisson: float = 0.3
40
+ beta_x: float = 0.0
41
+ beta_y: float = 0.0
42
+ diffusivity: float = 0.0
43
+ solubility: float = 1.0
44
+ stiffness: tuple | None = None
45
+ beta_xy: float = 0.0
46
+
47
+ def plane_stiffness(self) -> np.ndarray:
48
+ """The plane-stress stiffness ``Q`` (3 x 3: xx, yy, xy)."""
49
+ if self.stiffness is not None:
50
+ return np.asarray(self.stiffness, dtype=float).reshape(3, 3)
51
+ e, nu = self.young, self.poisson
52
+ q = e / (1.0 - nu * nu)
53
+ return np.array([[q, nu * q, 0.0], [nu * q, q, 0.0], [0.0, 0.0, 0.5 * e / (1.0 + nu)]])
54
+
55
+ @classmethod
56
+ def from_microstructure(
57
+ cls, thickness: float, sample, materials, *, solubility=None, normal: int = 2, **options
58
+ ) -> Layer:
59
+ """A layer whose properties are the apparent ones of a microstructure (a voxel
60
+ image or a conforming mesh, periodic homogenization by
61
+ :func:`~morphogen.homogenization.homogenize`): the plane-stress stiffness of the
62
+ apparent stiffness tensor in the plane normal to ``normal``, the swelling of its
63
+ apparent expansion tensor (give each material its swelling strain per unit
64
+ concentration as ``expansion``), the diffusivity through the thickness, the
65
+ apparent conductivity across it (give each material its permeability, diffusivity
66
+ times solubility, as ``conductivity``) over the mean ``solubility`` of the phases
67
+ (a mapping phase -> solubility, default 1)."""
68
+ from morphogen.homogenization.apparent import homogenize
69
+
70
+ props = ("stiffness", "conductivity_tensor", "thermal_expansion")
71
+ out = homogenize(sample, materials, bcs=("periodic",), properties=props, **options)
72
+ c = np.asarray(out["stiffness.periodic"]["tensor"])
73
+ k = np.asarray(out["conductivity_tensor.periodic"]["tensor"])
74
+ a = np.asarray(out["thermal_expansion.periodic"]["tensor"])
75
+ (i, j), voigt = _IN_PLANE[int(normal)]
76
+ compliance = np.linalg.inv(c)[np.ix_(voigt, voigt)]
77
+ q = np.linalg.inv(compliance)
78
+ fractions = _fractions(sample)
79
+ solubility = solubility or {}
80
+ mean_solubility = sum(f * float(solubility.get(r, 1.0)) for r, f in fractions.items())
81
+ return cls(
82
+ thickness=float(thickness),
83
+ young=float(1.0 / compliance[0, 0]),
84
+ poisson=float(-compliance[0, 1] / compliance[0, 0]),
85
+ beta_x=float(a[i, i]),
86
+ beta_y=float(a[j, j]),
87
+ beta_xy=float(2.0 * a[i, j]),
88
+ diffusivity=float(k[normal, normal] / mean_solubility),
89
+ solubility=float(mean_solubility),
90
+ stiffness=tuple(map(tuple, q)),
91
+ )
92
+
93
+
94
+ def _fractions(sample) -> dict[int, float]:
95
+ """Volume fractions of the phases of an image or a mesh."""
96
+ from morphogen.image import VoxelImage
97
+
98
+ if isinstance(sample, VoxelImage):
99
+ labels, counts = np.unique(np.asarray(sample.data), return_counts=True)
100
+ return {int(r): float(n) / counts.sum() for r, n in zip(labels, counts, strict=True)}
101
+ volumes = np.abs(sample.volumes())
102
+ return {
103
+ int(r): float(volumes[sample.phase == r].sum() / volumes.sum())
104
+ for r in np.unique(sample.phase)
105
+ }
106
+
107
+
108
+ class Multilayer:
109
+ """A free plate of layers stacked from ``z = 0`` (the bottom face) upwards."""
110
+
111
+ def __init__(self, layers, nodes_per_layer: int = 40) -> None:
112
+ self.layers = tuple(layers)
113
+ if not self.layers:
114
+ raise ValueError("Multilayer: at least one layer")
115
+ edges = np.concatenate([[0.0], np.cumsum([lay.thickness for lay in self.layers])])
116
+ self.thickness = float(edges[-1])
117
+ cells = []
118
+ for i in range(len(self.layers)):
119
+ e = np.linspace(edges[i], edges[i + 1], nodes_per_layer + 1)
120
+ cells.append(np.column_stack([e[:-1], e[1:], np.full(nodes_per_layer, i)]))
121
+ cells = np.vstack(cells)
122
+ self.lower, self.upper, self.index = cells[:, 0], cells[:, 1], cells[:, 2].astype(int)
123
+ self.z = 0.5 * (self.lower + self.upper)
124
+ self.dz = self.upper - self.lower
125
+
126
+ def _prop(self, name: str) -> np.ndarray:
127
+ return np.array([getattr(self.layers[i], name) for i in self.index], dtype=float)
128
+
129
+ def _q(self) -> np.ndarray:
130
+ """Plane-stress stiffness of each cell (cells x 3 x 3)."""
131
+ per_layer = np.stack([lay.plane_stiffness() for lay in self.layers])
132
+ return per_layer[self.index]
133
+
134
+ def stiffness(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
135
+ """``A``, ``B`` and ``D`` (3 x 3: xx, yy, xy) about ``z = 0``."""
136
+ q = self._q()
137
+ z0, z1 = self.lower, self.upper
138
+ a = np.einsum("nij,n->ij", q, z1 - z0)
139
+ b = np.einsum("nij,n->ij", q, (z1**2 - z0**2) / 2.0)
140
+ d = np.einsum("nij,n->ij", q, (z1**3 - z0**3) / 3.0)
141
+ return a, b, d
142
+
143
+ def deformation(self, concentration, *, full: bool = False) -> tuple[np.ndarray, np.ndarray]:
144
+ """Mid-plane strains (about ``z = 0``) and curvatures ``(kappa_x, kappa_y)`` of
145
+ the free plate under the swelling of the concentrations of the cells (a profile,
146
+ or an array of profiles: times x cells); ``full``: also the shear strain and the
147
+ twist (``kappa_xy``) of anisotropic layers."""
148
+ c = np.atleast_2d(np.asarray(concentration, dtype=float))
149
+ q = self._q()
150
+ beta = np.stack([self._prop("beta_x"), self._prop("beta_y"), self._prop("beta_xy")], axis=1)
151
+ sig = np.einsum("nij,nj->ni", q, beta) # Q : beta of each cell
152
+ w0, w1 = self.dz, (self.upper**2 - self.lower**2) / 2.0
153
+ n_star = (c * w0) @ sig # times x 3
154
+ m_star = (c * w1) @ sig
155
+ a, b, d = self.stiffness()
156
+ big = np.block([[a, b], [b, d]])
157
+ sol = np.linalg.solve(big, np.concatenate([n_star, m_star], axis=-1).T).T
158
+ strains, curvatures = sol[:, :3], sol[:, 3:]
159
+ if not full:
160
+ strains, curvatures = strains[:, :2], curvatures[:, :2]
161
+ if np.ndim(concentration) == 1:
162
+ return strains[0], curvatures[0]
163
+ return strains, curvatures
164
+
165
+ def moisture(
166
+ self,
167
+ times,
168
+ *,
169
+ exposed: str = "bottom",
170
+ activity: float | Callable[[float], float] = 1.0,
171
+ initial: float = 0.0,
172
+ steps: int = 200,
173
+ ) -> np.ndarray:
174
+ """Concentration profiles (times x cells) as moisture enters through the
175
+ ``exposed`` face (``bottom``, ``top`` or ``both``) held at ``activity`` (a number
176
+ or a function of time); the activity is continuous between layers, the
177
+ concentration is the solubility times it."""
178
+ if exposed not in ("bottom", "top", "both"):
179
+ raise ValueError('exposed: "bottom", "top" or "both"')
180
+ d, s = self._prop("diffusivity"), self._prop("solubility")
181
+ perm = d * s
182
+ h = self.dz
183
+ # conductances between neighbouring cells (half-cells in series)
184
+ g = 1.0 / (
185
+ 0.5 * h[:-1] / np.maximum(perm[:-1], 1e-300)
186
+ + 0.5 * h[1:] / np.maximum(perm[1:], 1e-300)
187
+ )
188
+ g_bot = perm[0] / (0.5 * h[0]) if exposed in ("bottom", "both") else 0.0
189
+ g_top = perm[-1] / (0.5 * h[-1]) if exposed in ("top", "both") else 0.0
190
+ diag = np.zeros(len(h))
191
+ diag[:-1] += g
192
+ diag[1:] += g
193
+ diag[0] += g_bot
194
+ diag[-1] += g_top
195
+ value = activity if callable(activity) else (lambda t, a=float(activity): a)
196
+ cap = s * h
197
+ u = np.full(len(h), float(initial))
198
+ times = np.asarray(times, dtype=float)
199
+ out, t = [], 0.0
200
+ for t_out in times:
201
+ span = t_out - t
202
+ if span > 0:
203
+ if t == 0.0:
204
+ r = 1.05
205
+ first = span * (r - 1.0) / (r**steps - 1.0)
206
+ dts = first * r ** np.arange(steps)
207
+ else:
208
+ dts = np.full(steps, span / steps)
209
+ for dt in dts:
210
+ t += dt
211
+ ab = np.zeros((3, len(h)))
212
+ ab[0, 1:] = -g
213
+ ab[1] = cap / dt + diag
214
+ ab[2, :-1] = -g
215
+ rhs = cap / dt * u
216
+ rhs[0] += g_bot * value(t)
217
+ rhs[-1] += g_top * value(t)
218
+ u = solve_banded((1, 1), ab, rhs)
219
+ t = float(t_out)
220
+ out.append(s * u)
221
+ return np.array(out)
222
+
223
+ def curvature_history(self, times, **moisture) -> dict[str, np.ndarray]:
224
+ """Moisture profiles, mid-plane strains and curvatures of the free plate at
225
+ ``times`` (keywords: those of :meth:`moisture`)."""
226
+ c = self.moisture(times, **moisture)
227
+ strains, curvatures = self.deformation(c)
228
+ return {
229
+ "times": np.asarray(times, float),
230
+ "concentration": c,
231
+ "strains": strains,
232
+ "curvatures": curvatures,
233
+ }
234
+
235
+
236
+ def timoshenko_curvature(strain: float, h1: float, h2: float, e1: float, e2: float) -> float:
237
+ """Curvature of a free bilayer whose upper layer (2) swells by ``strain`` relative to
238
+ the lower one (Timoshenko 1925): ``6 de (1 + m)^2 / (h (3 (1 + m)^2 + (1 + m n)
239
+ (m^2 + 1/(m n))))``, ``m = h1/h2``, ``n = E1/E2``; positive: the plate bends towards
240
+ its lower face (centre of curvature below)."""
241
+ m, n, h = h1 / h2, e1 / e2, h1 + h2
242
+ return (
243
+ 6.0
244
+ * strain
245
+ * (1.0 + m) ** 2
246
+ / (h * (3.0 * (1.0 + m) ** 2 + (1.0 + m * n) * (m * m + 1.0 / (m * n))))
247
+ )