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,336 @@
1
+ """Tile sets for combinatorial design: cubic building blocks with labelled faces.
2
+
3
+ A tile is a cubic block of ``k^3`` voxels (its geometry) whose six faces carry integer
4
+ labels. Two tiles can be neighbours along an axis when the labels of the faces in
5
+ contact match: equal labels (``match="equal"``, Wang tiles), or opposite labels
6
+ (``match="opposite"``: a face that moves out against a face that moves in). An
7
+ assembly is an array of tile indices; it is compatible when every pair of neighbouring
8
+ tiles matches. Faces are numbered ``-x, +x, -y, +y, -z, +z`` (face ``2 a`` is the lower
9
+ face along axis ``a``, ``2 a + 1`` the upper one). Planar tile sets (``dims=2``) ignore
10
+ the z faces: their assemblies have one tile through the thickness.
11
+
12
+ Built-in sets:
13
+
14
+ ``polarized_blocks``
15
+ The building blocks of combinatorial mechanical metamaterials (after Coulais et al.
16
+ 2016): each block has a single deformation mode in which it elongates along its axis
17
+ and shrinks along the two others, or the reverse. Its faces move out or in
18
+ accordingly; neighbouring blocks are compatible when their common face moves the
19
+ same way (out of one block, into the other). Six tiles: three axes, two signs.
20
+ ``pipe_tiles``
21
+ Nodes with channels (or struts) towards some of their faces; compatible
22
+ assemblies are networks without dead ends at the tile boundaries, with controlled
23
+ node degrees.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import itertools
29
+ from dataclasses import dataclass, field
30
+
31
+ import numpy as np
32
+
33
+ FACES = ("-x", "+x", "-y", "+y", "-z", "+z")
34
+ MATCHES = ("equal", "opposite")
35
+
36
+
37
+ def _signed_permutations(dims: int) -> list[np.ndarray]:
38
+ """Proper rotations of the cube (24), or the 4 rotations about z (dims=2), as
39
+ signed permutation matrices."""
40
+ out = []
41
+ for perm in itertools.permutations(range(3)):
42
+ for signs in itertools.product((1, -1), repeat=3):
43
+ m = np.zeros((3, 3), dtype=int)
44
+ for j in range(3):
45
+ m[j, perm[j]] = signs[j]
46
+ if round(np.linalg.det(m)) != 1:
47
+ continue
48
+ if dims == 2 and m[2, 2] != 1:
49
+ continue
50
+ out.append(m)
51
+ return out
52
+
53
+
54
+ def _rotate_faces(faces: np.ndarray, m: np.ndarray) -> np.ndarray:
55
+ """Face labels after the rotation m: the face of direction m e carries the label of
56
+ the face of direction e."""
57
+ out = np.empty_like(faces)
58
+ for a in range(3):
59
+ j = int(np.flatnonzero(m[:, a])[0])
60
+ s = int(m[j, a])
61
+ for side in (0, 1): # 0: lower (-), 1: upper (+)
62
+ sigma = -1 if side == 0 else 1
63
+ new_side = 0 if sigma * s < 0 else 1
64
+ out[..., 2 * j + new_side] = faces[..., 2 * a + side]
65
+ return out
66
+
67
+
68
+ def _rotate_block(block: np.ndarray, m: np.ndarray) -> np.ndarray:
69
+ """Voxels of a block after the rotation m (about the centre of the block)."""
70
+ perm = [int(np.flatnonzero(m[j])[0]) for j in range(3)]
71
+ out = np.transpose(block, perm)
72
+ for j in range(3):
73
+ if m[j, perm[j]] < 0:
74
+ out = np.flip(out, axis=j)
75
+ return np.ascontiguousarray(out)
76
+
77
+
78
+ @dataclass
79
+ class TileSet:
80
+ """Tiles with labelled faces, their geometry and their weights.
81
+
82
+ Parameters
83
+ ----------
84
+ faces
85
+ Integer labels ``(n, 6)`` of the faces ``-x, +x, -y, +y, -z, +z``.
86
+ match
87
+ ``equal`` or ``opposite``: rule for the labels of faces in contact.
88
+ voxels
89
+ Optional geometry ``(n, k, k, k)`` (``(n, k, k, 1)`` for planar sets): phase of
90
+ each voxel of each tile.
91
+ weights
92
+ Relative frequencies of the tiles in random choices (default: equal).
93
+ names
94
+ Tile names.
95
+ dims
96
+ 3, or 2 for planar tile sets (z faces ignored).
97
+ """
98
+
99
+ faces: np.ndarray
100
+ match: str = "equal"
101
+ voxels: np.ndarray | None = None
102
+ weights: np.ndarray | None = None
103
+ names: tuple[str, ...] | None = None
104
+ dims: int = 3
105
+ _compat: np.ndarray | None = field(default=None, init=False, repr=False)
106
+
107
+ def __post_init__(self) -> None:
108
+ self.faces = np.asarray(self.faces, dtype=np.int64).reshape(-1, 6)
109
+ n = len(self.faces)
110
+ if n < 1:
111
+ raise ValueError("a tile set needs at least one tile")
112
+ if self.match not in MATCHES:
113
+ raise ValueError(f"match: one of {MATCHES}, got {self.match!r}")
114
+ if self.dims not in (2, 3):
115
+ raise ValueError("dims: 2 or 3")
116
+ if self.voxels is not None:
117
+ self.voxels = np.ascontiguousarray(self.voxels, dtype=np.uint8)
118
+ if self.voxels.ndim != 4 or len(self.voxels) != n:
119
+ raise ValueError("voxels: an array (n_tiles, k, k, k)")
120
+ k = self.voxels.shape[1]
121
+ expected = (k, k, 1) if self.dims == 2 else (k, k, k)
122
+ if self.voxels.shape[1:] != expected:
123
+ raise ValueError(f"voxels: blocks of shape {expected}")
124
+ w = np.ones(n) if self.weights is None else np.asarray(self.weights, dtype=float)
125
+ if w.shape != (n,) or np.any(w < 0) or not np.any(w > 0):
126
+ raise ValueError("weights: one non-negative weight per tile, not all zero")
127
+ self.weights = w
128
+ if self.names is None:
129
+ self.names = tuple(f"t{i}" for i in range(n))
130
+ self.names = tuple(str(s) for s in self.names)
131
+ if len(self.names) != n:
132
+ raise ValueError("names: one per tile")
133
+
134
+ @property
135
+ def n_tiles(self) -> int:
136
+ return len(self.faces)
137
+
138
+ @property
139
+ def tile_size(self) -> int | None:
140
+ """Voxels per tile edge (None without geometry)."""
141
+ return None if self.voxels is None else int(self.voxels.shape[1])
142
+
143
+ def label_matches(self, upper, lower):
144
+ """Whether an upper face label (of the lower tile) matches a lower face label."""
145
+ upper = np.asarray(upper)
146
+ lower = np.asarray(lower)
147
+ return upper == lower if self.match == "equal" else upper == -lower
148
+
149
+ def compatibility(self) -> np.ndarray:
150
+ """Boolean array ``(3, n, n)``: ``[a, A, B]`` when tile B may follow tile A along
151
+ axis a (planar sets: every pair along z)."""
152
+ if self._compat is None:
153
+ n = self.n_tiles
154
+ c = np.ones((3, n, n), dtype=bool)
155
+ for a in range(self.dims):
156
+ c[a] = self.label_matches(
157
+ self.faces[:, None, 2 * a + 1], self.faces[None, :, 2 * a]
158
+ )
159
+ self._compat = c
160
+ return self._compat
161
+
162
+ def boundary_tiles(self, axis: int, side: int, label: int) -> np.ndarray:
163
+ """Tiles whose face (axis, side) matches a boundary of the given label."""
164
+ face = self.faces[:, 2 * axis + side]
165
+ if side == 1:
166
+ return self.label_matches(face, label)
167
+ return self.label_matches(label, face)
168
+
169
+ def mismatches(self, assembly, periodic: bool = True) -> int:
170
+ """Number of incompatible pairs of neighbouring tiles."""
171
+ t = np.asarray(assembly, dtype=np.int64)
172
+ if t.ndim != 3:
173
+ raise ValueError("assembly: a 3D array of tile indices ((n0, n1, 1) in 2D)")
174
+ compat = self.compatibility()
175
+ bad = 0
176
+ for a in range(self.dims):
177
+ if t.shape[a] < 2 and not periodic:
178
+ continue
179
+ if periodic:
180
+ nxt = np.roll(t, -1, axis=a)
181
+ bad += int(np.count_nonzero(~compat[a][t, nxt]))
182
+ else:
183
+ lo = np.take(t, range(t.shape[a] - 1), axis=a)
184
+ hi = np.take(t, range(1, t.shape[a]), axis=a)
185
+ bad += int(np.count_nonzero(~compat[a][lo, hi]))
186
+ return bad
187
+
188
+ def is_compatible(self, assembly, periodic: bool = True) -> bool:
189
+ return self.mismatches(assembly, periodic) == 0
190
+
191
+ def assemble(self, assembly) -> np.ndarray:
192
+ """Voxels of an assembly: the blocks of its tiles side by side."""
193
+ if self.voxels is None:
194
+ raise ValueError("this tile set has no geometry (voxels)")
195
+ t = np.asarray(assembly, dtype=np.int64)
196
+ n0, n1, n2 = t.shape
197
+ blocks = self.voxels[t] # (n0, n1, n2, k0, k1, k2)
198
+ k0, k1, k2 = self.voxels.shape[1:]
199
+ return np.ascontiguousarray(
200
+ blocks.transpose(0, 3, 1, 4, 2, 5).reshape(n0 * k0, n1 * k1, n2 * k2)
201
+ )
202
+
203
+ def subset(self, keep) -> TileSet:
204
+ """The tiles selected by a boolean mask or an index list."""
205
+ idx = np.arange(self.n_tiles)[np.asarray(keep)]
206
+ if idx.size == 0:
207
+ raise ValueError("subset: no tile left")
208
+ return TileSet(
209
+ self.faces[idx],
210
+ self.match,
211
+ None if self.voxels is None else self.voxels[idx],
212
+ self.weights[idx],
213
+ tuple(self.names[i] for i in idx),
214
+ self.dims,
215
+ )
216
+
217
+ def with_rotations(self) -> TileSet:
218
+ """The set closed under the rotations of the cube (about z for planar sets),
219
+ without duplicates; rotated tiles keep the weight of their original."""
220
+ faces, voxels, weights, names = [], [], [], []
221
+ seen = set()
222
+ for i in range(self.n_tiles):
223
+ for r, m in enumerate(_signed_permutations(self.dims)):
224
+ f = _rotate_faces(self.faces[i], m)
225
+ v = None if self.voxels is None else _rotate_block(self.voxels[i], m)
226
+ key = (tuple(f), None if v is None else v.tobytes())
227
+ if key in seen:
228
+ continue
229
+ seen.add(key)
230
+ faces.append(f)
231
+ voxels.append(v)
232
+ weights.append(self.weights[i])
233
+ names.append(self.names[i] if r == 0 else f"{self.names[i]}/r{r}")
234
+ return TileSet(
235
+ np.array(faces),
236
+ self.match,
237
+ None if self.voxels is None else np.array(voxels),
238
+ np.array(weights),
239
+ tuple(names),
240
+ self.dims,
241
+ )
242
+
243
+
244
+ # -- built-in sets -------------------------------------------------------------------------
245
+
246
+
247
+ def _centred_coordinates(k: int, dims: int) -> np.ndarray:
248
+ """Coordinates of the voxel centres of a block, in units of the block edge, centred."""
249
+ c = (np.arange(k) + 0.5) / k - 0.5
250
+ kz = k if dims == 3 else 1
251
+ cz = c if dims == 3 else np.zeros(1)
252
+ return np.stack(np.meshgrid(c, c, cz, indexing="ij"), axis=-1).reshape(k, k, kz, 3)
253
+
254
+
255
+ def polarized_blocks(size: int = 8, channel: float = 0.25, dims: int = 3) -> TileSet:
256
+ """Blocks with one deformation mode: elongation along their axis and contraction
257
+ along the others (sign +), or the reverse (sign -).
258
+
259
+ The faces normal to the axis carry the sign of the mode, the others its opposite
260
+ (+1: the face moves out); faces in contact must move the same way, hence opposite
261
+ labels (``match="opposite"``). Along every line of blocks, the strain along the line
262
+ alternates in sign. The geometry is a solid block pierced along its axis by a
263
+ channel of radius ``channel`` (in block edges), which draws the orientation of the
264
+ block; replace it with the geometry of an actual building block if needed.
265
+ """
266
+ if not 0.0 <= channel < 0.5:
267
+ raise ValueError("channel: a radius in [0, 0.5) block edges")
268
+ axes = range(dims)
269
+ faces, voxels, names = [], [], []
270
+ x = _centred_coordinates(int(size), dims)
271
+ for a in axes:
272
+ r2 = sum(x[..., b] ** 2 for b in range(dims) if b != a)
273
+ block = (r2 > channel**2).astype(np.uint8)
274
+ for s in (1, -1):
275
+ f = np.empty(6, dtype=np.int64)
276
+ for b in range(3):
277
+ f[2 * b] = f[2 * b + 1] = s if b == a else -s
278
+ if dims == 2:
279
+ f[4] = f[5] = 0
280
+ faces.append(f)
281
+ voxels.append(block)
282
+ names.append(f"{'xyz'[a]}{'+' if s > 0 else '-'}")
283
+ return TileSet(np.array(faces), "opposite", np.array(voxels), None, tuple(names), dims)
284
+
285
+
286
+ def pipe_tiles(
287
+ size: int = 8,
288
+ radius: float = 0.2,
289
+ dims: int = 3,
290
+ *,
291
+ open_probability: float = 0.5,
292
+ degrees=None,
293
+ ) -> TileSet:
294
+ """Nodes joined to some of their faces by straight pipes (phase 1).
295
+
296
+ One tile per subset of open faces (64 in 3D, 16 in 2D); open faces carry the label
297
+ 1 and must face open faces (``match="equal"``). Each open face independently has
298
+ probability ``open_probability`` (tile weights ``p^m (1 - p)^(2 d - m)`` for ``m``
299
+ open faces); ``degrees`` restricts the numbers of open faces allowed (e.g. no 1 to
300
+ forbid dead ends).
301
+ """
302
+ if not 0.0 < radius < 0.5:
303
+ raise ValueError("radius: in (0, 0.5) block edges")
304
+ if not 0.0 < open_probability < 1.0:
305
+ raise ValueError("open_probability: in (0, 1)")
306
+ n_faces = 2 * dims
307
+ x = _centred_coordinates(int(size), dims)
308
+ faces, voxels, weights, names = [], [], [], []
309
+ for mask in range(2**n_faces):
310
+ open_faces = [f for f in range(n_faces) if mask >> f & 1]
311
+ m = len(open_faces)
312
+ if degrees is not None and m not in set(degrees):
313
+ continue
314
+ f = np.zeros(6, dtype=np.int64)
315
+ block = np.zeros(x.shape[:3], dtype=bool)
316
+ for face in open_faces:
317
+ f[face] = 1
318
+ a, side = divmod(face, 2)
319
+ sign = 1.0 if side else -1.0
320
+ along = x[..., a] * sign
321
+ r2 = sum(x[..., b] ** 2 for b in range(dims) if b != a)
322
+ block |= (along >= -radius) & (r2 <= radius**2)
323
+ if m:
324
+ block |= (x[..., :dims] ** 2).sum(axis=-1) <= radius**2
325
+ faces.append(f)
326
+ voxels.append(block.astype(np.uint8))
327
+ weights.append(open_probability**m * (1.0 - open_probability) ** (n_faces - m))
328
+ names.append("".join(FACES[i] for i in open_faces) or "empty")
329
+ if not faces:
330
+ raise ValueError("degrees: no tile left")
331
+ return TileSet(
332
+ np.array(faces), "equal", np.array(voxels), np.array(weights), tuple(names), dims
333
+ )
334
+
335
+
336
+ TILE_SETS = {"polarized": polarized_blocks, "pipes": pipe_tiles}
@@ -0,0 +1,312 @@
1
+ """Probability distributions of positive scalars (radii, lengths, weights...).
2
+
3
+ A distribution is given in configuration files either as a number (constant) or as a
4
+ mapping with a ``type`` key::
5
+
6
+ radius: 1.0
7
+ radius: {type: uniform, low: 0.5, high: 1.5}
8
+ radius: {type: lognormal, mean: 1.0, std: 0.3}
9
+ radius: {type: normal, mean: 20.0, std: 13.5} # truncated to positive values
10
+ radius: {type: discrete, values: [1.0, 2.0], weights: [0.7, 0.3]}
11
+
12
+ Unbounded distributions are truncated at their ``1 - 1e-9`` quantile so that every
13
+ model can bound the extent of its grains (needed to generate unbiased samples).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from abc import ABC, abstractmethod
20
+ from dataclasses import dataclass
21
+
22
+ import numpy as np
23
+ from scipy import stats
24
+
25
+ from morphogen._utils import check_positive
26
+
27
+ #: Quantile at which unbounded distributions are truncated.
28
+ TAIL_QUANTILE = 1.0 - 1e-9
29
+
30
+
31
+ class Distribution(ABC):
32
+ """Distribution of a positive random variable."""
33
+
34
+ kind: str = ""
35
+
36
+ @abstractmethod
37
+ def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
38
+ """Draw ``n`` values."""
39
+
40
+ @abstractmethod
41
+ def moment(self, k: int) -> float:
42
+ """Raw moment ``E[X**k]``."""
43
+
44
+ @abstractmethod
45
+ def upper(self) -> float:
46
+ """Largest value that can be drawn."""
47
+
48
+ @abstractmethod
49
+ def quadrature(self, n: int = 128) -> tuple[np.ndarray, np.ndarray]:
50
+ """Nodes and weights approximating ``E[f(X)]`` by ``sum(w * f(x))``."""
51
+
52
+ @abstractmethod
53
+ def to_config(self):
54
+ """Plain configuration value (number or mapping)."""
55
+
56
+ def mean(self) -> float:
57
+ return self.moment(1)
58
+
59
+ def std(self) -> float:
60
+ return math.sqrt(max(self.moment(2) - self.moment(1) ** 2, 0.0))
61
+
62
+ def median(self) -> float:
63
+ x, w = self.quadrature(257)
64
+ c = np.cumsum(w)
65
+ return float(x[np.searchsorted(c, 0.5 * c[-1])])
66
+
67
+ @property
68
+ def is_constant(self) -> bool:
69
+ return False
70
+
71
+ def expect(self, f, n: int = 128) -> float:
72
+ """``E[f(X)]`` for a vectorized function ``f``."""
73
+ x, w = self.quadrature(n)
74
+ return float(np.sum(w * f(x)))
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class Constant(Distribution):
79
+ value: float
80
+ kind = "constant"
81
+
82
+ def __post_init__(self) -> None:
83
+ object.__setattr__(self, "value", check_positive(self.value, "constant value"))
84
+
85
+ def sample(self, rng, n):
86
+ return np.full(int(n), self.value)
87
+
88
+ def moment(self, k):
89
+ return self.value**k
90
+
91
+ def upper(self):
92
+ return self.value
93
+
94
+ def quadrature(self, n=128):
95
+ return np.array([self.value]), np.array([1.0])
96
+
97
+ @property
98
+ def is_constant(self):
99
+ return True
100
+
101
+ def median(self):
102
+ return self.value
103
+
104
+ def to_config(self):
105
+ return self.value
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class Uniform(Distribution):
110
+ low: float
111
+ high: float
112
+ kind = "uniform"
113
+
114
+ def __post_init__(self) -> None:
115
+ lo = check_positive(self.low, "uniform.low", allow_zero=True)
116
+ hi = check_positive(self.high, "uniform.high")
117
+ if not hi > lo:
118
+ raise ValueError(f"uniform: high must exceed low, got low={lo}, high={hi}")
119
+ object.__setattr__(self, "low", lo)
120
+ object.__setattr__(self, "high", hi)
121
+
122
+ def sample(self, rng, n):
123
+ return rng.uniform(self.low, self.high, int(n))
124
+
125
+ def moment(self, k):
126
+ a, b = self.low, self.high
127
+ return (b ** (k + 1) - a ** (k + 1)) / ((k + 1) * (b - a))
128
+
129
+ def upper(self):
130
+ return self.high
131
+
132
+ def quadrature(self, n=128):
133
+ x, w = np.polynomial.legendre.leggauss(n)
134
+ return self.low + (x + 1) * 0.5 * (self.high - self.low), 0.5 * w
135
+
136
+ def to_config(self):
137
+ return {"type": "uniform", "low": self.low, "high": self.high}
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class LogNormal(Distribution):
142
+ """Log-normal distribution given by the mean and standard deviation of X itself."""
143
+
144
+ mean_value: float
145
+ std_value: float
146
+ kind = "lognormal"
147
+
148
+ def __post_init__(self) -> None:
149
+ m = check_positive(self.mean_value, "lognormal.mean")
150
+ s = check_positive(self.std_value, "lognormal.std")
151
+ object.__setattr__(self, "mean_value", m)
152
+ object.__setattr__(self, "std_value", s)
153
+
154
+ @property
155
+ def sigma(self) -> float:
156
+ return math.sqrt(math.log1p((self.std_value / self.mean_value) ** 2))
157
+
158
+ @property
159
+ def mu(self) -> float:
160
+ return math.log(self.mean_value) - 0.5 * self.sigma**2
161
+
162
+ @property
163
+ def _frozen(self):
164
+ return stats.lognorm(s=self.sigma, scale=math.exp(self.mu))
165
+
166
+ def sample(self, rng, n):
167
+ x = rng.lognormal(self.mu, self.sigma, int(n))
168
+ return np.minimum(x, self.upper())
169
+
170
+ def moment(self, k):
171
+ return math.exp(k * self.mu + 0.5 * k * k * self.sigma**2)
172
+
173
+ def upper(self):
174
+ return float(self._frozen.ppf(TAIL_QUANTILE))
175
+
176
+ def quadrature(self, n=128):
177
+ u = (np.arange(n) + 0.5) / n
178
+ return self._frozen.ppf(u), np.full(n, 1.0 / n)
179
+
180
+ def to_config(self):
181
+ return {"type": "lognormal", "mean": self.mean_value, "std": self.std_value}
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class TruncatedNormal(Distribution):
186
+ """Normal distribution N(mean, std) truncated to ``[low, high]`` (default: positive)."""
187
+
188
+ loc: float
189
+ scale: float
190
+ low: float = 0.0
191
+ high: float = math.inf
192
+ kind = "normal"
193
+
194
+ def __post_init__(self) -> None:
195
+ object.__setattr__(self, "loc", float(self.loc))
196
+ object.__setattr__(self, "scale", check_positive(self.scale, "normal.std"))
197
+ object.__setattr__(self, "low", check_positive(self.low, "normal.low", allow_zero=True))
198
+ object.__setattr__(self, "high", float(self.high))
199
+ if not self.high > self.low:
200
+ raise ValueError("normal: high must exceed low")
201
+ if not (self.low < self.loc + 8 * self.scale and self.high > self.loc - 8 * self.scale):
202
+ raise ValueError("normal: the truncation interval has negligible probability")
203
+
204
+ @property
205
+ def _frozen(self):
206
+ a = (self.low - self.loc) / self.scale
207
+ b = (self.high - self.loc) / self.scale
208
+ return stats.truncnorm(a, b, loc=self.loc, scale=self.scale)
209
+
210
+ def sample(self, rng, n):
211
+ x = self._frozen.rvs(size=int(n), random_state=rng)
212
+ return np.minimum(np.atleast_1d(x).astype(float), self.upper())
213
+
214
+ def moment(self, k):
215
+ return float(self._frozen.moment(k))
216
+
217
+ def upper(self):
218
+ if math.isfinite(self.high):
219
+ return float(self.high)
220
+ return float(self._frozen.ppf(TAIL_QUANTILE))
221
+
222
+ def quadrature(self, n=128):
223
+ u = (np.arange(n) + 0.5) / n
224
+ return self._frozen.ppf(u), np.full(n, 1.0 / n)
225
+
226
+ def to_config(self):
227
+ cfg = {"type": "normal", "mean": self.loc, "std": self.scale}
228
+ if self.low != 0.0:
229
+ cfg["low"] = self.low
230
+ if math.isfinite(self.high):
231
+ cfg["high"] = self.high
232
+ return cfg
233
+
234
+
235
+ @dataclass(frozen=True)
236
+ class Discrete(Distribution):
237
+ values: tuple[float, ...]
238
+ weights: tuple[float, ...]
239
+ kind = "discrete"
240
+
241
+ def __post_init__(self) -> None:
242
+ v = tuple(check_positive(x, "discrete.values") for x in self.values)
243
+ w = np.asarray(self.weights, dtype=float)
244
+ if len(v) == 0 or w.shape != (len(v),):
245
+ raise ValueError("discrete: 'values' and 'weights' must have the same non-zero length")
246
+ if np.any(w < 0) or not w.sum() > 0:
247
+ raise ValueError("discrete: weights must be non-negative and not all zero")
248
+ object.__setattr__(self, "values", v)
249
+ object.__setattr__(self, "weights", tuple(float(x) for x in w / w.sum()))
250
+
251
+ def sample(self, rng, n):
252
+ return rng.choice(np.array(self.values), size=int(n), p=np.array(self.weights))
253
+
254
+ def moment(self, k):
255
+ return float(np.dot(self.weights, np.array(self.values) ** k))
256
+
257
+ def upper(self):
258
+ return max(self.values)
259
+
260
+ def quadrature(self, n=128):
261
+ return np.array(self.values), np.array(self.weights)
262
+
263
+ def to_config(self):
264
+ return {"type": "discrete", "values": list(self.values), "weights": list(self.weights)}
265
+
266
+
267
+ def distribution_from_config(value, name: str = "distribution") -> Distribution:
268
+ """Build a distribution from a number or a mapping (see the module docstring)."""
269
+ if isinstance(value, Distribution):
270
+ return value
271
+ if isinstance(value, bool):
272
+ raise ValueError(f"{name}: expected a number or a distribution mapping, got {value!r}")
273
+ if isinstance(value, (int, float)):
274
+ return Constant(float(value))
275
+ if not isinstance(value, dict) or "type" not in value:
276
+ raise ValueError(
277
+ f"{name}: expected a number or a mapping with a 'type' key "
278
+ f"(constant, uniform, lognormal, normal, discrete), got {value!r}"
279
+ )
280
+ cfg = dict(value)
281
+ kind = str(cfg.pop("type")).lower()
282
+ allowed = {
283
+ "constant": {"value"},
284
+ "uniform": {"low", "high"},
285
+ "lognormal": {"mean", "std"},
286
+ "normal": {"mean", "std", "low", "high"},
287
+ "discrete": {"values", "weights"},
288
+ }
289
+ if kind not in allowed:
290
+ raise ValueError(
291
+ f"{name}: unknown distribution type {kind!r}; use one of {sorted(allowed)}"
292
+ )
293
+ unknown = set(cfg) - allowed[kind]
294
+ missing = allowed[kind] - set(cfg) - ({"low", "high"} if kind == "normal" else set())
295
+ if unknown:
296
+ raise ValueError(f"{name}: unknown keys {sorted(unknown)} for a {kind} distribution")
297
+ if missing:
298
+ raise ValueError(f"{name}: missing keys {sorted(missing)} for a {kind} distribution")
299
+ try:
300
+ if kind == "constant":
301
+ return Constant(cfg["value"])
302
+ if kind == "uniform":
303
+ return Uniform(cfg["low"], cfg["high"])
304
+ if kind == "lognormal":
305
+ return LogNormal(cfg["mean"], cfg["std"])
306
+ if kind == "normal":
307
+ return TruncatedNormal(
308
+ cfg["mean"], cfg["std"], cfg.get("low", 0.0), cfg.get("high", math.inf)
309
+ )
310
+ return Discrete(tuple(cfg["values"]), tuple(cfg["weights"]))
311
+ except (TypeError, ValueError) as exc:
312
+ raise ValueError(f"{name}: {exc}") from None