"""Known-support digital connectivity; caller binds evidence, never full-object topology.""" import hashlib from collections import deque import numpy as np from scipy.ndimage import label def _sha(array): return hashlib.sha256(array.tobytes()).hexdigest() def _path(allowed, start, goal, offsets, budget, origin, max_path): h, w = allowed.shape parents = np.full(h * w, -2, np.int32) seeds = np.flatnonzero(start & allowed) parents[seeds] = -1 queue = deque(map(int, seeds)) while queue: if budget[0] <= 0: raise ValueError("Connectivity work budget exceeded") budget[0] -= 1 here = queue.popleft() y, x = divmod(here, w) if goal[y, x]: path = [] while here != -1: y, x = divmod(here, w) path.append([x + origin[0], y + origin[1]]) if len(path) > max_path: raise ValueError("Complete witness exceeds path budget") here = int(parents[here]) return path[::-1] for dy, dx in offsets: yy, xx = y + dy, x + dx if 0 <= yy < h and 0 <= xx < w: nxt = yy * w + xx if parents[nxt] == -2 and allowed[yy, xx]: parents[nxt] = here queue.append(nxt) return None def audit_topology( probability, target, cores, relations, *, roi, connectivity, max_nodes=1_000_000, max_path=4096 ): """Native bool cores by ID; relations are {left,right,gap:bool mask}. Exclusive ROI [x0,y0,x1,y1], fixed >=.5, native integer path centres. Each known-core CC is independent; no full-object/exterior claim. Resource refusal returns no partial result or truncated witness. """ if ( not isinstance(target, np.ndarray) or target.ndim != 2 or target.dtype != np.uint8 or not 0 < target.size <= 1_048_576 or not np.isin(target, [0, 1, 255]).all() ): raise ValueError("Bounded native uint8 0/1/255 target required") if ( not isinstance(probability, np.ndarray) or probability.shape != target.shape or probability.dtype.kind != "f" or not np.isfinite(probability).all() or not ((probability >= 0) & (probability <= 1)).all() ): raise ValueError("Aligned finite probabilities in [0,1] required") h, w = target.shape if ( len(roi) != 4 or any(type(v) is not int for v in roi) or not 0 <= roi[0] < roi[2] <= w or not 0 <= roi[1] < roi[3] <= h ): raise ValueError("Exclusive native ROI required") if type(connectivity) is not int or connectivity not in (4, 8): raise ValueError("Explicit connectivity 4 or 8 required") if any(type(v) is not int or not 0 < v <= 1_000_000 for v in (max_nodes, max_path)): raise ValueError("Positive bounded work/path limits required") if ( not isinstance(cores, dict) or not 1 <= len(cores) <= 32 or any(not isinstance(k, str) or not k for k in cores) or not isinstance(relations, list) or len(relations) > 32 ): raise ValueError("Bounded named cores/relations required") x0, y0, x1, y1 = roi sl = np.s_[y0:y1, x0:x1] t, pred = target[sl], probability[sl] >= 0.5 if t.size * (3 * len(cores) + 2 * len(relations)) > 64_000_000: raise ValueError("Array work budget exceeded") structure = np.ones((3, 3), bool) if connectivity == 4: structure[[0, 0, 2, 2], [0, 2, 0, 2]] = False offsets = [(int(y) - 1, int(x) - 1) for y, x in np.argwhere(structure) if (y, x) != (1, 1)] budget = [max_nodes] def mask(value, wanted): if ( not isinstance(value, np.ndarray) or value.dtype != bool or value.shape != target.shape or np.any(value & (target != wanted)) or int(value.sum()) != int(value[sl].sum()) ): raise ValueError("Mask must match its known class and stay inside ROI") return value[sl] def find_path(allowed, start, goal): return _path(allowed, start, goal, offsets, budget, (x0, y0), max_path) checked, occupied, objects = {}, np.zeros(t.shape, bool), [] for name, raw in cores.items(): core = mask(raw, 1) if not core.any() or (occupied & core).any(): raise ValueError("Nonempty disjoint accepted paint cores required") occupied |= core checked[name] = core truth, nt = label(core, structure) recovered, nr = label(core & pred, structure) ids = np.unique(truth[core & pred].astype(np.int64) * (nr + 1) + recovered[core & pred]) counts = np.bincount(ids // (nr + 1), minlength=nt + 1) fragments = np.flatnonzero(counts[1:] > 1) + 1 witness = None if len(fragments): component = truth == fragments[0] rs = np.unique(recovered[component]) rs = rs[rs != 0] witness = find_path(component, recovered == rs[0], recovered == rs[1]) objects.append( dict( id=name, core_sha256=_sha(raw), known_pixels=int(core.sum()), recovered_pixels=int((core & pred).sum()), original_components=nt, recovered_components=nr, fragmented_original_components=len(fragments), fully_missed_original_components=int((counts[1:] == 0).sum()), known_core_fragmentation_witness=witness, touches_roi_edge=bool( core[0].any() or core[-1].any() or core[:, 0].any() or core[:, -1].any() ), full_object_split_assessed=False, ) ) pairs, seen = [], set() for relation in relations: left, right = relation["left"], relation["right"] if left not in checked or right not in checked or left == right: raise ValueError("Declared distinct core IDs required") key = tuple(sorted((left, right))) if key in seen: raise ValueError("Duplicate relation") seen.add(key) gap = mask(relation["gap"], 0) start, goal = checked[left] & pred, checked[right] & pred corridor = checked[left] | checked[right] | gap path = None if not start.any() or not goal.any(): status = "unassessed_missing_predicted_endpoint" elif not gap.any(): status = "unassessed_no_known_gap" else: path = find_path(pred & corridor, start, goal) if path is not None: status = ( "confirmed_known_support_bridge" if any(gap[y - y0, x - x0] for x, y in path) else "unassessed_core_adjacency_without_background" ) else: path = find_path(pred & (corridor | (t == 255)), start, goal) status = ( "indeterminate_unknown_connection" if path is not None else "no_connection_within_reviewed_corridor" ) pairs.append( dict( left=left, right=right, status=status, witness=path, gap_pixels=int(gap.sum()), gap_sha256=_sha(relation["gap"]), witness_unknown_pixels=int(sum(t[y - y0, x - x0] == 255 for x, y in path or [])), exterior_connection_assessed=False, full_object_merge_assessed=False, ) ) return dict( schema="missioncore.observed-topology/v1", threshold=0.5, connectivity=connectivity, roi=list(roi), shape=list(target.shape), target_sha256=_sha(target), probability_sha256=_sha(probability), cores=objects, relations=pairs, graph_nodes_visited=max_nodes - budget[0], semantics="Known-support connectivity only; unassessed is not separation.", )