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,51 @@
|
|
|
1
|
+
"""Combinatorial design: tile assemblies, strut frameworks and search algorithms.
|
|
2
|
+
|
|
3
|
+
* :mod:`morphogen.design.tiles`: tile sets with labelled faces (polarized blocks of
|
|
4
|
+
combinatorial metamaterials, pipe networks), rotations, geometry of assemblies;
|
|
5
|
+
* :mod:`morphogen.design.csp`: compatible assemblies by wave function collapse with
|
|
6
|
+
backtracking, exact counting and uniform sampling by transfer matrices, exact count
|
|
7
|
+
of polarized-block assemblies;
|
|
8
|
+
* :mod:`morphogen.design.frames`: periodic pin-jointed frameworks, random dilution and
|
|
9
|
+
perturbation, Maxwell-Calladine rigidity analysis;
|
|
10
|
+
* :mod:`morphogen.design.search`: simulated annealing, genetic algorithm, inverse
|
|
11
|
+
design of cellular-automaton rules.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from morphogen.design.csp import (
|
|
15
|
+
TransferMatrix,
|
|
16
|
+
count_assemblies,
|
|
17
|
+
count_polarized_blocks,
|
|
18
|
+
sample_uniform,
|
|
19
|
+
wave_function_collapse,
|
|
20
|
+
)
|
|
21
|
+
from morphogen.design.frames import Framework
|
|
22
|
+
from morphogen.design.search import (
|
|
23
|
+
RuleFit,
|
|
24
|
+
SearchResult,
|
|
25
|
+
descriptor_cost,
|
|
26
|
+
fit_rule,
|
|
27
|
+
genetic_algorithm,
|
|
28
|
+
simulated_annealing,
|
|
29
|
+
structure_descriptors,
|
|
30
|
+
)
|
|
31
|
+
from morphogen.design.tiles import TILE_SETS, TileSet, pipe_tiles, polarized_blocks
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"TILE_SETS",
|
|
35
|
+
"Framework",
|
|
36
|
+
"RuleFit",
|
|
37
|
+
"SearchResult",
|
|
38
|
+
"TileSet",
|
|
39
|
+
"TransferMatrix",
|
|
40
|
+
"count_assemblies",
|
|
41
|
+
"count_polarized_blocks",
|
|
42
|
+
"descriptor_cost",
|
|
43
|
+
"fit_rule",
|
|
44
|
+
"genetic_algorithm",
|
|
45
|
+
"pipe_tiles",
|
|
46
|
+
"polarized_blocks",
|
|
47
|
+
"sample_uniform",
|
|
48
|
+
"simulated_annealing",
|
|
49
|
+
"structure_descriptors",
|
|
50
|
+
"wave_function_collapse",
|
|
51
|
+
]
|
morphogen/design/csp.py
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
"""Constraint solvers for tile assemblies.
|
|
2
|
+
|
|
3
|
+
``wave_function_collapse``
|
|
4
|
+
Random compatible assemblies of any size: arc consistency (each tile left in the
|
|
5
|
+
domain of a cell has a compatible tile in every neighbouring domain), then cells of
|
|
6
|
+
least entropy are given a tile at random (with the tile weights) and the choice is
|
|
7
|
+
propagated, backtracking on contradictions (domains are bit sets, Numba).
|
|
8
|
+
``TransferMatrix``
|
|
9
|
+
Exact counting and exact uniform sampling of the compatible assemblies of a box,
|
|
10
|
+
with a transfer matrix between the admissible cross-sections along x (statistical
|
|
11
|
+
physics). It needs few admissible cross-sections: small sections, or constrained
|
|
12
|
+
tile sets.
|
|
13
|
+
``count_polarized_blocks``
|
|
14
|
+
Exact number of compatible assemblies of polarized blocks, for larger boxes: the
|
|
15
|
+
strain sign along every line of blocks alternates, which reduces the problem to
|
|
16
|
+
sign variables on the faces of the box (a gauge), summed by dynamic programming.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import math
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
from numba import njit
|
|
25
|
+
from scipy import sparse
|
|
26
|
+
|
|
27
|
+
from morphogen.design.tiles import TileSet
|
|
28
|
+
|
|
29
|
+
MAX_TILES = 64 # bit sets of 64 bits
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# -- wave function collapse ----------------------------------------------------------------
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@njit(cache=True)
|
|
36
|
+
def _popcount(x):
|
|
37
|
+
x = x - ((x >> np.uint64(1)) & np.uint64(0x5555555555555555))
|
|
38
|
+
x = (x & np.uint64(0x3333333333333333)) + ((x >> np.uint64(2)) & np.uint64(0x3333333333333333))
|
|
39
|
+
x = (x + (x >> np.uint64(4))) & np.uint64(0x0F0F0F0F0F0F0F0F)
|
|
40
|
+
return int((x * np.uint64(0x0101010101010101)) >> np.uint64(56))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@njit(cache=True)
|
|
44
|
+
def _propagate(
|
|
45
|
+
dom,
|
|
46
|
+
sw,
|
|
47
|
+
swl,
|
|
48
|
+
nb,
|
|
49
|
+
allowed,
|
|
50
|
+
w,
|
|
51
|
+
wlogw,
|
|
52
|
+
n_tiles,
|
|
53
|
+
stack,
|
|
54
|
+
n_stack,
|
|
55
|
+
in_stack,
|
|
56
|
+
trail_c,
|
|
57
|
+
trail_d,
|
|
58
|
+
trail_w,
|
|
59
|
+
trail_l,
|
|
60
|
+
n_trail,
|
|
61
|
+
):
|
|
62
|
+
"""Arc consistency from the cells on the stack; returns (ok, n_trail)."""
|
|
63
|
+
one = np.uint64(1)
|
|
64
|
+
while n_stack > 0:
|
|
65
|
+
n_stack -= 1
|
|
66
|
+
c = stack[n_stack]
|
|
67
|
+
in_stack[c] = 0
|
|
68
|
+
dc = dom[c]
|
|
69
|
+
for d in range(6):
|
|
70
|
+
q = nb[c, d]
|
|
71
|
+
if q < 0:
|
|
72
|
+
continue
|
|
73
|
+
sup = np.uint64(0)
|
|
74
|
+
for t in range(n_tiles):
|
|
75
|
+
if (dc >> np.uint64(t)) & one:
|
|
76
|
+
sup |= allowed[d, t]
|
|
77
|
+
old = dom[q]
|
|
78
|
+
new = old & sup
|
|
79
|
+
if new == old:
|
|
80
|
+
continue
|
|
81
|
+
if new == 0:
|
|
82
|
+
# leave the stack clean for the next propagation
|
|
83
|
+
while n_stack > 0:
|
|
84
|
+
n_stack -= 1
|
|
85
|
+
in_stack[stack[n_stack]] = 0
|
|
86
|
+
return False, n_trail
|
|
87
|
+
trail_c[n_trail] = q
|
|
88
|
+
trail_d[n_trail] = old
|
|
89
|
+
trail_w[n_trail] = sw[q]
|
|
90
|
+
trail_l[n_trail] = swl[q]
|
|
91
|
+
n_trail += 1
|
|
92
|
+
removed = old & ~new
|
|
93
|
+
for t in range(n_tiles):
|
|
94
|
+
if (removed >> np.uint64(t)) & one:
|
|
95
|
+
sw[q] -= w[t]
|
|
96
|
+
swl[q] -= wlogw[t]
|
|
97
|
+
dom[q] = new
|
|
98
|
+
if not in_stack[q]:
|
|
99
|
+
stack[n_stack] = q
|
|
100
|
+
n_stack += 1
|
|
101
|
+
in_stack[q] = 1
|
|
102
|
+
return True, n_trail
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@njit(cache=True)
|
|
106
|
+
def _undo(dom, sw, swl, trail_c, trail_d, trail_w, trail_l, n_trail, target):
|
|
107
|
+
while n_trail > target:
|
|
108
|
+
n_trail -= 1
|
|
109
|
+
c = trail_c[n_trail]
|
|
110
|
+
dom[c] = trail_d[n_trail]
|
|
111
|
+
sw[c] = trail_w[n_trail]
|
|
112
|
+
swl[c] = trail_l[n_trail]
|
|
113
|
+
return n_trail
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@njit(cache=True)
|
|
117
|
+
def _wfc(dom, nb, allowed, w, n_tiles, prio, rng, max_backtracks):
|
|
118
|
+
"""Search from the domains ``dom`` (modified in place). Status: 1 solved, 0 gave up
|
|
119
|
+
(too many backtracks), -1 no solution."""
|
|
120
|
+
n = dom.size
|
|
121
|
+
one = np.uint64(1)
|
|
122
|
+
wlogw = np.zeros(n_tiles)
|
|
123
|
+
for t in range(n_tiles):
|
|
124
|
+
if w[t] > 0:
|
|
125
|
+
wlogw[t] = w[t] * math.log(w[t])
|
|
126
|
+
sw = np.zeros(n)
|
|
127
|
+
swl = np.zeros(n)
|
|
128
|
+
for c in range(n):
|
|
129
|
+
for t in range(n_tiles):
|
|
130
|
+
if (dom[c] >> np.uint64(t)) & one:
|
|
131
|
+
sw[c] += w[t]
|
|
132
|
+
swl[c] += wlogw[t]
|
|
133
|
+
size = n * (n_tiles + 1) + 1
|
|
134
|
+
trail_c = np.empty(size, dtype=np.int64)
|
|
135
|
+
trail_d = np.empty(size, dtype=np.uint64)
|
|
136
|
+
trail_w = np.empty(size)
|
|
137
|
+
trail_l = np.empty(size)
|
|
138
|
+
stack = np.empty(n, dtype=np.int64)
|
|
139
|
+
in_stack = np.zeros(n, dtype=np.uint8)
|
|
140
|
+
n_stack = 0
|
|
141
|
+
for c in range(n):
|
|
142
|
+
if dom[c] == 0:
|
|
143
|
+
return -1
|
|
144
|
+
stack[n_stack] = c
|
|
145
|
+
n_stack += 1
|
|
146
|
+
in_stack[c] = 1
|
|
147
|
+
ok, n_trail = _propagate(
|
|
148
|
+
dom,
|
|
149
|
+
sw,
|
|
150
|
+
swl,
|
|
151
|
+
nb,
|
|
152
|
+
allowed,
|
|
153
|
+
w,
|
|
154
|
+
wlogw,
|
|
155
|
+
n_tiles,
|
|
156
|
+
stack,
|
|
157
|
+
n_stack,
|
|
158
|
+
in_stack,
|
|
159
|
+
trail_c,
|
|
160
|
+
trail_d,
|
|
161
|
+
trail_w,
|
|
162
|
+
trail_l,
|
|
163
|
+
0,
|
|
164
|
+
)
|
|
165
|
+
if not ok:
|
|
166
|
+
return -1
|
|
167
|
+
n_trail = 0 # the initial reduction is never undone
|
|
168
|
+
dec_cell = np.empty(n, dtype=np.int64)
|
|
169
|
+
dec_tried = np.zeros(n, dtype=np.uint64)
|
|
170
|
+
dec_trail = np.zeros(n, dtype=np.int64)
|
|
171
|
+
depth = 0
|
|
172
|
+
backtracks = 0
|
|
173
|
+
while True:
|
|
174
|
+
best = -1
|
|
175
|
+
best_h = np.inf
|
|
176
|
+
for c in range(n):
|
|
177
|
+
if _popcount(dom[c]) > 1:
|
|
178
|
+
h = math.log(sw[c]) - swl[c] / sw[c] + 1e-7 * prio[c]
|
|
179
|
+
if h < best_h:
|
|
180
|
+
best_h = h
|
|
181
|
+
best = c
|
|
182
|
+
if best < 0:
|
|
183
|
+
return 1
|
|
184
|
+
dec_cell[depth] = best
|
|
185
|
+
dec_tried[depth] = 0
|
|
186
|
+
dec_trail[depth] = n_trail
|
|
187
|
+
depth += 1
|
|
188
|
+
while True:
|
|
189
|
+
k = depth - 1
|
|
190
|
+
n_trail = _undo(dom, sw, swl, trail_c, trail_d, trail_w, trail_l, n_trail, dec_trail[k])
|
|
191
|
+
c = dec_cell[k]
|
|
192
|
+
options = dom[c] & ~dec_tried[k]
|
|
193
|
+
total = 0.0
|
|
194
|
+
for t in range(n_tiles):
|
|
195
|
+
if (options >> np.uint64(t)) & one:
|
|
196
|
+
total += w[t]
|
|
197
|
+
if total <= 0.0:
|
|
198
|
+
depth -= 1
|
|
199
|
+
backtracks += 1
|
|
200
|
+
if depth == 0:
|
|
201
|
+
return -1
|
|
202
|
+
if backtracks > max_backtracks:
|
|
203
|
+
return 0
|
|
204
|
+
continue
|
|
205
|
+
r = rng.random() * total
|
|
206
|
+
choice = -1
|
|
207
|
+
for t in range(n_tiles):
|
|
208
|
+
if (options >> np.uint64(t)) & one:
|
|
209
|
+
choice = t
|
|
210
|
+
r -= w[t]
|
|
211
|
+
if r < 0.0:
|
|
212
|
+
break
|
|
213
|
+
bit = one << np.uint64(choice)
|
|
214
|
+
dec_tried[k] |= bit
|
|
215
|
+
trail_c[n_trail] = c
|
|
216
|
+
trail_d[n_trail] = dom[c]
|
|
217
|
+
trail_w[n_trail] = sw[c]
|
|
218
|
+
trail_l[n_trail] = swl[c]
|
|
219
|
+
n_trail += 1
|
|
220
|
+
dom[c] = bit
|
|
221
|
+
sw[c] = w[choice]
|
|
222
|
+
swl[c] = wlogw[choice]
|
|
223
|
+
stack[0] = c
|
|
224
|
+
in_stack[c] = 1
|
|
225
|
+
ok, n_trail = _propagate(
|
|
226
|
+
dom,
|
|
227
|
+
sw,
|
|
228
|
+
swl,
|
|
229
|
+
nb,
|
|
230
|
+
allowed,
|
|
231
|
+
w,
|
|
232
|
+
wlogw,
|
|
233
|
+
n_tiles,
|
|
234
|
+
stack,
|
|
235
|
+
1,
|
|
236
|
+
in_stack,
|
|
237
|
+
trail_c,
|
|
238
|
+
trail_d,
|
|
239
|
+
trail_w,
|
|
240
|
+
trail_l,
|
|
241
|
+
n_trail,
|
|
242
|
+
)
|
|
243
|
+
if ok:
|
|
244
|
+
break
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _neighbours(shape, periodic: bool, dims: int) -> np.ndarray:
|
|
248
|
+
"""Index of the neighbour of every cell in the directions -x, +x, -y, +y, -z, +z
|
|
249
|
+
(-1: none)."""
|
|
250
|
+
idx = np.arange(int(np.prod(shape))).reshape(shape)
|
|
251
|
+
nb = np.full((idx.size, 6), -1, dtype=np.int64)
|
|
252
|
+
for a in range(dims):
|
|
253
|
+
for side, step in ((0, 1), (1, -1)):
|
|
254
|
+
rolled = np.roll(idx, step, axis=a) # side 0: value at i-1; side 1: at i+1
|
|
255
|
+
ok = np.ones(shape, dtype=bool)
|
|
256
|
+
if not periodic:
|
|
257
|
+
edge = [slice(None)] * 3
|
|
258
|
+
edge[a] = 0 if side == 0 else -1
|
|
259
|
+
ok[tuple(edge)] = False
|
|
260
|
+
if shape[a] == 1 and not periodic:
|
|
261
|
+
ok[:] = False
|
|
262
|
+
nb[:, 2 * a + side] = np.where(ok, rolled, -1).ravel()
|
|
263
|
+
return nb
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _allowed_bits(tileset: TileSet) -> np.ndarray:
|
|
267
|
+
"""``allowed[d, t]``: bit set of the tiles allowed next to tile t in direction d."""
|
|
268
|
+
n = tileset.n_tiles
|
|
269
|
+
compat = tileset.compatibility()
|
|
270
|
+
bits = (np.uint64(1) << np.arange(n, dtype=np.uint64)).astype(np.uint64)
|
|
271
|
+
allowed = np.zeros((6, n), dtype=np.uint64)
|
|
272
|
+
for a in range(3):
|
|
273
|
+
allowed[2 * a + 1] = np.bitwise_or.reduce(np.where(compat[a], bits[None, :], 0), axis=1)
|
|
274
|
+
allowed[2 * a] = np.bitwise_or.reduce(np.where(compat[a].T, bits[None, :], 0), axis=1)
|
|
275
|
+
return allowed
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def initial_domains(
|
|
279
|
+
tileset: TileSet, shape, *, periodic: bool = True, boundary=None, allowed=None
|
|
280
|
+
) -> np.ndarray:
|
|
281
|
+
"""Boolean domains ``(n0, n1, n2, n_tiles)``: tiles of positive weight, restricted
|
|
282
|
+
by ``allowed`` (same shape) and, on the faces of non-periodic boxes, to tiles whose
|
|
283
|
+
outer faces match the label ``boundary``."""
|
|
284
|
+
shape = tuple(int(n) for n in shape)
|
|
285
|
+
dom = np.broadcast_to(tileset.weights > 0, (*shape, tileset.n_tiles)).copy()
|
|
286
|
+
if allowed is not None:
|
|
287
|
+
dom &= np.asarray(allowed, dtype=bool).reshape(dom.shape)
|
|
288
|
+
if boundary is not None and not periodic:
|
|
289
|
+
for a in range(tileset.dims):
|
|
290
|
+
for side in (0, 1):
|
|
291
|
+
face = [slice(None)] * 3
|
|
292
|
+
face[a] = 0 if side == 0 else shape[a] - 1
|
|
293
|
+
dom[tuple(face)] &= tileset.boundary_tiles(a, side, boundary)
|
|
294
|
+
return dom
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def wave_function_collapse(
|
|
298
|
+
tileset: TileSet,
|
|
299
|
+
shape,
|
|
300
|
+
rng: np.random.Generator,
|
|
301
|
+
*,
|
|
302
|
+
periodic: bool = True,
|
|
303
|
+
boundary: int | None = None,
|
|
304
|
+
allowed=None,
|
|
305
|
+
max_backtracks: int | None = None,
|
|
306
|
+
restarts: int = 5,
|
|
307
|
+
) -> np.ndarray:
|
|
308
|
+
"""A random compatible assembly of ``shape`` tiles (``(n0, n1, 1)`` for planar sets).
|
|
309
|
+
|
|
310
|
+
``allowed`` (boolean, ``shape + (n_tiles,)``) restricts the tiles of each cell, e.g.
|
|
311
|
+
to grade a design in space; ``boundary`` is the label the outer faces of a
|
|
312
|
+
non-periodic box must match. Raises ValueError when no assembly exists, or when the
|
|
313
|
+
search gave up after ``restarts`` attempts of ``max_backtracks`` backtracks.
|
|
314
|
+
"""
|
|
315
|
+
if tileset.n_tiles > MAX_TILES:
|
|
316
|
+
raise ValueError(f"wave function collapse handles up to {MAX_TILES} tiles")
|
|
317
|
+
shape = tuple(int(n) for n in shape)
|
|
318
|
+
if len(shape) != 3 or min(shape) < 1:
|
|
319
|
+
raise ValueError("shape: three positive numbers of tiles")
|
|
320
|
+
if tileset.dims == 2 and shape[2] != 1:
|
|
321
|
+
raise ValueError("planar tile sets: shape (n0, n1, 1)")
|
|
322
|
+
dom_bool = initial_domains(
|
|
323
|
+
tileset, shape, periodic=periodic, boundary=boundary, allowed=allowed
|
|
324
|
+
)
|
|
325
|
+
bits = np.uint64(1) << np.arange(tileset.n_tiles, dtype=np.uint64)
|
|
326
|
+
dom0 = np.bitwise_or.reduce(np.where(dom_bool, bits, np.uint64(0)), axis=-1).ravel()
|
|
327
|
+
nb = _neighbours(shape, periodic, tileset.dims)
|
|
328
|
+
allowed_bits = _allowed_bits(tileset)
|
|
329
|
+
n_cells = dom0.size
|
|
330
|
+
limit = 10 * n_cells + 100 if max_backtracks is None else int(max_backtracks)
|
|
331
|
+
w = tileset.weights.astype(float)
|
|
332
|
+
for _ in range(max(1, int(restarts))):
|
|
333
|
+
dom = dom0.astype(np.uint64).copy()
|
|
334
|
+
prio = rng.random(n_cells)
|
|
335
|
+
status = _wfc(dom, nb, allowed_bits, w, tileset.n_tiles, prio, rng, limit)
|
|
336
|
+
if status == 1:
|
|
337
|
+
tiles = np.array([int(d).bit_length() - 1 for d in dom], dtype=np.int64)
|
|
338
|
+
return tiles.reshape(shape)
|
|
339
|
+
if status == -1:
|
|
340
|
+
raise ValueError("no compatible assembly exists for these tiles and constraints")
|
|
341
|
+
raise ValueError(
|
|
342
|
+
f"no compatible assembly found after {restarts} restarts of {limit} backtracks"
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# -- transfer matrices ---------------------------------------------------------------------
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@njit(cache=True)
|
|
350
|
+
def _enumerate_slices(n1, n2, n_tiles, compat, usable, periodic, max_states, out):
|
|
351
|
+
npos = n1 * n2
|
|
352
|
+
cur = np.full(npos, -1, dtype=np.int64)
|
|
353
|
+
count = 0
|
|
354
|
+
p = 0
|
|
355
|
+
while p >= 0:
|
|
356
|
+
cur[p] += 1
|
|
357
|
+
if cur[p] >= n_tiles:
|
|
358
|
+
cur[p] = -1
|
|
359
|
+
p -= 1
|
|
360
|
+
continue
|
|
361
|
+
t = cur[p]
|
|
362
|
+
if not usable[t]:
|
|
363
|
+
continue
|
|
364
|
+
j = p // n2
|
|
365
|
+
k = p % n2
|
|
366
|
+
if j > 0 and not compat[1, cur[p - n2], t]:
|
|
367
|
+
continue
|
|
368
|
+
if k > 0 and not compat[2, cur[p - 1], t]:
|
|
369
|
+
continue
|
|
370
|
+
if periodic and j == n1 - 1 and not compat[1, t, cur[k]]:
|
|
371
|
+
continue
|
|
372
|
+
if periodic and k == n2 - 1 and not compat[2, t, cur[j * n2]]:
|
|
373
|
+
continue
|
|
374
|
+
if p == npos - 1:
|
|
375
|
+
if count >= max_states:
|
|
376
|
+
return -1
|
|
377
|
+
for q in range(npos):
|
|
378
|
+
out[count, q] = cur[q]
|
|
379
|
+
count += 1
|
|
380
|
+
continue
|
|
381
|
+
p += 1
|
|
382
|
+
return count
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class TransferMatrix:
|
|
386
|
+
"""Admissible cross-sections ``(n1, n2)`` of a tile set and the transfer matrix
|
|
387
|
+
between consecutive sections along x (``T[s, s'] = 1`` when section s' may follow
|
|
388
|
+
section s).
|
|
389
|
+
|
|
390
|
+
Counting and sampling use exact integer arithmetic. Periodic boxes need the closed
|
|
391
|
+
walks of the transfer matrix (one sum per section): keep the number of sections
|
|
392
|
+
modest (``max_states``).
|
|
393
|
+
"""
|
|
394
|
+
|
|
395
|
+
def __init__(
|
|
396
|
+
self, tileset: TileSet, section, *, periodic: bool = False, max_states: int = 20000
|
|
397
|
+
):
|
|
398
|
+
self.tileset = tileset
|
|
399
|
+
self.section = (int(section[0]), int(section[1]))
|
|
400
|
+
if tileset.dims == 2 and self.section[1] != 1:
|
|
401
|
+
raise ValueError("planar tile sets: sections (n1, 1)")
|
|
402
|
+
self.periodic = bool(periodic)
|
|
403
|
+
n1, n2 = self.section
|
|
404
|
+
compat = tileset.compatibility()
|
|
405
|
+
out = np.empty((max_states, n1 * n2), dtype=np.int64)
|
|
406
|
+
count = _enumerate_slices(
|
|
407
|
+
n1,
|
|
408
|
+
n2,
|
|
409
|
+
tileset.n_tiles,
|
|
410
|
+
compat,
|
|
411
|
+
tileset.weights > 0,
|
|
412
|
+
self.periodic,
|
|
413
|
+
int(max_states),
|
|
414
|
+
out,
|
|
415
|
+
)
|
|
416
|
+
if count < 0:
|
|
417
|
+
raise ValueError(
|
|
418
|
+
f"more than {max_states} admissible sections: the box is too wide for "
|
|
419
|
+
"exact counting (use wave_function_collapse to sample)"
|
|
420
|
+
)
|
|
421
|
+
self.states = out[:count].copy()
|
|
422
|
+
self.matrix = self._build(compat[0])
|
|
423
|
+
|
|
424
|
+
def _build(self, compat_x) -> sparse.csr_matrix:
|
|
425
|
+
s = self.states
|
|
426
|
+
n = len(s)
|
|
427
|
+
rows, cols = [], []
|
|
428
|
+
block = max(1, 2_000_000 // max(1, n))
|
|
429
|
+
for start in range(0, n, block):
|
|
430
|
+
ok = np.ones((min(block, n - start), n), dtype=bool)
|
|
431
|
+
for c in range(s.shape[1]):
|
|
432
|
+
ok &= compat_x[s[start : start + block, c]][:, s[:, c]]
|
|
433
|
+
r, q = np.nonzero(ok)
|
|
434
|
+
rows.append(r + start)
|
|
435
|
+
cols.append(q)
|
|
436
|
+
r = np.concatenate(rows) if rows else np.empty(0, dtype=int)
|
|
437
|
+
q = np.concatenate(cols) if cols else np.empty(0, dtype=int)
|
|
438
|
+
return sparse.csr_matrix((np.ones(len(r), dtype=np.int8), (r, q)), shape=(n, n))
|
|
439
|
+
|
|
440
|
+
@property
|
|
441
|
+
def n_states(self) -> int:
|
|
442
|
+
return len(self.states)
|
|
443
|
+
|
|
444
|
+
def _step(self, v: np.ndarray) -> np.ndarray:
|
|
445
|
+
"""(T v)[s] = sum of v over the sections s' allowed after s (exact integers)."""
|
|
446
|
+
m = self.matrix
|
|
447
|
+
out = np.zeros(len(v), dtype=object)
|
|
448
|
+
nonempty = np.diff(m.indptr) > 0
|
|
449
|
+
if np.any(nonempty):
|
|
450
|
+
out[nonempty] = np.add.reduceat(v[m.indices], m.indptr[:-1][nonempty])
|
|
451
|
+
return out
|
|
452
|
+
|
|
453
|
+
def _backward(self, length: int, end=None) -> list[np.ndarray]:
|
|
454
|
+
"""b[k][s]: number of ways to complete the sections k+1..length-1 after section s
|
|
455
|
+
at position k (ending at section ``end`` when given)."""
|
|
456
|
+
n = self.n_states
|
|
457
|
+
last = np.ones(n, dtype=object)
|
|
458
|
+
if end is not None:
|
|
459
|
+
last = np.zeros(n, dtype=object)
|
|
460
|
+
# completions must end with a section followed by `end` (periodic closure)
|
|
461
|
+
col = self.matrix[:, end].toarray().ravel()
|
|
462
|
+
last[col > 0] = 1
|
|
463
|
+
b = [last]
|
|
464
|
+
for _ in range(length - 1):
|
|
465
|
+
b.append(self._step(b[-1]))
|
|
466
|
+
return b[::-1]
|
|
467
|
+
|
|
468
|
+
def count(self, length: int) -> int:
|
|
469
|
+
"""Number of compatible assemblies of ``length`` sections (exact)."""
|
|
470
|
+
length = int(length)
|
|
471
|
+
if length < 1:
|
|
472
|
+
raise ValueError("length: at least 1")
|
|
473
|
+
if not self.periodic:
|
|
474
|
+
return int(self._backward(length)[0].sum())
|
|
475
|
+
return int(sum(self._closed_walks(length)))
|
|
476
|
+
|
|
477
|
+
def _closed_walks(self, length: int) -> list[int]:
|
|
478
|
+
"""Number of periodic assemblies starting with each section."""
|
|
479
|
+
out = []
|
|
480
|
+
for s in range(self.n_states):
|
|
481
|
+
b = self._backward(length, end=s)
|
|
482
|
+
out.append(int(b[0][s]))
|
|
483
|
+
return out
|
|
484
|
+
|
|
485
|
+
def sample(self, length: int, rng: np.random.Generator) -> np.ndarray:
|
|
486
|
+
"""An assembly ``(length, n1, n2)`` drawn uniformly among the compatible ones."""
|
|
487
|
+
length = int(length)
|
|
488
|
+
if self.periodic:
|
|
489
|
+
weights = self._closed_walks(length)
|
|
490
|
+
first = _choose(weights, rng)
|
|
491
|
+
b = self._backward(length, end=first)
|
|
492
|
+
else:
|
|
493
|
+
b = self._backward(length)
|
|
494
|
+
first = _choose(list(b[0]), rng)
|
|
495
|
+
path = [first]
|
|
496
|
+
m = self.matrix
|
|
497
|
+
for k in range(1, length):
|
|
498
|
+
s = path[-1]
|
|
499
|
+
nxt = m.indices[m.indptr[s] : m.indptr[s + 1]]
|
|
500
|
+
path.append(int(nxt[_choose([b[k][q] for q in nxt], rng)]))
|
|
501
|
+
n1, n2 = self.section
|
|
502
|
+
return self.states[np.array(path)].reshape(length, n1, n2)
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _choose(weights, rng: np.random.Generator) -> int:
|
|
506
|
+
"""Index drawn with probability proportional to non-negative integer weights."""
|
|
507
|
+
total = int(sum(int(w) for w in weights))
|
|
508
|
+
if total <= 0:
|
|
509
|
+
raise ValueError("no compatible assembly")
|
|
510
|
+
nbits = total.bit_length()
|
|
511
|
+
while True: # uniform integer in [0, total) by rejection
|
|
512
|
+
r = int.from_bytes(rng.bytes((nbits + 7) // 8), "little") >> ((8 - nbits % 8) % 8)
|
|
513
|
+
if r < total:
|
|
514
|
+
break
|
|
515
|
+
for i, w in enumerate(weights):
|
|
516
|
+
r -= int(w)
|
|
517
|
+
if r < 0:
|
|
518
|
+
return i
|
|
519
|
+
return len(weights) - 1 # pragma: no cover
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def count_assemblies(
|
|
523
|
+
tileset: TileSet, shape, *, periodic: bool = False, max_states: int = 20000
|
|
524
|
+
) -> int:
|
|
525
|
+
"""Exact number of compatible assemblies of a box of ``shape`` tiles."""
|
|
526
|
+
shape = tuple(int(n) for n in shape)
|
|
527
|
+
tm = TransferMatrix(tileset, shape[1:], periodic=periodic, max_states=max_states)
|
|
528
|
+
return tm.count(shape[0])
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def sample_uniform(
|
|
532
|
+
tileset: TileSet,
|
|
533
|
+
shape,
|
|
534
|
+
rng: np.random.Generator,
|
|
535
|
+
*,
|
|
536
|
+
periodic: bool = False,
|
|
537
|
+
max_states: int = 20000,
|
|
538
|
+
) -> np.ndarray:
|
|
539
|
+
"""A compatible assembly drawn uniformly at random (exact, by transfer matrix)."""
|
|
540
|
+
shape = tuple(int(n) for n in shape)
|
|
541
|
+
tm = TransferMatrix(tileset, shape[1:], periodic=periodic, max_states=max_states)
|
|
542
|
+
return tm.sample(shape[0], rng)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
# -- polarized blocks ----------------------------------------------------------------------
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
@njit(cache=True)
|
|
549
|
+
def _polarized_sum(nx, ny, nz):
|
|
550
|
+
"""Sum over the signs F_x(j, k) of R_0^ceil(nx/2) R_1^floor(nx/2) (see below)."""
|
|
551
|
+
n_fx = 1 << (ny * nz)
|
|
552
|
+
total = 0.0
|
|
553
|
+
exact = np.int64(0)
|
|
554
|
+
big = False
|
|
555
|
+
for fx in range(n_fx):
|
|
556
|
+
r = np.zeros(2, dtype=np.int64)
|
|
557
|
+
for parity in range(2):
|
|
558
|
+
acc = np.int64(0)
|
|
559
|
+
for y in range(1 << nz):
|
|
560
|
+
prod = np.int64(1)
|
|
561
|
+
for j in range(ny):
|
|
562
|
+
# c = 2 - |{X_k (-1)^k : X_k = Y_k}| for the column (i, j)
|
|
563
|
+
seen_p = False
|
|
564
|
+
seen_m = False
|
|
565
|
+
for k in range(nz):
|
|
566
|
+
xk = 1 if (fx >> (j * nz + k)) & 1 else -1
|
|
567
|
+
if parity:
|
|
568
|
+
xk = -xk
|
|
569
|
+
yk = 1 if (y >> k) & 1 else -1
|
|
570
|
+
if j % 2 == 1:
|
|
571
|
+
yk = -yk
|
|
572
|
+
if xk == yk:
|
|
573
|
+
v = xk if k % 2 == 0 else -xk
|
|
574
|
+
if v > 0:
|
|
575
|
+
seen_p = True
|
|
576
|
+
else:
|
|
577
|
+
seen_m = True
|
|
578
|
+
c = 2 - (1 if seen_p else 0) - (1 if seen_m else 0)
|
|
579
|
+
prod *= c
|
|
580
|
+
if prod == 0:
|
|
581
|
+
break
|
|
582
|
+
acc += prod
|
|
583
|
+
r[parity] = acc
|
|
584
|
+
term = 1.0
|
|
585
|
+
term_exact = np.int64(1)
|
|
586
|
+
for i in range(nx):
|
|
587
|
+
term *= float(r[i % 2])
|
|
588
|
+
term_exact *= r[i % 2]
|
|
589
|
+
total += term
|
|
590
|
+
exact += term_exact
|
|
591
|
+
if total > 2.0**62:
|
|
592
|
+
big = True
|
|
593
|
+
return exact, total, big
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def count_polarized_blocks(shape, *, periodic: bool = False) -> int:
|
|
597
|
+
"""Number of compatible assemblies of polarized blocks in a box of ``shape`` blocks.
|
|
598
|
+
|
|
599
|
+
Writing the strain signs of the block (i, j, k) as ``e_x = F_x(j, k) (-1)^i``,
|
|
600
|
+
``e_y = F_y(i, k) (-1)^j``, ``e_z = F_z(i, j) (-1)^k`` (alternation along every
|
|
601
|
+
line), an assembly is a choice of the sign arrays such that no block has three equal
|
|
602
|
+
signs. The sum over ``F_z`` factorizes over the columns, then over ``F_y`` over the
|
|
603
|
+
rows i, which leaves a sum over ``F_x`` (``2^(ny nz)`` terms, the smallest section
|
|
604
|
+
is chosen). Periodic boxes need even numbers of blocks. Exact up to 2^62.
|
|
605
|
+
"""
|
|
606
|
+
nx, ny, nz = sorted((int(n) for n in shape), reverse=True)
|
|
607
|
+
if min(nx, ny, nz) < 1:
|
|
608
|
+
raise ValueError("shape: positive numbers of blocks")
|
|
609
|
+
if periodic and any(n % 2 for n in (nx, ny, nz)):
|
|
610
|
+
return 0
|
|
611
|
+
if ny * nz > 24:
|
|
612
|
+
raise ValueError("box too wide: the two smallest edges must hold at most 24 blocks")
|
|
613
|
+
exact, total, big = _polarized_sum(nx, ny, nz)
|
|
614
|
+
if big:
|
|
615
|
+
raise OverflowError(f"about {total:.4g} assemblies: beyond exact 64-bit counting")
|
|
616
|
+
return int(exact)
|