Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/yang/blob/main/scripts/nested_face_cut.py # yang This project has not described itself yet. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `yang / scripts / nested_face_cut.py` 247 lines ยท 10844 bytes Raw Blame History 1 """Exact minimum total split-face count for two nested, face-disjoint masks.""" 2 from itertools import product 3 4 import numpy as np 5 6 if __package__: 7 from .face_min_cut import _Network 8 else: 9 from face_min_cut import _Network 10 11 12 def minimum_nested(faces, pinned, left, right): 13 """Return (small, big, total); raise ValueError for invalid or infeasible input. 14 15 All masks are flat boolean arrays indexed by link. The caller supplies the 16 two already-protected sets of free links: left <= small <= big <= ~right. 17 Neither returned mask contains pins. A face row costs one per mask splitting 18 its free links; the two sets of split rows must be disjoint. 19 """ 20 faces = np.asarray(faces) 21 pinned, left, right = map(np.asarray, (pinned, left, right)) 22 if (pinned.ndim != 1 or any(a.dtype != np.bool_ or a.shape != pinned.shape 23 for a in (pinned, left, right))): 24 raise ValueError('pinned, left and right must be matching flat boolean arrays') 25 if faces.ndim != 2 or faces.shape[1] != 4 or faces.dtype.kind not in 'iu': 26 raise ValueError('faces must be an integer array of shape (nfaces, 4)') 27 n, m = len(pinned), len(faces) 28 if faces.size and (faces.min() < 0 or faces.max() >= n): 29 raise ValueError('out-of-range face incidence') 30 if (pinned & (left | right)).any(): 31 raise ValueError('protected sets must contain only free links') 32 if (left & right).any(): 33 raise ValueError('intersecting protected regions') 34 if (left[faces].any(axis=1) & right[faces].any(axis=1)).any(): 35 raise ValueError('one face meets both protected regions') 36 37 # Nodes v and n+v encode high (small) and low (big) membership. Putting 38 # all unforced free links at height 1 now witnesses feasibility. 39 s = 2*n + 4*m 40 t, hard = s + 1, 2*m + 1 41 network = _Network(t + 1) 42 for v in np.flatnonzero(~pinned).tolist(): 43 network.add(v, n + v, hard) # also needed for nonincident free links 44 for v in np.flatnonzero(left).tolist(): 45 network.add(s, v, hard) 46 for v in np.flatnonzero(right).tolist(): 47 network.add(n + v, t, hard) 48 49 free = ~pinned[faces] 50 for j, face in enumerate(faces): 51 links = dict.fromkeys(face[free[j]].tolist()) 52 if len(links) < 2: 53 continue 54 hi = 2*n + 4*j 55 lo = hi + 2 56 network.add(hi, hi + 1, 1) 57 network.add(lo, lo + 1, 1) 58 # One shared hard arc: any high link forces every low copy on the face. 59 network.add(hi, lo + 1, hard) 60 for v in links: 61 network.add(v, hi, hard) 62 network.add(hi + 1, v, hard) 63 network.add(n + v, lo, hard) 64 network.add(lo + 1, n + v, hard) 65 66 side = network.source_side(s, t) 67 small, big = side[:n].copy(), side[n:2*n].copy() 68 69 def splits(mask): 70 labels = mask[faces] 71 return (free & labels).any(axis=1) & (free & ~labels).any(axis=1) 72 73 a, b = splits(small), splits(big) 74 if ((left & ~small).any() or (big & right).any() or (small & ~big).any() 75 or (big & pinned).any() or (a & b).any()): 76 raise RuntimeError('cut violates an anchor, pin, nesting, or boundary disjointness') 77 total = int(a.sum()) + int(b.sum()) 78 network.certify(s, t, side, total) 79 return small, big, total 80 81 82 def _oracle(faces, pinned, left, right): 83 """Independent tiny reference: enumerate pairs, not graph/height gadgets.""" 84 masks = [] 85 for bits in product((False, True), repeat=int((~pinned).sum())): 86 mask = np.zeros(len(pinned), dtype=bool) 87 mask[~pinned] = bits 88 if (left & ~mask).any() or (right & mask).any(): 89 continue 90 boundary = set() 91 for j, face in enumerate(faces): 92 labels = {bool(mask[v]) for v in face if not pinned[v]} 93 if len(labels) == 2: 94 boundary.add(j) 95 masks.append((mask, boundary)) 96 best = None 97 for small, a in masks: 98 for big, b in masks: 99 if not (small & ~big).any() and not a.intersection(b): 100 cost = len(a) + len(b) 101 best = cost if best is None else min(best, cost) 102 return best 103 104 105 def _controls(): 106 from itertools import combinations, combinations_with_replacement 107 108 checked = rejected = 0 109 110 def compare(faces, pinned, left, right): 111 nonlocal checked, rejected 112 original = tuple(x.copy() for x in (faces, pinned, left, right)) 113 best = _oracle(faces, pinned, left, right) 114 try: 115 small, big, total = minimum_nested(faces, pinned, left, right) 116 except ValueError: 117 assert best is None, ('false infeasibility', original, best) 118 rejected += 1 119 else: 120 assert best == total and type(total) is int, (original, best, total) 121 assert small.dtype == big.dtype == np.bool_ 122 assert small.shape == big.shape == pinned.shape 123 assert not (small & ~big).any() 124 assert not (big & pinned).any() 125 assert not (left & ~small).any() and not (big & right).any() 126 boundaries = [] 127 for mask in (small, big): 128 boundaries.append({j for j, face in enumerate(faces) 129 if len({bool(mask[v]) for v in face 130 if not pinned[v]}) == 2}) 131 assert boundaries[0].isdisjoint(boundaries[1]) 132 assert sum(map(len, boundaries)) == total 133 assert all(np.array_equal(a, b) for a, b in zip( 134 original, (faces, pinned, left, right))) 135 checked += 1 136 137 # Exhaust every multiset of up to two face supports on three links, all 138 # pin sets, and all disjoint free left/right sets. Pad singleton/triple 139 # supports by repeated incidences; repeated rows remain distinct costs. 140 supports = [c for k in range(1, 4) for c in combinations(range(3), k)] 141 families = [()] + [(f,) for f in supports] 142 families += list(combinations_with_replacement(supports, 2)) 143 for family in families: 144 faces = np.array([list(f) + [f[-1]]*(4-len(f)) for f in family], 145 dtype=int).reshape(-1, 4) 146 for statuses in product(range(4), repeat=3): 147 status = np.array(statuses) 148 compare(faces, status == 3, status == 1, status == 2) 149 150 # Both cuts are necessary. Expanding these already-protected anchors would 151 # wrongly make the chain infeasible. Link 3 tests an isolated left anchor. 152 faces = np.array([[0, 1, 1, 1], [1, 2, 2, 2]]) 153 pinned = np.zeros(4, dtype=bool) 154 left = np.array([True, False, False, True]) 155 right = np.array([False, False, True, False]) 156 compare(faces, pinned, left, right) 157 small, big, total = minimum_nested(faces, pinned, left, right) 158 assert total == 2 and small[3] and big[3] 159 assert np.array_equal(small, left) 160 assert np.array_equal(big, np.array([True, True, False, True])) 161 162 # Two-versus-two split of a four-link hyperedge costs one, not four; 163 # duplicating its row charges it twice. The second face forces the other cut. 164 faces = np.array([[0, 1, 2, 3], [0, 1, 2, 3], [2, 3, 4, 4]]) 165 left = np.array([True, True, False, False, False]) 166 right = np.array([False, False, False, False, True]) 167 compare(faces, np.zeros(5, bool), left, right) 168 assert minimum_nested(faces, np.zeros(5, bool), left, right)[2] == 3 169 # All pins, empty graph, and isolated right/unforced. 170 compare(np.empty((0, 4), int), np.zeros(0, bool), 171 np.zeros(0, bool), np.zeros(0, bool)) 172 compare(np.array([[0, 1, 2, 3]]), np.ones(4, bool), 173 np.zeros(4, bool), np.zeros(4, bool)) 174 compare(np.empty((0, 4), int), np.zeros(3, bool), 175 np.array([True, False, False]), np.array([False, True, False])) 176 177 # Dropping disjointness makes this impossible instance seem feasible: 178 # choose both masks equal to left, splitting the same face twice. Merely 179 # enforcing per-link nesting does not forbid that double split. 180 direct = np.array([[0, 1, 1, 1]]) 181 left, right = np.array([True, False]), np.array([False, True]) 182 compare(direct, np.zeros(2, bool), left, right) 183 assert len({bool(left[v]) for v in direct[0]}) == 2 184 assert not (left & ~left).any() 185 186 # Crossed masks may have disjoint boundaries but are not nested. This 187 # control is not a claim to prove the separate uncrossing theorem. 188 crossed_a = np.array([True, True, False, False]) 189 crossed_b = np.array([True, False, True, False]) 190 assert (crossed_a & ~crossed_b).any() and (crossed_b & ~crossed_a).any() 191 crossed_faces = np.array([[0, 1, 1, 1], [0, 2, 2, 2]]) 192 a = {j for j, f in enumerate(crossed_faces) if len(set(crossed_a[f])) == 2} 193 b = {j for j, f in enumerate(crossed_faces) if len(set(crossed_b[f])) == 2} 194 assert a and b and a.isdisjoint(b) 195 compare(np.array([[0, 1, 1, 1], [0, 2, 2, 2]]), np.zeros(4, bool), 196 np.array([True, False, False, False]), 197 np.array([False, False, False, True])) 198 199 empty = np.empty((0, 4), int) 200 zeros = np.zeros(3, bool) 201 invalid = [ 202 (np.zeros((1, 3), int), zeros, zeros, zeros), 203 (np.zeros((1, 4), float), zeros, zeros, zeros), 204 (np.array([[0, 1, 2, 3]]), zeros, zeros, zeros), 205 (np.array([[-1, 0, 0, 0]]), zeros, zeros, zeros), 206 (empty, zeros, np.zeros(3, int), zeros), 207 (empty, np.zeros((1, 3), bool), np.zeros((1, 3), bool), np.zeros((1, 3), bool)), 208 (empty, zeros, np.zeros(2, bool), zeros), 209 (empty, np.array([True]), np.array([True]), np.array([False])), 210 (empty, np.array([False]), np.array([True]), np.array([True])), 211 ] 212 for args in invalid: 213 try: 214 minimum_nested(*args) 215 except ValueError: 216 pass 217 else: 218 raise AssertionError('accepted malformed or contradictory input') 219 220 # Actual feasible flow, then intentional certificate faults. 221 net = _Network(3) 222 net.add(0, 1, 1) 223 net.add(1, 2, 1) 224 side = net.source_side(0, 2) 225 net.certify(0, 2, side, 1) 226 for bad in (0, 2): 227 try: 228 net.certify(0, 2, side, bad) 229 except RuntimeError: 230 pass 231 else: 232 raise AssertionError('accepted false primal value') 233 net.residual[1] = 0.5 234 try: 235 net.certify(0, 2, side, 1) 236 except RuntimeError: 237 pass 238 else: 239 raise AssertionError('accepted fractional flow') 240 print(f'independent pair oracle: {checked} cases; {rejected} infeasible') 241 print('anchors not expanded; pins, isolated links, repeated rows/incidences: PASS') 242 print('semantic negatives: double-split and crossed masks are inadmissible: PASS') 243 print(f'invalid-input controls: {len(invalid)}; certificate corruption controls: PASS') 244 245 246 if __name__ == '__main__': 247 _controls()