morphogen 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,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
+ ]
@@ -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)