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,595 @@
1
+ """The tools of the tab Learning: a behaviour learned from data (:mod:`morphogen.learning`).
2
+ The responses of a behaviour at a material point, or the homogenized responses of a
3
+ morphology of the workspace (FFT on its voxels), along random strain paths; a network
4
+ trained on them in the background (its losses reported epoch by epoch); its learning
5
+ curves and its law along a validation path against the reference; the model saved
6
+ (``learned.npz``) and its learned law kept in the workspace (B), from which the loading
7
+ paths of morphologies give it to a phase.
8
+
9
+ The fields of the paths, of the model and of the training are those of the sections
10
+ ``data``, ``model`` and ``training`` of the configurations of ``morphogen learn``
11
+ (:mod:`morphogen.learning.run`), with their defaults; the run writes the configuration that
12
+ learns the law again (a material point, or a morphology of isotropic phases: its voxel
13
+ image)."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import time
19
+ from dataclasses import replace
20
+
21
+ import numpy as np
22
+
23
+ from morphogen.gui.tools import Field, elastic_tables, tab, tool
24
+ from morphogen.gui.tools.mechanics import (
25
+ BEHAVIOURS_FIELD,
26
+ COMPONENTS,
27
+ SHADES,
28
+ _behaviour,
29
+ _behaviour_fields,
30
+ _check_voxels,
31
+ _json,
32
+ _materials,
33
+ _path,
34
+ _path_fields,
35
+ )
36
+ from morphogen.learning.run import DATA, MODEL, TRAINING
37
+
38
+ tab(
39
+ "learning",
40
+ "Learning",
41
+ "Behaviours learned from data: the responses of a behaviour at a material point, or "
42
+ "the homogenized responses of a morphology, along random strain paths; a perceptron, "
43
+ "a learned convex potential (hyperelastic) or a recurrent network (path-dependent "
44
+ "laws: plasticity) trained on them in the background, its learning curves and its law "
45
+ "along a validation path against the reference; the model saved and its law kept in "
46
+ "the workspace (B), the behaviour of a phase in the loading paths of morphologies.",
47
+ order=45,
48
+ )
49
+
50
+ POINT = {"data": "point"}
51
+ MORPHOLOGY = {"data": "morphology"}
52
+ #: The rotations of the mini-batches of the form (``rotate`` of the training)
53
+ ROTATIONS = {"false": False, "true": True, "cubic": "cubic"}
54
+ #: The models (:data:`morphogen.learning.KINDS`)
55
+ MODELS = (
56
+ ("recurrent", "recurrent: a gated recurrent unit, learned internal variables (plasticity)"),
57
+ (
58
+ "standard",
59
+ "standard: a learned convex free energy and dissipation of learned internal "
60
+ "variables (plasticity, viscosity; thermodynamically consistent)",
61
+ ),
62
+ ("potential", "potential: the stress of a learned convex energy (hyperelasticity)"),
63
+ ("feedforward", "perceptron: the stress a function of the strain (nonlinear elasticity)"),
64
+ )
65
+
66
+
67
+ def _fields(section: dict, specs: dict) -> list[Field]:
68
+ """The fields of a section of the configurations of ``morphogen learn``, their
69
+ defaults those of ``section``: ``specs`` maps each key of the section to the options of
70
+ its :class:`~morphogen.gui.tools.Field` (``name``: that of the form, by default the
71
+ key)."""
72
+ out = []
73
+ for key, spec in specs.items():
74
+ spec = dict(spec)
75
+ out.append(Field(spec.pop("name", key), default=spec.pop("default", section[key]), **spec))
76
+ return out
77
+
78
+
79
+ #: The fields of the random paths (the section ``data``)
80
+ PATH_FIELDS = _fields(
81
+ DATA,
82
+ {
83
+ "paths": {"kind": "int", "doc": "random strain paths, their responses the data"},
84
+ "segments": {"kind": "int", "doc": "linear segments of a path, from the natural state"},
85
+ "increments": {"kind": "int", "label": "increments of a segment"},
86
+ "amplitude": {
87
+ "kind": "float",
88
+ "label": "strain amplitude",
89
+ "doc": "of the tensor components (a random walk held within it)",
90
+ },
91
+ "volumetric": {
92
+ "kind": "float",
93
+ "label": "volumetric ratio",
94
+ "doc": "of the volumetric strains: 0.2 for metals (elastic, small volume "
95
+ "changes), 1 for porous media",
96
+ },
97
+ "kind": {
98
+ "kind": "choice",
99
+ "label": "paths",
100
+ "choices": (
101
+ ("walk", "random walks: each strain the previous one plus a random step"),
102
+ ("linear", "independent strains: each component uniform"),
103
+ ),
104
+ },
105
+ "components": {
106
+ "kind": "choices",
107
+ "default": list(COMPONENTS),
108
+ "label": "components driven",
109
+ "choices": COMPONENTS,
110
+ "doc": "the others held at zero strain, or free; a learned law runs the paths "
111
+ "of the components of its data only",
112
+ },
113
+ "free": {
114
+ "kind": "bool",
115
+ "label": "the others free",
116
+ "doc": "the components not driven at zero stress, rather than at zero strain "
117
+ "(a tension-torsion test drives 11 and 12)",
118
+ },
119
+ "rate": {
120
+ "kind": "float",
121
+ "label": "strain rate",
122
+ "unit": "1/time",
123
+ "doc": "the largest rate of a component on each segment (blank: a unit time "
124
+ "each); rate-dependent behaviours",
125
+ },
126
+ "seed": {"kind": "int", "label": "seed of the paths"},
127
+ "validation": {
128
+ "kind": "float",
129
+ "label": "validation fraction",
130
+ "doc": "the paths of the early stopping and of the errors, kept out of the training",
131
+ },
132
+ },
133
+ )
134
+ #: The fields of the model (the section ``model``)
135
+ MODEL_FIELDS = _fields(
136
+ MODEL,
137
+ {
138
+ "kind": {"name": "model", "kind": "choice", "choices": MODELS},
139
+ "hidden": {
140
+ "kind": "ints",
141
+ "label": "hidden sizes",
142
+ "doc": "the size of the state of a recurrent network, the ridges of the free "
143
+ "energy of a standard model, or the hidden layers of the others (blank: 32; 32, "
144
+ "32)",
145
+ },
146
+ "rate": {
147
+ "name": "model_rate",
148
+ "kind": "bool",
149
+ "label": "time step as an input",
150
+ "when": {"model": ["recurrent", "standard"]},
151
+ "doc": "rate-dependent behaviours (viscoplasticity; a viscous dissipation of a "
152
+ "standard model)",
153
+ },
154
+ "internal": {
155
+ "kind": "int",
156
+ "label": "internal variables",
157
+ "when": {"model": "standard"},
158
+ "doc": "of a standard model (blank: 8)",
159
+ },
160
+ "strain": {
161
+ "name": "energy_strain",
162
+ "kind": "choice",
163
+ "default": "logarithmic",
164
+ "label": "strain of the law",
165
+ "when": {"kinematics": "finite"},
166
+ "choices": (
167
+ (
168
+ "logarithmic",
169
+ "logarithmic: ½ ln C and its conjugate stress T, S = Jᵀ T, as the Hencky "
170
+ "points (plasticity, Hencky's elasticity)",
171
+ ),
172
+ ("green-lagrange", "Green-Lagrange: E and the second Piola-Kirchhoff stress"),
173
+ ),
174
+ "doc": "in finite strains, the strain the model sees: the input of a perceptron or "
175
+ "of a recurrent network (its increments), the strain of a potential or of the free "
176
+ "energy of a standard model (its internal variables additive in it)",
177
+ },
178
+ "seed": {"name": "model_seed", "kind": "int", "label": "seed of the parameters"},
179
+ },
180
+ )
181
+ #: The fields of the training (the section ``training``)
182
+ TRAINING_FIELDS = _fields(
183
+ TRAINING,
184
+ {
185
+ "epochs": {"kind": "int"},
186
+ "batch": {
187
+ "kind": "int",
188
+ "label": "mini-batch",
189
+ "doc": "paths of a recurrent model, points of the others",
190
+ },
191
+ "learning_rate": {"kind": "float", "label": "learning rate", "doc": "of Adam"},
192
+ "final": {
193
+ "kind": "float",
194
+ "label": "final rate",
195
+ "doc": "a fraction of the first, reached geometrically at the last epoch",
196
+ },
197
+ "patience": {
198
+ "kind": "int",
199
+ "doc": "epochs without a better validation loss before it stops (blank: all)",
200
+ },
201
+ "clip": {"kind": "float", "label": "gradient clipping", "doc": "its global norm"},
202
+ "rotate": {
203
+ "kind": "choice",
204
+ "default": "false",
205
+ "label": "random rotations",
206
+ "choices": (
207
+ ("false", "none"),
208
+ ("true", "uniform: an isotropic behaviour, data of every direction"),
209
+ ("cubic", "of the cube: a cubic crystal in its axes (24 rotations)"),
210
+ ),
211
+ "doc": "each mini-batch turned at each epoch by symmetries of the behaviour: "
212
+ "data without more responses",
213
+ },
214
+ "seed": {"name": "training_seed", "kind": "int", "label": "seed of the shuffles"},
215
+ },
216
+ )
217
+
218
+
219
+ @tool(
220
+ "learn",
221
+ "learning",
222
+ "Learn a behaviour",
223
+ "A behaviour learned from data: the responses of a behaviour at a material point, or "
224
+ "the homogenized responses of a morphology (FFT on its voxels), along random strain "
225
+ "paths, then a network trained on them in the background (Adam, early stopping on the "
226
+ "validation paths; its losses reported at each epoch). Its learning curves, its errors "
227
+ "on the validation paths and its law at a material point along a validation path "
228
+ "against the reference; the model saved (learned.npz, with the data and the "
229
+ "configuration that learns it again), and the learned law joins the workspace (B): the "
230
+ "loading paths of morphologies give it to a phase (a behaviour of the workspace).",
231
+ [
232
+ Field(
233
+ "data",
234
+ "choice",
235
+ "point",
236
+ label="data of",
237
+ choices=(
238
+ ("point", "a behaviour at a material point"),
239
+ ("morphology", "a morphology: its homogenized responses (FFT on its voxels)"),
240
+ ),
241
+ ),
242
+ Field("source", "item", label="morphology", required=True, when=MORPHOLOGY),
243
+ Field(
244
+ "materials",
245
+ "materials",
246
+ of="source",
247
+ when=MORPHOLOGY,
248
+ doc="elastic constants of the phases (the unit of the stresses), or voids",
249
+ ),
250
+ Field(
251
+ "phase",
252
+ "int",
253
+ label="phase of the behaviour",
254
+ when=MORPHOLOGY,
255
+ doc="blank: the first phase that is not a void",
256
+ ),
257
+ Field("young", "float", 1.0, label="Young's modulus E", unit="stress", when=POINT),
258
+ Field("poisson", "float", 0.3, label="Poisson's ratio ν", when=POINT),
259
+ *_behaviour_fields("learned: at the point, or that phase of the morphology"),
260
+ Field(
261
+ "material",
262
+ "text",
263
+ label="material of the configurations (JSON)",
264
+ when=POINT,
265
+ doc='replaces the behaviour of the form: e.g. {"young": 1, "poisson": 0.3, '
266
+ '"plasticity": {"yield": 0.002, "hardening": 0.05}}',
267
+ ),
268
+ replace(BEHAVIOURS_FIELD, when=MORPHOLOGY),
269
+ Field("voxels", "int", 8, label="voxels per edge", when=MORPHOLOGY),
270
+ Field(
271
+ "integration",
272
+ "choice",
273
+ "bbar",
274
+ when=MORPHOLOGY,
275
+ choices=(
276
+ ("bbar", "B-bar (F-bar in finite strains): no locking under plastic flow"),
277
+ ("full", "full: 8 Gauss points per voxel"),
278
+ ),
279
+ ),
280
+ Field(
281
+ "kinematics",
282
+ "choice",
283
+ "small",
284
+ choices=(
285
+ ("small", "small strains"),
286
+ (
287
+ "finite",
288
+ "finite strains: the Green-Lagrange strain, the second Piola-Kirchhoff stress",
289
+ ),
290
+ ),
291
+ ),
292
+ *PATH_FIELDS,
293
+ *MODEL_FIELDS,
294
+ *TRAINING_FIELDS,
295
+ *_path_fields("cycle", prefix="check_"),
296
+ Field(
297
+ "check_orientation",
298
+ "floats",
299
+ label="orientation of the validation point",
300
+ unit="degrees",
301
+ when=POINT,
302
+ doc="Bunge angles φ1, Φ, φ2: the behaviour and its learned law turned by them "
303
+ "(a crystal learned in its axes, checked in another frame); blank: the axes of "
304
+ "the data",
305
+ ),
306
+ ],
307
+ order=1,
308
+ groups=(
309
+ ("Data", "data"),
310
+ ("Behaviour", "behaviour"),
311
+ ("Solver", "voxels"),
312
+ ("Random paths", "paths"),
313
+ ("Model", "model"),
314
+ ("Training", "epochs", True),
315
+ ("Validation path", "check_loading"),
316
+ ),
317
+ )
318
+ def learn_behaviour(p: dict, ctx) -> dict:
319
+ from morphogen.gui.api import behaviour_summary
320
+ from morphogen.homogenization.paths import LoadingPath
321
+ from morphogen.learning import (
322
+ errors,
323
+ generate,
324
+ learned_material,
325
+ random_paths,
326
+ responder,
327
+ train,
328
+ )
329
+ from morphogen.learning.run import compare_path, reference_elasticity
330
+
331
+ kinematics = p["kinematics"]
332
+ name, check = _path(p, "check_")
333
+ check = LoadingPath.from_spec(check)
334
+ orientation = p.get("check_orientation") or None
335
+ if orientation is not None and len(orientation) != 3:
336
+ raise ValueError("orientation of the validation point: three Bunge angles φ1, Φ, φ2")
337
+ rotate = ROTATIONS[p["rotate"]]
338
+ respond, source, sample, origin = _source(p, ctx, kinematics, len(check.schedule()))
339
+ options = {k: p[k] for k in ("segments", "increments", "amplitude", "volumetric", "kind")}
340
+ options.update(components=p["components"] or None, free=bool(p["free"]), rate=p["rate"],
341
+ seed=p["seed"]) # fmt: skip
342
+ if not 0.0 < p["validation"] < 1.0 or p["paths"] < 2:
343
+ raise ValueError("validation fraction: between 0 and 1, of two paths at least")
344
+ paths = random_paths(p["paths"], **options)
345
+ model = _model(p)
346
+ info = {"source": source, "kinematics": kinematics, "paths": {"count": p["paths"], **options}}
347
+
348
+ def generated(done, total):
349
+ ctx.progress(0.02 + 0.38 * done / total, f"data: path {done} of {total}")
350
+
351
+ started = time.perf_counter()
352
+ data = generate(respond, paths, kinematics=kinematics, info=info, callback=generated)
353
+ data_s = time.perf_counter() - started
354
+ train_set, valid = data.split(p["validation"], seed=p["seed"])
355
+ epochs = p["epochs"]
356
+
357
+ def trained(epoch, loss, check_loss):
358
+ ctx.progress(0.4 + 0.55 * (epoch + 1) / epochs,
359
+ f"epoch {epoch + 1} of {epochs}: loss {loss:.3g}, validation "
360
+ f"{check_loss:.3g}") # fmt: skip
361
+
362
+ model.metadata["data"] = info
363
+ fit = train(model, train_set, valid, epochs=epochs, batch=p["batch"],
364
+ learning_rate=p["learning_rate"], final=p["final"], patience=p["patience"],
365
+ clip=p["clip"], rotate=rotate, seed=p["training_seed"],
366
+ callback=trained) # fmt: skip
367
+ scores = errors(model, valid)
368
+ model.metadata["validation"] = {k: v for k, v in scores.items() if k != "paths"}
369
+ path = model.save(ctx.folder / "learned.npz")
370
+ data.save(ctx.folder / "data.npz")
371
+ ctx.progress(0.96, f"validation path {name}")
372
+ elastic = reference_elasticity(source) if p["data"] == "point" else {}
373
+ material = learned_material(model, **elastic)
374
+ if orientation is not None: # the behaviour at the point turned with its law
375
+ respond = responder(source, kinematics, orientation)
376
+ ref, got, gaps = compare_path(material, respond, check, kinematics, orientation)
377
+ ctx.figure(_curves_figure(fit), "learning_curves", "learning curves")
378
+ ctx.figure(_check_figure(ref, got, f"validation path {name}"), "validation_path",
379
+ f"validation path {name}: the learned law against the reference") # fmt: skip
380
+ ctx.table([{"epoch": k + 1, "training loss": a, "validation loss": b} for k, (a, b) in
381
+ enumerate(zip(fit.train_loss, fit.validation_loss, strict=True))],
382
+ "learning_curves", "learning curves") # fmt: skip
383
+ ctx.table([{"path": k + 1, "relative error": e} for k, e in enumerate(scores["paths"])],
384
+ "validation_paths", "errors of the validation paths") # fmt: skip
385
+ ctx.table(ref.rows(), f"reference_{name}", f"reference along the path {name}")
386
+ _elastic_comparison(ctx, model, source if p["data"] == "point" else None)
387
+ if got is not None:
388
+ ctx.table(got.rows(), f"learned_{name}", f"learned law along the path {name}")
389
+ else:
390
+ import warnings
391
+
392
+ warnings.warn(f"the learned law along the path {name}: {gaps['failed']}", stacklevel=1)
393
+ # the behaviour of the workspace: the model by its name in the folder of the run
394
+ config = material.to_config()
395
+ config["learned"] = {**config["learned"], "model": path.name}
396
+ (ctx.folder / "material.json").write_text(json.dumps(config, indent=1), encoding="utf-8")
397
+ _configuration(p, ctx, source, sample, options, name, check)
398
+ label, details = behaviour_summary(config)
399
+ details.update(model=model.kind, data=data.measure, validation=round(scores["relative"], 4))
400
+ item = ctx.session.add(ctx.key, "behaviour", f"{label} ({model.kind}) of {origin}",
401
+ material=config, info=details) # fmt: skip
402
+ values = {
403
+ "paths": data.n_paths,
404
+ "points per path": data.n_points,
405
+ "epochs": fit.epochs,
406
+ "best epoch": fit.best_epoch + 1,
407
+ "training loss": fit.train_loss[fit.best_epoch],
408
+ "validation loss": fit.best_loss,
409
+ "validation error": scores["relative"],
410
+ "validation error, worst path": scores["max"],
411
+ f"stress gap along {name}": gaps["stress"],
412
+ f"strain gap along {name}": gaps["strain"],
413
+ "data_s": round(data_s, 2),
414
+ "training_s": round(fit.time_s, 2),
415
+ "young": material.young,
416
+ "poisson": material.poisson,
417
+ }
418
+ return {"values": values, "items": [ctx.session.public(item)]}
419
+
420
+
421
+ def _elastic_comparison(ctx, model, reference) -> None:
422
+ """The elasticity of the learned law, its tangent at the natural state (stiffness and
423
+ compliance, ``tangent_stiffness.csv`` and ``tangent_compliance.csv``), beside that of
424
+ the reference material of a material point (``reference_stiffness.csv``...; none for
425
+ a morphology, or a law without elastic constants of its own)."""
426
+ from morphogen.homogenization.materials import Material
427
+ from morphogen.learning.behaviour import initial_tangent
428
+
429
+ names = ("tangent_stiffness", "tangent_compliance")
430
+ try:
431
+ elastic_tables(ctx, initial_tangent(model), "of the learned law at the natural state",
432
+ names=names, kind="tangent") # fmt: skip
433
+ except np.linalg.LinAlgError: # a learned law without a stiffness at the natural state
434
+ pass
435
+ try:
436
+ material = Material.from_config(reference) if reference is not None else None
437
+ except (ValueError, TypeError, KeyError, OSError):
438
+ material = None
439
+ if material is not None and material.elastic:
440
+ elastic_tables(ctx, material.matrix("elastic"), "of the reference",
441
+ names=("reference_stiffness", "reference_compliance")) # fmt: skip
442
+
443
+
444
+ def _source(p: dict, ctx, kinematics: str, steps: int):
445
+ """The response to a path of the source of the form (``respond``), its description
446
+ (the material of a material point, or the morphology and its materials), the voxel
447
+ image of a morphology (None at a material point, or when its grains are turned) and
448
+ the name of the source in the title of the learned law."""
449
+ from morphogen.gui.api import behaviour_summary
450
+ from morphogen.homogenization.materials import Material
451
+ from morphogen.learning import responder
452
+
453
+ if p["data"] == "point":
454
+ spec = _json(p.get("material"), "material of the configurations")
455
+ kept = p["kept"] if spec is None and p["behaviour"] == "workspace" else None
456
+ if spec is None:
457
+ spec = _behaviour(p, {"young": p["young"], "poisson": p["poisson"]}, ctx.folder)
458
+ Material.from_config(spec) # checked
459
+ origin = kept["title"] if kept else behaviour_summary(spec)[0]
460
+ return responder(spec, kinematics), spec, None, origin
461
+ from morphogen.homogenization import materials_from_config
462
+ from morphogen.homogenization.fft_nonlinear import NonlinearFFTProblem
463
+ from morphogen.homogenization.materials import any_oriented
464
+
465
+ item = p["source"]
466
+ micro = item["micro"]
467
+ materials, phase = _materials(p, item, ctx.folder)
468
+ n = p["voxels"]
469
+ if not 4 <= n <= 64:
470
+ raise ValueError("voxels per edge: from 4 to 64 for the data of a learned law")
471
+ _check_voxels(micro, n, steps, "learning on voxels")
472
+ image = micro.voxelize(shape=n)
473
+ mats = materials_from_config(materials)
474
+ grains = {}
475
+ if any_oriented(mats) and getattr(micro, "orientations", None) is not None:
476
+ grains = {"grains": micro.labels(grid=image.grid()), "orientations": micro.orientations}
477
+ problem = NonlinearFFTProblem(image, mats, "periodic", kinematics=kinematics,
478
+ integration=p["integration"], **grains) # fmt: skip
479
+ source = {"morphology": item["title"], "phase": phase, "voxels": n,
480
+ "materials": {str(k): v for k, v in materials.items()}} # fmt: skip
481
+ return problem.run, source, None if grains else image, f"#{item['number']}"
482
+
483
+
484
+ def _model(p: dict):
485
+ """The model of the form (:func:`~morphogen.learning.make_model`)."""
486
+ from morphogen.learning import make_model
487
+
488
+ options = {"seed": p["model_seed"]}
489
+ if p.get("energy_strain"): # in finite strains
490
+ options["strain"] = p["energy_strain"]
491
+ hidden = p.get("hidden")
492
+ if p["model"] in ("recurrent", "standard"):
493
+ options["rate"] = bool(p.get("model_rate"))
494
+ if p["model"] == "standard" and p.get("internal"):
495
+ options["internal"] = p["internal"]
496
+ if hidden:
497
+ if len(hidden) != 1:
498
+ raise ValueError("hidden sizes: one, the size of the state of a recurrent "
499
+ "network or the ridges of a standard model") # fmt: skip
500
+ options["hidden"] = hidden[0]
501
+ elif hidden:
502
+ options["hidden"] = list(hidden)
503
+ return make_model(p["model"], **options)
504
+
505
+
506
+ def _curves_figure(fit):
507
+ """The losses of the training and validation sets at each epoch, the best one marked."""
508
+ from matplotlib.figure import Figure
509
+
510
+ fig = Figure(figsize=(5.4, 3.8), layout="constrained")
511
+ ax = fig.subplots()
512
+ epochs = np.arange(1, fit.epochs + 1)
513
+ ax.semilogy(epochs, fit.train_loss, "-", lw=1.6, color=SHADES[1], label="training paths")
514
+ ax.semilogy(epochs, fit.validation_loss, "-", lw=1.6, color=SHADES[0],
515
+ label="validation paths") # fmt: skip
516
+ best = fit.best_epoch + 1
517
+ ax.axvline(best, color="0.5", ls=":", lw=1.0)
518
+ ax.plot([best], [fit.best_loss], "o", color=SHADES[0], ms=5,
519
+ label=f"kept: epoch {best}, {fit.best_loss:.3g}") # fmt: skip
520
+ ax.set_xlabel("epoch")
521
+ ax.set_ylabel("mean square of the normalized stress gaps")
522
+ ax.set_title(f"training of the {fit.model.kind} model", fontsize=10)
523
+ ax.grid(alpha=0.3, which="both")
524
+ ax.legend(fontsize=8, frameon=False)
525
+ return fig
526
+
527
+
528
+ def _check_figure(ref, got, title: str):
529
+ """The learned law (dashed) against the reference (solid) along a path: the stress of
530
+ the strain that varies most, and the stresses that vary against time."""
531
+ from matplotlib.figure import Figure
532
+
533
+ from morphogen.gui.tools.mechanics import _driven
534
+
535
+ fig = Figure(figsize=(9.6, 3.8), layout="constrained")
536
+ ax, ax2 = fig.subplots(1, 2)
537
+ strain, stress, e_name, s_name, i = _driven(ref)
538
+ j = int(np.argmax(np.ptp(stress, axis=0)))
539
+ ax.plot(strain[:, i], stress[:, j], "k-", lw=1.8, marker=".", ms=4, label="reference")
540
+ ptp = np.ptp(stress, axis=0)
541
+ shown = [c for c in range(6) if ptp[c] > 0.05 * ptp.max()]
542
+ for k, c in enumerate(shown):
543
+ shade = SHADES[k % len(SHADES)]
544
+ label = f"{s_name}{COMPONENTS[c]}"
545
+ ax2.plot(ref.times, stress[:, c], "-", lw=1.8, color=shade, label=label)
546
+ if got is not None:
547
+ e2, s2, *_ = _driven(got)
548
+ ax.plot(e2[:, i], s2[:, j], "--", color=SHADES[0], lw=1.8, label="learned law")
549
+ for k, c in enumerate(shown):
550
+ ax2.plot(got.times, s2[:, c], "--", lw=1.4, color=SHADES[k % len(SHADES)])
551
+ ax.set_xlabel(e_name + COMPONENTS[i])
552
+ ax.set_ylabel(s_name + COMPONENTS[j])
553
+ ax.locator_params(axis="x", nbins=5)
554
+ ax2.set_xlabel("time")
555
+ ax2.set_ylabel("stress (solid: reference, dashed: learned)")
556
+ for a in (ax, ax2):
557
+ a.grid(alpha=0.3)
558
+ a.legend(fontsize=8, frameon=False)
559
+ fig.suptitle(title + ("" if got is not None else ": the learned law failed"), fontsize=10)
560
+ return fig
561
+
562
+
563
+ def _configuration(p: dict, ctx, source, sample, options: dict, name: str, check) -> None:
564
+ """The configuration of ``morphogen learn`` that learns the law again (beside the files
565
+ it names): at a material point, or on the voxel image of a morphology (not of turned
566
+ grains)."""
567
+ import yaml
568
+
569
+ from morphogen import io
570
+
571
+ cfg: dict = {}
572
+ if p["data"] == "point":
573
+ cfg["material"] = source
574
+ elif sample is not None:
575
+ io.save_image(sample, ctx.folder / "sample.vti")
576
+ cfg.update(sample="sample.vti", materials=source["materials"], bc="periodic")
577
+ else:
578
+ return
579
+ model = {"kind": p["model"], "hidden": p.get("hidden") or None, "seed": p["model_seed"]}
580
+ if p["model"] in ("recurrent", "standard"):
581
+ model["rate"] = bool(p.get("model_rate"))
582
+ if model["hidden"]:
583
+ model["hidden"] = model["hidden"][0]
584
+ if p["model"] == "standard" and p.get("internal"):
585
+ model["internal"] = p["internal"]
586
+ if p.get("energy_strain"):
587
+ model["strain"] = p["energy_strain"]
588
+ training = {k: p[k] for k in ("epochs", "batch", "learning_rate", "final", "patience", "clip")}
589
+ training.update(rotate=ROTATIONS[p["rotate"]], seed=p["training_seed"])
590
+ cfg.update(kinematics=p["kinematics"],
591
+ data={"paths": p["paths"], **options, "validation": p["validation"]},
592
+ model=model, training=training, paths={name: check.to_dict()},
593
+ output="learned.npz", save_data="data.npz") # fmt: skip
594
+ text = yaml.safe_dump({"learning": json.loads(json.dumps(cfg))}, sort_keys=False)
595
+ (ctx.folder / "learning.yaml").write_text(text, encoding="utf-8")