beacon-attraction 0.1.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.
- beacon_attraction/__init__.py +63 -0
- beacon_attraction/_attraction/__init__.py +2 -0
- beacon_attraction/_attraction/queries.py +202 -0
- beacon_attraction/_attraction/results.py +148 -0
- beacon_attraction/_cover/.mypy_cache/.gitignore +2 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.0.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.1.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.10.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.11.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.12.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.13.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.14.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.15.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.2.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.3.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.4.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.5.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.6.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.7.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.8.db +0 -0
- beacon_attraction/_cover/.mypy_cache/3.14/cache.9.db +0 -0
- beacon_attraction/_cover/.mypy_cache/CACHEDIR.TAG +3 -0
- beacon_attraction/_cover/__init__.py +2 -0
- beacon_attraction/_cover/bits.py +21 -0
- beacon_attraction/_cover/cover.py +38 -0
- beacon_attraction/_cover/cover_cleanup.py +133 -0
- beacon_attraction/_cover/cover_search.py +126 -0
- beacon_attraction/_cover/covers.py +51 -0
- beacon_attraction/_cover/greedy_covers.py +71 -0
- beacon_attraction/_cover/greedy_set_cover.py +126 -0
- beacon_attraction/_cover/minimum_covers.py +61 -0
- beacon_attraction/_cover/set_cover.py +151 -0
- beacon_attraction/_cover/splitmix64.py +25 -0
- beacon_attraction/_graph/__init__.py +2 -0
- beacon_attraction/_graph/component_table.py +156 -0
- beacon_attraction/_graph/components.py +98 -0
- beacon_attraction/_graph/frozen.py +85 -0
- beacon_attraction/_graph/graphs.py +436 -0
- beacon_attraction/_graph/index_kind.py +15 -0
- beacon_attraction/_graph/mutable.py +220 -0
- beacon_attraction/_graph/validation.py +200 -0
- beacon_attraction/_graph/view.py +101 -0
- beacon_attraction/_graph/violations.py +52 -0
- beacon_attraction/_indexes/__init__.py +2 -0
- beacon_attraction/_indexes/circular.py +87 -0
- beacon_attraction/_indexes/geometric.py +97 -0
- beacon_attraction/_indexes/kd_tree.py +249 -0
- beacon_attraction/_indexes/linear.py +26 -0
- beacon_attraction/_indexes/precomputed.py +77 -0
- beacon_attraction/_indexes/search.py +27 -0
- beacon_attraction/_indexes/steps.py +27 -0
- beacon_attraction/_kernel/__init__.py +1 -0
- beacon_attraction/_kernel/kernels.py +127 -0
- beacon_attraction/_kernel/witness_order.py +51 -0
- beacon_attraction/_numerics/__init__.py +2 -0
- beacon_attraction/_numerics/precision.py +87 -0
- beacon_attraction/_numerics/predicates.py +181 -0
- beacon_attraction/_numerics/vectors.py +26 -0
- beacon_attraction/py.typed +0 -0
- beacon_attraction-0.1.0.dist-info/METADATA +102 -0
- beacon_attraction-0.1.0.dist-info/RECORD +63 -0
- beacon_attraction-0.1.0.dist-info/WHEEL +4 -0
- beacon_attraction-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Beacon attraction in geometric graphs: attracted sets, kernels and covers, with exact integer
|
|
2
|
+
predicates (docs/MODEL.md; the Python API is in docs/PYTHON-API.md).
|
|
3
|
+
|
|
4
|
+
Everything public is imported from here; the modules beneath are internal.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from beacon_attraction._attraction.results import (
|
|
8
|
+
AttractionEnd,
|
|
9
|
+
AttractionForest,
|
|
10
|
+
AttractionPath,
|
|
11
|
+
AttractionTree,
|
|
12
|
+
BeaconEnd,
|
|
13
|
+
DeadPointEnd,
|
|
14
|
+
DeadVertexEnd,
|
|
15
|
+
StuckReason,
|
|
16
|
+
)
|
|
17
|
+
from beacon_attraction._cover.cover import Cover
|
|
18
|
+
from beacon_attraction._graph.component_table import ComponentTable
|
|
19
|
+
from beacon_attraction._graph.graphs import (
|
|
20
|
+
AttractionGraph,
|
|
21
|
+
DirectedGeometricGraph,
|
|
22
|
+
DirectedGraph,
|
|
23
|
+
FrozenDirectedGeometricGraph,
|
|
24
|
+
FrozenGeometricGraph,
|
|
25
|
+
GeometricGraph,
|
|
26
|
+
UndirectedGraph,
|
|
27
|
+
)
|
|
28
|
+
from beacon_attraction._graph.index_kind import NeighborIndexKind
|
|
29
|
+
from beacon_attraction._graph.violations import (
|
|
30
|
+
CoincidentVertices,
|
|
31
|
+
GraphValidationError,
|
|
32
|
+
PrecisionExceeded,
|
|
33
|
+
SelfLoop,
|
|
34
|
+
VertexInsideSegment,
|
|
35
|
+
Violation,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"AttractionEnd",
|
|
40
|
+
"AttractionForest",
|
|
41
|
+
"AttractionGraph",
|
|
42
|
+
"AttractionPath",
|
|
43
|
+
"AttractionTree",
|
|
44
|
+
"BeaconEnd",
|
|
45
|
+
"CoincidentVertices",
|
|
46
|
+
"ComponentTable",
|
|
47
|
+
"Cover",
|
|
48
|
+
"DeadPointEnd",
|
|
49
|
+
"DeadVertexEnd",
|
|
50
|
+
"DirectedGeometricGraph",
|
|
51
|
+
"DirectedGraph",
|
|
52
|
+
"FrozenDirectedGeometricGraph",
|
|
53
|
+
"FrozenGeometricGraph",
|
|
54
|
+
"GeometricGraph",
|
|
55
|
+
"GraphValidationError",
|
|
56
|
+
"NeighborIndexKind",
|
|
57
|
+
"PrecisionExceeded",
|
|
58
|
+
"SelfLoop",
|
|
59
|
+
"StuckReason",
|
|
60
|
+
"UndirectedGraph",
|
|
61
|
+
"VertexInsideSegment",
|
|
62
|
+
"Violation",
|
|
63
|
+
]
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""The four attraction queries (MODEL.md §6): a path, the tree of a vertex, the beacon's tree, and
|
|
2
|
+
the forest. They share one steepest step, and their results agree: every path is the branch of
|
|
3
|
+
its vertex's tree, and every tree is a tree of the forest."""
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, MutableMapping
|
|
6
|
+
|
|
7
|
+
from beacon_attraction._attraction.results import (
|
|
8
|
+
AttractionEnd,
|
|
9
|
+
AttractionForest,
|
|
10
|
+
AttractionPath,
|
|
11
|
+
AttractionTree,
|
|
12
|
+
BeaconEnd,
|
|
13
|
+
DeadPointEnd,
|
|
14
|
+
DeadVertexEnd,
|
|
15
|
+
StuckReason,
|
|
16
|
+
)
|
|
17
|
+
from beacon_attraction._graph.view import GraphView
|
|
18
|
+
from beacon_attraction._indexes.precomputed import PrecomputedIndex
|
|
19
|
+
from beacon_attraction._indexes.search import NeighborSearch
|
|
20
|
+
from beacon_attraction._indexes.steps import Step, StepKind
|
|
21
|
+
from beacon_attraction._numerics.vectors import direction, dot
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def path(view: GraphView, beacon: int, vertex: int) -> AttractionPath:
|
|
25
|
+
"""The path of ``vertex``: its steepest steps, from it to its end."""
|
|
26
|
+
search = view.index.search(beacon)
|
|
27
|
+
motion, step = _follow(search, vertex, known=None)
|
|
28
|
+
end = _end_for(view, beacon, motion[-1], step)
|
|
29
|
+
return AttractionPath(beacon, tuple(motion), end)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def tree(view: GraphView, beacon: int, vertex: int) -> AttractionTree:
|
|
33
|
+
"""The tree ``vertex`` belongs to: up its path to the end, then a reverse search down from
|
|
34
|
+
that end. The steps computed on the way up are kept, so the search reuses them."""
|
|
35
|
+
search = view.index.search(beacon)
|
|
36
|
+
known = _step_cache(view)
|
|
37
|
+
motion, step = _follow(search, vertex, known)
|
|
38
|
+
end = _end_for(view, beacon, motion[-1], step)
|
|
39
|
+
return _reverse_search(view, search, beacon, end, known)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def beacon_tree(view: GraphView, beacon: int) -> AttractionTree:
|
|
43
|
+
"""The beacon's tree, whose vertices are the attracted set ``A_V(b)``: a reverse search from
|
|
44
|
+
the beacon, at most ``O(E)``."""
|
|
45
|
+
search = view.index.search(beacon)
|
|
46
|
+
return _reverse_search(view, search, beacon, BeaconEnd(beacon), _step_cache(view))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def forest(view: GraphView, beacon: int) -> AttractionForest:
|
|
50
|
+
"""Every vertex's next vertex and end: one steepest step per vertex, ``O(E)``."""
|
|
51
|
+
search = view.index.search(beacon)
|
|
52
|
+
steps = [search.steepest(v) for v in range(view.vertex_count)]
|
|
53
|
+
nexts = [next_vertex if kind is StepKind.MOVES else -1 for kind, next_vertex in steps]
|
|
54
|
+
|
|
55
|
+
# Each vertex's end: follow its path to a vertex whose end is known, or to where it ends, and
|
|
56
|
+
# give every vertex passed the same end. The beacon's end is index 0. Going up the ids, the
|
|
57
|
+
# first vertex met in a tree is its smallest, so the other ends get their indices in the
|
|
58
|
+
# order of their trees' smallest vertices.
|
|
59
|
+
ends: list[AttractionEnd] = [BeaconEnd(beacon)]
|
|
60
|
+
end_index = [-1] * view.vertex_count
|
|
61
|
+
end_index[beacon] = 0
|
|
62
|
+
dead_points: dict[tuple[int, int], int] = {} # both endpoints of a segment share its dead point
|
|
63
|
+
|
|
64
|
+
def new_end(u: int) -> int:
|
|
65
|
+
kind, next_vertex = steps[u]
|
|
66
|
+
if kind is StepKind.DEAD_POINT:
|
|
67
|
+
segment = (min(u, next_vertex), max(u, next_vertex))
|
|
68
|
+
shared = dead_points.get(segment)
|
|
69
|
+
if shared is not None:
|
|
70
|
+
return shared
|
|
71
|
+
dead_points[segment] = len(ends)
|
|
72
|
+
ends.append(_end_for(view, beacon, u, steps[u]))
|
|
73
|
+
return len(ends) - 1
|
|
74
|
+
|
|
75
|
+
for v in range(view.vertex_count):
|
|
76
|
+
if end_index[v] >= 0:
|
|
77
|
+
continue
|
|
78
|
+
passed = []
|
|
79
|
+
u = v
|
|
80
|
+
while end_index[u] < 0 and nexts[u] >= 0:
|
|
81
|
+
passed.append(u)
|
|
82
|
+
u = nexts[u]
|
|
83
|
+
if end_index[u] < 0:
|
|
84
|
+
end_index[u] = new_end(u) # u is where the path ends, and its end is new
|
|
85
|
+
for w in passed:
|
|
86
|
+
end_index[w] = end_index[u]
|
|
87
|
+
|
|
88
|
+
return AttractionForest(beacon, tuple(ends), tuple(nexts), tuple(end_index))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _step_cache(view: GraphView) -> dict[int, Step] | None:
|
|
92
|
+
"""Where a tree keeps the steps it computes, so that it computes each once; ``None`` for a
|
|
93
|
+
precomputed copy, whose steps are lookups already, cheaper than the cache."""
|
|
94
|
+
if isinstance(view.index, PrecomputedIndex):
|
|
95
|
+
return None
|
|
96
|
+
return {}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _follow(
|
|
100
|
+
search: NeighborSearch, vertex: int, known: MutableMapping[int, Step] | None
|
|
101
|
+
) -> tuple[list[int], Step]:
|
|
102
|
+
"""Follows the steps from ``vertex`` while it moves: the vertices in the order visited, and
|
|
103
|
+
the step that ends the motion. The distance to the beacon strictly decreases, so no vertex
|
|
104
|
+
repeats. ``known``, if given, keeps each step computed."""
|
|
105
|
+
motion = [vertex]
|
|
106
|
+
step = search.steepest(vertex)
|
|
107
|
+
if known is not None:
|
|
108
|
+
known[vertex] = step
|
|
109
|
+
while step[0] is StepKind.MOVES:
|
|
110
|
+
motion.append(step[1])
|
|
111
|
+
step = search.steepest(step[1])
|
|
112
|
+
if known is not None:
|
|
113
|
+
known[motion[-1]] = step
|
|
114
|
+
return motion, step
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _end_for(view: GraphView, beacon: int, last: int, step: Step) -> AttractionEnd:
|
|
118
|
+
"""The end of a motion whose last vertex is ``last``, which stops with ``step``."""
|
|
119
|
+
kind, next_vertex = step
|
|
120
|
+
match kind:
|
|
121
|
+
case StepKind.AT_BEACON:
|
|
122
|
+
return BeaconEnd(last)
|
|
123
|
+
case StepKind.TIE:
|
|
124
|
+
return DeadVertexEnd(last, StuckReason.TIE)
|
|
125
|
+
case StepKind.NO_DESCENT:
|
|
126
|
+
return DeadVertexEnd(last, StuckReason.NO_DESCENT)
|
|
127
|
+
case StepKind.DEAD_POINT:
|
|
128
|
+
return _dead_point_end(view, beacon, last, next_vertex)
|
|
129
|
+
raise ValueError("A step that moves does not end a motion.")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _dead_point_end(view: GraphView, beacon: int, u: int, v: int) -> DeadPointEnd:
|
|
133
|
+
"""The dead point on the segment from ``u`` toward ``v``: the foot of the perpendicular from
|
|
134
|
+
the beacon, ``f = (m·u + n·uv) / m`` with P3's integers ``n = ub·uv`` and ``m = |uv|²``."""
|
|
135
|
+
pu = view.coordinates[u]
|
|
136
|
+
uv = direction(pu, view.coordinates[v])
|
|
137
|
+
ub = direction(pu, view.coordinates[beacon])
|
|
138
|
+
n, m = dot(ub, uv), dot(uv, uv)
|
|
139
|
+
numerators = [m * x + n * component for x, component in zip(pu, uv, strict=True)]
|
|
140
|
+
return DeadPointEnd((min(u, v), max(u, v)), view.precision.to_fractions(numerators, m))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _reverse_search(
|
|
144
|
+
view: GraphView,
|
|
145
|
+
search: NeighborSearch,
|
|
146
|
+
beacon: int,
|
|
147
|
+
end: AttractionEnd,
|
|
148
|
+
known: dict[int, Step] | None,
|
|
149
|
+
) -> AttractionTree:
|
|
150
|
+
"""Every vertex that ends at ``end``, with its next vertex: a search down from the end, level
|
|
151
|
+
by level. An in-neighbor ``v`` of a tree vertex ``u`` joins the tree with next vertex ``u``
|
|
152
|
+
when its step moves to ``u``. A vertex's step never changes, so it joins at most once.
|
|
153
|
+
``known`` holds the steps already computed, and the search adds the ones it computes; with
|
|
154
|
+
``None`` it looks every step up in the search instead."""
|
|
155
|
+
step_of: Callable[[int], Step] = search.steepest
|
|
156
|
+
if known is not None:
|
|
157
|
+
cache = known
|
|
158
|
+
|
|
159
|
+
def step_of(v: int) -> Step: # computed once, then kept
|
|
160
|
+
step = cache.get(v)
|
|
161
|
+
if step is None:
|
|
162
|
+
step = search.steepest(v)
|
|
163
|
+
cache[v] = step
|
|
164
|
+
return step
|
|
165
|
+
|
|
166
|
+
# The tree's vertices with their next vertices, in the order found; the first level is the
|
|
167
|
+
# vertices directly under the end, whose paths end there (-1).
|
|
168
|
+
level = _under_end(end, step_of)
|
|
169
|
+
vertices = list(level)
|
|
170
|
+
nexts = [-1] * len(level)
|
|
171
|
+
in_neighbors = view.in_neighbors
|
|
172
|
+
while level:
|
|
173
|
+
children = []
|
|
174
|
+
for u in level:
|
|
175
|
+
for v in in_neighbors[u]:
|
|
176
|
+
kind, next_vertex = step_of(v)
|
|
177
|
+
if kind is StepKind.MOVES and next_vertex == u:
|
|
178
|
+
children.append(v)
|
|
179
|
+
vertices.append(v)
|
|
180
|
+
nexts.append(u)
|
|
181
|
+
level = children
|
|
182
|
+
|
|
183
|
+
order = sorted(range(len(vertices)), key=vertices.__getitem__)
|
|
184
|
+
return AttractionTree(
|
|
185
|
+
beacon, end, tuple(vertices[i] for i in order), tuple(nexts[i] for i in order)
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _under_end(end: AttractionEnd, step_of: Callable[[int], Step]) -> list[int]:
|
|
190
|
+
"""The vertices directly under ``end``: the beacon or the dead vertex itself, or the
|
|
191
|
+
endpoints that slide into the dead point (one or two)."""
|
|
192
|
+
match end:
|
|
193
|
+
case BeaconEnd(vertex) | DeadVertexEnd(vertex, _):
|
|
194
|
+
return [vertex]
|
|
195
|
+
case DeadPointEnd((u, v), _):
|
|
196
|
+
under = []
|
|
197
|
+
for p, q in ((u, v), (v, u)):
|
|
198
|
+
kind, next_vertex = step_of(p)
|
|
199
|
+
if kind is StepKind.DEAD_POINT and next_vertex == q:
|
|
200
|
+
under.append(p)
|
|
201
|
+
return under
|
|
202
|
+
raise ValueError(f"Unknown end {end!r}.")
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""The results of the attraction queries (MODEL.md §6; docs/PYTHON-API.md, "Attraction"): ends,
|
|
2
|
+
paths, trees and forests. They are computed eagerly and never consult the graph again.
|
|
3
|
+
|
|
4
|
+
Results are read bottom-up, the way they are computed: each vertex has a next vertex, the one
|
|
5
|
+
its steepest step moves to, and every path ends at an end. There are no node objects.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from bisect import bisect_left
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from fractions import Fraction
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class StuckReason(Enum):
|
|
16
|
+
"""Why an object stops at a vertex (MODEL.md §4)."""
|
|
17
|
+
|
|
18
|
+
TIE = "tie"
|
|
19
|
+
"""Two or more directions are equally steepest (R2)."""
|
|
20
|
+
NO_DESCENT = "no_descent"
|
|
21
|
+
"""No direction decreases the distance to the beacon (R3)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class AttractionEnd:
|
|
26
|
+
"""Where an object stops: one of three kinds, so match on them.
|
|
27
|
+
|
|
28
|
+
Two vertices are in the same tree exactly when their ends are equal.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class BeaconEnd(AttractionEnd):
|
|
34
|
+
"""The object reaches the beacon: its vertex is attracted."""
|
|
35
|
+
|
|
36
|
+
vertex: int
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True, slots=True)
|
|
40
|
+
class DeadVertexEnd(AttractionEnd):
|
|
41
|
+
"""The object stops at a vertex, the dead vertex."""
|
|
42
|
+
|
|
43
|
+
vertex: int
|
|
44
|
+
reason: StuckReason
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
48
|
+
class DeadPointEnd(AttractionEnd):
|
|
49
|
+
"""The object stops inside a segment, at the foot of the perpendicular from the beacon.
|
|
50
|
+
|
|
51
|
+
A dead point is identified by its segment, smaller id first, so it compares and hashes by
|
|
52
|
+
the segment alone; in a directed graph, the two arcs of a segment share its dead point. The
|
|
53
|
+
point is exact, in original units (MODEL.md §8.3).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
segment: tuple[int, int]
|
|
57
|
+
point: tuple[Fraction, ...]
|
|
58
|
+
|
|
59
|
+
def __eq__(self, other: object) -> bool:
|
|
60
|
+
if not isinstance(other, DeadPointEnd):
|
|
61
|
+
return NotImplemented
|
|
62
|
+
return self.segment == other.segment
|
|
63
|
+
|
|
64
|
+
def __hash__(self) -> int:
|
|
65
|
+
return hash((DeadPointEnd, self.segment))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class AttractionPath:
|
|
70
|
+
"""The path of one vertex: the vertices it visits, in travel order, then its end."""
|
|
71
|
+
|
|
72
|
+
beacon: int
|
|
73
|
+
vertices: tuple[int, ...]
|
|
74
|
+
"""The start first, the last vertex reached last. A ``BeaconEnd`` or ``DeadVertexEnd`` is at
|
|
75
|
+
that last vertex; a ``DeadPointEnd`` comes after it, on a segment of it."""
|
|
76
|
+
end: AttractionEnd
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class AttractionTree:
|
|
81
|
+
"""The vertices with the same end, each with its next vertex: the tree is read from any vertex
|
|
82
|
+
up to its end. Supports ``v in tree``, ``len(tree)`` and iteration over its vertices.
|
|
83
|
+
|
|
84
|
+
To walk it top-down, group the vertices by their next vertex: the vertices directly under the
|
|
85
|
+
end are the group ``-1``.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
beacon: int
|
|
89
|
+
end: AttractionEnd
|
|
90
|
+
vertices: tuple[int, ...]
|
|
91
|
+
"""The tree's vertices, ascending."""
|
|
92
|
+
nexts: tuple[int, ...]
|
|
93
|
+
"""By position: ``nexts[i]`` is where ``vertices[i]`` moves, or ``-1`` where its path ends (at
|
|
94
|
+
the end's vertex, or into the dead point)."""
|
|
95
|
+
|
|
96
|
+
def next_of(self, vertex: int) -> int:
|
|
97
|
+
"""The next vertex of ``vertex``, which must be in the tree, or ``-1`` where its path
|
|
98
|
+
ends. A binary search."""
|
|
99
|
+
i = bisect_left(self.vertices, vertex)
|
|
100
|
+
if i == len(self.vertices) or self.vertices[i] != vertex:
|
|
101
|
+
raise ValueError(f"Vertex {vertex} is not in the tree.")
|
|
102
|
+
return self.nexts[i]
|
|
103
|
+
|
|
104
|
+
def __contains__(self, vertex: object) -> bool:
|
|
105
|
+
if not isinstance(vertex, int):
|
|
106
|
+
return False
|
|
107
|
+
i = bisect_left(self.vertices, vertex)
|
|
108
|
+
return i < len(self.vertices) and self.vertices[i] == vertex
|
|
109
|
+
|
|
110
|
+
def __len__(self) -> int:
|
|
111
|
+
return len(self.vertices)
|
|
112
|
+
|
|
113
|
+
def __iter__(self) -> Iterator[int]:
|
|
114
|
+
return iter(self.vertices)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True, slots=True)
|
|
118
|
+
class AttractionForest:
|
|
119
|
+
"""Every vertex's next vertex and end: the attraction trees of one beacon, covering every
|
|
120
|
+
vertex once. It stores no trees; :meth:`build_tree` builds one."""
|
|
121
|
+
|
|
122
|
+
beacon: int
|
|
123
|
+
ends: tuple[AttractionEnd, ...]
|
|
124
|
+
"""One per tree: the beacon's first, then the others in the order of their tree's smallest
|
|
125
|
+
vertex."""
|
|
126
|
+
nexts: tuple[int, ...]
|
|
127
|
+
"""By vertex id: where each vertex moves, or ``-1`` where its path ends."""
|
|
128
|
+
_end_index: tuple[int, ...] = field(repr=False)
|
|
129
|
+
"""By vertex id: the index of the vertex's end in ``ends``."""
|
|
130
|
+
|
|
131
|
+
def end_of(self, vertex: int) -> AttractionEnd:
|
|
132
|
+
"""Where the path of ``vertex`` ends."""
|
|
133
|
+
self._check(vertex)
|
|
134
|
+
return self.ends[self._end_index[vertex]]
|
|
135
|
+
|
|
136
|
+
def build_tree(self, vertex: int) -> AttractionTree:
|
|
137
|
+
"""The tree that contains ``vertex``, built from the forest: a new tree on each call,
|
|
138
|
+
``O(V)``. Keep the result if you need it more than once."""
|
|
139
|
+
self._check(vertex)
|
|
140
|
+
end = self._end_index[vertex]
|
|
141
|
+
members = [u for u, index in enumerate(self._end_index) if index == end] # ascending
|
|
142
|
+
return AttractionTree(
|
|
143
|
+
self.beacon, self.ends[end], tuple(members), tuple(self.nexts[u] for u in members)
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
def _check(self, vertex: int) -> None:
|
|
147
|
+
if not 0 <= vertex < len(self.nexts):
|
|
148
|
+
raise IndexError(f"There is no vertex {vertex}; the forest has {len(self.nexts)}.")
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Python integers as bitsets: the sets of the exact cover's set cover.
|
|
2
|
+
|
|
3
|
+
Number ``i`` is in the set ``bits`` when bit ``i`` is one. The operators work on whole sets at C
|
|
4
|
+
speed: ``a & b`` is the intersection, ``a & ~b`` the difference, ``a | b`` the union, and
|
|
5
|
+
``bits.bit_count()`` the size. Only walking the members needs a helper.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def members(bits: int) -> Iterator[int]:
|
|
12
|
+
"""The numbers in the set ``bits``, ascending."""
|
|
13
|
+
while bits:
|
|
14
|
+
lowest = bits & -bits
|
|
15
|
+
yield lowest.bit_length() - 1
|
|
16
|
+
bits ^= lowest
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_subset(bits: int, of: int) -> bool:
|
|
20
|
+
"""Whether every number of ``bits`` is in ``of``."""
|
|
21
|
+
return bits & ~of == 0
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The result of both covers (MODEL.md §6, "Cover"; docs/PYTHON-API.md, "Covers")."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable, Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True, slots=True)
|
|
8
|
+
class Cover:
|
|
9
|
+
"""Beacons that together attract every vertex, with a proven lower bound on the size of a
|
|
10
|
+
minimum cover. Supports ``len(cover)``, ``b in cover`` and iteration over the beacons.
|
|
11
|
+
|
|
12
|
+
``minimum_cover()`` without a time limit always returns a minimum cover; a greedy cover is
|
|
13
|
+
proven minimum when its large components have one or two beacons each.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
beacons: tuple[int, ...]
|
|
17
|
+
"""The beacons, ascending. Every vertex is attracted by at least one of them."""
|
|
18
|
+
lower_bound: int
|
|
19
|
+
"""No cover has fewer beacons than this."""
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def of(cls, beacons: Iterable[int], lower_bound: int) -> Cover:
|
|
23
|
+
"""A cover of these beacons, in any order."""
|
|
24
|
+
return cls(tuple(sorted(beacons)), lower_bound)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def is_optimal(self) -> bool:
|
|
28
|
+
"""Whether the cover is proven minimum: it has ``lower_bound`` beacons."""
|
|
29
|
+
return len(self.beacons) == self.lower_bound
|
|
30
|
+
|
|
31
|
+
def __len__(self) -> int:
|
|
32
|
+
return len(self.beacons)
|
|
33
|
+
|
|
34
|
+
def __contains__(self, beacon: object) -> bool:
|
|
35
|
+
return beacon in self.beacons
|
|
36
|
+
|
|
37
|
+
def __iter__(self) -> Iterator[int]:
|
|
38
|
+
return iter(self.beacons)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The prune and the swaps of a set cover (MODEL.md §9, "Greedy cover algorithm", steps 5 and 6)."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from collections.abc import Mapping, Sequence
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CoverCleanup:
|
|
8
|
+
"""The prune and the swaps of a set cover: the sets that the others make redundant leave the
|
|
9
|
+
cover, last chosen first, and a set of the pool that makes two or more sets of the cover
|
|
10
|
+
redundant replaces them, until no set of the pool does. The greedy cover cleans up its
|
|
11
|
+
rounds' cover this way (``GreedySetCover``), and the exact search its starting cover
|
|
12
|
+
(``CoverSearch``).
|
|
13
|
+
|
|
14
|
+
It keeps, for each element, the sets of the cover that cover it, and for each set of the
|
|
15
|
+
cover, how many elements it covers alone. A set is redundant when it covers none alone, and a
|
|
16
|
+
set of the pool can only replace the sets whose elements covered alone it holds, so most sets
|
|
17
|
+
of the pool are ruled out by reading those counts, without touching the cover.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
__slots__ = ("_cover", "_covered_alone", "_covering_sets", "_pool")
|
|
21
|
+
|
|
22
|
+
def __init__(self, pool: Mapping[int, Sequence[int]], count: int) -> None:
|
|
23
|
+
"""``pool``: the sets a cover may use, each with the elements it covers; the swaps walk
|
|
24
|
+
them in ascending order. ``count``: the sets and the elements are numbered below it."""
|
|
25
|
+
self._pool = pool
|
|
26
|
+
self._cover: set[int] = set()
|
|
27
|
+
self._covering_sets: defaultdict[int, list[int]] = defaultdict(list)
|
|
28
|
+
"""``_covering_sets[element]``: the sets of the cover that cover the element, a list made
|
|
29
|
+
when first needed."""
|
|
30
|
+
self._covered_alone = [0] * count
|
|
31
|
+
"""``_covered_alone[set]``, for a set of the cover: how many elements it covers that no
|
|
32
|
+
other set of the cover covers. The set is redundant when there are none."""
|
|
33
|
+
|
|
34
|
+
def run(self, chosen: Sequence[int]) -> list[int]:
|
|
35
|
+
"""The cover ``chosen``, sets of the pool in the order they were chosen, pruned and then
|
|
36
|
+
swapped. Returns its sets, ascending."""
|
|
37
|
+
for s in chosen:
|
|
38
|
+
self._add_to_cover(s)
|
|
39
|
+
self._prune(chosen)
|
|
40
|
+
self._swap()
|
|
41
|
+
return sorted(self._cover)
|
|
42
|
+
|
|
43
|
+
def _prune(self, chosen: Sequence[int]) -> None:
|
|
44
|
+
"""Removes each chosen set whose elements the other sets left all cover, from the last
|
|
45
|
+
chosen to the first (step 5)."""
|
|
46
|
+
for s in reversed(chosen):
|
|
47
|
+
if self._is_redundant(s):
|
|
48
|
+
self._remove_from_cover(s)
|
|
49
|
+
|
|
50
|
+
def _swap(self) -> None:
|
|
51
|
+
"""Walks the pool by set number, trying to swap each set outside the cover for two or
|
|
52
|
+
more sets of it, and walks it again until a walk swaps nothing (step 6). Each swap makes
|
|
53
|
+
the cover smaller, so the walks end."""
|
|
54
|
+
pool = sorted(self._pool)
|
|
55
|
+
swapped = True
|
|
56
|
+
while swapped:
|
|
57
|
+
swapped = False
|
|
58
|
+
for s in pool:
|
|
59
|
+
if s not in self._cover and self._try_swap(s):
|
|
60
|
+
swapped = True
|
|
61
|
+
|
|
62
|
+
def _try_swap(self, s: int) -> bool:
|
|
63
|
+
"""Swaps set ``s``, outside the cover, for two or more sets of it, if it can: it joins the
|
|
64
|
+
cover, and the sets it makes redundant leave it, by set number. Fewer than two leaving
|
|
65
|
+
would not make the cover smaller, so then nothing changes. Returns whether the swap was
|
|
66
|
+
made.
|
|
67
|
+
|
|
68
|
+
MODEL.md walks every set of the cover that shares an element with ``s``. This walk skips
|
|
69
|
+
the sets that cannot become redundant, so the result is the same:
|
|
70
|
+
|
|
71
|
+
- no set of the cover is redundant before ``s`` joins: the prune and each swap see to
|
|
72
|
+
that;
|
|
73
|
+
- once it joins, a set of the cover is redundant if ``s`` holds every element that the
|
|
74
|
+
set covered alone (``_replaceable``);
|
|
75
|
+
- a set leaving the cover never makes another one redundant.
|
|
76
|
+
|
|
77
|
+
So only the replaceable sets are walked, and with fewer than two the cover is not touched.
|
|
78
|
+
"""
|
|
79
|
+
replaceable = self._replaceable(s)
|
|
80
|
+
if len(replaceable) < 2:
|
|
81
|
+
return False
|
|
82
|
+
|
|
83
|
+
self._add_to_cover(s)
|
|
84
|
+
removed = []
|
|
85
|
+
for other in replaceable:
|
|
86
|
+
if self._is_redundant(other):
|
|
87
|
+
self._remove_from_cover(other)
|
|
88
|
+
removed.append(other)
|
|
89
|
+
|
|
90
|
+
if len(removed) < 2:
|
|
91
|
+
for other in removed:
|
|
92
|
+
self._add_to_cover(other)
|
|
93
|
+
self._remove_from_cover(s)
|
|
94
|
+
return False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
def _replaceable(self, s: int) -> list[int]:
|
|
98
|
+
"""The sets of the cover whose elements covered alone are all elements of set ``s``,
|
|
99
|
+
ascending: those that ``s`` joining the cover makes redundant."""
|
|
100
|
+
# For each set of the cover, how many of its elements covered alone ``s`` holds.
|
|
101
|
+
held: dict[int, int] = {}
|
|
102
|
+
for element in self._pool[s]:
|
|
103
|
+
covering = self._covering_sets[element]
|
|
104
|
+
if len(covering) == 1:
|
|
105
|
+
held[covering[0]] = held.get(covering[0], 0) + 1
|
|
106
|
+
return sorted(other for other, count in held.items() if count == self._covered_alone[other])
|
|
107
|
+
|
|
108
|
+
def _is_redundant(self, s: int) -> bool:
|
|
109
|
+
"""Whether every element of set ``s``, a set of the cover, is covered by another set of
|
|
110
|
+
the cover too."""
|
|
111
|
+
return self._covered_alone[s] == 0
|
|
112
|
+
|
|
113
|
+
def _add_to_cover(self, s: int) -> None:
|
|
114
|
+
"""Adds set ``s`` to the cover: an element that one set covered alone is now shared."""
|
|
115
|
+
self._cover.add(s)
|
|
116
|
+
for element in self._pool[s]:
|
|
117
|
+
covering = self._covering_sets[element]
|
|
118
|
+
if len(covering) == 1:
|
|
119
|
+
self._covered_alone[covering[0]] -= 1
|
|
120
|
+
covering.append(s)
|
|
121
|
+
if len(covering) == 1:
|
|
122
|
+
self._covered_alone[s] += 1
|
|
123
|
+
|
|
124
|
+
def _remove_from_cover(self, s: int) -> None:
|
|
125
|
+
"""Removes set ``s`` from the cover: an element that it shared with one other set is now
|
|
126
|
+
covered by that set alone."""
|
|
127
|
+
self._cover.remove(s)
|
|
128
|
+
for element in self._pool[s]:
|
|
129
|
+
covering = self._covering_sets[element]
|
|
130
|
+
covering.remove(s)
|
|
131
|
+
if len(covering) == 1:
|
|
132
|
+
self._covered_alone[covering[0]] += 1
|
|
133
|
+
self._covered_alone[s] = 0
|