yang
This project has not described itself yet.
Brought by drakestapleton
yang / scripts / face_min_cut.py
| 1 | """Certified unit split-face cut on the free links of a fixed geometry.""" |
| 2 | from collections import deque |
| 3 | from itertools import product |
| 4 | |
| 5 | import numpy as np |
| 6 | |
| 7 | |
| 8 | class _Network: |
| 9 | """Paired residual arcs; even indices are the original directed arcs.""" |
| 10 | |
| 11 | def __init__(self, n): |
| 12 | self.adj = [[] for _ in range(n)] |
| 13 | self.head = [] |
| 14 | self.residual = [] |
| 15 | self.capacity = [] # original capacities, never changed by augmentation |
| 16 | |
| 17 | def add(self, u, v, capacity): |
| 18 | i = len(self.head) |
| 19 | self.adj[u].append(i) |
| 20 | self.adj[v].append(i + 1) |
| 21 | self.head.extend((v, u)) |
| 22 | self.residual.extend((capacity, 0)) |
| 23 | self.capacity.append(capacity) |
| 24 | |
| 25 | def source_side(self, s, t): |
| 26 | """Augment along shortest residual paths until no path reaches t.""" |
| 27 | while True: |
| 28 | parent = [-1] * len(self.adj) |
| 29 | parent[s] = -2 |
| 30 | queue = deque([s]) |
| 31 | while queue and parent[t] == -1: |
| 32 | u = queue.popleft() |
| 33 | for i in self.adj[u]: |
| 34 | v = self.head[i] |
| 35 | if self.residual[i] and parent[v] == -1: |
| 36 | parent[v] = i |
| 37 | if v == t: |
| 38 | break |
| 39 | queue.append(v) |
| 40 | if parent[t] == -1: |
| 41 | return np.asarray(parent) != -1 |
| 42 | path = [] |
| 43 | v = t |
| 44 | while v != s: |
| 45 | i = parent[v] |
| 46 | path.append(i) |
| 47 | v = self.head[i ^ 1] |
| 48 | delta = min(self.residual[i] for i in path) |
| 49 | for i in path: |
| 50 | self.residual[i] -= delta |
| 51 | self.residual[i ^ 1] += delta |
| 52 | |
| 53 | def certify(self, s, t, side, mixed_count): |
| 54 | """Check the actual flow on original arcs, not an augmentation counter.""" |
| 55 | net_out = [0] * len(self.adj) |
| 56 | cut = 0 |
| 57 | for k, capacity in enumerate(self.capacity): |
| 58 | i = 2 * k |
| 59 | v, u = self.head[i], self.head[i + 1] |
| 60 | flow = self.residual[i + 1] |
| 61 | if (type(flow) is not int or not 0 <= flow <= capacity |
| 62 | or self.residual[i] != capacity - flow): |
| 63 | raise RuntimeError('invalid integral arc flow or residual capacity') |
| 64 | net_out[u] += flow |
| 65 | net_out[v] -= flow |
| 66 | if side[u] and not side[v]: |
| 67 | cut += capacity |
| 68 | if not side[s] or side[t] or cut != mixed_count: |
| 69 | raise RuntimeError('network cut does not certify the geometric cut') |
| 70 | net_out[s] -= mixed_count |
| 71 | net_out[t] += mixed_count |
| 72 | if any(net_out): |
| 73 | raise RuntimeError('flow does not conserve mass or match the primal value') |
| 74 | |
| 75 | |
| 76 | def minimum_middle(faces, pinned, source, target): |
| 77 | """Return (flat bool middle, integer minimum); raise ValueError if infeasible. |
| 78 | |
| 79 | Each row of faces is one unit of cost if it has free links on both sides. |
| 80 | The middle contains source and excludes target, and its mixed faces cannot |
| 81 | be mixed by either endpoint mask. Pinned links have no label in the cut; |
| 82 | their returned bits are False. Nonincident links are allowed. |
| 83 | """ |
| 84 | faces = np.asarray(faces) |
| 85 | pinned, source, target = map(np.asarray, (pinned, source, target)) |
| 86 | if (pinned.ndim != 1 or any(a.shape != pinned.shape or a.dtype != np.bool_ |
| 87 | for a in (pinned, source, target))): |
| 88 | raise ValueError('pinned, source and target must be matching flat boolean arrays') |
| 89 | if faces.ndim != 2 or faces.shape[1] != 4 or faces.dtype.kind not in 'iu': |
| 90 | raise ValueError('faces must be an integer array of shape (nfaces, 4)') |
| 91 | n = len(pinned) |
| 92 | if faces.size and (faces.min() < 0 or faces.max() >= n): |
| 93 | raise ValueError('face contains an out-of-range link index') |
| 94 | free = ~pinned[faces] |
| 95 | |
| 96 | def mixed(mask): |
| 97 | labels = mask[faces] |
| 98 | return (labels & free).any(axis=1) & (~labels & free).any(axis=1) |
| 99 | |
| 100 | def force(mask, boundary): |
| 101 | forced = mask & ~pinned |
| 102 | forced[faces[free & boundary[:, None]]] = True |
| 103 | return forced |
| 104 | |
| 105 | sb, tb = mixed(source), mixed(target) |
| 106 | left, right = force(source, sb), force(target, tb) |
| 107 | if (left & right).any(): |
| 108 | raise ValueError('intersecting forced source and target regions') |
| 109 | |
| 110 | s = n + 2 * len(faces) |
| 111 | t = s + 1 |
| 112 | network = _Network(t + 1) |
| 113 | hard = len(faces) + 1 |
| 114 | for v in np.flatnonzero(left).tolist(): |
| 115 | network.add(s, v, hard) |
| 116 | for v in np.flatnonzero(right).tolist(): |
| 117 | network.add(v, t, hard) |
| 118 | for j, face in enumerate(faces): |
| 119 | links = dict.fromkeys(face[free[j]].tolist()) |
| 120 | if len(links) < 2: |
| 121 | continue # no mask can split this face |
| 122 | a = n + 2 * j |
| 123 | network.add(a, a + 1, 1) |
| 124 | for v in links: |
| 125 | network.add(v, a, hard) |
| 126 | network.add(a + 1, v, hard) |
| 127 | |
| 128 | side = network.source_side(s, t) |
| 129 | middle = side[:n].copy() |
| 130 | mb = mixed(middle) |
| 131 | if ((middle & pinned).any() or (source & ~pinned & ~middle).any() |
| 132 | or (target & ~pinned & middle).any() or (mb & (sb | tb)).any()): |
| 133 | raise RuntimeError('middle violates an anchor or splits an endpoint boundary face') |
| 134 | count = int(mb.sum()) |
| 135 | network.certify(s, t, side, count) |
| 136 | return middle, count |
| 137 | |
| 138 | |
| 139 | def _oracle(faces, pinned, source, target): |
| 140 | """Small-instance reference: enumerate masks, without expanding anchors.""" |
| 141 | links = set(range(len(pinned))) - set(np.flatnonzero(pinned)) |
| 142 | src = set(np.flatnonzero(source)) & links |
| 143 | dst = set(np.flatnonzero(target)) & links |
| 144 | rows = [set(row) & links for row in faces] |
| 145 | |
| 146 | def boundary(mask): |
| 147 | return {j for j, row in enumerate(rows) if row & mask and row - mask} |
| 148 | |
| 149 | forbidden = boundary(src) | boundary(dst) |
| 150 | best = None |
| 151 | admissible = 0 |
| 152 | vertices = sorted(links) |
| 153 | for bits in product((False, True), repeat=len(vertices)): |
| 154 | mask = {v for v, bit in zip(vertices, bits) if bit} |
| 155 | if src <= mask and not dst & mask: |
| 156 | cut = boundary(mask) |
| 157 | if not cut & forbidden: |
| 158 | admissible += 1 |
| 159 | best = len(cut) if best is None else min(best, len(cut)) |
| 160 | return best, admissible |
| 161 | |
| 162 | |
| 163 | def _controls(): |
| 164 | # Anchors 10 and 11, and optional link 12, occur in no face. Link 9 is |
| 165 | # pinned. The third row necessarily splits two versus two at cost one. |
| 166 | faces = np.array([[0, 1, 2, 9], [6, 7, 8, 9], [1, 2, 6, 8], |
| 167 | [1, 3, 3, 9], [2, 4, 4, 9], [3, 4, 5, 9], |
| 168 | [5, 6, 6, 9], [4, 8, 8, 9], [9, 9, 9, 9], [3, 9, 9, 9]]) |
| 169 | pinned, source, target = np.zeros((3, 13), dtype=bool) |
| 170 | pinned[9] = True |
| 171 | source[[0, 10]] = True |
| 172 | target[[7, 11]] = True |
| 173 | expected, admissible = _oracle(faces, pinned, source, target) |
| 174 | middle, count = minimum_middle(faces, pinned, source, target) |
| 175 | if count != expected or not middle[10] or middle[11] or middle[12]: |
| 176 | raise AssertionError('exhaustive minimum or isolated links disagree') |
| 177 | print(f'exhaustive: admissible={admissible} min_mixed_faces={expected} certified_flow={count}') |
| 178 | for x, y in product((False, True), repeat=2): |
| 179 | source[9], target[9] = x, y |
| 180 | other, value = minimum_middle(faces, pinned, source, target) |
| 181 | if value != count or not np.array_equal(other, middle): |
| 182 | raise AssertionError('pin labels changed the solution') |
| 183 | print('pin labels: all endpoint labelings leave middle and cost unchanged') |
| 184 | |
| 185 | # Disjoint raw anchors, but distinct endpoint boundary faces share link 2. |
| 186 | conflict = np.array([[0, 1, 2, 9], [2, 6, 7, 9]]) |
| 187 | if _oracle(conflict, pinned, source, target) != (None, 0): |
| 188 | raise AssertionError('infeasible control has an admissible mask') |
| 189 | try: |
| 190 | minimum_middle(conflict, pinned, source, target) |
| 191 | except ValueError as exc: |
| 192 | if str(exc) != 'intersecting forced source and target regions': |
| 193 | raise |
| 194 | print(f'infeasible: admissible=0 rejected={exc}') |
| 195 | else: |
| 196 | raise AssertionError('accepted intersecting forced regions') |
| 197 | |
| 198 | # Exhaust all ternary anchor assignments for several tiny geometries, |
| 199 | # with and without a pinned link, including empty and duplicate faces. |
| 200 | families = [[], [[0, 1, 2, 3]], [[0, 1, 1, 1], [1, 2, 2, 2]], |
| 201 | [[0, 1, 1, 1], [1, 2, 2, 2], [2, 3, 3, 3]], |
| 202 | [[0, 1, 2, 3], [0, 1, 2, 3]], |
| 203 | [[0, 0, 0, 0], [0, 1, 1, 1], [2, 3, 3, 3]]] |
| 204 | feasible = infeasible = 0 |
| 205 | for rows, pin_last in product(families, (False, True)): |
| 206 | tiny_faces = np.asarray(rows, dtype=int).reshape(-1, 4) |
| 207 | pins = np.array([False, False, False, pin_last]) |
| 208 | for labels in product(range(3), repeat=4): |
| 209 | labels = np.asarray(labels) |
| 210 | src, dst = (labels == 1) & ~pins, (labels == 2) & ~pins |
| 211 | expected, _ = _oracle(tiny_faces, pins, src, dst) |
| 212 | try: |
| 213 | actual, value = minimum_middle(tiny_faces, pins, src, dst) |
| 214 | except ValueError: |
| 215 | if expected is not None: |
| 216 | raise AssertionError('rejected an exhaustively feasible instance') |
| 217 | infeasible += 1 |
| 218 | continue |
| 219 | if expected is None or value != expected: |
| 220 | raise AssertionError('minimum disagrees with exhaustive tiny oracle') |
| 221 | again, repeat_value = minimum_middle(tiny_faces, pins, src, dst) |
| 222 | if actual.dtype != np.bool_ or actual.shape != pins.shape: |
| 223 | raise AssertionError('wrong API result type or shape') |
| 224 | if not np.array_equal(again, actual) or repeat_value != value: |
| 225 | raise AssertionError('nondeterministic result') |
| 226 | feasible += 1 |
| 227 | print(f'tiny families: feasible={feasible} infeasible={infeasible} all agree with enumeration') |
| 228 | |
| 229 | # Negative certificate controls exercise every part of the lower bound. |
| 230 | def certificate_network(): |
| 231 | graph = _Network(3) |
| 232 | graph.add(0, 1, 1) |
| 233 | graph.add(1, 2, 1) |
| 234 | cut = graph.source_side(0, 2) |
| 235 | graph.certify(0, 2, cut, 1) |
| 236 | return graph, cut |
| 237 | |
| 238 | for defect in ('unit capacity', 'integrality', 'conservation', 'primal equality'): |
| 239 | graph, cut = certificate_network() |
| 240 | value = 1 |
| 241 | if defect == 'unit capacity': |
| 242 | graph.residual[0:2] = [-1, 2] |
| 243 | elif defect == 'integrality': |
| 244 | graph.residual[0:2] = [0.5, 0.5] |
| 245 | elif defect == 'conservation': |
| 246 | graph.residual[2:4] = [1, 0] |
| 247 | else: |
| 248 | value = 0 |
| 249 | try: |
| 250 | graph.certify(0, 2, cut, value) |
| 251 | except RuntimeError: |
| 252 | continue |
| 253 | raise AssertionError(f'accepted defective certificate: {defect}') |
| 254 | print('certificate rejection: unit capacity, integrality, conservation, primal equality') |
| 255 | |
| 256 | |
| 257 | if __name__ == '__main__': |
| 258 | _controls() |