Datasets:
File size: 7,109 Bytes
987b273 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """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()
|