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,1715 @@
1
+ """Tilings of the plane and of space: lattices of cellular automata beyond the square grid.
2
+
3
+ A :class:`Tiling` is a set of cells (convex polygons in 2D, convex polyhedra in 3D) with
4
+ their centres, areas or volumes, shapes and adjacency: the CSR lists of the cells sharing
5
+ a face (an edge in 2D), an edge or a vertex with each cell.
6
+
7
+ ``square``
8
+ squares (cubes in 3D): the grid of :mod:`morphogen.automata.lattice`, as a tiling;
9
+ ``triangular``
10
+ equilateral triangles: 3 edge and 12 vertex neighbours;
11
+ ``hexagonal``
12
+ regular hexagons (honeycomb cells): 6 neighbours, each sharing an edge;
13
+ ``penrose``
14
+ the thick and thin rhombi of Penrose's quasi-periodic tiling, by de Bruijn's
15
+ pentagrid method: 4 edge neighbours, 7 to 11 vertex neighbours; finite patches only;
16
+ ``ammann_beenker``
17
+ the squares and 45-degree rhombi of the octagonal Ammann-Beenker tiling, by the same
18
+ method on four grids (the cut-and-project of Z^4): 4 edge neighbours; finite patches;
19
+ ``bcc``, ``fcc`` (3D)
20
+ the Voronoi cells of the body- and face-centred cubic lattices: truncated octahedra
21
+ (14 faces: 8 hexagons towards the nearest neighbours, 6 squares towards the second
22
+ ones) and rhombic dodecahedra (12 faces; 18 vertex neighbours);
23
+ ``icosahedral`` (3D)
24
+ the prolate and oblate golden rhombohedra of the icosahedral tiling (Ammann,
25
+ Kramer & Neri), by the dual method on six grids of planes normal to the fivefold
26
+ axes of the icosahedron (the cut-and-project of Z^6): 6 face neighbours; finite
27
+ patches only. Its 24 vertex stars (:meth:`Tiling.vertex_stars`) have the frequencies
28
+ of :data:`ICOSAHEDRAL_STARS`, the shares of its acceptance window
29
+ (:func:`window_stars`).
30
+
31
+ In 3D, the planar tilings are stacked in layers of prisms (``hexagonal``: hexagonal
32
+ prisms, 8 face and 20 vertex neighbours; ``square``: cubes). Cells have the area
33
+ ``cell_size**2`` (planar tilings; the mean area for quasi-periodic tilings) or the
34
+ volume ``cell_size**3``, and prisms are ``cell_size`` high: every lattice has about as
35
+ many cells as the square grid of the same cell size.
36
+
37
+ Periodic tilings fill a box with a whole number of unit cells, scaled along each axis to
38
+ fit it exactly (the cells are then slightly distorted, like the cells of the square grid
39
+ of a box whose edges are not multiples of the cell size): the tiling is the affine image
40
+ of a reference tiling, the Voronoi tessellation of its centres (the triangles are the
41
+ Voronoi cells of the honeycomb of their centroids), in which points are located by their
42
+ nearest centre. Quasi-periodic tilings have no period: they cover boxes as finite
43
+ patches whose cells at the edges have fewer neighbours (free boundaries). Their periodic
44
+ approximants (``approximant``: an order ``k``) fill periodic boxes with the same tiles:
45
+ the rational approximants of the cut-and-project (a phason strain), whose grids replace
46
+ the golden mean τ by ``F_{k+1}/F_k`` (Fibonacci numbers; Penrose rhombi, golden
47
+ rhombohedra: the cubic approximants 1/1, 2/1, 3/2...) or the silver mean ``1 + √2`` by
48
+ ``P_{k+1}/P_k`` (Pell numbers; Ammann-Beenker tiles), periodic in a rectangle or a cube
49
+ (:func:`approximant_period`) of which the box holds a whole number, fitted to it like
50
+ the unit cells of the periodic tilings.
51
+
52
+ :meth:`Tiling.diffusion_weights` gives the finite-volume Laplacian of every tiling (the
53
+ flux through each face: its length or area over the distance between the centres), on
54
+ which :func:`morphogen.automata.reaction.gray_scott_tiling` runs reaction-diffusion.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import itertools
60
+ import math
61
+
62
+ import numpy as np
63
+ from numba import njit, prange
64
+ from scipy import sparse
65
+ from scipy.spatial import cKDTree
66
+
67
+ from morphogen.automata.lattice import NEIGHBOURHOODS
68
+
69
+ #: Lattices of cells: the planar tilings (prisms in 3D), then the 3D lattices.
70
+ LATTICES = (
71
+ "square", "triangular", "hexagonal", "penrose", "ammann_beenker", "bcc", "fcc",
72
+ "icosahedral",
73
+ ) # fmt: skip
74
+ PLANAR = ("square", "triangular", "hexagonal", "penrose", "ammann_beenker")
75
+ #: Quasi-periodic tilings: finite patches, never periodic boxes.
76
+ QUASIPERIODIC = ("penrose", "ammann_beenker", "icosahedral")
77
+ GOLDEN = (1.0 + math.sqrt(5.0)) / 2.0
78
+ SILVER = 1.0 + math.sqrt(2.0)
79
+ _EPS = 1e-6
80
+
81
+ #: Grids of lines of the planar quasi-periodic tilings (de Bruijn): their number and the
82
+ #: angle between consecutive ones (unit vectors e_j at angles j * step).
83
+ MULTIGRIDS = {"penrose": (5, 2 * math.pi / 5), "ammann_beenker": (4, math.pi / 4)}
84
+
85
+
86
+ def _icosahedral_axes(t: float = GOLDEN) -> np.ndarray:
87
+ """The six fivefold axes of the icosahedron, unit vectors ``(0, ±1, τ)`` and their
88
+ cyclic permutations (pairwise at ``arccos(±1/√5)``). With ``t = -1/τ``, the conjugate
89
+ of the golden mean: their images in the perpendicular space of the cut-and-project of
90
+ Z^6, whose cosines have the opposite signs."""
91
+ a = np.array([[1, t, 0], [-1, t, 0], [0, 1, t], [0, -1, t], [t, 0, 1], [-t, 0, 1]])
92
+ return a / np.linalg.norm(a, axis=1, keepdims=True)
93
+
94
+
95
+ #: Volumes of the prolate and oblate golden rhombohedra of unit edge (in the ratio τ).
96
+ GOLDEN_RHOMBOHEDRA = (
97
+ 2.0 * math.sqrt(GOLDEN / (5.0 * math.sqrt(5.0))),
98
+ 2.0 / math.sqrt(5.0 * math.sqrt(5.0) * GOLDEN),
99
+ )
100
+
101
+
102
+ def _tau(*powers: int) -> float:
103
+ """``τ^-n`` summed over the powers ``n`` (a negative one: ``-τ^n``)."""
104
+ return sum(math.copysign(GOLDEN ** -abs(n), n) for n in powers)
105
+
106
+
107
+ #: The 24 vertex stars of the icosahedral tiling (the kinds of
108
+ #: :meth:`Tiling.vertex_stars`) and their frequencies in the infinite tiling: the shares
109
+ #: of its acceptance window, the rhombic triacontahedron, in which the images of the
110
+ #: vertices of each star fall (measured there by :func:`window_stars`; these expressions
111
+ #: of the golden mean sum to 1 and give the mean coordination 6 exactly).
112
+ ICOSAHEDRAL_STARS = {
113
+ ((0, 2, 2, 0), (3, 3, 3, 3)): _tau(3),
114
+ ((0, 4, 1, 1), (3, 3, 4, 4, 4)): _tau(3),
115
+ ((0, 6, 0, 2), (3, 3, 4, 4, 5, 5)): _tau(3),
116
+ ((1, 3, 1, 3), (3, 3, 4, 4, 5, 5)): _tau(6),
117
+ ((1, 5, 0, 4), (3, 3, 4, 4, 5, 5, 6)): _tau(6),
118
+ ((2, 4, 0, 6), (3, 3, 4, 4, 5, 5, 5, 7)): _tau(7, 7),
119
+ ((3, 3, 0, 8), (3, 3, 3, 4, 5, 5, 5, 6, 8)): _tau(9, 9),
120
+ ((5, 3, 0, 6), (3, 4, 4, 4, 4, 5, 5, 6, 7)): _tau(9, 12),
121
+ ((4, 2, 0, 10), (3, 3, 3, 3, 5, 5, 5, 5, 7, 9)): _tau(12, 12),
122
+ ((6, 2, 0, 8), (3, 3, 4, 4, 4, 5, 5, 5, 7, 8)): _tau(12, 15),
123
+ ((8, 2, 0, 6), (4, 4, 4, 4, 4, 4, 5, 5, 7, 7)): _tau(12),
124
+ ((6, 0, 0, 14), (3, 3, 3, 3, 3, 3, 5, 5, 7, 7, 8, 10)): _tau(12, 15),
125
+ ((8, 0, 0, 12), (3, 3, 3, 3, 3, 4, 5, 6, 6, 7, 7, 10)): _tau(12),
126
+ ((8, 0, 0, 12), (3, 3, 3, 3, 4, 4, 4, 5, 7, 7, 8, 9)): _tau(12, -15),
127
+ ((10, 0, 0, 10), (3, 3, 3, 3, 3, 5, 6, 6, 6, 6, 6, 10)): _tau(12),
128
+ ((10, 0, 0, 10), (3, 3, 3, 4, 4, 4, 4, 6, 6, 7, 7, 9)): _tau(12),
129
+ ((10, 0, 0, 10), (3, 3, 4, 4, 4, 4, 4, 4, 7, 7, 8, 8)): _tau(12, 12, 15),
130
+ ((12, 0, 0, 8), (3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 9)): _tau(15),
131
+ ((12, 0, 0, 8), (3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 7, 8)): _tau(12, 15),
132
+ ((14, 0, 0, 6), (3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 8)): _tau(12, -15),
133
+ ((14, 0, 0, 6), (4, 4, 4, 4, 4, 4, 5, 5, 5, 7, 7, 7)): _tau(12, 12),
134
+ ((16, 0, 0, 4), (4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 7)): _tau(12, 15),
135
+ ((18, 0, 0, 2), (4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6)): _tau(12),
136
+ ((20, 0, 0, 0), (5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)): _tau(9),
137
+ }
138
+
139
+
140
+ def tile_edge(name: str, cell_size: float = 1.0) -> float:
141
+ """Edge of the tiles of the quasi-periodic tiling ``name`` whose mean area (volume
142
+ for ``icosahedral``) is ``cell_size**2`` (``**3``): Penrose's thick and thin rhombi
143
+ (areas ``sin 72°`` and ``sin 36°`` times the squared edge, in the ratio of the golden
144
+ mean τ), Ammann-Beenker's squares and 45° rhombi (areas 1 and ``1/√2``, in the
145
+ ratio ``1 : √2``), the prolate and oblate golden rhombohedra (in the ratio τ)."""
146
+ if name == "penrose":
147
+ mean = (GOLDEN * math.sin(2 * math.pi / 5) + math.sin(math.pi / 5)) / (GOLDEN + 1)
148
+ return float(cell_size) / math.sqrt(mean)
149
+ if name == "ammann_beenker":
150
+ return float(cell_size) / math.sqrt(2.0 / SILVER)
151
+ if name == "icosahedral":
152
+ prolate, oblate = GOLDEN_RHOMBOHEDRA
153
+ return float(cell_size) / ((GOLDEN * prolate + oblate) / (GOLDEN + 1)) ** (1 / 3)
154
+ raise ValueError(f"tile_edge: one of {QUASIPERIODIC}, got {name!r}")
155
+
156
+
157
+ def penrose_edge(cell_size: float = 1.0) -> float:
158
+ """Edge of the Penrose rhombi whose mean area is ``cell_size**2`` (thick and thin
159
+ rhombi, of areas ``sin 72°`` and ``sin 36°`` times the squared edge, in the ratio of
160
+ the golden mean)."""
161
+ return tile_edge("penrose", cell_size)
162
+
163
+
164
+ #: Largest distance between the centres of two cells sharing a vertex, in cell sizes:
165
+ #: the reach of one step of a radius-1 neighbourhood (along an axis for the grid).
166
+ #: Rhombi and rhombohedra: twice their largest half-diagonal (the thin Penrose rhombus,
167
+ #: the 45° rhombus, the prolate rhombohedron along its threefold axis).
168
+ REACH = {
169
+ "square": 1.0,
170
+ "triangular": 4.0 / 3**0.75,
171
+ "hexagonal": (2.0 / 3**0.5) ** 0.5,
172
+ "penrose": 2.0 * math.cos(math.pi / 10) * penrose_edge(),
173
+ "ammann_beenker": 2.0 * math.cos(math.pi / 8) * tile_edge("ammann_beenker"),
174
+ "bcc": 2.0 ** (1 / 3),
175
+ "fcc": 4.0 ** (1 / 3),
176
+ "icosahedral": math.sqrt(3.0 + 6.0 / math.sqrt(5.0)) * tile_edge("icosahedral"),
177
+ }
178
+
179
+
180
+ def _star(name: str) -> np.ndarray:
181
+ """Unit vectors ``e_j`` of the grids of a quasi-periodic tiling (rows): the edges of
182
+ its tiles."""
183
+ if name == "icosahedral":
184
+ return _icosahedral_axes()
185
+ n, step = MULTIGRIDS[name]
186
+ t = step * np.arange(n)
187
+ return np.c_[np.cos(t), np.sin(t)]
188
+
189
+
190
+ # -- periodic approximants -----------------------------------------------------------------
191
+
192
+
193
+ def _fibonacci(k: int) -> tuple[int, int, int]:
194
+ """Fibonacci numbers ``F_{k-1}, F_k, F_{k+1}`` (``F_0 = 0``, ``F_1 = 1``)."""
195
+ a, b = 0, 1
196
+ for _ in range(k - 1):
197
+ a, b = b, a + b
198
+ return a, b, a + b
199
+
200
+
201
+ def _pell(k: int) -> tuple[int, int]:
202
+ """Pell number ``P_k`` and its companion ``H_k = P_k + P_{k-1}``: ``(1 + √2)^k = H_k +
203
+ P_k √2``."""
204
+ a, b = 0, 1 # P_0, P_1
205
+ for _ in range(k - 1):
206
+ a, b = b, 2 * b + a
207
+ return b, a + b
208
+
209
+
210
+ def _orders(name: str, order) -> tuple[int, ...]:
211
+ """The order of the approximant along each axis of its period (``order``: one for
212
+ every axis, or one per axis)."""
213
+ d = 3 if name == "icosahedral" else 2
214
+ values = (order,) * d if np.ndim(order) == 0 else tuple(order)
215
+ if len(values) != d or not all(
216
+ not isinstance(v, (bool, np.bool_)) and float(v).is_integer() and v >= 1 for v in values
217
+ ):
218
+ raise ValueError(
219
+ f"approximant: an order of at least 1, or {d} of them (one per axis), got {order!r}"
220
+ )
221
+ return tuple(int(v) for v in values)
222
+
223
+
224
+ def approximant_grid(name: str, order) -> np.ndarray:
225
+ """Integer grid vectors ``g_j`` (rows, one per grid) of the periodic approximant of
226
+ order ``order`` (one, or one per axis) of the quasi-periodic tiling ``name``.
227
+
228
+ They are the unit vectors ``e_j`` of its grids (:func:`make_tiling`) with their
229
+ irrational ratios made rational, scaled along each axis to integers: τ replaced by
230
+ ``F_{k+1}/F_k`` in the components ``(1, (τ - 1)/2, -τ/2, -τ/2, (τ - 1)/2)`` (times
231
+ ``2 F_k``) and ``(0, 1, 1/τ, -1/τ, -1)`` (times ``F_{k+1}``) of the Penrose grids, and in
232
+ the axes ``(±1, τ, 0)`` and their cyclic permutations (times ``F_k``) of the icosahedral
233
+ ones; ``√2`` replaced by ``H_k/P_k`` (Pell numbers, so that ``1 + √2`` becomes
234
+ ``P_{k+1}/P_k``) in the Ammann-Beenker grids. Column ``a`` is the period along axis
235
+ ``a`` of the multigrid ``x . g_j + γ_j ∈ Z``, in Z^n: the multigrid has the period 1
236
+ along each axis of ``x``, and its dual tiling, of edges ``e_j`` (the same tiles), the
237
+ period ``sum_j g_ja e_j``, along axis ``a`` (:func:`approximant_period`).
238
+ """
239
+ k = _orders(name, order)
240
+ if name == "penrose":
241
+ a0, a1, a2 = _fibonacci(k[0])
242
+ _, b1, b2 = _fibonacci(k[1])
243
+ return np.array([[2 * a1, 0], [a0, b2], [-a2, b1], [-a2, -b1], [a0, -b2]])
244
+ if name == "ammann_beenker":
245
+ pa, ha = _pell(k[0])
246
+ pb, hb = _pell(k[1])
247
+ return np.array([[ha, 0], [pa, pb], [0, hb], [-pa, pb]])
248
+ if name == "icosahedral":
249
+ _, x1, x2 = _fibonacci(k[0])
250
+ _, y1, y2 = _fibonacci(k[1])
251
+ _, z1, z2 = _fibonacci(k[2])
252
+ return np.array(
253
+ [[x1, y2, 0], [-x1, y2, 0], [0, y1, z2], [0, -y1, z2], [x2, 0, z1], [-x2, 0, z1]]
254
+ )
255
+ raise ValueError(
256
+ f"approximant: one of the quasi-periodic tilings {QUASIPERIODIC}, got {name!r}"
257
+ )
258
+
259
+
260
+ def approximant_period(name: str, order, cell_size: float = 1.0) -> np.ndarray:
261
+ """Edges of the rectangular or cuboid period of the approximant of order ``order``
262
+ (one, or one per axis) of the quasi-periodic tiling ``name`` whose tiles are those of
263
+ mean area ``cell_size**2`` (volume ``**3``), :func:`tile_edge`: ``√5 τ^k`` by ``2 sin 72°
264
+ τ^k`` edges for Penrose rhombi, ``(1 + √2)^k`` for Ammann-Beenker tiles (a square), and
265
+ the cube of edge ``2 τ^(k+1) / √(2 + τ)`` for golden rhombohedra. A periodic box holds a
266
+ whole number of periods along each axis (:func:`make_tiling`)."""
267
+ period = _star(name).T @ approximant_grid(name, order)
268
+ return np.diag(period) * tile_edge(name, cell_size)
269
+
270
+
271
+ def _reduction(periods: np.ndarray):
272
+ """Reduction of integer vectors (in rows) modulo the lattice of the columns of
273
+ ``periods`` (``n x d`` integers): ``K - periods @ c``, ``c = floor(adj(B) K_I / det B)``
274
+ for the ``d x d`` minor ``B`` of rows ``I`` of largest determinant, the representative
275
+ of its class with ``0 <= adj(B) K_I < det B``, in exact integer arithmetic (the
276
+ vertices of a tiling of the torus, numbered without tolerance)."""
277
+ periods = np.asarray(periods, dtype=np.int64)
278
+ n, d = periods.shape
279
+ rows = list(max(itertools.combinations(range(n), d), key=lambda r: abs(_det(periods[list(r)]))))
280
+ minor = periods[rows]
281
+ det = _det(minor)
282
+ if d == 2:
283
+ adj = np.array([[minor[1, 1], -minor[0, 1]], [-minor[1, 0], minor[0, 0]]])
284
+ else:
285
+ adj = np.array([np.cross(minor[1], minor[2]), np.cross(minor[2], minor[0]),
286
+ np.cross(minor[0], minor[1])]).T # fmt: skip
287
+ if det < 0:
288
+ det, adj = -det, -adj
289
+
290
+ def reduce(keys: np.ndarray) -> np.ndarray:
291
+ c = (keys[..., rows] @ adj.T) // det
292
+ return keys - c @ periods.T
293
+
294
+ return reduce
295
+
296
+
297
+ def _det(m: np.ndarray) -> int:
298
+ """Determinant of a 2 x 2 or 3 x 3 integer matrix, exactly."""
299
+ if len(m) == 2:
300
+ return int(m[0, 0]) * int(m[1, 1]) - int(m[0, 1]) * int(m[1, 0])
301
+ return int(np.dot(m[0], np.cross(m[1], m[2])))
302
+
303
+
304
+ def _periodic_dual_cells(e, grid, gamma, counts, families, reduce, what: str):
305
+ """Cells of the periodic tiling dual to the multigrid ``x . g_j + gamma_j = k`` (the
306
+ integer rows ``g_j`` of ``grid``, of period 1 along each axis of ``x``) over the box
307
+ ``[0, counts)`` of grid periods, as :func:`_dual_cells` gives them over a patch: for
308
+ each tuple of ``families`` (of hyperplanes ``g_r`` in the same orientation as their
309
+ edges ``e_r``, refused otherwise), the integer indices ``K`` of the corners of the
310
+ cells reduced by ``reduce`` modulo the periods (:func:`_reduction`), one per
311
+ intersection of the torus (the box is enlarged by 1e-7 grid periods so that none is
312
+ missed, the images met twice kept once, and the count checked against ``|det g|
313
+ prod(counts)``).
314
+ """
315
+ counts = np.asarray(counts)
316
+ gamma = np.asarray(gamma, dtype=float)
317
+ span = grid * counts # the values g_j . x over the box: between the sums of its signs
318
+ lo = np.minimum(span, 0).sum(axis=1) + gamma
319
+ hi = np.maximum(span, 0).sum(axis=1) + gamma
320
+ for fam in families:
321
+ fam = list(fam)
322
+ det = _det(grid[fam])
323
+ if det == 0: # parallel hyperplanes: no cell of these edges
324
+ continue
325
+ if det * np.linalg.det(e[fam]) < 0:
326
+ raise ValueError(f"approximant: grids {fam} of the other orientation than their tiles")
327
+ ranges = [np.arange(math.floor(lo[r]) - 1, math.ceil(hi[r]) + 2) for r in fam]
328
+ k = np.stack([g.ravel() for g in np.meshgrid(*ranges, indexing="ij")], axis=1)
329
+ z = np.linalg.solve(grid[fam].astype(float), (k - gamma[fam]).T).T
330
+ keep = np.all((z > -1e-7) & (z < counts + 1e-7), axis=1)
331
+ k, z = k[keep], z[keep]
332
+ w = z @ grid.T + gamma
333
+ _check_regular(np.delete(w, fam, axis=1), gamma, what)
334
+ big_k = np.ceil(w).astype(np.int64)
335
+ big_k[:, fam] = k
336
+ big_k = np.unique(reduce(big_k), axis=0)
337
+ if len(big_k) != abs(det) * int(np.prod(counts)):
338
+ raise RuntimeError(
339
+ f"approximant: {len(big_k)} cells of the grids {fam}, "
340
+ f"{abs(det) * int(np.prod(counts))} expected"
341
+ )
342
+ yield fam, big_k
343
+
344
+
345
+ # -- sparse adjacency --------------------------------------------------------------------
346
+
347
+
348
+ def _csr(n: int, rows, cols, mirror: bool = True) -> tuple[np.ndarray, np.ndarray]:
349
+ """Symmetric CSR lists ``(indptr, indices)`` of the pairs ``(rows, cols)``, with
350
+ their mirror images unless the pairs are symmetric already (duplicates and loops
351
+ dropped, indices sorted)."""
352
+ rows = np.asarray(rows, dtype=np.int64).ravel()
353
+ cols = np.asarray(cols, dtype=np.int64).ravel()
354
+ keep = rows != cols
355
+ r, c = rows[keep], cols[keep]
356
+ if mirror:
357
+ r, c = np.concatenate([r, c]), np.concatenate([c, r])
358
+ m = sparse.csr_matrix((np.ones(len(r), dtype=np.int32), (r, c)), shape=(n, n))
359
+ m.sum_duplicates()
360
+ m.sort_indices()
361
+ return m.indptr.astype(np.int64), m.indices.astype(np.int64)
362
+
363
+
364
+ def _lattice_adjacency(n, basis, cell, radius: float, periodic: bool):
365
+ """Pairs of points of a lattice closer than ``radius`` (CSR): ``basis`` fractions of a
366
+ rectangular unit ``cell``, ``n`` cells per axis, the point ``i`` of the cell ``c`` (C
367
+ order) numbered ``c * len(basis) + i``. The neighbours of each basis point are found
368
+ once in a block of cells, then translated to every cell."""
369
+ n = np.asarray(n)
370
+ d, nb = len(n), len(basis)
371
+ m = math.ceil(radius / float(np.min(cell))) + 1
372
+ span = np.arange(-m, m + 1)
373
+ shifts = np.stack(np.meshgrid(*[span] * d, indexing="ij"), -1).reshape(-1, d)
374
+ units = np.stack(np.meshgrid(*(np.arange(k) for k in n), indexing="ij"), -1).reshape(-1, d)
375
+ rows, cols = [], []
376
+ for b0 in range(nb):
377
+ dist = np.linalg.norm((shifts[:, None, :] + basis[None] - basis[b0]) * cell, axis=-1)
378
+ shift, b1 = np.nonzero((dist <= radius) & (dist > 1e-9 * radius))
379
+ target = units[:, None, :] + shifts[shift][None]
380
+ if periodic:
381
+ target %= n
382
+ valid = np.ones(target.shape[:2], dtype=bool)
383
+ else:
384
+ valid = np.all((target >= 0) & (target < n), axis=-1)
385
+ target = np.where(valid[..., None], target, 0)
386
+ flat = np.ravel_multi_index(tuple(np.moveaxis(target, -1, 0)), tuple(n)) * nb + b1
387
+ rows.append(np.broadcast_to((np.arange(len(units)) * nb + b0)[:, None], flat.shape)[valid])
388
+ cols.append(flat[valid])
389
+ return _csr(len(units) * nb, np.concatenate(rows), np.concatenate(cols), mirror=False)
390
+
391
+
392
+ def _pairs(indptr, indices) -> tuple[np.ndarray, np.ndarray]:
393
+ return np.repeat(np.arange(len(indptr) - 1), np.diff(indptr)), np.asarray(indices)
394
+
395
+
396
+ def _power(indptr, indices, m: int) -> tuple[np.ndarray, np.ndarray]:
397
+ """Cells at graph distance 1 to ``m`` (CSR)."""
398
+ n = len(indptr) - 1
399
+ a = sparse.csr_matrix((np.ones(len(indices), dtype=np.int32), indices, indptr), shape=(n, n))
400
+ reach = a.copy()
401
+ for _ in range(m - 1):
402
+ reach = reach + reach @ a
403
+ reach.data[:] = 1
404
+ c = reach.tocoo()
405
+ return _csr(n, c.row, c.col)
406
+
407
+
408
+ def _shells(points, box, radius) -> tuple[np.ndarray, np.ndarray]:
409
+ """Pairs of points closer than ``radius`` (periodic in ``box`` unless it is None)."""
410
+ if box is None:
411
+ tree = cKDTree(points)
412
+ else:
413
+ tree = cKDTree(np.mod(points, box), boxsize=box)
414
+ p = tree.query_pairs(radius, output_type="ndarray")
415
+ return _csr(len(points), p[:, 0], p[:, 1])
416
+
417
+
418
+ @njit(parallel=True, cache=True)
419
+ def _csr_count(state, indptr, indices, out):
420
+ for i in prange(out.shape[0]):
421
+ s = 0
422
+ for p in range(indptr[i], indptr[i + 1]):
423
+ s += state[indices[p]]
424
+ out[i] = s
425
+
426
+
427
+ @njit(parallel=True, cache=True)
428
+ def _csr_differ(state, indptr, indices):
429
+ """Number of (ordered) pairs of neighbours in different states."""
430
+ n = indptr.shape[0] - 1
431
+ total = 0
432
+ for i in prange(n):
433
+ s = 0
434
+ for p in range(indptr[i], indptr[i + 1]):
435
+ s += state[indices[p]] != state[i]
436
+ total += s
437
+ return total
438
+
439
+
440
+ @njit(cache=True)
441
+ def _greedy_colours(indptr, indices):
442
+ """Greedy colouring: neighbours never share a colour."""
443
+ n = indptr.shape[0] - 1
444
+ degree = 0
445
+ for i in range(n):
446
+ degree = max(degree, indptr[i + 1] - indptr[i])
447
+ colour = -np.ones(n, dtype=np.int64)
448
+ mark = -np.ones(degree + 2, dtype=np.int64)
449
+ for i in range(n):
450
+ for p in range(indptr[i], indptr[i + 1]):
451
+ c = colour[indices[p]]
452
+ if c >= 0:
453
+ mark[c] = i
454
+ c = 0
455
+ while mark[c] == i:
456
+ c += 1
457
+ colour[i] = c
458
+ return colour
459
+
460
+
461
+ @njit(parallel=True, cache=True)
462
+ def _in_polygons(points, candidates, centres, poly_ptr, poly, box, periodic, out):
463
+ """First candidate cell whose polygon (offsets from its centre, counterclockwise)
464
+ contains each point; the nearest candidate when none does (round-off)."""
465
+ for p in prange(points.shape[0]):
466
+ out[p] = candidates[p, 0]
467
+ for q in range(candidates.shape[1]):
468
+ c = candidates[p, q]
469
+ if c < 0 or c >= centres.shape[0]:
470
+ break
471
+ dx = points[p, 0] - centres[c, 0]
472
+ dy = points[p, 1] - centres[c, 1]
473
+ if periodic:
474
+ dx -= box[0] * np.floor(dx / box[0] + 0.5)
475
+ dy -= box[1] * np.floor(dy / box[1] + 0.5)
476
+ a = poly_ptr[c]
477
+ b = poly_ptr[c + 1]
478
+ inside = True
479
+ for v in range(a, b):
480
+ w = v + 1 if v + 1 < b else a
481
+ ex = poly[w, 0] - poly[v, 0]
482
+ ey = poly[w, 1] - poly[v, 1]
483
+ if ex * (dy - poly[v, 1]) - ey * (dx - poly[v, 0]) < -1e-9 * (abs(ex) + abs(ey)):
484
+ inside = False
485
+ break
486
+ if inside:
487
+ out[p] = c
488
+ break
489
+
490
+
491
+ # -- the tiling ----------------------------------------------------------------------------
492
+
493
+
494
+ class Tiling:
495
+ """Cells of a tiling: centres, shapes, areas or volumes and adjacency.
496
+
497
+ Build tilings with :func:`make_tiling`. Cells are numbered layer by layer for prisms
498
+ (``layer * n_planar + planar_cell``). ``adjacency(kind)`` gives the CSR lists of the
499
+ cells sharing a ``"faces"`` (an edge in 2D), ``"edges"`` or ``"vertices"`` with each
500
+ cell; :meth:`neighbours` the neighbourhoods of the automata.
501
+ """
502
+
503
+ def __init__(self, spec: dict, plane: dict | None, solid: dict | None) -> None:
504
+ self.spec = dict(spec)
505
+ self.name = spec["name"]
506
+ self.dims = int(spec["dims"])
507
+ self.cell_size = float(spec["cell_size"])
508
+ self.periodic = bool(spec["periodic"])
509
+ self.origin = np.asarray(spec["origin"], dtype=float)
510
+ self.size = np.asarray(spec["size"], dtype=float)
511
+ self._plane = plane
512
+ self._solid = solid
513
+ self._cache: dict = {}
514
+ if plane is not None:
515
+ m = len(plane["centres"])
516
+ layers = plane["layers"]
517
+ hz = plane["layer_height"]
518
+ sx, sy, sz = plane["scale"]
519
+ xy = plane["centres"] * (sx, sy)
520
+ z = (np.arange(layers) + 0.5) * hz * sz
521
+ self.centres = np.empty((m * layers, 3))
522
+ self.centres[:, :2] = np.tile(xy, (layers, 1))
523
+ self.centres[:, 2] = np.repeat(z, m)
524
+ self.centres += self.origin
525
+ area = plane["areas"] * sx * sy
526
+ measure = area if self.dims == 2 else area * hz * sz
527
+ self.volumes = np.tile(measure, layers)
528
+ self.kinds = np.tile(plane["kinds"], layers)
529
+ elif "volumes" in solid: # cells of several shapes (icosahedral)
530
+ self.centres = solid["centres"] + self.origin
531
+ self.volumes = solid["volumes"]
532
+ self.kinds = solid["kinds"]
533
+ else:
534
+ self.centres = solid["centres"] * solid["scale"] + self.origin
535
+ self.volumes = np.full(len(self.centres), solid["volume"] * np.prod(solid["scale"]))
536
+ self.kinds = np.zeros(len(self.centres), dtype=np.int8)
537
+ self._adjacency: dict = {}
538
+
539
+ def _build_adjacency(self, kind: str) -> tuple[np.ndarray, np.ndarray]:
540
+ if self._plane is not None:
541
+ return _prism_adjacency(self._plane, self.dims, self.periodic, kind)
542
+ s = self._solid
543
+ if kind in s: # from the vertices shared by the cells
544
+ return s[kind]
545
+ r = s["shells"][kind]
546
+ key = ("shell", r)
547
+ if key not in self._cache:
548
+ self._cache[key] = _lattice_adjacency(*s["lattice"], r * (1 + _EPS), self.periodic)
549
+ return self._cache[key]
550
+
551
+ # -- description -------------------------------------------------------------------
552
+
553
+ @property
554
+ def n_cells(self) -> int:
555
+ return len(self.centres)
556
+
557
+ def adjacency(self, kind: str = "faces") -> tuple[np.ndarray, np.ndarray]:
558
+ """CSR lists ``(indptr, indices)`` of the cells sharing a face (an edge in 2D),
559
+ an edge or a vertex (``kind``: faces, edges or vertices) with each cell."""
560
+ if kind not in ("faces", "edges", "vertices"):
561
+ raise ValueError(f"adjacency: faces, edges or vertices, got {kind!r}")
562
+ if kind not in self._adjacency:
563
+ self._adjacency[kind] = self._build_adjacency(kind)
564
+ return self._adjacency[kind]
565
+
566
+ def neighbours(
567
+ self, neighbourhood: str = "moore", radius: float = 1
568
+ ) -> tuple[np.ndarray, np.ndarray]:
569
+ """Neighbourhood of every cell (CSR), the counterpart of the grid's offsets.
570
+
571
+ ``von_neumann``, ``edges`` and ``moore``: the cells within ``floor(radius)``
572
+ steps across faces (edges in 2D), edges or vertices (on the square grid: the
573
+ L1, edge and max-norm balls); ``euclidean``: the cells whose centres lie within
574
+ ``radius`` cell sizes, refused when it reaches none (the nearest centres lie 1.075,
575
+ 1.091 and 1.122 cell sizes apart on undistorted hexagonal, BCC and FCC lattices).
576
+ """
577
+ if neighbourhood not in NEIGHBOURHOODS:
578
+ raise ValueError(f"neighbourhood: one of {NEIGHBOURHOODS}, got {neighbourhood!r}")
579
+ r = float(radius)
580
+ if not r >= 1:
581
+ raise ValueError(f"radius: must be at least 1, got {radius!r}")
582
+ key = (neighbourhood, r if neighbourhood == "euclidean" else int(r))
583
+ if key not in self._cache:
584
+ if neighbourhood == "euclidean":
585
+ ball = self.ball(r, include_self=False)
586
+ if ball[0][-1] == 0: # the automaton would change nothing
587
+ d = 2 if self.dims == 2 else 3
588
+ pts = self.centres[:, :d] - self.origin[:d]
589
+ box = self.size[:d] if self.periodic else None
590
+ tree = cKDTree(pts) if box is None else cKDTree(np.mod(pts, box), boxsize=box)
591
+ gap = float(tree.query(tree.data, k=2)[0][:, 1].min()) / self.cell_size
592
+ raise ValueError(
593
+ f"radius {r:g}: no cell centre within it of another on the {self.name} "
594
+ f"lattice, the nearest {gap:.4g} cell sizes apart (take a larger radius)"
595
+ )
596
+ self._cache[key] = ball
597
+ else:
598
+ kind = {"von_neumann": "faces", "edges": "edges", "moore": "vertices"}
599
+ base = self.adjacency(kind[neighbourhood])
600
+ self._cache[key] = base if int(r) == 1 else _power(*base, int(r))
601
+ return self._cache[key]
602
+
603
+ def ball(self, radius: float, include_self: bool = True) -> tuple[np.ndarray, np.ndarray]:
604
+ """Cells whose centres lie within ``radius`` cell sizes of each centre (CSR)."""
605
+ key = ("ball", float(radius), bool(include_self))
606
+ if key not in self._cache:
607
+ d = 2 if self.dims == 2 else 3
608
+ pts = self.centres[:, :d] - self.origin[:d]
609
+ box = self.size[:d] if self.periodic else None
610
+ indptr, indices = _shells(pts, box, float(radius) * self.cell_size * (1 + 1e-9))
611
+ if include_self:
612
+ rows, cols = _pairs(indptr, indices)
613
+ n = self.n_cells
614
+ a = sparse.csr_matrix(
615
+ (np.ones(len(rows) + n, dtype=np.int32),
616
+ (np.concatenate([rows, np.arange(n)]), np.concatenate([cols, np.arange(n)]))),
617
+ shape=(n, n),
618
+ ) # fmt: skip
619
+ a.sort_indices()
620
+ indptr, indices = a.indptr.astype(np.int64), a.indices.astype(np.int64)
621
+ self._cache[key] = (indptr, indices)
622
+ return self._cache[key]
623
+
624
+ def counts(self, state, indptr, indices) -> np.ndarray:
625
+ """Number of cells in state 1 in the CSR neighbourhoods ``(indptr, indices)``."""
626
+ out = np.empty(len(indptr) - 1, dtype=np.int32)
627
+ _csr_count(np.ascontiguousarray(state, dtype=np.uint8), indptr, indices, out)
628
+ return out
629
+
630
+ def colours(self, indptr, indices) -> np.ndarray:
631
+ """Colour of each cell such that neighbours (CSR) never share one (greedy)."""
632
+ return _greedy_colours(np.asarray(indptr, np.int64), np.asarray(indices, np.int64))
633
+
634
+ def face_measures(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
635
+ """Length (2D) or area (3D) of the face shared by each pair of face neighbours:
636
+ CSR lists ``(indptr, indices, measures)`` aligned with ``adjacency("faces")``.
637
+
638
+ Periodic tilings are the affine images ``S`` of Voronoi tilings: a face of area
639
+ ``A`` normal to the offset ``n`` of the centres becomes ``A |det S| |S^-1 n|``
640
+ (Nanson). Rhombi and rhombohedra measure the edges and faces they share: the
641
+ tiles' edge, and the area ``(2 / √5) a^2`` of golden rhombi, unless an approximant
642
+ is fitted to its box (their images by ``S``)."""
643
+ if "face_measures" not in self._cache:
644
+ indptr, indices = self.adjacency("faces")
645
+ rows, cols = _pairs(indptr, indices)
646
+ if self._plane is not None:
647
+ measure = self._prism_faces(rows, cols)
648
+ else:
649
+ s = self._solid
650
+ if "frames" in s: # golden rhombi
651
+ measure = _shared_measures(*_rhombohedron_faces(s), rows, cols)
652
+ else: # Voronoi cells of the BCC and FCC lattices
653
+ d = s["centres"][cols] - s["centres"][rows]
654
+ if self.periodic:
655
+ d -= s["box"] * np.round(d / s["box"])
656
+ r = np.linalg.norm(d, axis=1)
657
+ a = float(s["lattice"][2][0])
658
+ if self.name == "bcc": # hexagons (nearest), squares (second)
659
+ area = np.where(r < 0.9 * a, 3 * math.sqrt(3) / 16, 1 / 8) * a**2
660
+ else: # rhombi
661
+ area = np.full(len(r), a**2 / (4 * math.sqrt(2)))
662
+ scale = s["scale"]
663
+ measure = area * np.prod(scale) * np.linalg.norm(d / r[:, None] / scale, axis=1)
664
+ self._cache["face_measures"] = (indptr, indices, measure)
665
+ return self._cache["face_measures"]
666
+
667
+ def _prism_faces(self, rows, cols) -> np.ndarray:
668
+ """Edges of planar cells (lengths) or faces of prisms (areas: the edges times the
669
+ layer height across the sides, the cell's area across the bases)."""
670
+ p = self._plane
671
+ sx, sy, sz = p["scale"]
672
+ m = len(p["centres"])
673
+ a, b = rows % m, cols % m
674
+ if "vertex_ids" in p: # rhombi: the edges they share, scaled
675
+ keys, owner, sides = _polygon_sides(p)
676
+ length = _shared_measures(keys, owner, np.hypot(sx * sides[:, 0], sy * sides[:, 1]),
677
+ a, b) # fmt: skip
678
+ else:
679
+ d = p["centres"][b] - p["centres"][a]
680
+ if self.periodic:
681
+ d -= p["box"] * np.round(d / p["box"]) # minimum image (reference tiling)
682
+ r = np.linalg.norm(d, axis=1)
683
+ r[r == 0] = 1.0 # bases of prisms
684
+ n = d / r[:, None]
685
+ edge = float(np.linalg.norm(p["poly"][1] - p["poly"][0])) # every edge
686
+ length = edge * np.hypot(sy * n[:, 0], sx * n[:, 1])
687
+ if self.dims == 2:
688
+ return length
689
+ return np.where(a == b, p["areas"][a] * sx * sy, length * p["layer_height"] * sz)
690
+
691
+ def diffusion_weights(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
692
+ """Weights of the finite-volume Laplacian of the tiling, in units of the cell
693
+ size: CSR lists ``(indptr, indices, w)`` with ``w = A / d`` for the face of measure
694
+ ``A`` (length or area) between centres ``d`` apart (two-point fluxes), so that
695
+ ``lap(u)_i = sum_j w_ij (u_j - u_i) / V_i`` (``V_i`` the cell's measure, also in
696
+ cell sizes): the 5- and 7-point Laplacians on the square tiling."""
697
+ if "diffusion" not in self._cache:
698
+ indptr, indices, measure = self.face_measures()
699
+ rows, cols = _pairs(indptr, indices)
700
+ d = self.centres[cols] - self.centres[rows]
701
+ if self.periodic:
702
+ d -= self.size * np.round(d / self.size)
703
+ k = 2 if self.dims == 2 else 3
704
+ dist = np.linalg.norm(d[:, :k], axis=1)
705
+ h = self.cell_size
706
+ self._cache["diffusion"] = (indptr, indices, measure / h ** (k - 1) / (dist / h))
707
+ return self._cache["diffusion"]
708
+
709
+ def interface_density(self, state) -> float:
710
+ """Fraction of the pairs of cells sharing a face that are in different states."""
711
+ indptr, indices = self.adjacency("faces")
712
+ if not len(indices):
713
+ return 0.0
714
+ s = np.ascontiguousarray(state, dtype=np.uint8)
715
+ return _csr_differ(s, indptr, indices) / len(indices)
716
+
717
+ def cell_vertices(self, i: int) -> np.ndarray:
718
+ """Vertices of cell ``i``: its polygon (counterclockwise, ``(k, 2)``) for planar
719
+ tilings in 2D, its corners ``(k, 3)`` in 3D."""
720
+ if self._plane is not None:
721
+ p = self._plane
722
+ m = len(p["centres"])
723
+ c = int(i) % m
724
+ off = p["poly"][p["poly_ptr"][c] : p["poly_ptr"][c + 1]] * p["scale"][:2]
725
+ xy = self.centres[i, :2] + off
726
+ if self.dims == 2:
727
+ return xy
728
+ hz = 0.5 * p["layer_height"] * p["scale"][2]
729
+ z = self.centres[i, 2]
730
+ return np.concatenate(
731
+ [np.c_[xy, np.full(len(xy), z - hz)], np.c_[xy, np.full(len(xy), z + hz)]]
732
+ )
733
+ s = self._solid
734
+ if "frames" in s: # the corners of a rhombohedron, in the order of _CUBE
735
+ return self.origin + s["corner"][i] + _CUBE @ s["frames"][s["triple"][i]]
736
+ return self.centres[i] + s["prototype"] * s["scale"]
737
+
738
+ @property
739
+ def circumradius(self) -> float:
740
+ """Largest distance from a cell centre to its vertices."""
741
+ if "circumradius" not in self._cache:
742
+ if self._plane is not None:
743
+ p = self._plane
744
+ r = float(np.max(np.linalg.norm(p["poly"] * p["scale"][:2], axis=1)))
745
+ if self.dims == 3:
746
+ r = math.hypot(r, 0.5 * p["layer_height"] * p["scale"][2])
747
+ elif "circumradius" in self._solid:
748
+ r = self._solid["circumradius"]
749
+ else:
750
+ s = self._solid
751
+ r = float(np.max(np.linalg.norm(s["prototype"] * s["scale"], axis=1)))
752
+ self._cache["circumradius"] = r
753
+ return self._cache["circumradius"]
754
+
755
+ # -- point location ----------------------------------------------------------------
756
+
757
+ def locate(self, points) -> np.ndarray:
758
+ """Index of the cell containing each point (``(n, 3)``; the nearest cell for
759
+ points outside a finite patch)."""
760
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
761
+ if self._plane is None:
762
+ s = self._solid
763
+ ref = (pts - self.origin) / s["scale"]
764
+ tree = self._tree()
765
+ if self.periodic:
766
+ ref = np.mod(ref, s["box"])
767
+ if "frames" in s:
768
+ return self._locate_cells(ref)
769
+ return tree.query(ref, k=1)[1].astype(np.int64)
770
+ c2 = self._locate_plane(pts[:, :2])
771
+ return self._layer(pts[:, 2]) * len(self._plane["centres"]) + c2
772
+
773
+ def _locate_cells(self, ref) -> np.ndarray:
774
+ """Rhombohedra containing the points (tested among the 16 nearest centres, then
775
+ among all the centres closer than the circumradius for the points left)."""
776
+ s = self._solid
777
+ tree = self._tree()
778
+ k = min(16, self.n_cells)
779
+ cand = tree.query(ref, k=k)[1].reshape(len(ref), k).astype(np.int64)
780
+ out = np.empty(len(ref), dtype=np.int64)
781
+ found = np.empty(len(ref), dtype=np.bool_)
782
+ box = s["box"] if self.periodic else np.ones(3)
783
+ args = (s["centres"], s["corner"], s["triple"].astype(np.int64), s["inverse"], box,
784
+ self.periodic) # fmt: skip
785
+ _in_parallelepipeds(ref, cand, *args, out, found)
786
+ left = np.flatnonzero(~found)
787
+ if len(left):
788
+ near = tree.query_ball_point(ref[left], self.circumradius * (1 + 1e-9))
789
+ width = max(1, max(len(c) for c in near))
790
+ more = np.full((len(left), width), -1, dtype=np.int64)
791
+ for row, c in enumerate(near):
792
+ more[row, : len(c)] = c
793
+ more[:, 0] = np.where(more[:, 0] < 0, out[left], more[:, 0])
794
+ sub, hit = np.empty(len(left), np.int64), np.empty(len(left), np.bool_)
795
+ _in_parallelepipeds(ref[left], more, *args, sub, hit)
796
+ out[left[hit]] = sub[hit] # outside the patch: the nearest centre
797
+ return out
798
+
799
+ def _tree(self) -> cKDTree:
800
+ if "tree" not in self._cache:
801
+ g = self._plane if self._plane is not None else self._solid
802
+ box = g["box"] if self.periodic else None
803
+ data = np.mod(g["centres"], box) if box is not None else g["centres"]
804
+ self._cache["tree"] = cKDTree(data, boxsize=box)
805
+ return self._cache["tree"]
806
+
807
+ def _locate_plane(self, xy) -> np.ndarray:
808
+ p = self._plane
809
+ ref = (np.asarray(xy, dtype=float) - self.origin[:2]) / p["scale"][:2]
810
+ box = p["box"] if self.periodic else np.ones(2)
811
+ if self.periodic:
812
+ ref = np.mod(ref, box)
813
+ k = min(12, len(p["centres"]))
814
+ cand = self._tree().query(ref, k=k)[1].reshape(len(ref), k).astype(np.int64)
815
+ out = np.empty(len(ref), dtype=np.int64)
816
+ _in_polygons(ref, cand, p["centres"], p["poly_ptr"], p["poly"], box, self.periodic, out)
817
+ return out
818
+
819
+ def _layer(self, z) -> np.ndarray:
820
+ p = self._plane
821
+ layers = p["layers"]
822
+ if self.dims == 2:
823
+ return np.zeros(len(z), dtype=np.int64)
824
+ u = np.floor((np.asarray(z) - self.origin[2]) / (p["layer_height"] * p["scale"][2]))
825
+ u = u.astype(np.int64)
826
+ return np.mod(u, layers) if self.periodic else np.clip(u, 0, layers - 1)
827
+
828
+ def cell_index(self, grid) -> np.ndarray:
829
+ """Index of the cell containing the centre of every voxel of ``grid`` (int32
830
+ image)."""
831
+ nx, ny, nz = grid.shape
832
+ if self._plane is not None:
833
+ x, y = np.meshgrid(grid.centers(0), grid.centers(1), indexing="ij")
834
+ c2 = self._locate_plane(np.c_[x.ravel(), y.ravel()]).reshape(nx, ny)
835
+ layer = self._layer(grid.centers(2)) * len(self._plane["centres"])
836
+ return (c2[:, :, None] + layer[None, None, :]).astype(np.int32)
837
+ out = np.empty((nx, ny, nz), dtype=np.int32)
838
+ step = max(1, (1 << 20) // max(1, nx * ny))
839
+ for k0 in range(0, nz, step):
840
+ k1 = min(nz, k0 + step)
841
+ out[:, :, k0:k1] = self.locate(grid.center_points(k0, k1)).reshape(nx, ny, k1 - k0)
842
+ return out
843
+
844
+ # -- quasi-periodic tilings ----------------------------------------------------------
845
+
846
+ def vertex_stars(self) -> dict[tuple, int]:
847
+ """Vertex stars of a Penrose, Ammann-Beenker or icosahedral tiling: the number of
848
+ interior vertices of each kind.
849
+
850
+ Penrose tilings: kinds ``(index, angles)``. ``angles`` is the cyclic sequence of
851
+ the angles of the rhombi around the vertex, in units of 36 degrees (thick rhombi:
852
+ 2 and 3; thin ones: 1 and 4), smallest over rotations and reflections; ``index``
853
+ is de Bruijn's index ``sum_j K_j`` of the vertex, folded to ``min(k, 5 - k)`` (1
854
+ or 2 for Penrose tilings), which separates the stars of five thick rhombi into his
855
+ S and S5. Ammann-Beenker tilings: kinds ``angles``, in units of 45 degrees
856
+ (squares: 2; rhombi: 1 and 3).
857
+
858
+ Icosahedral tilings: the star of a vertex is the set of the golden rhombohedra
859
+ around it; kinds ``(corners, valences)``. ``corners``: the numbers of the cells
860
+ that meet the vertex by a tip of a prolate rhombohedron (the corner of its three
861
+ acute angles), by another corner of a prolate one, by a tip of an oblate one
862
+ (three obtuse angles) and by another corner of an oblate one; ``valences``: the
863
+ number of cells around each of its edges, sorted (as many as its coordination
864
+ ``Z``; its cells number ``2 Z - 4``). These tell apart the 24 stars of the tiling
865
+ up to the 120 symmetries of the icosahedron (:data:`ICOSAHEDRAL_STARS`, their
866
+ frequencies in the infinite tiling); the directions of the edges alone would give
867
+ 9 kinds. The interior vertices are those around which the solid angles of the
868
+ cells add up to the whole sphere (all of them in a periodic approximant, whose
869
+ phason strain leaves a few stars of other kinds)."""
870
+ if self.name == "icosahedral":
871
+ return _icosahedral_stars(self._solid)
872
+ p = self._plane
873
+ if p is None or "vertex_ids" not in p:
874
+ raise ValueError(
875
+ "vertex stars are defined for Penrose, Ammann-Beenker and icosahedral tilings"
876
+ )
877
+ families = MULTIGRIDS[self.name][0]
878
+ ids, poly, ptr = p["vertex_ids"], p["poly"], p["poly_ptr"]
879
+ nxt = np.arange(len(poly)) + 1
880
+ prv = np.arange(len(poly)) - 1
881
+ ends = ptr[1:] - 1
882
+ starts = ptr[:-1]
883
+ nxt[ends] = starts
884
+ prv[starts] = ends
885
+ u = poly[prv] - poly
886
+ v = poly[nxt] - poly
887
+ cos = np.einsum("ij,ij->i", u, v) / np.linalg.norm(u, axis=1) / np.linalg.norm(v, axis=1)
888
+ unit = 180.0 / families # degrees
889
+ units = np.rint(np.degrees(np.arccos(np.clip(cos, -1, 1))) / unit).astype(int)
890
+ # direction from the vertex to the cell centre orders the cells around it
891
+ direction = np.arctan2(-poly[:, 1], -poly[:, 0])
892
+ order = np.lexsort((direction, ids))
893
+ out: dict[tuple, int] = {}
894
+ bounds = np.flatnonzero(np.diff(ids[order])) + 1
895
+ for group in np.split(order, bounds):
896
+ seq = tuple(int(a) for a in units[group])
897
+ if sum(seq) != 2 * families:
898
+ continue # vertex on the edge of the patch
899
+ if self.name == "penrose":
900
+ k = int(p["vertex_index"][group[0]])
901
+ key = (min(k, 5 - k), _canonical(seq))
902
+ else:
903
+ key = _canonical(seq)
904
+ out[key] = out.get(key, 0) + 1
905
+ return out
906
+
907
+
908
+ def _canonical(seq: tuple[int, ...]) -> tuple[int, ...]:
909
+ """Smallest rotation of a cyclic sequence or of its reverse."""
910
+ k = len(seq)
911
+ forms = [seq[i:] + seq[:i] for i in range(k)]
912
+ rev = seq[::-1]
913
+ forms += [rev[i:] + rev[:i] for i in range(k)]
914
+ return min(forms)
915
+
916
+
917
+ def _icosahedral_corners() -> tuple[np.ndarray, np.ndarray]:
918
+ """The 160 corners that golden rhombohedra can have at a vertex, numbered ``8 * triple
919
+ + corner`` (the triples of axes in the order of ``itertools.combinations``, the
920
+ corners in that of the vertex numbers of the cells): the three edges that leave each,
921
+ numbered ``2 j + s`` (along ``+e_j``: ``s = 0``; along ``-e_j``: ``s = 1``), and its
922
+ species: 0, a tip of a prolate rhombohedron (three acute angles); 1, another of its
923
+ corners; 2, a tip of an oblate one (three obtuse angles); 3, another of its corners."""
924
+ e = _icosahedral_axes()
925
+ triples = itertools.combinations(range(6), 3)
926
+ edges = np.array(
927
+ [[2 * fam[k] + (c >> k & 1) for k in range(3)] for fam in triples for c in range(8)]
928
+ )
929
+ signed = np.stack([e, -e], axis=1).reshape(12, 3) # the edge 2 j + s
930
+ a, b, c = (signed[edges[:, k]] for k in range(3))
931
+ acute = sum(
932
+ (np.einsum("ij,ij->i", u, v) > 0).astype(np.int64) for u, v in ((a, b), (b, c), (c, a))
933
+ )
934
+ return edges, np.array([2, 1, 3, 0])[acute]
935
+
936
+
937
+ def _star_key(row) -> tuple:
938
+ """The kind of an icosahedral star from its four numbers of corners and its twelve
939
+ sorted valences (zero for the edges that it has not)."""
940
+ return tuple(int(v) for v in row[:4]), tuple(int(v) for v in row[4:] if v)
941
+
942
+
943
+ def _icosahedral_stars(solid: dict) -> dict[tuple, int]:
944
+ """The stars of the interior vertices of an icosahedral tiling (see
945
+ :meth:`Tiling.vertex_stars`)."""
946
+ edges, species = _icosahedral_corners()
947
+ ids = solid["vertex_ids"].ravel()
948
+ corner = (8 * solid["triple"].astype(np.int64)[:, None] + np.arange(8)).ravel()
949
+ n = int(ids.max()) + 1
950
+ # the solid angle of each corner from the edge vectors of its cell (those of an
951
+ # approximant are scaled with its box; van Oosterom & Strackee 1983)
952
+ unit = solid["frames"] / np.linalg.norm(solid["frames"], axis=2, keepdims=True)
953
+ a, b, c = ((1.0 - 2.0 * _CUBE[None, :, k, None]) * unit[:, None, k, :] for k in range(3))
954
+ volume = np.abs(np.einsum("tci,tci->tc", a, np.cross(b, c)))
955
+ cosines = sum(np.einsum("tci,tci->tc", u, v) for u, v in ((a, b), (b, c), (c, a)))
956
+ angles = (2.0 * np.arctan2(volume, 1.0 + cosines)).ravel()
957
+ whole = np.bincount(ids, weights=angles[corner], minlength=n)
958
+ interior = np.abs(whole - 4.0 * math.pi) < 1e-6
959
+ corners = np.zeros((n, 4), dtype=np.int64)
960
+ np.add.at(corners, (ids, species[corner]), 1)
961
+ valences = np.zeros((n, 12), dtype=np.int64)
962
+ np.add.at(valences, (ids[:, None], edges[corner]), 1)
963
+ valences.sort(axis=1)
964
+ rows, counts = np.unique(np.hstack([corners, valences])[interior], axis=0, return_counts=True)
965
+ return {_star_key(row): int(count) for row, count in zip(rows, counts, strict=True)}
966
+
967
+
968
+ @njit(parallel=True, cache=True)
969
+ def _window_star_rows(points, normals, low, high, species, edges, rows):
970
+ """The star of the vertex whose image in the perpendicular space is each of
971
+ ``points``: the cells that have it for a corner are those of the 160 corners whose
972
+ eight vertices fall in the window, the intervals ``[low, high]`` of its coordinates
973
+ along the 15 ``normals``; ``rows``: the numbers of corners of each species and the
974
+ sorted valences of the twelve edges."""
975
+ for p in prange(points.shape[0]):
976
+ along = np.zeros(15)
977
+ for k in range(15):
978
+ along[k] = (
979
+ normals[k, 0] * points[p, 0]
980
+ + normals[k, 1] * points[p, 1]
981
+ + normals[k, 2] * points[p, 2]
982
+ )
983
+ valences = np.zeros(12, dtype=np.int64)
984
+ for corner in range(160):
985
+ inside = True
986
+ for k in range(15):
987
+ if along[k] < low[corner, k] or along[k] > high[corner, k]:
988
+ inside = False
989
+ break
990
+ if inside:
991
+ rows[p, species[corner]] += 1
992
+ for j in range(3):
993
+ valences[edges[corner, j]] += 1
994
+ rows[p, 4:] = np.sort(valences)
995
+
996
+
997
+ def window_stars(samples: int = 1 << 20, rng: np.random.Generator | None = None) -> dict:
998
+ """Frequencies of the vertex stars of the icosahedral tiling by cut and projection
999
+ (the kinds of :meth:`Tiling.vertex_stars`): the tiling is the projection of the points
1000
+ of Z^6 whose images in the perpendicular space fall in a window, the rhombic
1001
+ triacontahedron (the zonotope of the six perpendicular axes); a rhombohedron is a
1002
+ cell when its eight corners do, so that the star of a vertex depends only on its
1003
+ image, and the frequency of a star is the share of the window in which the images of
1004
+ its vertices fall. That share is measured here on ``samples`` points drawn uniformly
1005
+ in the box of the window (about 0.59 of them fall in it): an estimate within
1006
+ ``sqrt(f (1 - f) / (0.59 samples))`` of each frequency ``f``, independent of the
1007
+ dual method that builds the tilings (:data:`ICOSAHEDRAL_STARS`: the 24 stars and
1008
+ their frequencies)."""
1009
+ rng = np.random.default_rng() if rng is None else rng
1010
+ axes = _icosahedral_axes(-1.0 / GOLDEN) # of the perpendicular space
1011
+ signed = np.stack([axes, -axes], axis=1).reshape(12, 3)
1012
+ # the faces of the zonotope: normal to the 15 pairs of axes
1013
+ normals = np.array([np.cross(axes[a], axes[b]) for a, b in itertools.combinations(range(6), 2)])
1014
+ normals /= np.linalg.norm(normals, axis=1, keepdims=True)
1015
+ support = 0.5 * np.abs(normals @ axes.T).sum(axis=1)
1016
+ edges, species = _icosahedral_corners()
1017
+ # a corner of a cell: the vertex and the sums of its three edges, all in the window
1018
+ sums = np.einsum("mk,ckj->cmj", _CUBE, signed[edges]) # corners x 8 x 3
1019
+ along = sums @ normals.T
1020
+ low, high = -support - along.min(axis=1), support - along.max(axis=1)
1021
+ reach = 0.5 * np.abs(axes).sum(axis=0)
1022
+ points = (2.0 * rng.random((int(samples), 3)) - 1.0) * reach
1023
+ points = points[np.all(np.abs(points @ normals.T) <= support, axis=1)]
1024
+ if not len(points):
1025
+ raise ValueError("samples: too few points to fall in the window")
1026
+ rows = np.zeros((len(points), 16), dtype=np.int64)
1027
+ _window_star_rows(points, normals, low, high, species, edges, rows)
1028
+ weights = 21 ** np.arange(4) * 11**12 # one number per row: fewer than 21 and 11 of each
1029
+ codes = rows[:, :4] @ weights + rows[:, 4:] @ 11 ** np.arange(12)
1030
+ _, first, counts = np.unique(codes, return_index=True, return_counts=True)
1031
+ return {_star_key(rows[i]): n / len(points) for i, n in zip(first, counts, strict=True)}
1032
+
1033
+
1034
+ def _prism_adjacency(plane: dict, dims: int, periodic: bool, kind: str):
1035
+ """Adjacency ``kind`` of the layers of prisms over a planar tiling (one layer in 2D):
1036
+ prisms share a face across a planar edge or a base, an edge across a planar vertex or
1037
+ the edges of a base, a vertex across a planar vertex within a layer or the next."""
1038
+ m = len(plane["centres"])
1039
+ layers = plane["layers"] if dims == 3 else 1
1040
+ if layers == 1:
1041
+ return plane["faces"] if kind == "faces" else plane["vertices"]
1042
+ faces2 = _pairs(*plane["faces"])
1043
+ vertices2 = _pairs(*plane["vertices"])
1044
+ same_cell = (np.arange(m), np.arange(m))
1045
+
1046
+ def join(*parts):
1047
+ return np.concatenate([p[0] for p in parts]), np.concatenate([p[1] for p in parts])
1048
+
1049
+ def stack(within, across):
1050
+ rows, cols = [], []
1051
+ for layer in range(layers):
1052
+ rows.append(within[0] + layer * m)
1053
+ cols.append(within[1] + layer * m)
1054
+ up = layer + 1
1055
+ if up == layers:
1056
+ if not (periodic and layers > 2):
1057
+ continue
1058
+ up = 0
1059
+ rows.append(across[0] + layer * m)
1060
+ cols.append(across[1] + up * m)
1061
+ return _csr(m * layers, np.concatenate(rows), np.concatenate(cols))
1062
+
1063
+ if kind == "faces":
1064
+ return stack(faces2, same_cell)
1065
+ if kind == "edges":
1066
+ return stack(vertices2, join(faces2, same_cell))
1067
+ return stack(vertices2, join(vertices2, same_cell))
1068
+
1069
+
1070
+ class TilingContext:
1071
+ """Neighbourhood of the cells of a tiling on which a rule acts: the counterpart of
1072
+ :class:`~morphogen.automata.rules.LatticeContext`, for states holding one value per
1073
+ cell. ``n_neighbours`` is a number, or an array when cells differ (Penrose tilings,
1074
+ edges of finite patches)."""
1075
+
1076
+ def __init__(self, tiling: Tiling, neighbourhood: str = "moore", radius: float = 1):
1077
+ self.tiling = tiling
1078
+ self.periodic = tiling.periodic
1079
+ self.dims = tiling.dims
1080
+ self.boundary = 0
1081
+ self.indptr, self.indices = tiling.neighbours(neighbourhood, radius)
1082
+ sizes = np.diff(self.indptr)
1083
+ regular = len(sizes) > 0 and bool(np.all(sizes == sizes[0]))
1084
+ self.n_neighbours = int(sizes[0]) if regular else sizes
1085
+ self.cache: dict = {}
1086
+
1087
+ def counts(self, state: np.ndarray) -> np.ndarray:
1088
+ return self.tiling.counts(state, self.indptr, self.indices)
1089
+
1090
+ def interface(self, state: np.ndarray) -> float:
1091
+ return self.tiling.interface_density(state)
1092
+
1093
+ def sublattices(self) -> list[np.ndarray]:
1094
+ """Classes of cells that are not neighbours (greedy colouring)."""
1095
+ colour = self.tiling.colours(self.indptr, self.indices)
1096
+ return [colour == c for c in np.unique(colour)]
1097
+
1098
+
1099
+ # -- generators ----------------------------------------------------------------------------
1100
+
1101
+
1102
+ def _regular_plane(name: str, size, h: float) -> dict:
1103
+ """Square, triangular or hexagonal tiling of whole rectangular unit cells about
1104
+ ``size``: the cell ``i`` of the unit cell ``c`` (C order) is ``c * n_basis + i``."""
1105
+ if name == "square":
1106
+ cell = np.array([h, h])
1107
+ basis = np.array([[0.5, 0.5]])
1108
+ kinds = np.zeros(1, dtype=np.int8)
1109
+ shapes = [0.5 * h * np.array([[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]])]
1110
+ shells = {"faces": h, "vertices": math.sqrt(2) * h}
1111
+ elif name == "hexagonal":
1112
+ a = h * math.sqrt(2 / math.sqrt(3)) # centre spacing of hexagons of area h^2
1113
+ cell = np.array([a, math.sqrt(3) * a])
1114
+ basis = np.array([[0.25, 0.25], [0.75, 0.75]])
1115
+ kinds = np.zeros(2, dtype=np.int8)
1116
+ t = np.radians(90 + 60 * np.arange(6))
1117
+ shapes = [a / math.sqrt(3) * np.c_[np.cos(t), np.sin(t)]]
1118
+ shells = {"faces": a, "vertices": a}
1119
+ else: # triangles: the Voronoi cells of the honeycomb of their centroids
1120
+ b = 2 * h / 3**0.25 # edge of the triangles of area h^2
1121
+ rise = math.sqrt(3) / 2 * b
1122
+ cell = np.array([b, 2 * rise])
1123
+ basis = np.array([[0.5, 1 / 6], [0.0, 1 / 3], [0.0, 2 / 3], [0.5, 5 / 6]])
1124
+ kinds = np.array([0, 1, 0, 1], dtype=np.int8) # pointing up, down
1125
+ shapes = [
1126
+ np.array([[-b / 2, -rise / 3], [b / 2, -rise / 3], [0.0, 2 * rise / 3]]),
1127
+ np.array([[0.0, -2 * rise / 3], [b / 2, rise / 3], [-b / 2, rise / 3]]),
1128
+ ]
1129
+ shells = {"faces": b / math.sqrt(3), "vertices": 2 * b / math.sqrt(3)}
1130
+ n = np.maximum(1, np.rint(np.asarray(size[:2], dtype=float) / cell)).astype(int)
1131
+ units = np.stack(np.meshgrid(*(np.arange(m) for m in n), indexing="ij"), -1).reshape(-1, 2)
1132
+ kinds = np.tile(kinds, len(units))
1133
+ k = np.array([len(shapes[c]) for c in kinds])
1134
+ return {
1135
+ "centres": ((units[:, None, :] + basis[None]) * cell).reshape(-1, 2),
1136
+ "poly": np.concatenate([shapes[c] for c in kinds]),
1137
+ "poly_ptr": np.concatenate([[0], np.cumsum(k)]).astype(np.int64),
1138
+ "areas": np.full(len(kinds), h * h),
1139
+ "kinds": kinds,
1140
+ "box": n * cell,
1141
+ "lattice": (n, basis, cell),
1142
+ "shells": shells,
1143
+ }
1144
+
1145
+
1146
+ def _dual_cells(e: np.ndarray, gamma, half, families):
1147
+ """Cells of the tiling dual to the multigrid ``x . e_j + gamma_j = k`` (``k``
1148
+ integer, ``e`` the unit vectors of the grids, in rows) whose centres lie within
1149
+ ``half`` (edges) of the origin: one cell per intersection of hyperplanes (lines in 2D,
1150
+ planes in 3D) of the ``d`` families of each tuple of ``families``.
1151
+
1152
+ The mesh of a point ``x`` maps to the vertex ``sum_j K_j e_j``, ``K_j = ceil(x . e_j +
1153
+ gamma_j)``, and an intersection to the cell of edges ``e_r`` (``r`` in its families)
1154
+ whose corners are those of the meshes around it (de Bruijn 1981; Kramer & Neri 1984).
1155
+ Since ``sum_j (x . e_j) e_j = (n / d) x`` for these grids, the tiling is the grid
1156
+ scaled by ``n / d``, up to a displacement of at most ``sum_j (1 + |gamma_j|)``, which
1157
+ bounds the hyperplanes to generate. Yields, for each tuple, its integer indices ``K``
1158
+ of the corner of the cell (of the meshes on the negative side of all its
1159
+ hyperplanes), its centre and the other grids' values at the intersection.
1160
+ """
1161
+ n, d = e.shape
1162
+ zr = (float(np.linalg.norm(half)) + n + float(np.abs(gamma).sum())) / (n / d) + 1.0
1163
+ for fam in families:
1164
+ fam = list(fam)
1165
+ ranges = [np.arange(math.floor(gamma[r] - zr), math.ceil(gamma[r] + zr) + 1) for r in fam]
1166
+ k = np.stack([g.ravel() for g in np.meshgrid(*ranges, indexing="ij")], axis=1)
1167
+ z = np.linalg.solve(e[fam], (k - gamma[fam]).T).T
1168
+ w = z @ e.T + gamma
1169
+ big_k = np.ceil(w).astype(np.int64)
1170
+ big_k[:, fam] = k
1171
+ centre = big_k @ e + 0.5 * e[fam].sum(axis=0)
1172
+ keep = np.all(np.abs(centre) <= half, axis=1)
1173
+ yield fam, big_k[keep], centre[keep], np.delete(w[keep], fam, axis=1)
1174
+
1175
+
1176
+ def _check_regular(other, gamma, what: str) -> None:
1177
+ """Refuse singular grids: more hyperplanes than the dimension through one point."""
1178
+ if np.any(np.abs(other - np.round(other)) < 1e-9):
1179
+ raise ValueError(
1180
+ f"offsets {np.round(gamma, 12).tolist()}: a singular {what}, whose cells would "
1181
+ "overlap (offsets drawn at random are regular)"
1182
+ )
1183
+
1184
+
1185
+ def _vertex_ids(keys: np.ndarray) -> np.ndarray:
1186
+ """Number of the vertex of each row of integer indices ``keys`` (the same numbers as
1187
+ the rows' lexicographic order: the indices are packed into one integer)."""
1188
+ lo = keys.min(axis=0)
1189
+ base = int((keys.max(axis=0) - lo).max()) + 1
1190
+ if base ** keys.shape[1] >= 2**62:
1191
+ return np.unique(keys, axis=0, return_inverse=True)[1].ravel().astype(np.int64)
1192
+ packed = np.zeros(len(keys), dtype=np.int64)
1193
+ for j in range(keys.shape[1]):
1194
+ packed = packed * base + (keys[:, j] - lo[j])
1195
+ return np.unique(packed, return_inverse=True)[1].ravel().astype(np.int64)
1196
+
1197
+
1198
+ def _shared_vertices(vertex_ids: np.ndarray, n: int):
1199
+ """Number of vertices shared by the pairs of cells (COO, the cells sharing one at
1200
+ least) from the vertex numbers of each cell (``(n, k)``)."""
1201
+ k = vertex_ids.shape[1]
1202
+ incidence = sparse.csr_matrix(
1203
+ (np.ones(k * n, dtype=np.int32), (np.repeat(np.arange(n), k), vertex_ids.ravel())),
1204
+ shape=(n, int(vertex_ids.max()) + 1),
1205
+ )
1206
+ return (incidence @ incidence.T).tocoo()
1207
+
1208
+
1209
+ def _polygon_sides(plane: dict):
1210
+ """Sides of the rhombi of a multigrid tiling: their vertex numbers (sorted pairs), the
1211
+ cell of each and its vector (in the reference tiling)."""
1212
+ ids = plane["vertex_ids"].reshape(-1, 4)
1213
+ poly = plane["poly"].reshape(-1, 4, 2)
1214
+ keys = np.sort(np.stack([ids, np.roll(ids, -1, axis=1)], axis=2), axis=2).reshape(-1, 2)
1215
+ owner = np.repeat(np.arange(len(ids)), 4)
1216
+ return keys, owner, (np.roll(poly, -1, axis=1) - poly).reshape(-1, 2)
1217
+
1218
+
1219
+ def _rhombohedron_faces(solid: dict):
1220
+ """Faces of the rhombohedra: their vertex numbers (sorted), the cell of each and its
1221
+ area (the cross product of the two edges spanning it)."""
1222
+ ids = solid["vertex_ids"]
1223
+ keys = np.sort(ids[:, PARALLELEPIPED_FACES], axis=2).reshape(-1, 4)
1224
+ owner = np.repeat(np.arange(len(ids)), 6)
1225
+ f = solid["frames"][solid["triple"]] # edge vectors in rows
1226
+ span = np.array([[1, 2], [1, 2], [0, 2], [0, 2], [0, 1], [0, 1]]) # of each face
1227
+ areas = np.linalg.norm(np.cross(f[:, span[:, 0]], f[:, span[:, 1]]), axis=2).ravel()
1228
+ return keys, owner, areas
1229
+
1230
+
1231
+ def _shared_measures(keys, owner, measures, rows, cols) -> np.ndarray:
1232
+ """Measures of the sides (or faces) shared by the pairs of cells ``(rows, cols)``: the
1233
+ sides of the cells ``owner`` met twice among ``keys`` (their vertex numbers), summed
1234
+ when a pair shares several (on the smallest tori); 0 for pairs sharing none."""
1235
+ order = np.lexsort(keys.T[::-1])
1236
+ same = np.all(keys[order[1:]] == keys[order[:-1]], axis=1)
1237
+ first, second = order[:-1][same], order[1:][same]
1238
+ i, j, w = owner[first], owner[second], measures[first]
1239
+ n = int(owner.max()) + 1
1240
+ m = sparse.csr_matrix((np.r_[w, w], (np.r_[i, j], np.r_[j, i])), shape=(n, n))
1241
+ if not len(rows):
1242
+ return np.zeros(0)
1243
+ return np.asarray(m[rows, cols]).ravel()
1244
+
1245
+
1246
+ def _multigrid_plane(name: str, size, h: float, gamma) -> dict:
1247
+ """Rhombi of the Penrose or Ammann-Beenker tiling dual to the multigrid of offsets
1248
+ ``gamma`` (the pentagrid, or four grids at 45°; de Bruijn 1981) whose centres lie
1249
+ within one edge of the box ``[0, size]``.
1250
+
1251
+ The lines ``x . e_j + gamma_j = k`` (``e_j`` at angles ``2 pi j / 5`` or ``pi j / 4``,
1252
+ ``k`` integer) split the plane into meshes, mapped to the vertices of the tiling; the
1253
+ intersection of lines of the families ``r < s`` maps to the rhombus of edges
1254
+ ``e_r, e_s``: thick when ``s - r`` is 1 or 4, thin otherwise (Penrose); a square when
1255
+ ``s - r = 2``, a 45° rhombus otherwise (Ammann-Beenker). Kind 0 is the larger tile.
1256
+ """
1257
+ edge = tile_edge(name, h)
1258
+ e = _star(name)
1259
+ gamma = np.asarray(gamma, dtype=float)
1260
+ half = np.asarray(size[:2], dtype=float) / (2 * edge) + 1.0 # in edges
1261
+ pairs = list(itertools.combinations(range(len(e)), 2))
1262
+ rhombi = _Rhombi(name, e)
1263
+ for (r, s), big_k, centre, third in _dual_cells(e, gamma, half, pairs):
1264
+ _check_regular(third, gamma, rhombi.what)
1265
+ rhombi.add(r, s, big_k, centre)
1266
+ return rhombi.plane(edge, 0.5 * np.asarray(size[:2], dtype=float), None, lambda keys: keys)
1267
+
1268
+
1269
+ def _approximant_plane(name: str, size, h: float, gamma, order) -> dict:
1270
+ """Rhombi of the periodic approximant of order ``order`` of the Penrose or
1271
+ Ammann-Beenker tiling (the multigrid of :func:`approximant_grid` and offsets
1272
+ ``gamma``) filling a whole number of periods, about ``size``: the box of the tiling.
1273
+
1274
+ The intersections of the lines of families ``r < s`` in the box of grid periods map
1275
+ to the rhombi of edges ``e_r, e_s`` as on the patches of :func:`_multigrid_plane`,
1276
+ ``|det(g_r, g_s)|`` per period; the vertices, integer vectors reduced modulo the
1277
+ periods, are those of the torus, whose adjacency wraps across the faces of the box.
1278
+ """
1279
+ edge = tile_edge(name, h)
1280
+ e = _star(name)
1281
+ grid = approximant_grid(name, order)
1282
+ counts = _period_counts(name, order, size[:2], h)
1283
+ reduce = _reduction(grid * counts)
1284
+ rhombi = _Rhombi(name, e)
1285
+ pairs = list(itertools.combinations(range(len(e)), 2))
1286
+ cells = _periodic_dual_cells(e, grid, gamma, counts, pairs, reduce, rhombi.what)
1287
+ for (r, s), big_k in cells:
1288
+ rhombi.add(r, s, big_k, big_k @ e + 0.5 * (e[r] + e[s]))
1289
+ box = np.diag(e.T @ grid) * counts * edge
1290
+ plane = rhombi.plane(edge, np.zeros(2), box, reduce)
1291
+ m = len(plane["centres"])
1292
+ corners = plane["poly"].reshape(m, 4, 2)
1293
+ why = _torus_defect(plane["vertex_ids"].reshape(m, 4), [_RHOMBUS_SIDES], corners,
1294
+ plane["centres"], box) # fmt: skip
1295
+ if why is not None:
1296
+ raise _degenerate(name, order, counts, h, why)
1297
+ return plane
1298
+
1299
+
1300
+ #: Corners of the sides of a rhombus (its polygon, counterclockwise).
1301
+ _RHOMBUS_SIDES = np.array([[0, 1], [1, 2], [2, 3], [3, 0]])
1302
+
1303
+
1304
+ def _torus_defect(ids, groups, corners, centres, box) -> str | None:
1305
+ """What makes a tiling of the torus degenerate, or None: ``ids``, the vertex numbers
1306
+ of the corners of each cell (``n x k``); ``groups``, the corners of its sides, then of
1307
+ its faces in 3D (index arrays); ``corners``, their positions from the cell centres.
1308
+
1309
+ On a torus too small for its cells, a cell meets its own image (a vertex twice among
1310
+ its corners), or two cells meet through several images: the vertices they share,
1311
+ counted before the adjacency is deduplicated, are then not those of a single common
1312
+ vertex, side or face, and their CSR neighbourhoods would be wrong (several faces, or
1313
+ two vertices taken for an edge); or two cells share a face through another image than
1314
+ the nearest, which the fluxes of the Laplacian take."""
1315
+ n = len(ids)
1316
+ ranked = np.sort(ids, axis=1)
1317
+ if np.any(ranked[:, 1:] == ranked[:, :-1]):
1318
+ return "a cell meets its own image"
1319
+ shared = _shared_vertices(ids, n) # with multiplicity: before any deduplication
1320
+ other = shared.row != shared.col
1321
+ rows, cols, count = shared.row[other], shared.col[other], shared.data[other]
1322
+ common = []
1323
+ for g in groups: # sides (faces) shared by the pairs of cells sharing vertices
1324
+ keys = _vertex_ids(np.sort(ids[:, g], axis=2).reshape(-1, g.shape[1]))
1325
+ m = _shared_vertices(keys.reshape(n, len(g)), n).tocsr()
1326
+ common.append(np.asarray(m[rows, cols]).ravel())
1327
+ single = (count == 1) | ((count == 2) & (common[0] == 1))
1328
+ if len(groups) == 2: # rhombohedra: a vertex, an edge or a face
1329
+ single |= (count == 4) & (common[1] == 1)
1330
+ if not np.all(single):
1331
+ return "two cells meet through several images: several faces, edges or vertices"
1332
+ g = groups[-1] # each face, seen from its two cells through the nearest image
1333
+ keys = np.sort(ids[:, g], axis=2).reshape(-1, g.shape[1])
1334
+ at = corners[:, g].mean(axis=2).reshape(-1, corners.shape[2])
1335
+ owner = np.repeat(np.arange(n), len(g))
1336
+ order = np.lexsort(keys.T[::-1])
1337
+ pair = np.all(keys[order[1:]] == keys[order[:-1]], axis=1)
1338
+ p, q = order[:-1][pair], order[1:][pair]
1339
+ d = centres[owner[q]] - centres[owner[p]]
1340
+ d -= box * np.round(d / box)
1341
+ if np.abs(at[p] - d - at[q]).max() > 1e-9 * np.abs(corners).max():
1342
+ return "two cells share a face through another image than the nearest"
1343
+ return None
1344
+
1345
+
1346
+ def _degenerate(name: str, order, counts, h: float, why: str) -> ValueError:
1347
+ period = approximant_period(name, order, h)
1348
+ return ValueError(
1349
+ f"approximant {order} of the {name} tiling: {np.asarray(counts).tolist()} periods of "
1350
+ f"{np.round(period, 3).tolist()} make a torus too small for its cells ({why}); take "
1351
+ "a larger box (more periods) or a higher order"
1352
+ )
1353
+
1354
+
1355
+ def _period_counts(name: str, order, size, h: float) -> np.ndarray:
1356
+ """Number of periods of an approximant along each axis of a box: the nearest whole
1357
+ number, refused when the box is less than half a period."""
1358
+ period = approximant_period(name, order, h)
1359
+ counts = np.rint(np.asarray(size, dtype=float) / period).astype(int)
1360
+ if np.any(counts < 1):
1361
+ raise ValueError(
1362
+ f"approximant {order}: the box {np.round(size, 4).tolist()} is less than half its "
1363
+ f"period {np.round(period, 4).tolist()} (take a lower order or a larger box)"
1364
+ )
1365
+ return counts
1366
+
1367
+
1368
+ class _Rhombi:
1369
+ """Rhombi of a planar multigrid tiling, gathered by families (:func:`_dual_cells`,
1370
+ :func:`_periodic_dual_cells`): kind 0 the larger tile."""
1371
+
1372
+ def __init__(self, name: str, e: np.ndarray) -> None:
1373
+ n, step = MULTIGRIDS[name]
1374
+ self.n, self.e = n, e
1375
+ self.sine = np.abs(np.sin(step * (np.arange(n)[None] - np.arange(n)[:, None])))
1376
+ self.what = (
1377
+ f"{'pentagrid' if n == 5 else 'multigrid'}, three of its lines through one point"
1378
+ )
1379
+ self.centres, self.polys, self.keys, self.kinds, self.areas = [], [], [], [], []
1380
+
1381
+ def add(self, r: int, s: int, big_k: np.ndarray, centre: np.ndarray) -> None:
1382
+ """Rhombi of edges ``e_r, e_s``, their corners ``big_k`` and centres (in edges)."""
1383
+ e, n, sine = self.e, self.n, self.sine
1384
+ corner = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
1385
+ if e[r, 0] * e[s, 1] - e[r, 1] * e[s, 0] < 0:
1386
+ corner = corner[::-1]
1387
+ offsets = corner @ np.array([e[r], e[s]]) - 0.5 * (e[r] + e[s])
1388
+ unit = np.zeros((4, n), dtype=np.int64)
1389
+ unit[:, r] = corner[:, 0]
1390
+ unit[:, s] = corner[:, 1]
1391
+ self.centres.append(centre)
1392
+ self.polys.append(np.broadcast_to(offsets, (len(centre), 4, 2)))
1393
+ self.keys.append(big_k[:, None, :] + unit[None])
1394
+ kind = 0 if sine[r, s] > sine.max() - 1e-9 else 1
1395
+ self.kinds.append(np.full(len(centre), kind, np.int8))
1396
+ self.areas.append(np.full(len(centre), sine[r, s]))
1397
+
1398
+ def plane(self, edge: float, shift, box, reduce) -> dict:
1399
+ """The planar tiling (centres shifted by ``shift``, wrapped into ``box`` when it is
1400
+ periodic, the corners reduced by ``reduce`` modulo its periods)."""
1401
+ centres = np.concatenate(self.centres) * edge + shift
1402
+ if box is not None:
1403
+ centres = np.mod(centres, box)
1404
+ m = len(centres)
1405
+ keys = reduce(np.concatenate(self.keys)).reshape(-1, self.n)
1406
+ vertex_ids = _vertex_ids(keys)
1407
+ shared = _shared_vertices(vertex_ids.reshape(m, 4), m)
1408
+ edge_pairs = shared.data >= 2
1409
+ return {
1410
+ "centres": centres,
1411
+ "poly": np.concatenate(self.polys).reshape(-1, 2) * edge,
1412
+ "poly_ptr": 4 * np.arange(m + 1, dtype=np.int64),
1413
+ "areas": np.concatenate(self.areas) * edge**2,
1414
+ "kinds": np.concatenate(self.kinds),
1415
+ "box": box,
1416
+ "edge": edge,
1417
+ "vertex_ids": vertex_ids,
1418
+ "vertex_index": keys.sum(axis=1),
1419
+ "faces": _csr(m, shared.row[edge_pairs], shared.col[edge_pairs]),
1420
+ "vertices": _csr(m, shared.row, shared.col),
1421
+ }
1422
+
1423
+
1424
+ def _cubic_solid(name: str, size, h: float) -> dict:
1425
+ """Body- or face-centred cubic lattice of whole cubic cells, about ``size``."""
1426
+ if name == "bcc":
1427
+ a = 2 ** (1 / 3) * h # two cells of volume h^3 per cube
1428
+ basis = np.array([[0.25, 0.25, 0.25], [0.75, 0.75, 0.75]])
1429
+ corners = set()
1430
+ for p in ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)):
1431
+ for sy in (-1.0, 1.0):
1432
+ for sz in (-1.0, 1.0):
1433
+ corners.add(tuple(np.array([0.0, sy, 2 * sz])[list(p)]))
1434
+ prototype = np.array(sorted(corners)) * a / 4 # truncated octahedron
1435
+ shells = {"faces": a, "edges": a, "vertices": a}
1436
+ volume = a**3 / 2
1437
+ else:
1438
+ a = 4 ** (1 / 3) * h # four cells of volume h^3 per cube
1439
+ basis = 0.25 + np.array([[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]])
1440
+ axes = np.concatenate([np.eye(3), -np.eye(3)]) * a / 2
1441
+ signs = np.array(np.meshgrid([-1, 1], [-1, 1], [-1, 1], indexing="ij")).reshape(3, -1).T
1442
+ prototype = np.concatenate([axes, signs * a / 4]) # rhombic dodecahedron
1443
+ shells = {"faces": a / math.sqrt(2), "edges": a / math.sqrt(2), "vertices": a}
1444
+ volume = a**3 / 4
1445
+ n = np.maximum(1, np.rint(np.asarray(size, dtype=float) / a)).astype(int)
1446
+ cells = np.stack(np.meshgrid(*(np.arange(m) for m in n), indexing="ij"), -1).reshape(-1, 3)
1447
+ centres = ((cells[:, None, :] + basis[None]) * a).reshape(-1, 3)
1448
+ return {
1449
+ "centres": centres,
1450
+ "box": n * a,
1451
+ "lattice": (n, basis, np.full(3, a)),
1452
+ "scale": np.asarray(size, dtype=float) / (n * a),
1453
+ "shells": shells,
1454
+ "prototype": prototype,
1455
+ "volume": volume,
1456
+ }
1457
+
1458
+
1459
+ #: Corners of the unit cube, the bits of the corners of a parallelepiped (x fastest).
1460
+ _CUBE = np.array([[i & 1, (i >> 1) & 1, (i >> 2) & 1] for i in range(8)], dtype=np.int64)
1461
+ #: The six faces of a parallelepiped, as indices of its corners in :data:`_CUBE`
1462
+ #: (around each face: x = 0, 1, y = 0, 1, z = 0, 1).
1463
+ PARALLELEPIPED_FACES = np.array(
1464
+ [[0, 2, 6, 4], [1, 3, 7, 5], [0, 1, 5, 4], [2, 3, 7, 6], [0, 1, 3, 2], [4, 5, 7, 6]]
1465
+ )
1466
+ #: Its twelve edges: the corners whose bits differ by one.
1467
+ _PARALLELEPIPED_EDGES = np.array(
1468
+ [(i, i | 1 << b) for b in range(3) for i in range(8) if not i >> b & 1]
1469
+ )
1470
+
1471
+
1472
+ def _icosahedral_solid(size, h: float, gamma) -> dict:
1473
+ """Golden rhombohedra of the icosahedral tiling dual to the six grids of planes
1474
+ ``x . e_j + gamma_j = k`` normal to the fivefold axes ``e_j`` of the icosahedron, whose
1475
+ centres lie within one edge of the box ``[0, size]`` (the generalized dual method of
1476
+ de Bruijn, Kramer & Neri 1984, Socolar & Steinhardt 1986).
1477
+
1478
+ The intersection of planes of the families ``r < s < t`` maps to the rhombohedron of
1479
+ edges ``e_r, e_s, e_t``: prolate (kind 0) when the product of their pairwise cosines
1480
+ (``±1/√5``) is positive, oblate (kind 1) otherwise. Its corners are integer vectors
1481
+ of Z^6, which number the vertices shared by the cells without tolerance.
1482
+ """
1483
+ edge = tile_edge("icosahedral", h)
1484
+ e = _icosahedral_axes()
1485
+ gamma = np.asarray(gamma, dtype=float)
1486
+ half = np.asarray(size, dtype=float) / (2 * edge) + 1.0 # in edges
1487
+ triples = list(itertools.combinations(range(6), 3))
1488
+ cells = []
1489
+ for fam, big_k, centre, other in _dual_cells(e, gamma, half, triples):
1490
+ _check_regular(other, gamma, _ICOSAHEDRAL_SINGULAR)
1491
+ cells.append((fam, big_k, centre))
1492
+ shift = 0.5 * np.asarray(size, dtype=float)
1493
+ return _rhombohedra(e, cells, edge, np.ones(3), shift, None, lambda keys: keys)
1494
+
1495
+
1496
+ _ICOSAHEDRAL_SINGULAR = "icosahedral grid, four of its planes through one point"
1497
+
1498
+
1499
+ def _approximant_solid(size, h: float, gamma, order) -> dict:
1500
+ """Golden rhombohedra of the periodic (cubic) approximant of order ``order`` of the
1501
+ icosahedral tiling (the grids of planes of :func:`approximant_grid`, offsets
1502
+ ``gamma``) filling a whole number of periods, scaled to the box ``size`` along each
1503
+ axis (the scale is part of the cells: edge vectors, corners, volumes). The
1504
+ intersections of planes of the families ``r < s < t`` in the box of grid periods map
1505
+ to the rhombohedra of edges ``e_r, e_s, e_t``, ``|det(g_r, g_s, g_t)|`` per period, and
1506
+ their vertices are reduced modulo the periods (those of the 3-torus)."""
1507
+ edge = tile_edge("icosahedral", h)
1508
+ e = _icosahedral_axes()
1509
+ grid = approximant_grid("icosahedral", order)
1510
+ size = np.asarray(size, dtype=float)
1511
+ counts = _period_counts("icosahedral", order, size, h)
1512
+ reduce = _reduction(grid * counts)
1513
+ triples = list(itertools.combinations(range(6), 3))
1514
+ cells = [
1515
+ (fam, big_k, big_k @ e + 0.5 * e[fam].sum(axis=0))
1516
+ for fam, big_k in _periodic_dual_cells(
1517
+ e, grid, gamma, counts, triples, reduce, _ICOSAHEDRAL_SINGULAR
1518
+ )
1519
+ ]
1520
+ scale = size / (np.diag(e.T @ grid) * counts * edge)
1521
+ solid = _rhombohedra(e, cells, edge, scale, np.zeros(3), size, reduce)
1522
+ frames = solid["frames"] # the corners from the centres, for each triple
1523
+ rel = np.einsum("vk,tkj->tvj", _CUBE, frames) - 0.5 * frames.sum(axis=1)[:, None]
1524
+ groups = [_PARALLELEPIPED_EDGES, PARALLELEPIPED_FACES]
1525
+ why = _torus_defect(solid["vertex_ids"], groups, rel[solid["triple"]], solid["centres"], size)
1526
+ if why is not None:
1527
+ raise _degenerate("icosahedral", order, counts, h, why)
1528
+ return solid
1529
+
1530
+
1531
+ def _rhombohedra(e, cells, edge: float, scale, shift, box, reduce) -> dict:
1532
+ """The rhombohedra of the triples ``fam`` of ``cells`` (``(fam, corners K, centres)``,
1533
+ in edges), scaled along the axes by ``scale`` and shifted by ``shift``: corners are
1534
+ integer vectors of Z^6 (reduced by ``reduce`` modulo the periods of a periodic
1535
+ ``box``, into which the centres are wrapped) that number the vertices shared by the
1536
+ cells without tolerance."""
1537
+ triples = list(itertools.combinations(range(6), 3))
1538
+ frames = np.array([e[list(f)] for f in triples]) * edge * scale # edge vectors, in rows
1539
+ dets = np.abs(np.linalg.det(frames))
1540
+ keys, triple, centres = [], [], []
1541
+ for fam, big_k, centre in cells:
1542
+ unit = np.zeros((8, 6), dtype=np.int64)
1543
+ unit[:, fam] = _CUBE
1544
+ centres.append(centre)
1545
+ keys.append(reduce(big_k[:, None, :] + unit[None]).astype(np.int32)) # small indices
1546
+ triple.append(np.full(len(centre), triples.index(tuple(fam)), dtype=np.int8))
1547
+ centres = np.concatenate(centres) * edge * scale + shift
1548
+ if box is not None:
1549
+ centres = np.mod(centres, box)
1550
+ n = len(centres)
1551
+ triple = np.concatenate(triple)
1552
+ vertex_ids = _vertex_ids(np.concatenate(keys).reshape(-1, 6)).reshape(n, 8)
1553
+ shared = _shared_vertices(vertex_ids, n)
1554
+ prolate = dets > dets.mean()
1555
+ # the corners of the cells, from their centres: the largest distance to them
1556
+ half = 0.5 * frames.sum(axis=1)
1557
+ reach = np.linalg.norm(_CUBE @ frames - half[:, None], axis=2).max()
1558
+ return {
1559
+ "centres": centres,
1560
+ "scale": np.ones(3),
1561
+ "box": box,
1562
+ "edge": edge,
1563
+ "volumes": dets[triple],
1564
+ "kinds": np.where(prolate[triple], 0, 1).astype(np.int8),
1565
+ "corner": centres - half[triple],
1566
+ "triple": triple,
1567
+ "frames": frames,
1568
+ "inverse": np.linalg.inv(frames),
1569
+ "circumradius": float(reach),
1570
+ "vertex_ids": vertex_ids,
1571
+ "faces": _csr(n, shared.row[shared.data == 4], shared.col[shared.data == 4]),
1572
+ "edges": _csr(n, shared.row[shared.data >= 2], shared.col[shared.data >= 2]),
1573
+ "vertices": _csr(n, shared.row, shared.col),
1574
+ }
1575
+
1576
+
1577
+ @njit(parallel=True, cache=True)
1578
+ def _in_parallelepipeds(
1579
+ points, candidates, centres, corner, triple, inverse, box, periodic, out, found
1580
+ ):
1581
+ """First candidate cell (parallelepiped of centre ``centres``, corner ``corner`` and
1582
+ edge vectors the rows of ``inv(inverse[triple])``) containing each point (the nearest
1583
+ image of the cell in a periodic ``box``); the nearest candidate and ``found = False``
1584
+ when none does."""
1585
+ for p in prange(points.shape[0]):
1586
+ out[p] = candidates[p, 0]
1587
+ found[p] = False
1588
+ for q in range(candidates.shape[1]):
1589
+ c = candidates[p, q]
1590
+ if c < 0 or c >= corner.shape[0]:
1591
+ break
1592
+ # the point from the corner of the nearest image of the cell
1593
+ dx = points[p, 0] - centres[c, 0]
1594
+ dy = points[p, 1] - centres[c, 1]
1595
+ dz = points[p, 2] - centres[c, 2]
1596
+ if periodic:
1597
+ dx -= box[0] * np.floor(dx / box[0] + 0.5)
1598
+ dy -= box[1] * np.floor(dy / box[1] + 0.5)
1599
+ dz -= box[2] * np.floor(dz / box[2] + 0.5)
1600
+ dx += centres[c, 0] - corner[c, 0]
1601
+ dy += centres[c, 1] - corner[c, 1]
1602
+ dz += centres[c, 2] - corner[c, 2]
1603
+ m = inverse[triple[c]]
1604
+ inside = True
1605
+ for a in range(3): # coordinates of the point along the edges of the cell
1606
+ u = dx * m[0, a] + dy * m[1, a] + dz * m[2, a]
1607
+ if u < -1e-9 or u > 1.0 + 1e-9:
1608
+ inside = False
1609
+ break
1610
+ if inside:
1611
+ out[p] = c
1612
+ found[p] = True
1613
+ break
1614
+
1615
+
1616
+ def make_tiling(
1617
+ name: str,
1618
+ size,
1619
+ cell_size: float = 1.0,
1620
+ *,
1621
+ dims: int = 2,
1622
+ periodic: bool = True,
1623
+ origin=(0.0, 0.0, 0.0),
1624
+ offsets=None,
1625
+ rng: np.random.Generator | None = None,
1626
+ approximant=None,
1627
+ ) -> Tiling:
1628
+ """Tiling ``name`` (see :data:`LATTICES`) of the box ``origin + [0, size]``.
1629
+
1630
+ ``dims=2``: one layer of planar cells through the thickness of the box; ``dims=3``:
1631
+ layers of prisms ``cell_size`` high (planar tilings), or the ``bcc``, ``fcc`` and
1632
+ ``icosahedral`` lattices. ``offsets``: the offsets of the grids of a quasi-periodic
1633
+ tiling, drawn from ``rng`` when not given (uniform, centred): five for the pentagrid
1634
+ of a Penrose tiling (summing to 0; other sums give de Bruijn's generalized Penrose
1635
+ tilings), four for an Ammann-Beenker tiling, six for an icosahedral tiling (any
1636
+ regular offsets give tilings of the same local isomorphism class). Singular grids,
1637
+ more lines (planes) than the dimension through one point in the box, are refused.
1638
+
1639
+ Quasi-periodic tilings tile no periodic box: ``approximant`` (an order ``k >= 1``, or
1640
+ one per axis) gives their periodic approximant of that order, the same tiles periodic
1641
+ in a rectangle or a cube (:func:`approximant_grid`, :func:`approximant_period`). The
1642
+ box holds the nearest whole number of periods along each axis (at least half of one),
1643
+ scaled to fit it exactly like the unit cells of the periodic tilings: the tiles keep
1644
+ their shapes when the box is a multiple of the period.
1645
+ """
1646
+ if name not in LATTICES:
1647
+ raise ValueError(f"lattice: one of {LATTICES}, got {name!r}")
1648
+ if dims not in (2, 3):
1649
+ raise ValueError("dims: 2 or 3")
1650
+ if name not in PLANAR and dims != 3:
1651
+ raise ValueError(f"the {name} lattice is three-dimensional (dims=3)")
1652
+ if approximant is not None:
1653
+ if name not in QUASIPERIODIC:
1654
+ raise ValueError(f"approximant: quasi-periodic tilings only {QUASIPERIODIC}")
1655
+ if not periodic:
1656
+ raise ValueError(
1657
+ "approximant: periodic tilings only (non-periodic boxes take patches of the "
1658
+ "quasi-periodic tiling, or windows of a larger periodic approximant)"
1659
+ )
1660
+ orders = _orders(name, approximant)
1661
+ approximant = orders[0] if len(set(orders)) == 1 else list(orders)
1662
+ elif name in QUASIPERIODIC and periodic:
1663
+ raise ValueError(
1664
+ f"the {name} tiling is quasi-periodic: it tiles no periodic box (use a non-periodic "
1665
+ "domain, or a periodic approximant: approximant=1, 2, ...)"
1666
+ )
1667
+ size = np.asarray(size, dtype=float).reshape(3)
1668
+ h = float(cell_size)
1669
+ if not (h > 0 and np.all(size > 0)):
1670
+ raise ValueError("cell_size and size: must be positive")
1671
+ spec = {
1672
+ "name": name,
1673
+ "size": size.tolist(),
1674
+ "cell_size": h,
1675
+ "dims": int(dims),
1676
+ "periodic": bool(periodic),
1677
+ "origin": [float(v) for v in origin],
1678
+ }
1679
+ if name in QUASIPERIODIC:
1680
+ k = 6 if name == "icosahedral" else MULTIGRIDS[name][0]
1681
+ if offsets is None:
1682
+ u = (np.random.default_rng() if rng is None else rng).random(k)
1683
+ offsets = u - u.mean()
1684
+ offsets = np.asarray(offsets, dtype=float)
1685
+ if offsets.shape != (k,):
1686
+ raise ValueError(f"offsets: {k} numbers for the {name} tiling, got {offsets.shape}")
1687
+ spec["offsets"] = offsets.tolist()
1688
+ if approximant is not None:
1689
+ spec["approximant"] = approximant
1690
+ if name == "icosahedral":
1691
+ if approximant is not None:
1692
+ return Tiling(spec, None, _approximant_solid(size, h, offsets, approximant))
1693
+ return Tiling(spec, None, _icosahedral_solid(size, h, offsets))
1694
+ if name not in PLANAR:
1695
+ return Tiling(spec, None, _cubic_solid(name, size, h))
1696
+ if approximant is not None:
1697
+ plane = _approximant_plane(name, size, h, offsets, approximant)
1698
+ scale = list(size[:2] / plane["box"])
1699
+ elif name in QUASIPERIODIC:
1700
+ plane = _multigrid_plane(name, size, h, offsets)
1701
+ scale = [1.0, 1.0]
1702
+ else:
1703
+ plane = _regular_plane(name, size, h)
1704
+ for kind, r in plane.pop("shells").items():
1705
+ plane[kind] = _lattice_adjacency(*plane["lattice"], r * (1 + _EPS), periodic)
1706
+ scale = list(size[:2] / plane["box"])
1707
+ if dims == 2:
1708
+ plane["layers"], plane["layer_height"] = 1, float(size[2])
1709
+ scale.append(1.0)
1710
+ else:
1711
+ layers = max(1, round(size[2] / h))
1712
+ plane["layers"], plane["layer_height"] = layers, h
1713
+ scale.append(float(size[2] / (layers * h)))
1714
+ plane["scale"] = np.array(scale)
1715
+ return Tiling(spec, plane, None)