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,353 @@
|
|
|
1
|
+
"""Transition rules of binary cellular automata (states 0 and 1).
|
|
2
|
+
|
|
3
|
+
A rule maps the state of the lattice to the next one. Most rules depend on the number
|
|
4
|
+
``n`` of neighbours in state 1 (outer-totalistic rules):
|
|
5
|
+
|
|
6
|
+
``life`` (``B.../S...``)
|
|
7
|
+
birth of a cell in state 0 when ``n`` is in the birth set, survival of a cell in
|
|
8
|
+
state 1 when ``n`` is in the survival set (Conway's Game of Life is ``B3/S23`` in 2D).
|
|
9
|
+
``majority``
|
|
10
|
+
the cell takes the state of the majority of its neighbourhood, itself included
|
|
11
|
+
(voting rule): sharp interfaces of positive curvature retreat.
|
|
12
|
+
``anneal``
|
|
13
|
+
twisted majority (Vichniac 1984): the outcome is inverted when the vote is closest
|
|
14
|
+
to a tie. Interfaces then move with their mean curvature, as in the annealing of
|
|
15
|
+
a binary alloy: domains coarsen into bicontinuous patterns.
|
|
16
|
+
``conserved``
|
|
17
|
+
majority with a conserved volume fraction: the cells with the highest local
|
|
18
|
+
density of phase 1 (random tie-breaking) take state 1, exactly as many as before.
|
|
19
|
+
Domains coarsen at constant volume fraction (spinodal-like patterns).
|
|
20
|
+
``probabilistic``
|
|
21
|
+
birth and survival probabilities depending on ``n``.
|
|
22
|
+
``activator_inhibitor``
|
|
23
|
+
Young's (1984) model of Turing patterns: a cell weighs the active cells of a near
|
|
24
|
+
disc or ball (activation) against those of a surrounding annulus or shell
|
|
25
|
+
(inhibition); spots, stripes or labyrinths of a characteristic wavelength emerge.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import re
|
|
31
|
+
from abc import ABC, abstractmethod
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
from scipy import sparse
|
|
36
|
+
|
|
37
|
+
from morphogen.automata.lattice import kernel_sum, neighbour_counts, offsets
|
|
38
|
+
from morphogen.automata.tilings import TilingContext
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class LatticeContext:
|
|
43
|
+
"""Neighbourhood and boundary of the lattice on which a rule acts."""
|
|
44
|
+
|
|
45
|
+
offsets: np.ndarray
|
|
46
|
+
periodic: bool = True
|
|
47
|
+
boundary: int = 0
|
|
48
|
+
dims: int = 3
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def n_neighbours(self) -> int:
|
|
52
|
+
return len(self.offsets)
|
|
53
|
+
|
|
54
|
+
def counts(self, state: np.ndarray) -> np.ndarray:
|
|
55
|
+
return neighbour_counts(state, self.offsets, periodic=self.periodic, boundary=self.boundary)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Rule(ABC):
|
|
59
|
+
"""Transition rule of a binary automaton."""
|
|
60
|
+
|
|
61
|
+
#: whether the volume fraction is conserved (synchronous updates only)
|
|
62
|
+
conserves_fraction = False
|
|
63
|
+
|
|
64
|
+
@abstractmethod
|
|
65
|
+
def next_state(
|
|
66
|
+
self, state: np.ndarray, lattice: LatticeContext, rng: np.random.Generator
|
|
67
|
+
) -> np.ndarray:
|
|
68
|
+
"""State after one synchronous update of every cell."""
|
|
69
|
+
|
|
70
|
+
def describe(self) -> str:
|
|
71
|
+
return type(self).__name__
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _count_set(text: str) -> set[int]:
|
|
75
|
+
"""'5678' (digits) or '13-14,17-19' (numbers and ranges) -> set of counts."""
|
|
76
|
+
text = text.strip()
|
|
77
|
+
if not text:
|
|
78
|
+
return set()
|
|
79
|
+
if re.fullmatch(r"\d+", text) and "," not in text:
|
|
80
|
+
return {int(c) for c in text} # Life-like notation: one digit per count
|
|
81
|
+
out: set[int] = set()
|
|
82
|
+
for part in text.split(","):
|
|
83
|
+
part = part.strip()
|
|
84
|
+
m = re.fullmatch(r"(\d+)(?:-(\d+))?", part)
|
|
85
|
+
if not m:
|
|
86
|
+
raise ValueError(f"rule: cannot read the counts {text!r}")
|
|
87
|
+
a = int(m.group(1))
|
|
88
|
+
b = int(m.group(2)) if m.group(2) else a
|
|
89
|
+
if b < a:
|
|
90
|
+
raise ValueError(f"rule: empty range {part!r}")
|
|
91
|
+
out.update(range(a, b + 1))
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _format_counts(values) -> str:
|
|
96
|
+
"""Counts as Life-like digits ('5678') when all are below 10, otherwise as numbers and
|
|
97
|
+
ranges ('13,15-26'), so that :func:`_count_set` reads them back."""
|
|
98
|
+
v = sorted(values)
|
|
99
|
+
if not v or v[-1] <= 9:
|
|
100
|
+
return "".join(str(c) for c in v)
|
|
101
|
+
runs = [[v[0], v[0]]]
|
|
102
|
+
for c in v[1:]:
|
|
103
|
+
if c == runs[-1][1] + 1:
|
|
104
|
+
runs[-1][1] = c
|
|
105
|
+
else:
|
|
106
|
+
runs.append([c, c])
|
|
107
|
+
text = ",".join(str(a) if a == b else f"{a}-{b}" for a, b in runs)
|
|
108
|
+
return f"{text}-{text}" if text.isdigit() else text # '13' would read as {1, 3}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class LifeRule(Rule):
|
|
112
|
+
"""Outer-totalistic rule ``B<birth>/S<survival>``.
|
|
113
|
+
|
|
114
|
+
Counts are written as digits (``B5678/S45678``) or as comma-separated numbers and
|
|
115
|
+
ranges for 3D neighbourhoods (``B13-14,17-19/S13-26``).
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(self, birth, survival):
|
|
119
|
+
self.birth = frozenset(int(b) for b in birth)
|
|
120
|
+
self.survival = frozenset(int(s) for s in survival)
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def parse(cls, text: str) -> LifeRule:
|
|
124
|
+
m = re.fullmatch(r"\s*B([\d,\- ]*)\s*/\s*S([\d,\- ]*)\s*", text, re.I)
|
|
125
|
+
if not m:
|
|
126
|
+
m2 = re.fullmatch(r"\s*S([\d,\- ]*)\s*/\s*B([\d,\- ]*)\s*", text, re.I)
|
|
127
|
+
if not m2:
|
|
128
|
+
raise ValueError(
|
|
129
|
+
f"rule: expected 'B<counts>/S<counts>' (e.g. B5678/S45678 or "
|
|
130
|
+
f"B13-14,17-19/S13-26), got {text!r}"
|
|
131
|
+
)
|
|
132
|
+
return cls(_count_set(m2.group(2)), _count_set(m2.group(1)))
|
|
133
|
+
return cls(_count_set(m.group(1)), _count_set(m.group(2)))
|
|
134
|
+
|
|
135
|
+
def _lut(self, values, n: int) -> np.ndarray:
|
|
136
|
+
lut = np.zeros(n + 1, dtype=np.uint8)
|
|
137
|
+
for v in values:
|
|
138
|
+
if 0 <= v <= n:
|
|
139
|
+
lut[v] = 1
|
|
140
|
+
return lut
|
|
141
|
+
|
|
142
|
+
def next_state(self, state, lattice, rng):
|
|
143
|
+
n = int(np.max(lattice.n_neighbours))
|
|
144
|
+
c = lattice.counts(state)
|
|
145
|
+
born = self._lut(self.birth, n)[c]
|
|
146
|
+
kept = self._lut(self.survival, n)[c]
|
|
147
|
+
return np.where(state == 1, kept, born).astype(np.uint8)
|
|
148
|
+
|
|
149
|
+
def describe(self) -> str:
|
|
150
|
+
return f"B{_format_counts(self.birth)}/S{_format_counts(self.survival)}"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class MajorityRule(Rule):
|
|
154
|
+
"""Majority vote over the neighbourhood and the cell itself; ``twist`` inverts the
|
|
155
|
+
outcome of the two votes closest to a tie (Vichniac's annealing rule).
|
|
156
|
+
|
|
157
|
+
With an odd number of neighbours (triangles across their edges, some Penrose rhombi
|
|
158
|
+
across their vertices), the cell's own vote counts twice, so that the number of votes
|
|
159
|
+
stays odd: ties keep the state of the cell.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
def __init__(self, twist: bool = False):
|
|
163
|
+
self.twist = bool(twist)
|
|
164
|
+
|
|
165
|
+
def next_state(self, state, lattice, rng):
|
|
166
|
+
n = lattice.n_neighbours
|
|
167
|
+
own = 1 + np.asarray(n) % 2 # 1 on the grid (symmetric neighbourhoods)
|
|
168
|
+
total = lattice.counts(state) + own * state
|
|
169
|
+
m = n + own # odd
|
|
170
|
+
half = m // 2
|
|
171
|
+
out = (total > half).astype(np.uint8)
|
|
172
|
+
if self.twist:
|
|
173
|
+
out[total == half] = 1
|
|
174
|
+
out[total == half + 1] = 0
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
def describe(self) -> str:
|
|
178
|
+
return "anneal" if self.twist else "majority"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _top_fraction(score: np.ndarray, n_ones: int) -> np.ndarray:
|
|
182
|
+
"""Binary array with ones at the ``n_ones`` largest scores."""
|
|
183
|
+
flat = score.ravel()
|
|
184
|
+
out = np.zeros(flat.size, dtype=np.uint8)
|
|
185
|
+
if n_ones >= flat.size:
|
|
186
|
+
out[:] = 1
|
|
187
|
+
elif n_ones > 0:
|
|
188
|
+
out[np.argpartition(-flat, n_ones - 1)[:n_ones]] = 1
|
|
189
|
+
return out.reshape(score.shape)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class ConservedMajorityRule(Rule):
|
|
193
|
+
"""Majority with a conserved number of cells in state 1 (``fraction`` of the cells):
|
|
194
|
+
the cells of highest local density of phase 1 win, ties broken at random (the density
|
|
195
|
+
is the fraction of phase 1 in the neighbourhood and the cell when neighbourhoods
|
|
196
|
+
differ in size)."""
|
|
197
|
+
|
|
198
|
+
conserves_fraction = True
|
|
199
|
+
|
|
200
|
+
def __init__(self, fraction: float):
|
|
201
|
+
if not 0.0 < float(fraction) < 1.0:
|
|
202
|
+
raise ValueError(f"fraction: must lie in (0, 1), got {fraction!r}")
|
|
203
|
+
self.fraction = float(fraction)
|
|
204
|
+
|
|
205
|
+
def n_ones(self, n_cells: int) -> int:
|
|
206
|
+
return round(self.fraction * n_cells)
|
|
207
|
+
|
|
208
|
+
def next_state(self, state, lattice, rng):
|
|
209
|
+
n = lattice.n_neighbours
|
|
210
|
+
if np.ndim(n) == 0:
|
|
211
|
+
score = lattice.counts(state) + state + rng.random(state.shape)
|
|
212
|
+
else: # fractions p / m differ by at least 1 / m_max^2: the noise only breaks ties
|
|
213
|
+
m = n + 1
|
|
214
|
+
score = (lattice.counts(state) + state) / m + rng.random(state.shape) / m.max() ** 2
|
|
215
|
+
return _top_fraction(score, self.n_ones(state.size))
|
|
216
|
+
|
|
217
|
+
def describe(self) -> str:
|
|
218
|
+
return f"conserved({self.fraction:g})"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class ProbabilisticRule(Rule):
|
|
222
|
+
"""Birth with probability ``p_birth[n]`` and survival with ``p_survival[n]``
|
|
223
|
+
(arrays indexed by the number ``n`` of neighbours in state 1)."""
|
|
224
|
+
|
|
225
|
+
def __init__(self, p_birth, p_survival):
|
|
226
|
+
self.p_birth = np.asarray(p_birth, dtype=float)
|
|
227
|
+
self.p_survival = np.asarray(p_survival, dtype=float)
|
|
228
|
+
for name, p in (("p_birth", self.p_birth), ("p_survival", self.p_survival)):
|
|
229
|
+
if p.ndim != 1 or np.any((p < 0) | (p > 1)):
|
|
230
|
+
raise ValueError(f"{name}: probabilities in [0, 1] indexed by counts")
|
|
231
|
+
|
|
232
|
+
def next_state(self, state, lattice, rng):
|
|
233
|
+
n = int(np.max(lattice.n_neighbours))
|
|
234
|
+
c = lattice.counts(state)
|
|
235
|
+
pb = np.zeros(n + 1)
|
|
236
|
+
ps = np.zeros(n + 1)
|
|
237
|
+
pb[: min(n + 1, len(self.p_birth))] = self.p_birth[: n + 1]
|
|
238
|
+
ps[: min(n + 1, len(self.p_survival))] = self.p_survival[: n + 1]
|
|
239
|
+
p = np.where(state == 1, ps[c], pb[c])
|
|
240
|
+
return (rng.random(state.shape) < p).astype(np.uint8)
|
|
241
|
+
|
|
242
|
+
def describe(self) -> str:
|
|
243
|
+
return "probabilistic"
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class ActivatorInhibitorRule(Rule):
|
|
247
|
+
"""Young's (1984) activator-inhibitor automaton.
|
|
248
|
+
|
|
249
|
+
The score of a cell is the number of active cells within ``activation_radius``
|
|
250
|
+
(itself included) minus ``weight`` times the number of active cells at distances in
|
|
251
|
+
(``activation_radius``, ``inhibition_radius``] (Euclidean distances in cells). The
|
|
252
|
+
cell becomes active if the score is positive, inactive if negative. With a
|
|
253
|
+
``fraction``, the cells of highest score are active instead (conserved volume
|
|
254
|
+
fraction). The default weight balances the two regions (a uniform state scores 0); on
|
|
255
|
+
tilings whose discs differ from cell to cell (Penrose), it is balanced cell by cell.
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
def __init__(
|
|
259
|
+
self,
|
|
260
|
+
activation_radius: float,
|
|
261
|
+
inhibition_radius: float,
|
|
262
|
+
weight: float | None = None,
|
|
263
|
+
fraction: float | None = None,
|
|
264
|
+
dims: int = 3,
|
|
265
|
+
):
|
|
266
|
+
r1, r2 = float(activation_radius), float(inhibition_radius)
|
|
267
|
+
if not (1.0 <= r1 < r2):
|
|
268
|
+
raise ValueError("radii: 1 <= activation_radius < inhibition_radius (in cells)")
|
|
269
|
+
self.r1, self.r2 = r1, r2
|
|
270
|
+
inner = offsets("euclidean", r1, dims=dims, include_center=True)
|
|
271
|
+
outer = offsets("euclidean", r2, dims=dims, include_center=True)
|
|
272
|
+
ring = outer[(outer * outer).sum(axis=1) > r1 * r1 + 1e-9]
|
|
273
|
+
self.balanced = weight is None
|
|
274
|
+
self.weight = len(inner) / len(ring) if weight is None else float(weight)
|
|
275
|
+
if not self.weight > 0:
|
|
276
|
+
raise ValueError("weight: must be positive")
|
|
277
|
+
self.offsets = np.concatenate([inner, ring])
|
|
278
|
+
self.weights = np.concatenate([np.ones(len(inner)), -self.weight * np.ones(len(ring))])
|
|
279
|
+
self.fraction = None if fraction is None else float(fraction)
|
|
280
|
+
self.conserves_fraction = self.fraction is not None
|
|
281
|
+
|
|
282
|
+
def tiling_kernels(self, lattice: TilingContext):
|
|
283
|
+
"""Discs (CSR, the cell included), rings (CSR) and weights on a tiling."""
|
|
284
|
+
key = ("activator_inhibitor", self.r1, self.r2, self.balanced, self.weight)
|
|
285
|
+
if key not in lattice.cache:
|
|
286
|
+
t = lattice.tiling
|
|
287
|
+
n = t.n_cells
|
|
288
|
+
|
|
289
|
+
def matrix(ball):
|
|
290
|
+
ip, ix = ball
|
|
291
|
+
return sparse.csr_matrix((np.ones(len(ix), dtype=np.int8), ix, ip), shape=(n, n))
|
|
292
|
+
|
|
293
|
+
disc = matrix(t.ball(self.r1))
|
|
294
|
+
ring = matrix(t.ball(self.r2)) - disc
|
|
295
|
+
ring.eliminate_zeros()
|
|
296
|
+
ring.sort_indices()
|
|
297
|
+
inner = (disc.indptr.astype(np.int64), disc.indices.astype(np.int64))
|
|
298
|
+
outer = (ring.indptr.astype(np.int64), ring.indices.astype(np.int64))
|
|
299
|
+
w = self.weight
|
|
300
|
+
if self.balanced:
|
|
301
|
+
w = np.diff(inner[0]) / np.maximum(1, np.diff(outer[0]))
|
|
302
|
+
w = float(w[0]) if np.ptp(w) == 0 else w
|
|
303
|
+
lattice.cache[key] = (inner, outer, w)
|
|
304
|
+
return lattice.cache[key]
|
|
305
|
+
|
|
306
|
+
def score(self, state, lattice) -> np.ndarray:
|
|
307
|
+
if isinstance(lattice, TilingContext):
|
|
308
|
+
inner, ring, w = self.tiling_kernels(lattice)
|
|
309
|
+
t = lattice.tiling
|
|
310
|
+
return t.counts(state, *inner) - w * t.counts(state, *ring)
|
|
311
|
+
return kernel_sum(
|
|
312
|
+
state, self.offsets, self.weights, periodic=lattice.periodic, boundary=lattice.boundary
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
def next_state(self, state, lattice, rng):
|
|
316
|
+
s = self.score(state, lattice)
|
|
317
|
+
if self.fraction is not None:
|
|
318
|
+
return _top_fraction(
|
|
319
|
+
s + 1e-6 * rng.random(state.shape), round(self.fraction * state.size)
|
|
320
|
+
)
|
|
321
|
+
tol = 1e-9 * (1.0 + self.weight) * len(self.offsets)
|
|
322
|
+
out = state.copy()
|
|
323
|
+
out[s > tol] = 1
|
|
324
|
+
out[s < -tol] = 0
|
|
325
|
+
return out
|
|
326
|
+
|
|
327
|
+
def describe(self) -> str:
|
|
328
|
+
return f"activator_inhibitor({self.r1:g}, {self.r2:g}, w={self.weight:.4g})"
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
#: Named rules. ``clouds`` is a 3D Moore rule known to turn noise into cave-like
|
|
332
|
+
#: structures (B13-14,17-19/S13-26).
|
|
333
|
+
NAMED_RULES = {
|
|
334
|
+
"majority": lambda: MajorityRule(twist=False),
|
|
335
|
+
"anneal": lambda: MajorityRule(twist=True),
|
|
336
|
+
"life": lambda: LifeRule.parse("B3/S23"),
|
|
337
|
+
"clouds": lambda: LifeRule.parse("B13-14,17-19/S13-26"),
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def make_rule(rule, *, fraction: float | None = None) -> Rule:
|
|
342
|
+
"""A rule from a name (``majority``, ``anneal``, ``conserved``, ``life``,
|
|
343
|
+
``clouds``), a ``B.../S...`` string, or a :class:`Rule`."""
|
|
344
|
+
if isinstance(rule, Rule):
|
|
345
|
+
return rule
|
|
346
|
+
text = str(rule).strip()
|
|
347
|
+
if text.lower() == "conserved":
|
|
348
|
+
if fraction is None:
|
|
349
|
+
raise ValueError("the 'conserved' rule needs the volume fraction")
|
|
350
|
+
return ConservedMajorityRule(fraction)
|
|
351
|
+
if text.lower() in NAMED_RULES:
|
|
352
|
+
return NAMED_RULES[text.lower()]()
|
|
353
|
+
return LifeRule.parse(text)
|