Datasets:
Download src/coverage.py from PureOne/ChronoSheaf-Input-Lag: direct link, hf CLI and curl.
- Browser
- Download file 7.11 kB
-
https://huggingface.co/datasets/PureOne/ChronoSheaf-Input-Lag/resolve/main/src/coverage.py
- Command line
-
hf download hf://datasets/PureOne/ChronoSheaf-Input-Lag/src/coverage.py
-
curl -L -o coverage.py https://huggingface.co/datasets/PureOne/ChronoSheaf-Input-Lag/resolve/main/src/coverage.py
7.11 kB
| """Exact persistent-edge, finite-pulse and timing-uncertainty comparisons. | |
| A trace entry is (input cut, eligible-output time). Times share one clock. | |
| The pulse is active on [start, start+width). Query intervals are (left,right]. | |
| """ | |
| import argparse | |
| import json | |
| from bisect import bisect_left, bisect_right | |
| from fractions import Fraction | |
| from math import inf | |
| from pathlib import Path | |
| class ActiveCuts: | |
| """Offline coordinate compression with Fenwick predecessor/successor queries.""" | |
| def __init__(self, cuts): | |
| self.cuts = sorted(set(cuts)) | |
| self.bit = [0] * (len(self.cuts) + 1) | |
| self.size = 0 | |
| def insert(self, x): | |
| i = bisect_left(self.cuts, x) + 1 | |
| self.size += 1 | |
| while i < len(self.bit): | |
| self.bit[i] += 1 | |
| i += i & -i | |
| def count_to(self, i): | |
| total = 0 | |
| while i: | |
| total += self.bit[i] | |
| i -= i & -i | |
| return total | |
| def kth(self, rank): | |
| if rank < 1 or rank > self.size: | |
| return None | |
| index = 0 | |
| step = 1 << (len(self.bit).bit_length() - 1) | |
| while step: | |
| trial = index + step | |
| if trial < len(self.bit) and self.bit[trial] < rank: | |
| rank -= self.bit[trial] | |
| index = trial | |
| step //= 2 | |
| return self.cuts[index] | |
| def bracket(self, b): | |
| left_count = self.count_to(bisect_right(self.cuts, b)) | |
| before = self.count_to(bisect_left(self.cuts, b)) | |
| return self.kth(left_count), self.kth(before + 1) | |
| def checked(trace): | |
| for cut, shown in trace: | |
| if type(cut) is not int or type(shown) is not int or cut > shown: | |
| raise ValueError("each observation needs integer cut <= output") | |
| return sorted(trace, key=lambda p: p[1]) | |
| def certificate(baseline, candidate, grace=0): | |
| if type(grace) is not int or grace < 0: | |
| raise ValueError("grace must be a nonnegative integer") | |
| base, cand = checked(baseline), checked(candidate) | |
| seen = ActiveCuts(s for s, _ in cand) | |
| at = 0 | |
| peak = 0 | |
| limiting = None | |
| edge_ok = True | |
| for b, due in base: | |
| while at < len(cand) and cand[at][1] <= due + grace: | |
| seen.insert(cand[at][0]) | |
| at += 1 | |
| left, right = seen.bracket(b) | |
| if right is None: | |
| edge_ok = False | |
| if left == b: | |
| width = 0 | |
| elif left is None or right is None: | |
| width = inf | |
| else: | |
| width = right-left | |
| if width > peak: | |
| peak = width | |
| limiting = dict(cut=b, due=due+grace, left=left, right=right) | |
| return dict(persistent=edge_ok, minimum_pulse_width=None if peak==inf else peak, | |
| all_finite_widths_impossible=peak==inf, limiting=limiting) | |
| def spectrum(baseline, candidate): | |
| """Exact finite width/grace staircase. For small diagnostic traces.""" | |
| base,cand=checked(baseline),checked(candidate) | |
| times=sorted({0}|{da-db for _,da in cand for _,db in base if da>=db}) | |
| curve=[] | |
| for g in times: | |
| result=certificate(base,cand,g) | |
| pair=(result["persistent"],result["minimum_pulse_width"]) | |
| if not curve or pair!=(curve[-1]["persistent"],curve[-1]["minimum_pulse_width"]): | |
| curve.append(dict(grace=g,persistent=pair[0],minimum_pulse_width=pair[1])) | |
| return curve | |
| def missing_start(needed, available): | |
| """Return a witness in an uncovered portion of a right-closed interval.""" | |
| lo, hi = needed | |
| cursor = lo | |
| for a, b in sorted(available): | |
| if b <= cursor or b <= a: | |
| continue | |
| if a > cursor: | |
| break_hi = min(a, hi) | |
| if break_hi > cursor: | |
| return Fraction(cursor+break_hi, 2) | |
| cursor = max(cursor, b) | |
| if cursor >= hi: | |
| return None | |
| return Fraction(cursor+hi, 2) if cursor < hi else None | |
| def robust_witness(baseline, candidate, width, grace=0): | |
| """Independent closed boxes (cut_lo, cut_hi, output_lo, output_hi).""" | |
| if width <= 0 or grace < 0: | |
| raise ValueError("positive pulse width and nonnegative grace required") | |
| for box in (*baseline, *candidate): | |
| if len(box) != 4 or not (box[0] <= box[1] <= box[2] <= box[3]): | |
| raise ValueError("invalid independent time box") | |
| for lo, hi, early, _ in baseline: | |
| cover = [(b-width, a) for a,b,_,late in candidate if late <= early+grace] | |
| u = missing_start((lo-width, hi),cover) | |
| if u is not None: | |
| return u, early+grace | |
| return None | |
| def front_area(baseline, candidate, band, horizon): | |
| """Signed integrated advantage on a clipped input-time by display-time rectangle.""" | |
| low, high = band | |
| first, last = horizon | |
| if low>=high or first>=last: | |
| raise ValueError("empty measurement rectangle") | |
| def area(trace): | |
| frontier = low | |
| t = first | |
| result = 0 | |
| for s,d in checked(trace): | |
| if d > last: | |
| break | |
| if d > t: | |
| result += (d-t)*(frontier-low) | |
| t = d | |
| frontier = max(frontier,min(high,s)) | |
| return result + (last-t)*(frontier-low) | |
| return area(candidate)-area(baseline) | |
| def repair_points(opportunities, obligations): | |
| """Fewest retained optional reads for a finite pulse/deadline catalogue. | |
| Opportunities (cut, output) must be strictly increasing in cut, nondecreasing | |
| in output. An obligation (start, end, deadline) requires a read in [start,end). | |
| Return None when infeasible, else indices in the input opportunity list. | |
| """ | |
| o = list(opportunities) | |
| if any(s>d for s,d in o) or any(o[i][0]>=o[i+1][0] or o[i][1]>o[i+1][1] for i in range(len(o)-1)): | |
| raise ValueError("ordered, causal opportunities required") | |
| s = [a for a,_ in o]; d = [t for _,t in o] | |
| intervals = [] | |
| for a,b,deadline in obligations: | |
| if b<=a: | |
| raise ValueError("empty pulse") | |
| left=bisect_left(s,a); right=min(bisect_left(s,b), bisect_right(d,deadline))-1 | |
| if left>right: | |
| return None | |
| intervals.append((right,left)) | |
| picks=[] | |
| for right,left in sorted(intervals): | |
| if not picks or picks[-1]<left: | |
| picks.append(right) | |
| return picks | |
| def main(): | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("trace",type=Path) | |
| parser.add_argument("--grace",type=int,default=0) | |
| parser.add_argument("--width",type=int) | |
| parser.add_argument("--spectrum",action="store_true") | |
| args=parser.parse_args() | |
| x=json.loads(args.trace.read_text()) | |
| base,cand=x["baseline"],x["candidate"] | |
| result=certificate(base,cand,args.grace) | |
| if args.spectrum:result["spectrum"]=spectrum(base,cand) | |
| if args.width is not None: | |
| boxes=lambda tr:[(s,s,d,d) for s,d in tr] | |
| witness=robust_witness(boxes(base),boxes(cand),args.width,args.grace) | |
| result["witness"]=None if witness is None else {"pulse_start":str(witness[0]),"deadline":witness[1]} | |
| print(json.dumps(result,indent=2)) | |
| if __name__=="__main__": | |
| main() | |