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.
- morphogen/__init__.py +60 -0
- morphogen/__main__.py +7 -0
- morphogen/_platform.py +55 -0
- morphogen/_public.py +153 -0
- morphogen/_utils.py +80 -0
- morphogen/_version.py +1 -0
- morphogen/analysis/__init__.py +174 -0
- morphogen/analysis/anisotropy.py +135 -0
- morphogen/analysis/basic.py +38 -0
- morphogen/analysis/cells.py +54 -0
- morphogen/analysis/connectivity.py +156 -0
- morphogen/analysis/correlation.py +195 -0
- morphogen/analysis/covariance.py +80 -0
- morphogen/analysis/fractal.py +54 -0
- morphogen/analysis/measures.py +188 -0
- morphogen/analysis/morphology.py +265 -0
- morphogen/analysis/particles.py +160 -0
- morphogen/analysis/percolation.py +2034 -0
- morphogen/analysis/power_laws.py +143 -0
- morphogen/analysis/random_sets.py +351 -0
- morphogen/analysis/stereology.py +289 -0
- morphogen/analysis/surface.py +107 -0
- morphogen/analysis/topology.py +92 -0
- morphogen/automata/__init__.py +74 -0
- morphogen/automata/engine.py +211 -0
- morphogen/automata/growth.py +686 -0
- morphogen/automata/lattice.py +143 -0
- morphogen/automata/reaction.py +255 -0
- morphogen/automata/rules.py +353 -0
- morphogen/automata/tilings.py +1715 -0
- morphogen/cli.py +3526 -0
- morphogen/config.py +2167 -0
- morphogen/contact/__init__.py +113 -0
- morphogen/contact/experiments.py +368 -0
- morphogen/contact/hertz.py +104 -0
- morphogen/contact/kernels.py +827 -0
- morphogen/contact/periodic.py +278 -0
- morphogen/contact/problem.py +578 -0
- morphogen/contact/surfaces.py +310 -0
- morphogen/coupling/__init__.py +43 -0
- morphogen/coupling/ageing.py +143 -0
- morphogen/coupling/diffusion.py +226 -0
- morphogen/coupling/fenicsx.py +484 -0
- morphogen/coupling/oxidation.py +447 -0
- morphogen/coupling/plates.py +247 -0
- morphogen/design/__init__.py +51 -0
- morphogen/design/csp.py +616 -0
- morphogen/design/frames.py +277 -0
- morphogen/design/search.py +287 -0
- morphogen/design/tiles.py +336 -0
- morphogen/distributions.py +312 -0
- morphogen/domain.py +203 -0
- morphogen/dynamics/__init__.py +179 -0
- morphogen/dynamics/model.py +638 -0
- morphogen/dynamics/openradioss.py +643 -0
- morphogen/dynamics/results.py +515 -0
- morphogen/fracture/__init__.py +170 -0
- morphogen/fracture/bulk.py +349 -0
- morphogen/fracture/cohesive.py +1614 -0
- morphogen/fracture/ductile.py +557 -0
- morphogen/fracture/lefm.py +1168 -0
- morphogen/fracture/mixed.py +1178 -0
- morphogen/fracture/periodic.py +733 -0
- morphogen/fracture/phasefield.py +714 -0
- morphogen/fracture/phasefield_finite.py +368 -0
- morphogen/fracture/surface.py +572 -0
- morphogen/fracture/toughness.py +566 -0
- morphogen/gpu.py +108 -0
- morphogen/gui/__init__.py +8 -0
- morphogen/gui/api.py +1927 -0
- morphogen/gui/desktop.py +387 -0
- morphogen/gui/icon.png +0 -0
- morphogen/gui/index.html +1909 -0
- morphogen/gui/server.py +229 -0
- morphogen/gui/tools/__init__.py +629 -0
- morphogen/gui/tools/compare.py +149 -0
- morphogen/gui/tools/contact.py +391 -0
- morphogen/gui/tools/couplings.py +1085 -0
- morphogen/gui/tools/crackfront.py +245 -0
- morphogen/gui/tools/design.py +224 -0
- morphogen/gui/tools/dynamics.py +824 -0
- morphogen/gui/tools/fracture.py +2586 -0
- morphogen/gui/tools/interop.py +1654 -0
- morphogen/gui/tools/learning.py +595 -0
- morphogen/gui/tools/mechanics.py +3881 -0
- morphogen/gui/tools/nonlocal_damage.py +1321 -0
- morphogen/gui/tools/phasefield.py +215 -0
- morphogen/gui/tools/physics.py +597 -0
- morphogen/gui/tools/stability.py +1756 -0
- morphogen/gui/tools/statistics.py +1408 -0
- morphogen/gui/viewer.js +1100 -0
- morphogen/homogenization/__init__.py +210 -0
- morphogen/homogenization/acoustics.py +566 -0
- morphogen/homogenization/amg.py +1005 -0
- morphogen/homogenization/apparent.py +1046 -0
- morphogen/homogenization/behaviours.cu +2285 -0
- morphogen/homogenization/behaviours.py +944 -0
- morphogen/homogenization/beremin.py +263 -0
- morphogen/homogenization/bifurcation.py +1085 -0
- morphogen/homogenization/bloch.py +507 -0
- morphogen/homogenization/bounds.py +226 -0
- morphogen/homogenization/core.py +458 -0
- morphogen/homogenization/coupled.py +1135 -0
- morphogen/homogenization/crystal.py +2967 -0
- morphogen/homogenization/dilatation.py +454 -0
- morphogen/homogenization/elements.py +157 -0
- morphogen/homogenization/fatigue.py +768 -0
- morphogen/homogenization/fe.py +1739 -0
- morphogen/homogenization/fenicsx.py +307 -0
- morphogen/homogenization/fft.py +499 -0
- morphogen/homogenization/fft_nonlinear.py +391 -0
- morphogen/homogenization/finite.py +613 -0
- morphogen/homogenization/flow.py +361 -0
- morphogen/homogenization/frames.py +1125 -0
- morphogen/homogenization/gpu.py +1241 -0
- morphogen/homogenization/harmonic.py +427 -0
- morphogen/homogenization/identification.py +579 -0
- morphogen/homogenization/kernels.py +760 -0
- morphogen/homogenization/laws.py +2061 -0
- morphogen/homogenization/materials.py +1080 -0
- morphogen/homogenization/mfront.py +589 -0
- morphogen/homogenization/networks.py +880 -0
- morphogen/homogenization/nonlinear.py +2612 -0
- morphogen/homogenization/ntfa.py +577 -0
- morphogen/homogenization/paths.py +476 -0
- morphogen/homogenization/photonic.py +467 -0
- morphogen/homogenization/poroelastic.py +212 -0
- morphogen/homogenization/porous.py +1120 -0
- morphogen/homogenization/postprocess.py +290 -0
- morphogen/homogenization/solvers.py +1140 -0
- morphogen/homogenization/tensors.py +240 -0
- morphogen/homogenization/voxel_fe.py +457 -0
- morphogen/homogenization/xfem.py +1016 -0
- morphogen/homogenization/zmat.py +1258 -0
- morphogen/iga/__init__.py +48 -0
- morphogen/iga/analysis.py +508 -0
- morphogen/iga/basis.py +214 -0
- morphogen/iga/geometry.py +501 -0
- morphogen/iga/homogenization.py +219 -0
- morphogen/iga/optimization.py +700 -0
- morphogen/iga/shapes.py +331 -0
- morphogen/image.py +128 -0
- morphogen/io/__init__.py +246 -0
- morphogen/io/amitex.py +741 -0
- morphogen/io/ebsd.py +881 -0
- morphogen/io/export.py +196 -0
- morphogen/io/geometry.py +158 -0
- morphogen/io/medit.py +147 -0
- morphogen/io/meshes.py +844 -0
- morphogen/io/metaimage.py +97 -0
- morphogen/io/mfront.py +1104 -0
- morphogen/io/native.py +57 -0
- morphogen/io/radioss.py +764 -0
- morphogen/io/solvers.py +371 -0
- morphogen/io/tables.py +278 -0
- morphogen/io/tiff.py +66 -0
- morphogen/io/vtk.py +701 -0
- morphogen/io/xdmf.py +200 -0
- morphogen/kernels/__init__.py +5 -0
- morphogen/kernels/annealing.py +192 -0
- morphogen/kernels/cells.py +69 -0
- morphogen/kernels/collective.py +87 -0
- morphogen/kernels/force_biased.py +595 -0
- morphogen/kernels/implicit.py +145 -0
- morphogen/kernels/leaves.py +132 -0
- morphogen/kernels/packing.py +304 -0
- morphogen/kernels/raster.py +279 -0
- morphogen/kernels/rsa.py +371 -0
- morphogen/kernels/union.py +135 -0
- morphogen/kernels/watershed.py +190 -0
- morphogen/laser/__init__.py +234 -0
- morphogen/laser/architectures.py +375 -0
- morphogen/laser/bending.py +216 -0
- morphogen/laser/cells.py +1694 -0
- morphogen/laser/design.py +940 -0
- morphogen/laser/figures.py +227 -0
- morphogen/laser/heat.py +804 -0
- morphogen/laser/materials.py +691 -0
- morphogen/laser/mechanics.py +1670 -0
- morphogen/laser/metallurgy.py +615 -0
- morphogen/laser/patterns.py +828 -0
- morphogen/laser/periodic.py +392 -0
- morphogen/laser/process.py +362 -0
- morphogen/laser/run.py +534 -0
- morphogen/laser/solid.py +216 -0
- morphogen/laser/specimen.py +200 -0
- morphogen/laser/structures.py +708 -0
- morphogen/learning/__init__.py +81 -0
- morphogen/learning/behaviour.py +398 -0
- morphogen/learning/data.py +328 -0
- morphogen/learning/learned.cpp +668 -0
- morphogen/learning/logarithmic.py +202 -0
- morphogen/learning/mfront.py +409 -0
- morphogen/learning/networks.py +767 -0
- morphogen/learning/run.py +212 -0
- morphogen/learning/standard.py +814 -0
- morphogen/learning/training.py +235 -0
- morphogen/mesh/__init__.py +29 -0
- morphogen/mesh/conforming.py +1423 -0
- morphogen/mesh/curved.py +600 -0
- morphogen/mesh/exact.py +1717 -0
- morphogen/mesh/octree.py +350 -0
- morphogen/mesh/polycrystal.py +1041 -0
- morphogen/mesh/polyhedra.py +677 -0
- morphogen/mesh/regularize.py +570 -0
- morphogen/mesh/surface.py +97 -0
- morphogen/mesh/tetra.py +512 -0
- morphogen/mesh/voxel.py +124 -0
- morphogen/micromorphic/__init__.py +31 -0
- morphogen/micromorphic/damage.py +359 -0
- morphogen/micromorphic/ductile.py +534 -0
- morphogen/micromorphic/finite.py +220 -0
- morphogen/micromorphic/microfoam.py +787 -0
- morphogen/micromorphic/space.py +341 -0
- morphogen/models/__init__.py +195 -0
- morphogen/models/affine.py +384 -0
- morphogen/models/automata.py +592 -0
- morphogen/models/base.py +500 -0
- morphogen/models/boolean.py +310 -0
- morphogen/models/bouligand.py +331 -0
- morphogen/models/branching.py +241 -0
- morphogen/models/combination.py +430 -0
- morphogen/models/deadleaves.py +766 -0
- morphogen/models/design.py +289 -0
- morphogen/models/ebsd.py +206 -0
- morphogen/models/fibers.py +1476 -0
- morphogen/models/foam.py +594 -0
- morphogen/models/gaussian.py +314 -0
- morphogen/models/growth.py +459 -0
- morphogen/models/hardcore.py +317 -0
- morphogen/models/hierarchical.py +269 -0
- morphogen/models/honeycomb.py +749 -0
- morphogen/models/implicit.py +177 -0
- morphogen/models/laminate.py +470 -0
- morphogen/models/lattice.py +351 -0
- morphogen/models/lattice_field.py +345 -0
- morphogen/models/levelset_foam.py +563 -0
- morphogen/models/nacre.py +411 -0
- morphogen/models/nested.py +924 -0
- morphogen/models/osteons.py +374 -0
- morphogen/models/pieces.py +167 -0
- morphogen/models/planar.py +126 -0
- morphogen/models/reconstruction.py +203 -0
- morphogen/models/scale_rich.py +1409 -0
- morphogen/models/scale_rich_3d.py +1616 -0
- morphogen/models/tessellation.py +735 -0
- morphogen/models/tiling_field.py +302 -0
- morphogen/models/tpms.py +197 -0
- morphogen/models/transparent.py +406 -0
- morphogen/models/union.py +141 -0
- morphogen/optimization/__init__.py +43 -0
- morphogen/optimization/cell.py +295 -0
- morphogen/optimization/filters.py +115 -0
- morphogen/optimization/mma.py +226 -0
- morphogen/optimization/run.py +219 -0
- morphogen/optimization/topology.py +632 -0
- morphogen/orientations.py +568 -0
- morphogen/parallel.py +599 -0
- morphogen/pipeline.py +978 -0
- morphogen/primitives.py +188 -0
- morphogen/results.py +564 -0
- morphogen/rve/__init__.py +73 -0
- morphogen/rve/report.py +627 -0
- morphogen/rve/scaling.py +363 -0
- morphogen/rve/study.py +1054 -0
- morphogen/rve/windows.py +345 -0
- morphogen/seeding.py +51 -0
- morphogen/settings.py +118 -0
- morphogen/stopping.py +48 -0
- morphogen/symmetry.py +384 -0
- morphogen/templates/activator_inhibitor.yaml +22 -0
- morphogen/templates/aggregation.yaml +23 -0
- morphogen/templates/boolean_cylinders.yaml +20 -0
- morphogen/templates/boolean_spheres.yaml +22 -0
- morphogen/templates/bouligand.yaml +28 -0
- morphogen/templates/cellular_automaton.yaml +25 -0
- morphogen/templates/coated_spheres.yaml +26 -0
- morphogen/templates/contact_fibers.yaml +27 -0
- morphogen/templates/cox_nanocomposite.yaml +22 -0
- morphogen/templates/cross_linked_fibers.yaml +26 -0
- morphogen/templates/curved_arcs.yaml +28 -0
- morphogen/templates/curved_fibers.yaml +24 -0
- morphogen/templates/dead_leaves.yaml +22 -0
- morphogen/templates/delaunay_network.yaml +22 -0
- morphogen/templates/dense_packing.yaml +22 -0
- morphogen/templates/diffusion.yaml +33 -0
- morphogen/templates/ebsd.yaml +34 -0
- morphogen/templates/ebsd_map.ctf +3087 -0
- morphogen/templates/fracture_composite.yaml +42 -0
- morphogen/templates/fracture_rubber.yaml +47 -0
- morphogen/templates/gaussian_excursion.yaml +17 -0
- morphogen/templates/graded_lattice.yaml +24 -0
- morphogen/templates/hardcore_fibers.yaml +22 -0
- morphogen/templates/hardcore_spheres.yaml +22 -0
- morphogen/templates/hierarchical_lattice.yaml +22 -0
- morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
- morphogen/templates/homogenization_beremin.yaml +50 -0
- morphogen/templates/homogenization_cleavage.yaml +51 -0
- morphogen/templates/homogenization_cleavage_band.yaml +55 -0
- morphogen/templates/homogenization_contact.yaml +43 -0
- morphogen/templates/homogenization_crack_closure.yaml +49 -0
- morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
- morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
- morphogen/templates/homogenization_crystallization.yaml +30 -0
- morphogen/templates/homogenization_debonding.yaml +43 -0
- morphogen/templates/homogenization_detwinning.yaml +58 -0
- morphogen/templates/homogenization_ductile_damage.yaml +47 -0
- morphogen/templates/homogenization_fatigue.yaml +40 -0
- morphogen/templates/homogenization_grain_fracture.yaml +56 -0
- morphogen/templates/homogenization_gyroid.yaml +30 -0
- morphogen/templates/homogenization_intergranular.yaml +43 -0
- morphogen/templates/homogenization_interphase.yaml +42 -0
- morphogen/templates/homogenization_mixed_loading.yaml +33 -0
- morphogen/templates/homogenization_ntfa.yaml +56 -0
- morphogen/templates/homogenization_piezoelectric.yaml +27 -0
- morphogen/templates/homogenization_polycrystal.yaml +30 -0
- morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
- morphogen/templates/homogenization_poroelastic.yaml +26 -0
- morphogen/templates/homogenization_rubber.yaml +40 -0
- morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
- morphogen/templates/homogenization_spheres.yaml +31 -0
- morphogen/templates/homogenization_transport.yaml +29 -0
- morphogen/templates/homogenization_twinning.yaml +54 -0
- morphogen/templates/homogenization_viscoelastic.yaml +34 -0
- morphogen/templates/homogenization_viscoplastic.yaml +42 -0
- morphogen/templates/homogenization_voronoi.yaml +26 -0
- morphogen/templates/homogenization_xfem.yaml +23 -0
- morphogen/templates/hyperuniform_cells.yaml +24 -0
- morphogen/templates/laguerre.yaml +18 -0
- morphogen/templates/laser_bending.yaml +35 -0
- morphogen/templates/laser_cells.yaml +38 -0
- morphogen/templates/laser_corrugated.yaml +36 -0
- morphogen/templates/level_set_foam.yaml +29 -0
- morphogen/templates/menger_sponge.yaml +17 -0
- morphogen/templates/nacre.yaml +25 -0
- morphogen/templates/nucleation_growth.yaml +25 -0
- morphogen/templates/optimize_auxetic.yaml +29 -0
- morphogen/templates/optimize_auxetic_3d.yaml +27 -0
- morphogen/templates/optimize_bulk.yaml +23 -0
- morphogen/templates/optimize_conductivity.yaml +20 -0
- morphogen/templates/osteons.yaml +28 -0
- morphogen/templates/penetrable_spheres.yaml +21 -0
- morphogen/templates/poisson_fibers.yaml +21 -0
- morphogen/templates/random_laminate.yaml +26 -0
- morphogen/templates/random_lattice.yaml +27 -0
- morphogen/templates/random_walk_fibers.yaml +26 -0
- morphogen/templates/reaction_diffusion.yaml +22 -0
- morphogen/templates/reconstruction.yaml +22 -0
- morphogen/templates/rve_cellular_automaton.yaml +23 -0
- morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
- morphogen/templates/rve_multiphysics.yaml +43 -0
- morphogen/templates/rve_poisson_fibers.yaml +22 -0
- morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
- morphogen/templates/rve_voronoi_windows.yaml +20 -0
- morphogen/templates/scale_rich_network.yaml +29 -0
- morphogen/templates/scale_rich_plates.yaml +30 -0
- morphogen/templates/sequential_dead_leaves.yaml +25 -0
- morphogen/templates/strut_lattice.yaml +21 -0
- morphogen/templates/tile_assembly.yaml +28 -0
- morphogen/templates/tpms.yaml +19 -0
- morphogen/templates/trabecular_bone.yaml +29 -0
- morphogen/templates/transparent_dead_leaves.yaml +23 -0
- morphogen/templates/vascular_tree.yaml +23 -0
- morphogen/templates/voronoi.yaml +20 -0
- morphogen/templates/wood.yaml +34 -0
- morphogen/templates/workflow.yaml +56 -0
- morphogen/texture.py +665 -0
- morphogen/theory.py +162 -0
- morphogen/viz/__init__.py +12 -0
- morphogen/viz/export.py +244 -0
- morphogen/viz/figures.py +707 -0
- morphogen/viz/png.py +148 -0
- morphogen/viz/sections.py +696 -0
- morphogen/viz/surfaces.py +1352 -0
- morphogen/viz/video.py +904 -0
- morphogen/viz/workflow.py +488 -0
- morphogen-1.0.0.dist-info/METADATA +2316 -0
- morphogen-1.0.0.dist-info/RECORD +381 -0
- morphogen-1.0.0.dist-info/WHEEL +4 -0
- morphogen-1.0.0.dist-info/entry_points.txt +5 -0
- 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
|