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,814 @@
1
+ """A learned generalized standard material (Halphen & Nguyen 1975) in small and finite
2
+ strains: a learned free energy ``psi(eps, alpha)`` of a few internal variables ``alpha``,
3
+ convex, and a learned dissipation potential ``phi(alpha')``, convex, nonnegative and zero
4
+ at zero; the state of a step is the minimizer of the incremental potential (Ortiz &
5
+ Stainier 1999),
6
+
7
+ alpha_{n+1} = argmin_alpha psi(eps_{n+1}, alpha) + dt phi((alpha - alpha_n) / dt),
8
+
9
+ a convex problem solved by Newton's method on its gradient (a backtracking line search on
10
+ the potential), and ``sigma = d psi / d eps``. By construction the dissipation of a step,
11
+ ``D dt = -d psi/d alpha . (alpha_{n+1} - alpha_n)``, is nonnegative (``phi`` convex and
12
+ least at zero), the consistent tangent is symmetric and positive definite (the Schur
13
+ complement of the Hessian of the incremental potential, by the implicit function theorem)
14
+ and the law is stable whatever its parameters.
15
+
16
+ In the normalized variables of the models (:class:`~morphogen.learning.data.Scales`; ``x
17
+ = eps / s_eps``, ``alpha`` dimensionless, ``z = (x, alpha)``):
18
+
19
+ * the free energy ``psi = s_sigma s_eps (W(z) - W(0) - z . dW/dz(0))``, ``W(z) = z . A z / 2
20
+ + sum_i w_i g(u_i . z + b_i)``: an input-convex network of one hidden layer (Amos, Xu &
21
+ Kolter 2017; ``g`` the softplus, ``w = softplus(.) >= 0``) and a quadratic term ``A = L
22
+ L^T``, convex in ``(eps, alpha)`` jointly, zero with its gradient at the natural state
23
+ (no stress, no thermodynamic force);
24
+ * the dissipation of a step ``Phi(dalpha) = phi_1(dalpha) + dalpha . V dalpha / (2 tau)``
25
+ (``tau = dt / s_t``): with ``plastic``, a rate-independent part ``phi_1``, positively
26
+ homogeneous of degree 1 beyond the smoothing ``delta`` and taken on the increment (the
27
+ time step drops out), ``phi_1(v) = sum_k S(t_k(v)) - S(0) - c_k . v / 2``, ``t_k = sum_j
28
+ P_kj n_j(v) + c_k . v``, ``n_j = sqrt(|B_j v|^2 + delta^2) - delta`` (smoothed norms),
29
+ ``S(t) = (t + sqrt(t^2 + delta^2)) / 2`` (a smoothed ramp), ``P = softplus(.) >= 0``:
30
+ convex, zero with its gradient at zero, hence nonnegative, its elastic domain the
31
+ support set of ``phi_1`` sharpened at the scale ``delta`` of the increments; with
32
+ ``rate``, a viscous part ``V = M M^T`` (a quadratic potential of the rate).
33
+
34
+ The training fits the stresses along whole paths from the natural state: the gradient of
35
+ the objective goes through the minimization of each step by implicit differentiation (the
36
+ adjoint of a step solves ``K mu = lambda`` with ``K`` the Hessian of the incremental
37
+ potential in ``alpha``) and back through the steps (``lambda_n = d2 Phi mu_n``, the next
38
+ state depending on the previous one through the dissipation only); the gradients of the
39
+ parameters are those of the derivatives of ``W`` and ``Phi`` along the adjoint directions,
40
+ written out and compiled by Numba (no automatic differentiation).
41
+
42
+ In finite strains (data of the Green-Lagrange strain ``E`` and the second Piola-Kirchhoff
43
+ stress ``S``) the free energy is of an objective Lagrangian strain, ``psi(H, alpha)``:
44
+
45
+ * ``strain="logarithmic"`` (the default): ``H = 1/2 ln C`` (``C = I + 2 E``), the space of
46
+ the Hencky points of morphoGen (Miehe, Apel & Lambrecht 2002): ``T = d psi/dH`` and ``S =
47
+ T : dH/dE = J^T T`` (``J = dH/dE``, 6 x 6, from the divided differences of ``1/2 ln``
48
+ in the eigenbasis of ``C``, Daleckii-Krein; :mod:`morphogen.learning.logarithmic`, the
49
+ kernels of every learned law of ``ln C``), the tangent ``dS/dE = J^T (dT/dH) J + T :
50
+ d2H/dE2``; internal variables additive in ``H`` (an isochoric flow of the logarithmic
51
+ strain) represent isotropic multiplicative plasticity;
52
+ * ``strain="green-lagrange"``: ``H = E``, ``S = d psi/dE``, the tangent the Schur
53
+ complement itself (positive definite in ``E``).
54
+
55
+ Either way ``S : dE = T : dH``, so that the dissipation of a step is the same
56
+ ``-d psi/d alpha . (alpha_{n+1} - alpha_n) >= 0`` and ``S`` derives from ``psi(E)``
57
+ (``J`` does not depend on the parameters: the training sees the gaps of ``S`` through
58
+ ``J``); a superposed rotation leaves ``C``, hence ``S`` and the state, unchanged.
59
+ """
60
+
61
+ from __future__ import annotations
62
+
63
+ import math
64
+
65
+ import numpy as np
66
+ from numba import njit
67
+
68
+ from morphogen.learning.data import Dataset
69
+ from morphogen.learning.logarithmic import (
70
+ _conjugate,
71
+ _geometric,
72
+ _logarithmic,
73
+ _measures,
74
+ _symmetrize,
75
+ )
76
+ from morphogen.learning.networks import (
77
+ STRAINS,
78
+ Model,
79
+ _inverse_softplus,
80
+ _linear_fit,
81
+ _sigmoid,
82
+ _softplus,
83
+ )
84
+
85
+ #: Newton's method of a step: the tolerance of the gradient of the incremental potential
86
+ #: (normalized forces), the iterations, the factor of Armijo's condition
87
+ NEWTON_TOL = 1e-10
88
+ NEWTON_MAX = 60
89
+ _ARMIJO = 1e-4
90
+ #: The parameters of a model: of the free energy, of the rate-independent and of the
91
+ #: viscous dissipation
92
+ _PSI = ("U", "b", "w", "L")
93
+ _PHI = ("B", "P", "C")
94
+ _VISCOUS = ("M",)
95
+
96
+
97
+ @njit(cache=True)
98
+ def _soft(t):
99
+ """The softplus of a scalar, without overflow."""
100
+ if t > 30.0:
101
+ return t
102
+ if t < -30.0:
103
+ return math.exp(t)
104
+ return math.log1p(math.exp(t))
105
+
106
+
107
+ @njit(cache=True)
108
+ def _sig(t):
109
+ return 0.5 * (1.0 + math.tanh(0.5 * t))
110
+
111
+
112
+ @njit(cache=True)
113
+ def _energy(z, U, b, w, A, g0, grad, hess, order):
114
+ """``W(z) - z . g0`` (``g0 = dW/dz(0)``) and, with ``order`` 1 or 2, its gradient and
115
+ Hessian (written into ``grad`` and ``hess``)."""
116
+ d, h = z.size, b.size
117
+ value = 0.0
118
+ for i in range(d):
119
+ s = 0.0
120
+ for j in range(d):
121
+ s += A[i, j] * z[j]
122
+ value += (0.5 * s - g0[i]) * z[i]
123
+ if order > 0:
124
+ grad[i] = s - g0[i]
125
+ if order > 1:
126
+ for i in range(d):
127
+ for j in range(d):
128
+ hess[i, j] = A[i, j]
129
+ for k in range(h):
130
+ a = b[k]
131
+ for j in range(d):
132
+ a += U[k, j] * z[j]
133
+ value += w[k] * _soft(a)
134
+ if order > 0:
135
+ sg = _sig(a)
136
+ c = w[k] * sg
137
+ for j in range(d):
138
+ grad[j] += c * U[k, j]
139
+ if order > 1:
140
+ c2 = c * (1.0 - sg)
141
+ for i in range(d):
142
+ ci = c2 * U[k, i]
143
+ for j in range(d):
144
+ hess[i, j] += ci * U[k, j]
145
+ return value
146
+
147
+
148
+ @njit(cache=True)
149
+ def _dissipation(v, B, G, P, C, V, tau, delta, plastic, viscous, grad, hess, order):
150
+ """The dissipation of a step ``Phi(v)`` of the increment ``v`` and, with ``order`` 1
151
+ or 2, its gradient and Hessian (``G_j = B_j^T B_j``)."""
152
+ m = v.size
153
+ value = 0.0
154
+ if order > 0:
155
+ grad[:] = 0.0
156
+ if order > 1:
157
+ hess[:, :] = 0.0
158
+ if viscous:
159
+ for i in range(m):
160
+ s = 0.0
161
+ for j in range(m):
162
+ s += V[i, j] * v[j]
163
+ value += 0.5 * s * v[i] / tau
164
+ if order > 0:
165
+ grad[i] += s / tau
166
+ if order > 1:
167
+ for j in range(m):
168
+ hess[i, j] += V[i, j] / tau
169
+ if not plastic:
170
+ return value
171
+ n_norms, n_ridges = B.shape[0], C.shape[0]
172
+ norm = np.empty(n_norms)
173
+ radius = np.empty(n_norms)
174
+ dn = np.empty((n_norms, m)) # the gradients of the norms
175
+ for j in range(n_norms):
176
+ ss = 0.0
177
+ for i in range(m):
178
+ s = 0.0
179
+ for l in range(m):
180
+ s += B[j, i, l] * v[l]
181
+ ss += s * s
182
+ radius[j] = math.sqrt(ss + delta * delta)
183
+ norm[j] = ss / (radius[j] + delta) # sqrt(ss + delta^2) - delta, without cancellation
184
+ if order > 0:
185
+ for l in range(m):
186
+ s = 0.0
187
+ for i in range(m):
188
+ s += G[j, l, i] * v[i]
189
+ dn[j, l] = s / radius[j]
190
+ f = np.zeros(n_norms)
191
+ dt = np.empty(m)
192
+ for k in range(n_ridges):
193
+ t = 0.0
194
+ for j in range(n_norms):
195
+ t += P[k, j] * norm[j]
196
+ lin = 0.0
197
+ for l in range(m):
198
+ t += C[k, l] * v[l]
199
+ lin += C[k, l] * v[l]
200
+ q = math.sqrt(t * t + delta * delta)
201
+ value += 0.5 * (t + q) - 0.5 * delta - 0.5 * lin
202
+ if order == 0:
203
+ continue
204
+ s1 = 0.5 * (1.0 + t / q)
205
+ for l in range(m):
206
+ s = C[k, l]
207
+ for j in range(n_norms):
208
+ s += P[k, j] * dn[j, l]
209
+ dt[l] = s
210
+ grad[l] += s1 * s - 0.5 * C[k, l]
211
+ if order > 1:
212
+ s2 = 0.5 * delta * delta / (q * q * q)
213
+ for l in range(m):
214
+ for i in range(m):
215
+ hess[l, i] += s2 * dt[l] * dt[i]
216
+ for j in range(n_norms):
217
+ f[j] += s1 * P[k, j]
218
+ if order > 1: # sum_j f_j d2 n_j, d2 n_j = (B_j^T B_j - dn_j dn_j^T) / r_j
219
+ for j in range(n_norms):
220
+ for l in range(m):
221
+ for i in range(m):
222
+ hess[l, i] += f[j] * (G[j, l, i] - dn[j, l] * dn[j, i]) / radius[j]
223
+ return value
224
+
225
+
226
+ @njit(cache=True)
227
+ def _solve(K, rhs, out):
228
+ """``K^-1 rhs`` of a symmetric positive definite matrix by Cholesky's factorization
229
+ (a small shift of the diagonal if round-off spoils it)."""
230
+ m = rhs.size
231
+ low = np.zeros((m, m))
232
+ shift = 0.0
233
+ for _ in range(8):
234
+ ok = True
235
+ for j in range(m):
236
+ s = K[j, j] + shift
237
+ for k in range(j):
238
+ s -= low[j, k] * low[j, k]
239
+ if not s > 0.0:
240
+ ok = False
241
+ break
242
+ low[j, j] = math.sqrt(s)
243
+ for i in range(j + 1, m):
244
+ s = K[i, j]
245
+ for k in range(j):
246
+ s -= low[i, k] * low[j, k]
247
+ low[i, j] = s / low[j, j]
248
+ if ok:
249
+ break
250
+ trace = 0.0
251
+ for j in range(m):
252
+ trace += abs(K[j, j])
253
+ shift = max(10.0 * shift, 1e-14 * trace / m + 1e-300)
254
+ for i in range(m):
255
+ s = rhs[i]
256
+ for k in range(i):
257
+ s -= low[i, k] * out[k]
258
+ out[i] = s / low[i, i]
259
+ for i in range(m - 1, -1, -1):
260
+ s = out[i]
261
+ for k in range(i + 1, m):
262
+ s -= low[k, i] * out[k]
263
+ out[i] = s / low[i, i]
264
+
265
+
266
+ @njit(cache=True)
267
+ def _update(x, a0, tau, U, b, w, A, g0, B, G, P, C, V, delta, plastic, viscous,
268
+ z, gz, hz, gp, hp, kmat): # fmt: skip
269
+ """The state of a step: the minimizer ``alpha`` of the incremental potential at the
270
+ strain ``x`` from the state ``a0`` (Newton's method from ``a0``, a backtracking line
271
+ search). On return ``z = (x, alpha)``, the gradient ``gz`` and Hessian ``hz`` of the
272
+ free energy at ``z``, those of the dissipation at ``alpha - a0`` (``gp``, ``hp``) and
273
+ ``kmat``, the Hessian of the potential in ``alpha``; returns the iterations, or minus
274
+ them without convergence."""
275
+ m = a0.size
276
+ d = 6 + m
277
+ for i in range(6):
278
+ z[i] = x[i]
279
+ for i in range(m):
280
+ z[6 + i] = a0[i]
281
+ inc = np.zeros(m)
282
+ res = np.empty(m)
283
+ step = np.empty(m)
284
+ trial = np.empty(d)
285
+ for it in range(NEWTON_MAX + 1):
286
+ value = _energy(z, U, b, w, A, g0, gz, hz, 2)
287
+ for i in range(m):
288
+ inc[i] = z[6 + i] - a0[i]
289
+ value += _dissipation(inc, B, G, P, C, V, tau, delta, plastic, viscous, gp, hp, 2)
290
+ size = 0.0
291
+ for i in range(m):
292
+ res[i] = gz[6 + i] + gp[i]
293
+ size = max(size, abs(res[i]))
294
+ for j in range(m):
295
+ kmat[i, j] = hz[6 + i, 6 + j] + hp[i, j]
296
+ if size <= NEWTON_TOL:
297
+ return it
298
+ if it == NEWTON_MAX:
299
+ break
300
+ _solve(kmat, res, step)
301
+ slope = 0.0
302
+ for i in range(m):
303
+ step[i] = -step[i]
304
+ slope += res[i] * step[i]
305
+ t = 1.0
306
+ # far from the solution: Armijo's backtracking on the potential, while the decrease
307
+ # it predicts is above the round-off of the potential (below, the test would fail
308
+ # whatever the step, and the full Newton step converges)
309
+ if size > 1e-6 and -slope > 1e-12 * (1.0 + abs(value)):
310
+ for i in range(6):
311
+ trial[i] = x[i]
312
+ for _ in range(40):
313
+ for i in range(m):
314
+ trial[6 + i] = z[6 + i] + t * step[i]
315
+ inc[i] = trial[6 + i] - a0[i]
316
+ got = _energy(trial, U, b, w, A, g0, gz, hz, 0)
317
+ got += _dissipation(inc, B, G, P, C, V, tau, delta, plastic, viscous, gp, hp, 0)
318
+ if got <= value + _ARMIJO * t * slope:
319
+ break
320
+ t *= 0.5
321
+ for i in range(m):
322
+ z[6 + i] += t * step[i]
323
+ return -NEWTON_MAX
324
+
325
+
326
+ @njit(cache=True)
327
+ def _schur(hz, kmat, out):
328
+ """The consistent tangent ``d2W/dx2 - d2W/dx dalpha K^-1 d2W/dalpha dx`` (6 x 6,
329
+ symmetrized: symmetric to round-off)."""
330
+ m = kmat.shape[0]
331
+ col = np.empty(m)
332
+ sol = np.empty(m)
333
+ for c in range(6):
334
+ for i in range(m):
335
+ col[i] = hz[6 + i, c]
336
+ _solve(kmat, col, sol)
337
+ for r in range(6):
338
+ s = hz[r, c]
339
+ for i in range(m):
340
+ s -= hz[r, 6 + i] * sol[i]
341
+ out[r, c] = s
342
+ for r in range(6):
343
+ for c in range(r):
344
+ s = 0.5 * (out[r, c] + out[c, r])
345
+ out[r, c] = s
346
+ out[c, r] = s
347
+
348
+
349
+ @njit(cache=True)
350
+ def _stress(gz, hz, kmat, log, jac, q, mu, dq, scale, y, tangent):
351
+ """The normalized stress ``y`` and tangent of a step from the derivatives of the free
352
+ energy at its state: the stress and the Schur complement in the strain of the free
353
+ energy, or (``log``) those conjugate to the Green-Lagrange strain of the stress ``T``
354
+ conjugate to the logarithmic strain, ``J^T T`` and ``J^T K J + T : d2H/dE2``."""
355
+ if not log:
356
+ for i in range(6):
357
+ y[i] = gz[i]
358
+ _schur(hz, kmat, tangent)
359
+ return
360
+ k6 = np.empty((6, 6))
361
+ _schur(hz, kmat, k6)
362
+ _conjugate(jac, gz[:6], k6, y, tangent)
363
+ _geometric(gz[:6], q, mu, dq, scale, tangent)
364
+ _symmetrize(tangent)
365
+
366
+
367
+ @njit(cache=True)
368
+ def _points(x, a0, tau, U, b, w, A, g0, B, G, P, C, V, delta, plastic, viscous, log, scale):
369
+ """A step of points (n x 6 strains, n x m states, n time steps): their normalized
370
+ stresses, tangents and states at its end, and the iterations of each (``log``: the
371
+ strains normalized Green-Lagrange strains, the free energy of their logarithmic
372
+ strains; NaN stresses where ``C`` is not positive definite)."""
373
+ n, m = a0.shape
374
+ d = 6 + m
375
+ y, tangent, alpha = np.empty((n, 6)), np.empty((n, 6, 6)), np.empty((n, m))
376
+ iterations = np.empty(n, dtype=np.int64)
377
+ z, gz, hz = np.empty(d), np.empty(d), np.empty((d, d))
378
+ gp, hp, kmat = np.empty(m), np.empty((m, m)), np.empty((m, m))
379
+ h, jac, q, mu = np.empty(6), np.empty((6, 6)), np.empty((3, 3)), np.empty(3)
380
+ dq = np.empty((6, 3, 3))
381
+ for p in range(n):
382
+ if log:
383
+ if _logarithmic(x[p], scale, h, jac, q, mu, dq):
384
+ y[p] = np.nan
385
+ tangent[p] = np.nan
386
+ alpha[p] = a0[p]
387
+ iterations[p] = -1
388
+ continue
389
+ else:
390
+ h[:] = x[p]
391
+ iterations[p] = _update(h, a0[p], tau[p], U, b, w, A, g0, B, G, P, C, V, delta,
392
+ plastic, viscous, z, gz, hz, gp, hp, kmat) # fmt: skip
393
+ for i in range(m):
394
+ alpha[p, i] = z[6 + i]
395
+ _stress(gz, hz, kmat, log, jac, q, mu, dq, scale, y[p], tangent[p])
396
+ return y, tangent, alpha, iterations
397
+
398
+
399
+ @njit(cache=True)
400
+ def _paths(x, tau, U, b, w, A, g0, w0, B, G, P, C, V, delta, plastic, viscous, log, scale):
401
+ """Paths from the natural state (paths x steps x 6 strains, paths x steps time steps):
402
+ the normalized stresses, states, free energies (``W(z) - W(0) - z . g0``,
403
+ ``w0 = W(0)``), dissipations of the steps (``-dpsi/dalpha . dalpha``), tangents and
404
+ the iterations of each step (``log``: see :func:`_points`)."""
405
+ n, steps = tau.shape
406
+ m = V.shape[0]
407
+ d = 6 + m
408
+ y, alpha = np.empty((n, steps, 6)), np.empty((n, steps, m))
409
+ energy, dissipation = np.empty((n, steps)), np.empty((n, steps))
410
+ tangent = np.empty((n, steps, 6, 6))
411
+ iterations = np.empty((n, steps), dtype=np.int64)
412
+ z, gz, hz = np.empty(d), np.empty(d), np.empty((d, d))
413
+ gp, hp, kmat = np.empty(m), np.empty((m, m)), np.empty((m, m))
414
+ h, jac, q, mu = np.empty(6), np.empty((6, 6)), np.empty((3, 3)), np.empty(3)
415
+ dq = np.empty((6, 3, 3))
416
+ for p in range(n):
417
+ state = np.zeros(m)
418
+ for t in range(steps):
419
+ if log:
420
+ if _logarithmic(x[p, t], scale, h, jac, q, mu, dq): # the rest of the path
421
+ y[p, t:] = np.nan
422
+ alpha[p, t:] = np.nan
423
+ energy[p, t:] = np.nan
424
+ dissipation[p, t:] = np.nan
425
+ tangent[p, t:] = np.nan
426
+ iterations[p, t:] = -1
427
+ break
428
+ else:
429
+ h[:] = x[p, t]
430
+ iterations[p, t] = _update(h, state, tau[p, t], U, b, w, A, g0, B, G, P, C, V,
431
+ delta, plastic, viscous, z, gz, hz, gp, hp,
432
+ kmat) # fmt: skip
433
+ spent = 0.0
434
+ for i in range(m):
435
+ spent -= gz[6 + i] * (z[6 + i] - state[i])
436
+ state[i] = z[6 + i]
437
+ alpha[p, t, i] = z[6 + i]
438
+ dissipation[p, t] = spent
439
+ _stress(gz, hz, kmat, log, jac, q, mu, dq, scale, y[p, t], tangent[p, t])
440
+ energy[p, t] = _energy(z, U, b, w, A, g0, gz, hz, 0) - w0
441
+ return y, alpha, energy, dissipation, tangent, iterations
442
+
443
+
444
+ @njit(cache=True)
445
+ def _energy_params(z, u, U, b, w, gU, gb, gw, gA):
446
+ """Adds the gradients with respect to ``U``, ``b``, ``w`` and ``A`` of ``u . dW/dz
447
+ (z)``, the derivative of the free energy along ``u``."""
448
+ d, h = z.size, b.size
449
+ for i in range(d):
450
+ for j in range(d):
451
+ gA[i, j] += u[i] * z[j]
452
+ for k in range(h):
453
+ a = b[k]
454
+ uu = 0.0
455
+ for j in range(d):
456
+ a += U[k, j] * z[j]
457
+ uu += U[k, j] * u[j]
458
+ sg = _sig(a)
459
+ ds = sg * (1.0 - sg)
460
+ gw[k] += sg * uu
461
+ gb[k] += w[k] * ds * uu
462
+ for j in range(d):
463
+ gU[k, j] += w[k] * (ds * uu * z[j] + sg * u[j])
464
+
465
+
466
+ @njit(cache=True)
467
+ def _dissipation_params(v, mu, B, P, C, tau, delta, plastic, viscous, gB, gP, gC, gV):
468
+ """Adds the gradients with respect to ``B``, ``P``, ``C`` and ``V`` of ``mu . dPhi/dv
469
+ (v)``, the derivative of the dissipation of the increment ``v`` along ``mu``."""
470
+ m = v.size
471
+ if viscous:
472
+ for i in range(m):
473
+ for j in range(m):
474
+ gV[i, j] += mu[i] * v[j] / tau
475
+ if not plastic:
476
+ return
477
+ n_norms, n_ridges = B.shape[0], C.shape[0]
478
+ bv, bm = np.empty((n_norms, m)), np.empty((n_norms, m))
479
+ norm, radius, along = np.empty(n_norms), np.empty(n_norms), np.empty(n_norms)
480
+ for j in range(n_norms):
481
+ ss = 0.0
482
+ cross = 0.0
483
+ for i in range(m):
484
+ s = 0.0
485
+ sm = 0.0
486
+ for l in range(m):
487
+ s += B[j, i, l] * v[l]
488
+ sm += B[j, i, l] * mu[l]
489
+ bv[j, i] = s
490
+ bm[j, i] = sm
491
+ ss += s * s
492
+ cross += s * sm
493
+ radius[j] = math.sqrt(ss + delta * delta)
494
+ norm[j] = ss / (radius[j] + delta)
495
+ along[j] = cross / radius[j] # mu . dn_j
496
+ e, f = np.zeros(n_norms), np.zeros(n_norms)
497
+ for k in range(n_ridges):
498
+ t = 0.0
499
+ g = 0.0
500
+ for j in range(n_norms):
501
+ t += P[k, j] * norm[j]
502
+ g += P[k, j] * along[j]
503
+ for l in range(m):
504
+ t += C[k, l] * v[l]
505
+ g += C[k, l] * mu[l]
506
+ q = math.sqrt(t * t + delta * delta)
507
+ s1 = 0.5 * (1.0 + t / q)
508
+ s2 = 0.5 * delta * delta / (q * q * q)
509
+ for l in range(m):
510
+ gC[k, l] += s2 * g * v[l] + (s1 - 0.5) * mu[l]
511
+ for j in range(n_norms):
512
+ gP[k, j] += s2 * g * norm[j] + s1 * along[j]
513
+ e[j] += s2 * g * P[k, j]
514
+ f[j] += s1 * P[k, j]
515
+ for j in range(n_norms):
516
+ r = radius[j]
517
+ cross = along[j] * r
518
+ for i in range(m):
519
+ for l in range(m):
520
+ gB[j, i, l] += (e[j] * bv[j, i] * v[l] / r
521
+ + f[j] * ((bv[j, i] * mu[l] + bm[j, i] * v[l]) / r
522
+ - cross * bv[j, i] * v[l] / (r * r * r))) # fmt: skip
523
+
524
+
525
+ @njit(cache=True)
526
+ def _gradients(x, tau, y, U, b, w, A, g0, B, G, P, C, V, delta, plastic, viscous, log, scale,
527
+ grad): # fmt: skip
528
+ """The mean square of the gaps of the normalized stresses of paths from the natural
529
+ state and, with ``grad``, its gradients with respect to ``U``, ``b``, ``w``, ``A``,
530
+ ``B``, ``P``, ``C`` and ``V`` (the values of the parameters, before their
531
+ reparametrizations): the minimization of each step differentiated implicitly, the
532
+ adjoints carried back through the steps. With ``log`` the strains are normalized
533
+ Green-Lagrange strains and the stresses ``S = J^T T``: the gaps of ``S`` reach ``T`` as
534
+ ``J r`` (``J`` of the data). Returns the loss, the gradients and the iterations of
535
+ Newton's method that did not converge."""
536
+ n, steps = tau.shape
537
+ m = V.shape[0]
538
+ d = 6 + m
539
+ total = steps * n * 6
540
+ gU, gb, gw, gA = np.zeros_like(U), np.zeros_like(b), np.zeros_like(w), np.zeros_like(A)
541
+ gB, gP, gC, gV = np.zeros_like(B), np.zeros_like(P), np.zeros_like(C), np.zeros_like(V)
542
+ zs, hs = np.empty((steps, d)), np.empty((steps, d, d))
543
+ ks, hps = np.empty((steps, m, m)), np.empty((steps, m, m))
544
+ incs, gaps = np.empty((steps, m)), np.empty((steps, 6))
545
+ z, gz, hz = np.empty(d), np.empty(d), np.empty((d, d))
546
+ gp, hp, kmat = np.empty(m), np.empty((m, m)), np.empty((m, m))
547
+ lam, mu, nxt, u = np.empty(m), np.empty(m), np.zeros(m), np.empty(d)
548
+ h, jac, q, eig = np.empty(6), np.empty((6, 6)), np.empty((3, 3)), np.empty(3)
549
+ dq, r = np.empty((6, 3, 3)), np.empty(6)
550
+ summed = np.zeros(d)
551
+ loss = 0.0
552
+ failed = 0
553
+ for p in range(n):
554
+ state = np.zeros(m)
555
+ for t in range(steps):
556
+ if log:
557
+ if _logarithmic(x[p, t], scale, h, jac, q, eig, dq):
558
+ return math.nan, gU, gb, gw, gA, gB, gP, gC, gV, failed + 1
559
+ else:
560
+ h[:] = x[p, t]
561
+ it = _update(h, state, tau[p, t], U, b, w, A, g0, B, G, P, C, V, delta,
562
+ plastic, viscous, z, gz, hz, gp, hp, kmat) # fmt: skip
563
+ if it < 0:
564
+ failed += 1
565
+ for i in range(6):
566
+ s = gz[i]
567
+ if log: # S = J^T T
568
+ s = 0.0
569
+ for k in range(6):
570
+ s += jac[k, i] * gz[k]
571
+ r[i] = s - y[p, t, i]
572
+ loss += r[i] * r[i]
573
+ for i in range(6):
574
+ if log: # d loss / dT = J d loss / dS
575
+ s = 0.0
576
+ for k in range(6):
577
+ s += jac[i, k] * r[k]
578
+ gaps[t, i] = 2.0 * s / total
579
+ else:
580
+ gaps[t, i] = 2.0 * r[i] / total
581
+ for i in range(m):
582
+ incs[t, i] = z[6 + i] - state[i]
583
+ state[i] = z[6 + i]
584
+ if grad:
585
+ zs[t] = z
586
+ hs[t] = hz
587
+ ks[t] = kmat
588
+ hps[t] = hp
589
+ if not grad:
590
+ continue
591
+ nxt[:] = 0.0
592
+ for t in range(steps - 1, -1, -1):
593
+ # the adjoint of the state of the step: the next steps and the stress of this one
594
+ for i in range(m):
595
+ s = nxt[i]
596
+ for c in range(6):
597
+ s += hs[t, 6 + i, c] * gaps[t, c]
598
+ lam[i] = s
599
+ _solve(ks[t], lam, mu)
600
+ for c in range(6):
601
+ u[c] = gaps[t, c]
602
+ for i in range(m):
603
+ u[6 + i] = -mu[i]
604
+ mu[i] = -mu[i]
605
+ for i in range(d):
606
+ summed[i] += u[i]
607
+ _energy_params(zs[t], u, U, b, w, gU, gb, gw, gA)
608
+ _dissipation_params(incs[t], mu, B, P, C, tau[p, t], delta, plastic, viscous,
609
+ gB, gP, gC, gV) # fmt: skip
610
+ for i in range(m): # the previous state: through the dissipation only
611
+ s = 0.0
612
+ for j in range(m):
613
+ s -= hps[t, i, j] * mu[j]
614
+ nxt[i] = s
615
+ if grad: # the gradient at the natural state g0 = dW/dz(0), subtracted from every one
616
+ for i in range(d):
617
+ summed[i] = -summed[i]
618
+ _energy_params(np.zeros(d), summed, U, b, w, gU, gb, gw, gA)
619
+ return loss / total, gU, gb, gw, gA, gB, gP, gC, gV, failed
620
+
621
+
622
+ class Standard(Model):
623
+ """A learned generalized standard material (see the module): ``internal``, the number
624
+ of internal variables; ``hidden``, the softplus ridges of its free energy; ``rate``, a
625
+ viscous dissipation (the time step matters); ``plastic``, a rate-independent one (by
626
+ default; ``rate`` alone gives viscoelasticity); ``smoothing``, the scale ``delta`` of
627
+ the normalized increments below which the rate-independent dissipation is smoothed;
628
+ ``seed``, that of its initial parameters. Its dissipation has ``internal`` smoothed
629
+ norms and ``internal`` ridges. ``strain``: that of its free energy in finite strains
630
+ (:data:`~morphogen.learning.networks.STRAINS`), the logarithmic strain (the default)
631
+ or the Green-Lagrange strain; in small strains the free energy is of the small strain,
632
+ which both linearize to."""
633
+
634
+ kind = "standard"
635
+ recurrent = True
636
+
637
+ def __init__(self, hidden: int = 32, *, internal: int = 8, rate: bool = False,
638
+ plastic: bool = True, smoothing: float = 0.01, strain: str = "logarithmic",
639
+ seed: int = 0) -> None: # fmt: skip
640
+ if any(isinstance(v, bool) or not isinstance(v, (int, np.integer)) or v < 1
641
+ for v in (hidden, internal)): # fmt: skip
642
+ raise ValueError(
643
+ "hidden, internal: the ridges of the energy and the internal variables, "
644
+ f"positive integers, got {hidden!r}, {internal!r}"
645
+ )
646
+ if not (rate or plastic):
647
+ raise ValueError("standard model: a dissipation, rate-independent (plastic) or "
648
+ "viscous (rate), or both") # fmt: skip
649
+ if not 0 < smoothing < math.inf:
650
+ raise ValueError("smoothing: positive and finite")
651
+ if strain not in STRAINS:
652
+ raise ValueError(f"strain: that of the free energy, one of {STRAINS}, got {strain!r}")
653
+ super().__init__(hidden=int(hidden), internal=int(internal), rate=bool(rate),
654
+ plastic=bool(plastic), smoothing=float(smoothing), strain=str(strain),
655
+ seed=int(seed)) # fmt: skip
656
+
657
+ @property
658
+ def n_state(self) -> int:
659
+ return self.options["internal"]
660
+
661
+ def prepare(self, data: Dataset) -> tuple:
662
+ """The normalized strains at the ends of the steps (paths x steps x 6), the
663
+ normalized time steps (paths x steps) and the normalized stresses."""
664
+ s = self._scales()
665
+ return (data.strain[:, 1:] / s.strain, np.diff(data.times, axis=1) / s.time,
666
+ data.stress[:, 1:] / s.stress) # fmt: skip
667
+
668
+ def _initial(self, rng, x, tau, y) -> dict:
669
+ h, m = self.options["hidden"], self.options["internal"]
670
+ d = 6 + m
671
+ # in ln C, the fit of T = J^-T S to the logarithmic strain
672
+ strain, stress = self._conjugates(x.reshape(-1, 6), y.reshape(-1, 6))
673
+ # the quadratic term: the symmetric positive part of the linear fit for the strain,
674
+ # the internal variables coupled to it at random
675
+ fit = _linear_fit(strain, stress)
676
+ values, vectors = np.linalg.eigh(0.5 * (fit + fit.T))
677
+ values = np.maximum(values, 1e-3 * max(values.max(), 1e-12))
678
+ low = np.zeros((d, d))
679
+ low[:6, :6] = vectors * np.sqrt(values)
680
+ low[6:, :6] = rng.normal(0.0, 0.5 * math.sqrt(values.mean() / 6.0), (m, 6))
681
+ low[6:, 6:] = np.eye(m)
682
+ p = {"U": rng.normal(0.0, 1.0 / math.sqrt(d), (h, d)), "b": np.zeros(h),
683
+ "w": _inverse_softplus(0.1 / h) + rng.normal(0.0, 0.3, h), "L": low} # fmt: skip
684
+ if self.options["plastic"]:
685
+ p["B"] = rng.normal(0.0, 1.0 / math.sqrt(m), (m, m, m))
686
+ p["P"] = _inverse_softplus(0.3 / m) + rng.normal(0.0, 0.3, (m, m))
687
+ p["C"] = rng.normal(0.0, 0.3 / math.sqrt(m), (m, m))
688
+ if self.options["rate"]: # relaxation times from one mean step to a whole path
689
+ times = np.geomspace(1.0, max(float(x.shape[1]), 2.0), m)
690
+ stiff = np.diag(low[6:] @ low[6:].T)
691
+ p["M"] = np.diag(np.sqrt(times * stiff)) + rng.normal(0.0, 0.03, (m, m))
692
+ return p
693
+
694
+ def _values(self) -> tuple:
695
+ """The arrays of the kernels: the values of the parameters (``w = softplus``, ``A =
696
+ L L^T``, ...), ``dW/dz(0)`` and ``W(0)``; then whether the free energy is of the
697
+ logarithmic strain and the scale of the strains."""
698
+ p, m = self.params, self.options["internal"]
699
+ w, low = _softplus(p["w"]), p["L"]
700
+ amat = low @ low.T
701
+ g0 = (w * _sigmoid(p["b"])) @ p["U"]
702
+ w0 = float(np.sum(w * _softplus(p["b"])))
703
+ if self.options["plastic"]:
704
+ b, c, pm = p["B"], p["C"], _softplus(p["P"])
705
+ g = np.einsum("jil,jik->jlk", b, b)
706
+ else: # placeholders the kernels skip
707
+ b, g, c, pm = (np.zeros((1, m, m)), np.zeros((1, m, m)), np.zeros((1, m)),
708
+ np.zeros((1, 1))) # fmt: skip
709
+ v = p["M"] @ p["M"].T if self.options["rate"] else np.zeros((m, m))
710
+ delta = self.options["smoothing"]
711
+ return (p["U"], p["b"], w, amat, g0, w0, b, g, pm, c, v, delta,
712
+ self.options["plastic"], self.options["rate"], self.logarithmic,
713
+ self._scales().strain) # fmt: skip
714
+
715
+ def _taus(self, times, shape) -> np.ndarray:
716
+ """The normalized time steps of paths (paths x steps), ones without a viscous
717
+ dissipation (the time step then drops out)."""
718
+ if not self.options["rate"]:
719
+ return np.ones(shape)
720
+ if times is None:
721
+ raise ValueError("standard model of a rate: give the times of the paths")
722
+ dt = np.diff(np.atleast_2d(np.asarray(times, dtype=float)), axis=1)
723
+ return np.ascontiguousarray(np.broadcast_to(dt, shape) / self._scales().time)
724
+
725
+ def objective(self, arrays, grad=True):
726
+ x, tau, y = (np.ascontiguousarray(a, dtype=float) for a in arrays)
727
+ u, b, w, amat, g0, _, bmat, g, pm, c, v, delta, plastic, viscous, log, scale = (
728
+ self._values()) # fmt: skip
729
+ if not self.options["rate"]:
730
+ tau = np.ones_like(tau)
731
+ loss, *grads, _ = _gradients(x, tau, y, u, b, w, amat, g0, bmat, g, pm, c, v, delta,
732
+ plastic, viscous, log, scale, grad) # fmt: skip
733
+ if not grad:
734
+ return float(loss), None
735
+ gu, gb, gw, ga, gbm, gpm, gc, gv = grads
736
+ p = self.params
737
+ out = {"U": gu, "b": gb, "w": gw * _sigmoid(p["w"]), "L": (ga + ga.T) @ p["L"]}
738
+ if plastic:
739
+ out.update(B=gbm, P=gpm * _sigmoid(p["P"]), C=gc)
740
+ if viscous:
741
+ out["M"] = (gv + gv.T) @ p["M"]
742
+ return float(loss), out
743
+
744
+ def history(self, strain, times=None) -> dict:
745
+ """The evolution of paths from the natural state (paths x points x 6, or one path):
746
+ their ``stress``, internal variables (``internal``), free energy (``energy``, per
747
+ unit volume) and the energy dissipated by each step (``dissipation``, ``-dpsi/
748
+ dalpha . dalpha``, nonnegative to the round-off of Newton's method), the first
749
+ point the natural state; the consistent ``tangent`` of each step (its first
750
+ point that of the natural state, not used); the ``iterations`` of Newton's method
751
+ of each step (negative where it stopped without converging). In finite strains:
752
+ the Green-Lagrange strains, the second Piola-Kirchhoff stresses and their tangents
753
+ ``dS/dE``."""
754
+ s = self._scales()
755
+ strain = np.asarray(strain, dtype=float)
756
+ single = strain.ndim == 2
757
+ strain = strain[None] if single else strain
758
+ if times is not None and single:
759
+ times = np.asarray(times, dtype=float)[None]
760
+ x = np.ascontiguousarray(strain[:, 1:] / s.strain)
761
+ tau = self._taus(times, x.shape[:2])
762
+ u, b, w, amat, g0, w0, bmat, g, pm, c, v, delta, plastic, viscous, log, scale = (
763
+ self._values()) # fmt: skip
764
+ y, alpha, energy, spent, tangent, its = _paths(x, tau, u, b, w, amat, g0, w0, bmat, g,
765
+ pm, c, v, delta, plastic, viscous, log,
766
+ scale) # fmt: skip
767
+ n = strain.shape[0]
768
+
769
+ def first(a, value=0.0): # the natural state before the steps
770
+ return np.concatenate([np.full((n, 1, *a.shape[2:]), value), a], axis=1)
771
+
772
+ work = s.stress * s.strain
773
+ out = {"stress": first(s.stress * y), "internal": first(alpha),
774
+ "energy": first(work * energy), "dissipation": first(work * spent),
775
+ "tangent": first(s.stress / s.strain * tangent, np.nan),
776
+ "iterations": first(its, 0)} # fmt: skip
777
+ return {k: a[0] for k, a in out.items()} if single else out
778
+
779
+ def predict(self, strain, times=None) -> np.ndarray:
780
+ return self.history(strain, times)["stress"]
781
+
782
+ def tangent(self, strain):
783
+ raise ValueError("a standard model has the tangents of its steps (step)")
784
+
785
+ def energy(self, strain, internal) -> np.ndarray:
786
+ """The free energy (per unit volume) at strains (..., 6; Green-Lagrange strains in
787
+ finite strains) and internal variables (..., internal)."""
788
+ s = self._scales()
789
+ x = np.asarray(strain, dtype=float) / s.strain
790
+ if self.logarithmic:
791
+ x = _measures(np.ascontiguousarray(x.reshape(-1, 6)), s.strain)[0].reshape(x.shape)
792
+ alpha = np.asarray(internal, dtype=float)
793
+ lead = np.broadcast_shapes(x.shape[:-1], alpha.shape[:-1])
794
+ z = np.concatenate([np.broadcast_to(x, (*lead, 6)),
795
+ np.broadcast_to(alpha, (*lead, alpha.shape[-1]))], axis=-1) # fmt: skip
796
+ u, b, w, amat, g0, w0, *_ = self._values()
797
+ flat = z.reshape(-1, z.shape[-1])
798
+ values = (0.5 * np.einsum("ni,ij,nj->n", flat, amat, flat) - flat @ g0
799
+ + _softplus(flat @ u.T + b) @ w - w0) # fmt: skip
800
+ return s.stress * s.strain * values.reshape(z.shape[:-1])
801
+
802
+ def step(self, e_new, e_old, h_old, dt):
803
+ s = self._scales()
804
+ e_new = np.asarray(e_new, dtype=float)
805
+ n = e_new.shape[0]
806
+ x = np.ascontiguousarray(e_new / s.strain)
807
+ a0 = np.ascontiguousarray(np.asarray(h_old, dtype=float).reshape(n, self.n_state))
808
+ # a step of no time: the viscous variables frozen (an infinite viscous resistance)
809
+ tau = np.full(n, max(float(dt) / s.time, 1e-12) if self.options["rate"] else 1.0)
810
+ u, b, w, amat, g0, _, bmat, g, pm, c, v, delta, plastic, viscous, log, scale = (
811
+ self._values()) # fmt: skip
812
+ y, tangent, alpha, _ = _points(x, a0, tau, u, b, w, amat, g0, bmat, g, pm, c, v, delta,
813
+ plastic, viscous, log, scale) # fmt: skip
814
+ return s.stress * y, s.stress / s.strain * tangent, alpha