Datasets:
cocogni4d / code /evaluation-code /v0.2-0c2690ae /embodied_pipeline /semantics /shared_quantities.py
Download code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/semantics/shared_quantities.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 35.5 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/semantics/shared_quantities.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/semantics/shared_quantities.py
-
curl -L -o shared_quantities.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/embodied_pipeline/semantics/shared_quantities.py
35.5 kB
| """Exact finite quantities on supplied piecewise-linear tracks and joint readings. | |
| These are contract calculations, not video reconstruction or world enumeration. | |
| Interval sets retain their gaps. All accepted-answer tests use a supplied actual | |
| consumer scorer; selection margins are not scoring tolerances. | |
| """ | |
| import bisect | |
| import math | |
| import itertools | |
| import struct | |
| from fractions import Fraction | |
| import numpy as np | |
| from . import piecewise as PW | |
| from .leaf_contracts import SharedContractError, finite, joint_records, parameter | |
| def point(value): | |
| if not isinstance(value, (list, tuple)) or len(value) not in (2, 3): | |
| raise SharedContractError('a horizontal point needs two coordinates, or z=0') | |
| values = [finite(x, 'coordinate') for x in value] | |
| if len(values) == 3 and values[2] != 0: | |
| raise SharedContractError('height is outside the horizontal answer domain') | |
| return values[:2] | |
| def intervals(values, allow_empty=True): | |
| if not isinstance(values, list): | |
| raise SharedContractError('interval set must be a list') | |
| pairs = [] | |
| for value in values: | |
| if not isinstance(value, (list, tuple)) or len(value) != 2: | |
| raise SharedContractError('interval needs two endpoints') | |
| lo, hi = (finite(x, 'interval endpoint') for x in value) | |
| if lo > hi: | |
| raise SharedContractError('reversed interval') | |
| pairs.append([lo, hi]) | |
| pairs.sort() | |
| merged = [] | |
| for lo, hi in pairs: | |
| if merged and lo <= merged[-1][1]: | |
| merged[-1][1] = max(hi, merged[-1][1]) | |
| else: | |
| merged.append([lo, hi]) | |
| if not merged and not allow_empty: | |
| raise SharedContractError('the requested quantity has no member interval') | |
| return merged | |
| def intersection(left, right): | |
| return intervals([[max(a, c), min(b, d)] for a, b in intervals(left) | |
| for c, d in intervals(right) if max(a, c) <= min(b, d)]) | |
| def duration(values): | |
| return sum(hi-lo for lo, hi in intervals(values)) | |
| class Track(dict): | |
| """A track validated once, so lookups within one calculation skip revalidation. Do not mutate it.""" | |
| def __init__(self, track): | |
| self.checked = validate_track(track) | |
| super().__init__(track) | |
| def prepared(track): | |
| return track if isinstance(track, Track) else Track(track) | |
| def validate_track(track): | |
| if isinstance(track, Track): | |
| return track.checked | |
| if not isinstance(track, dict) or not track.get('source'): | |
| raise SharedContractError('track needs its supplied-data source') | |
| times = track.get('times', []) | |
| points = track.get('points', []) | |
| if len(times) != len(points) or len(times) < 2: | |
| raise SharedContractError('track must have at least two paired states') | |
| times = [finite(t, 'track time') for t in times] | |
| if any(a >= b for a, b in zip(times, times[1:])): | |
| raise SharedContractError('track times must be strictly increasing') | |
| return times, [point(p) for p in points] | |
| def position(track, time): | |
| times, points = validate_track(track) | |
| time = finite(time, 'requested world time') | |
| if time < times[0] or time > times[-1]: | |
| raise SharedContractError('world time outside track definition domain') | |
| return PW.at(times, points, time).tolist() | |
| def velocity(track, time): | |
| times, points = validate_track(track) | |
| time = finite(time,'requested velocity time') | |
| if time < times[0] or time > times[-1]: | |
| raise SharedContractError('world time outside track definition domain') | |
| v = PW.velocity(times, points, time) # 采样点上取两段平均,转过 CORNER_TURN_MAX_DEG 以上才未定义 | |
| if np.isnan(v).any(): | |
| raise SharedContractError('velocity is undefined at a corner') | |
| return [float(c) for c in v] | |
| def path_length(track, members): | |
| track = prepared(track) | |
| times, points = validate_track(track) | |
| members = intervals(members) | |
| if any(lo < times[0] or hi > times[-1] for lo, hi in members): | |
| raise SharedContractError('world time outside track definition domain') | |
| cum = PW.cumulative(points) | |
| return float(sum(PW.path_between(times, cum, lo, hi) for lo, hi in members)) | |
| def endpoint_displacement(start, end): | |
| """World-frame endpoint difference; arrays keep their leading batch axes.""" | |
| return np.asarray(end)-np.asarray(start) | |
| def net_vector(track, members): | |
| members = intervals(members, False) | |
| if len(members) != 1: | |
| raise SharedContractError('endpoint displacement needs one interval') | |
| lo, hi = members[0] | |
| track = prepared(track) | |
| return endpoint_displacement(position(track, lo), position(track, hi)).tolist() | |
| def relative(track, target, time): | |
| other = position(target, time) if isinstance(target, dict) else point(target) | |
| return [a-b for a, b in zip(position(track, time), other)] | |
| def _distance_curve(track, target): | |
| """到对象的距离曲线的三样:节点时刻、各节点的向量、(线段极小, 点距离)。对象是另一条轨迹或一点时向量是相对位置、距离是模长; | |
| 对象是 {'polygon': 顶点} 时向量是本人位置、距离量到多边形表面(面内为 0;同证明器 fixture_distance)。""" | |
| track = prepared(track) | |
| times, _ = validate_track(track) | |
| if isinstance(target, dict) and 'polygon' in target: | |
| poly = [point(x) for x in target['polygon']] | |
| return times, lambda t: position(track, t), (PW.poly_seg_min(poly), lambda p: PW.poly_gap(p, poly)) | |
| if isinstance(target, dict): | |
| target = prepared(target) | |
| times = sorted(set(times+validate_track(target)[0])) | |
| return times, lambda t: relative(track, target, t), (None, None) | |
| def distance_extrema(track, target, members): | |
| """Include exact interior minima of distance, separately per member.""" | |
| times, vec, (seg_min, norm) = _distance_curve(track, target) | |
| seg_min, norm = seg_min or PW._pair_min, norm or (lambda p: np.linalg.norm(p, axis=-1)) | |
| candidates = [] | |
| for lo, hi in intervals(members, False): | |
| knots = [lo]+[t for t in times if lo < t < hi]+[hi] | |
| rel = np.array([vec(t) for t in knots], float) | |
| candidates.extend((t, float(g)) for t, g in zip(knots, norm(rel))) | |
| if len(knots) > 1: | |
| gap, u = seg_min(rel[:-1], rel[1:]) | |
| when = np.asarray(knots[:-1])+u*np.diff(knots) | |
| candidates.extend((float(w), float(g)) for x, w, g in zip(u, when, gap) if 0 < x < 1) | |
| return sorted(set(candidates)) | |
| def extremum_query(track, target, mode): | |
| """[lo, hi] 上到对象距离的极值查询(PW.min_norm/max_norm,证明器 instant.extremum 调同一个):query(s, e) 给 (极值, 时刻)。""" | |
| times, vec, (seg_min, norm) = _distance_curve(track, target) | |
| r = np.array([vec(t) for t in times], float) | |
| return PW.min_norm(times, r, seg_min) if mode == 'min' else PW.max_norm(times, r, norm) | |
| FLOAT_MAX = float.fromhex('0x1.fffffffffffffp+1023') | |
| def answer_domain(scoring): | |
| """Closed original submission domain, without inventing new bounds.""" | |
| domain = scoring.get('answer_domain') | |
| if domain is None: | |
| return None | |
| if isinstance(domain, dict): # one-sided ({'minimum': 1}): the open side is bounded as with no domain at all | |
| domain = [domain.get('minimum', -FLOAT_MAX), domain.get('maximum', FLOAT_MAX)] | |
| if not isinstance(domain, (list, tuple)) or len(domain) != 2: | |
| raise SharedContractError('original answer domain needs two bounds') | |
| lo, hi = [finite(x, 'answer-domain bound') for x in domain] | |
| if lo > hi: | |
| raise SharedContractError('reversed original answer domain') | |
| return lo, hi | |
| def ratio_accepts(submitted, truth, factor): | |
| """Positive finite ratios, symmetric under reciprocal and common scaling.""" | |
| a, y = np.asarray(submitted, float), np.asarray(truth, float) | |
| with np.errstate(divide='ignore', invalid='ignore', over='ignore'): | |
| return (np.isfinite(a) & np.isfinite(y) & (a > 0) & (y > 0) | |
| & np.isfinite(factor) & (factor > 1) & (np.maximum(a/y, y/a) <= factor)) | |
| def tolerance_radius(tol, truth): | |
| """Fixed/additive allowance or the multiplicative upper-side radius; ratio acceptance uses ratio_accepts.""" | |
| if 'factor' in tol: | |
| return np.abs(truth)*(tol['factor']-1) | |
| if 'absolute' in tol: | |
| return tol['absolute'] | |
| return np.maximum(tol['floor'], tol['relative']*np.abs(truth)) if np.ndim(truth) else max(tol['floor'], tol['relative']*abs(float(truth))) | |
| def scoring_radius(value, scoring): | |
| """Original fixed tolerance or floor/relative radius at the actual truth.""" | |
| if 'floor_m' in scoring or 'relative' in scoring: | |
| floor = finite(scoring.get('floor_m'), 'original scoring floor') | |
| relative = finite(scoring.get('relative'), 'original relative tolerance') | |
| if min(floor, relative) < 0: | |
| raise SharedContractError('negative original scoring allowance') | |
| if scoring.get('kind') in {'coordinate', 'vector'}: | |
| location = point(value) | |
| # Coordinates already expressed in the queried frame have origin 0. | |
| # Supplied world-coordinate readouts must bind that frame's origin. | |
| origin = point(scoring.get('reference_origin', [0, 0])) if scoring.get('kind') == 'coordinate' else [0, 0] | |
| magnitude = math.dist(location, origin) | |
| else: | |
| magnitude = abs(finite(value, 'original numeric truth')) | |
| return tolerance_radius(dict(floor=floor, relative=relative), magnitude) | |
| tolerance = finite(scoring.get('tolerance'), 'original scoring tolerance') | |
| if tolerance < 0: | |
| raise SharedContractError('negative original scoring tolerance') | |
| return tolerance_radius(dict(absolute=tolerance), value) | |
| def item_scorers(scoring, length): | |
| if 'items' in scoring: | |
| items = scoring['items'] | |
| if not isinstance(items, list) or len(items) != length or any(not isinstance(x, dict) for x in items): | |
| raise SharedContractError('list scorers must bind every original item') | |
| return items | |
| if not isinstance(scoring.get('item'), dict): | |
| raise SharedContractError('complete list needs its original item scorer') | |
| return [scoring['item']] * length | |
| def witness_candidates(lo, hi): | |
| """Try rounded boundary neighbours even when the ideal interval is empty.""" | |
| return [lo / 2 + hi / 2, lo, hi, math.nextafter(lo, hi), math.nextafter(hi, lo)] | |
| def supported_witness(candidates, values, scoring): | |
| """Only return a submission accepted by every unchanged original scorer.""" | |
| return next((candidate for candidate in candidates | |
| if all(score(candidate, value, scoring) for value in values)), None) | |
| def consensus_result(answer=None, proof=None, **details): | |
| """Failure to find a witness is not a proof that one does not exist.""" | |
| state = 'accepted' if answer is not None else 'proven_none' if proof is not None else 'undecided' | |
| result = dict(accepted=state == 'accepted', state=state, answer=answer, **details) | |
| if proof is not None: | |
| result['proof'] = proof | |
| if state != 'accepted': | |
| result['reason'] = 'no_common_answer' if state == 'proven_none' else 'consensus_undecided' | |
| return result | |
| def float_index(value): | |
| """Binary64 values in increasing order, retaining both signed zeroes.""" | |
| bits = struct.unpack('>Q', struct.pack('>d', value))[0] | |
| return (~bits & ((1 << 64) - 1)) if bits >> 63 else bits | (1 << 63) | |
| def indexed_float(index): | |
| bits = index & ((1 << 63) - 1) if index >> 63 else ~index & ((1 << 64) - 1) | |
| return struct.unpack('>d', struct.pack('>Q', bits))[0] | |
| def first_true(lo, hi, predicate): | |
| """First index of a monotone false/true binary64 predicate (hi+1 if empty).""" | |
| end = hi + 1 | |
| while lo < end: | |
| middle = (lo + end) // 2 | |
| if predicate(indexed_float(middle)): | |
| end = middle | |
| else: | |
| lo = middle + 1 | |
| return lo | |
| def last_true(lo, hi, predicate): | |
| return first_true(lo, hi, lambda x: not predicate(x)) - 1 | |
| def numeric_float_interval(truth, radius, domain=None): | |
| """Exact endpoints for abs(submitted-truth)<=radius over finite binary64. | |
| The subtraction is the original operation, not ideal truth +/- radius. | |
| On either side of truth its rounded absolute value is monotone; the two | |
| searches therefore certify all representable submissions between endpoints. | |
| """ | |
| lo, hi = domain if domain is not None else (-FLOAT_MAX, FLOAT_MAX) | |
| anchor = float_index(truth) | |
| predicate = lambda x: abs(x - truth) <= radius | |
| return (first_true(float_index(lo), anchor, predicate), | |
| last_true(anchor, float_index(hi), predicate)) | |
| def interval_intersection(left, right): | |
| return [(max(a, c), min(b, d)) for a, b in left for c, d in right if max(a, c) <= min(b, d)] | |
| def angle_float_intervals(truth, tolerance): | |
| """Original angular predicate on the existing canonical answer range [0,360). | |
| Split the monotone rounded (submitted-truth+180) at exact multiples of 360. | |
| Within each piece, remainder-180 is monotone. Integer-index binary search | |
| finds its accepted endpoints without normalizing the supplied truth or | |
| adding a scoring allowance. A trailing interval can include signed zero. | |
| """ | |
| lo, hi = float_index(0.0), float_index(math.nextafter(360.0, 0.0)) | |
| before_mod = lambda x: x - truth + 180 | |
| lower = Fraction(before_mod(indexed_float(lo))) // 360 | |
| upper = Fraction(before_mod(indexed_float(hi))) // 360 | |
| splits = [lo] + [first_true(lo, hi, lambda x, k=k: before_mod(x) >= k * 360) | |
| for k in range(lower + 1, upper + 1)] + [hi + 1] | |
| result = [] | |
| for start, end in zip(splits, splits[1:]): | |
| if start >= end: | |
| continue | |
| remainder = lambda x: before_mod(x) % 360 - 180 | |
| first = first_true(start, end - 1, lambda x: remainder(x) >= -tolerance) | |
| last = last_true(start, end - 1, lambda x: remainder(x) <= tolerance) | |
| if first <= last: | |
| result.append((first, last)) | |
| return result | |
| def angle_interior_candidates(regions): | |
| # Integer midpoints remain inside the exact representable intersection. | |
| return [indexed_float((lo + hi) // 2) for lo, hi in regions] | |
| def disk_candidates(points, radii): | |
| """Useful finite geometric guesses, with no completeness claim.""" | |
| candidates = points[:] + [[0.0, 0.0]] | |
| for i, a in enumerate(points): | |
| for j, b in enumerate(points[i + 1:], i + 1): | |
| dist = math.dist(a, b) | |
| ra, rb = radii[i], radii[j] | |
| if ra + rb: | |
| candidates.append([a[k] + ra / (ra + rb) * (b[k] - a[k]) for k in (0, 1)]) | |
| if not dist or dist > ra + rb or dist < abs(ra - rb): | |
| continue | |
| along = (ra * ra - rb * rb + dist * dist) / (2 * dist) | |
| middle = [a[k] + along * (b[k] - a[k]) / dist for k in (0, 1)] | |
| height = math.sqrt(max(0, ra * ra - along * along)) | |
| perpendicular = [-(b[1] - a[1]) / dist, (b[0] - a[0]) / dist] | |
| candidates.extend([[middle[j] + sign * height * perpendicular[j] for j in (0, 1)] | |
| for sign in (-1, 1)]) | |
| candidates.append([math.fsum(p[k] for p in points) / len(points) for k in (0, 1)]) | |
| return candidates | |
| def minimax_disk_candidate(points, radii, candidates): | |
| """Improve a guess for max(distance-to-center - radius), never a proof.""" | |
| objective = lambda p: max(math.dist(p, q) - r for q, r in zip(points, radii)) | |
| best = min(candidates, key=objective) | |
| step = max([math.dist(best, p) for p in points] + radii) | |
| directions = list(itertools.product((-1, 0, 1), repeat=2)) | |
| for _ in range(160): | |
| options = [[best[k] + direction[k] * step for k in (0, 1)] for direction in directions] | |
| improved = min(options, key=objective) | |
| if objective(improved) < objective(best): | |
| best = improved | |
| else: | |
| step /= 2 | |
| if not step: | |
| break | |
| return best | |
| def disk_separation_proof(points, radii): | |
| """Only certify widely separated pairs, never ideal empty intersections. | |
| Allow 64 ulps per supplied coordinate/radius and computed center distance: | |
| this bounds subtraction, two-dimensional norm rounding, and radius-sum | |
| rounding for binary64 math.dist in the supported Python versions. A putative | |
| accepted point is bounded by one center plus its radius; its subtraction | |
| errors are bounded by the same scale. Overflow makes the bound infinite and | |
| therefore cannot certify separation. This allowance is used only for the | |
| proof direction; every returned witness still uses the unchanged scorer. | |
| """ | |
| for i, a in enumerate(points): | |
| for j, b in enumerate(points[i + 1:], i + 1): | |
| distance = math.dist(a, b) | |
| scale = a + b + [radii[i], radii[j], distance] | |
| allowance = 64 * sum(math.ulp(x) for x in scale) | |
| gap = distance - (radii[i] + radii[j]) | |
| if gap > allowance: | |
| return dict(method='pairwise_disk_separation_with_roundoff_bound', | |
| pair=[i, j], separation=gap, roundoff_bound=allowance) | |
| return None | |
| def acceptance(values, scoring): | |
| """Find an original-score witness, certify absence, or explicitly abstain.""" | |
| if not values: | |
| raise SharedContractError('empty consumer answers') | |
| kind = scoring.get('kind') | |
| if kind == 'list': | |
| if any(not isinstance(x, list) or not x for x in values) or len({len(x) for x in values}) != 1: | |
| raise SharedContractError('complete answer lists must have the same nonzero length') | |
| items = [acceptance([value[i] for value in values], scorer) | |
| for i, scorer in enumerate(item_scorers(scoring, len(values[0])))] | |
| if all(item['accepted'] for item in items): | |
| return consensus_result([item['answer'] for item in items], items=items) | |
| disjoint = [i for i, item in enumerate(items) if item['state'] == 'proven_none'] | |
| proof = dict(method='disjoint_list_item', item=disjoint[0], | |
| item_proof=items[disjoint[0]]['proof']) if disjoint else None | |
| return consensus_result(proof=proof, items=items) | |
| if kind == 'exact': | |
| if all(type(x) == type(values[0]) and x == values[0] for x in values): | |
| return dict(accepted=True, state='accepted', answer=values[0]) | |
| return consensus_result(proof=dict(method='unequal_exact_values_or_types')) | |
| if kind == 'log_ratio': | |
| numbers = [finite(x, 'positive ratio truth') for x in values] | |
| if any(x <= 0 for x in numbers): | |
| raise SharedContractError('ratio truth must be positive') | |
| factor = scoring['factor'] | |
| lo, hi = max(x/factor for x in numbers), min(x*factor for x in numbers) | |
| answer = supported_witness(witness_candidates(lo, hi)+numbers, values, scoring) | |
| if answer is not None: | |
| return consensus_result(answer) | |
| # Certify disjointness with the same rounded division predicate. | |
| regions = [(first_true(float_index(0.), float_index(x), lambda a: bool(ratio_accepts(a,x,factor))), | |
| last_true(float_index(x), float_index(FLOAT_MAX), lambda a: bool(ratio_accepts(a,x,factor)))) | |
| for x in numbers] | |
| lower, upper = max(a for a,_ in regions), min(b for _,b in regions) | |
| return consensus_result(supported_witness([indexed_float(lower)], values, scoring) if lower <= upper else None, | |
| proof=dict(method='disjoint_ratio_intervals') if lower > upper else None) | |
| if kind == 'numeric': | |
| numbers = [finite(x, 'consumer answer') for x in values] | |
| radii = [scoring_radius(x, scoring) for x in numbers] | |
| domain = answer_domain(scoring) | |
| if domain is not None and any(not domain[0] <= x <= domain[1] for x in numbers): | |
| raise SharedContractError('truth outside original answer domain') | |
| lo = max(x - r for x, r in zip(numbers, radii)) | |
| hi = min(x + r for x, r in zip(numbers, radii)) | |
| answer = supported_witness(witness_candidates(lo, hi) + numbers, values, scoring) | |
| if answer is not None: | |
| return consensus_result(answer) | |
| regions = [numeric_float_interval(x, r, domain) for x, r in zip(numbers, radii)] | |
| lower, upper = max(a for a, _ in regions), min(b for _, b in regions) | |
| if lower > upper: | |
| return consensus_result(proof=dict(method='disjoint_original_numeric_float_intervals')) | |
| return consensus_result(supported_witness([indexed_float(lower)], values, scoring)) | |
| if kind == 'time_pair': | |
| tolerance = scoring_radius(0, scoring) | |
| if any(not isinstance(x, list) or len(x) != 2 or x[0] > x[1] for x in values): | |
| raise SharedContractError('time answer must be an ordered pair') | |
| regions = [[numeric_float_interval(finite(x[i], 'time answer'), tolerance) for x in values] | |
| for i in (0, 1)] | |
| lower = [max(a for a, _ in items) for items in regions] | |
| upper = [min(b for _, b in items) for items in regions] | |
| if any(a > b for a, b in zip(lower, upper)) or lower[0] > upper[1]: | |
| return consensus_result(proof=dict(method='disjoint_or_unordered_original_time_float_intervals')) | |
| pair = [indexed_float(lower[0]), indexed_float(max(lower))] | |
| return consensus_result(supported_witness([pair], values, scoring)) | |
| if kind == 'angle': | |
| tolerance = scoring_radius(0, scoring) | |
| angles = [finite(x, 'angle answer') % 360 for x in values] | |
| candidates = angles + [(x + s * tolerance) % 360 for x in angles for s in (-1, 1)] | |
| regions = [(float_index(0.0), float_index(math.nextafter(360.0, 0.0)))] | |
| for truth in values: | |
| regions = interval_intersection(regions, angle_float_intervals(truth, tolerance)) | |
| candidates.extend(angle_interior_candidates(regions)) | |
| answer = supported_witness(candidates, values, scoring) | |
| if answer is not None: | |
| return consensus_result(answer) | |
| proof = dict(method='disjoint_original_canonical_angle_float_intervals', | |
| answer_domain=[0, 360], upper_exclusive=True) if not regions else None | |
| return consensus_result(proof=proof) | |
| if kind in {'vector', 'coordinate'}: | |
| points = [point(x) for x in values] | |
| radii = [scoring_radius(value, scoring) for value in values] | |
| candidates = disk_candidates(points, radii) | |
| answer = supported_witness((p + [0] for p in candidates), values, scoring) | |
| if answer is not None: | |
| return consensus_result(answer) | |
| best = minimax_disk_candidate(points, radii, candidates) | |
| neighbours = itertools.product(*[[math.nextafter(x, -math.inf), x, math.nextafter(x, math.inf)] | |
| for x in best]) | |
| answer = supported_witness((list(p) + [0] for p in neighbours), values, scoring) | |
| return consensus_result(answer, proof=None if answer is not None else disk_separation_proof(points, radii)) | |
| raise SharedContractError('undeclared actual scoring kind') | |
| def first_fraction(track, members, quantity, fraction): | |
| members = intervals(members, False) | |
| if len(members) != 1 or not 0 < finite(fraction, 'fraction') < 1: | |
| raise SharedContractError('fraction needs one interval and 0<q<1') | |
| lo, hi = members[0] | |
| track = prepared(track) | |
| times, track_points = validate_track(track) | |
| knots = [lo]+[t for t in times if lo < t < hi]+[hi] | |
| total = path_length(track, members) if quantity == 'path_length' else math.hypot(*net_vector(track, members)) if quantity == 'displacement' else None | |
| if total is None or total <= 0: | |
| raise SharedContractError('fraction denominator is undefined') | |
| target = fraction*total | |
| for t in (lo, hi): # position() 的两项检查,对区间两端做一次;中间的拐点都在区间内 | |
| if finite(t, 'requested world time') < times[0] or t > times[-1]: | |
| raise SharedContractError('world time outside track definition domain') | |
| points = PW.at(times, track_points, knots).tolist() | |
| if quantity == 'path_length': | |
| when = PW.reach_level(knots, PW.cumulative(points), target) | |
| else: | |
| when = PW.reach_radius(knots, [[x-y for x, y in zip(p, points[0])] for p in points], target) | |
| if when is None: | |
| raise SharedContractError('no first attainment in the supplied trajectory') | |
| return when | |
| def local_window(definitions, at, purpose): | |
| ids = {'instantaneous_direction_or_rate': 'local_process_half_window_s', | |
| 'speed_estimation': 'speed_estimation_half_window_s'} | |
| if purpose not in ids: | |
| raise SharedContractError('undeclared local-window purpose') | |
| half = parameter(definitions, ids[purpose]) | |
| return [finite(at, 'query instant')-half, at+half] | |
| def extremum_contract(definitions, records, profile, scoring): | |
| if profile not in {'value', 'time', 'state'}: | |
| raise SharedContractError('undeclared extremum consumer') | |
| answers = [] | |
| for row in joint_records(records): | |
| members = intervals(row['intervals'], False) | |
| if profile != 'value' and len(members) != 1: | |
| raise SharedContractError('extremum time/state requires one interval') | |
| candidates = distance_extrema(row['track'], row['target'], members) | |
| if row.get('mode') not in {'min', 'max'}: | |
| raise SharedContractError('extremum mode must be min or max') | |
| select = min if row['mode'] == 'min' else max | |
| value = select(v for _, v in candidates) | |
| if profile == 'value': | |
| answers.append(value) | |
| continue | |
| half = parameter(definitions, 'extremum_neighborhood_half_width_s') | |
| endpoint = parameter(definitions, 'extremum_endpoint_margin_s') | |
| gap = parameter(definitions, 'extremum_margin') | |
| lo, hi = members[0] | |
| query = extremum_query(row['track'], row['target'], row['mode']) | |
| value, center = (float(x) for x in query(lo, hi)) | |
| if PW.tied(query, lo, hi, center): | |
| return {'accepted': False, 'reason': 'outside_neighborhood_not_separated', 'scope': 'supplied_joint_readings'} # 并列:极值不唯一 | |
| if center-half-lo < endpoint or hi-center-half < endpoint: | |
| return {'accepted': False, 'reason': 'extremum_at_endpoint', 'scope': 'supplied_joint_readings'} | |
| difference = float(PW.runner_up(query, lo, hi, center, half))-query.sgn*value | |
| if difference < gap: | |
| return {'accepted': False, 'reason': 'outside_neighborhood_not_separated', 'scope': 'supplied_joint_readings'} | |
| if profile == 'time': | |
| answers.extend([center-half, center+half]) | |
| else: | |
| if not row.get('neighborhood_answers'): | |
| raise SharedContractError('state consumer needs supplied neighborhood answers') | |
| answers.extend(row['neighborhood_answers']) | |
| return dict(acceptance(answers, scoring), scope='supplied_joint_readings') | |
| def footprint_centroid(vertices): | |
| points = [point(x) for x in vertices] | |
| if len(points) < 3: | |
| raise SharedContractError('footprint needs a polygon') | |
| cross = [a[0]*b[1]-b[0]*a[1] for a, b in zip(points, points[1:]+points[:1])] | |
| twice_area = sum(cross) | |
| if not twice_area: | |
| raise SharedContractError('footprint area is zero') | |
| return [sum((a[j]+b[j])*c for a, b, c in zip(points, points[1:]+points[:1], cross))/(3*twice_area) for j in (0, 1)] | |
| def interval_relation(left, right, kind): | |
| left, right = intervals([left], False)[0], intervals([right], False)[0] | |
| if kind == 'overlaps': | |
| return min(left[1], right[1]) > max(left[0], right[0]) | |
| if kind == 'contains': | |
| return left[0] <= right[0] and right[1] <= left[1] | |
| raise SharedContractError('undeclared interval relation') | |
| def segment_speeds(track, members): | |
| track = prepared(track) | |
| times, _ = validate_track(track) | |
| speeds = [] | |
| for lo, hi in intervals(members, False): | |
| knots = [lo]+[t for t in times if lo < t < hi]+[hi] | |
| speeds.extend(math.dist(position(track, a), position(track, b))/(b-a) | |
| for a, b in zip(knots, knots[1:]) if a < b) | |
| if not speeds: | |
| raise SharedContractError('speed window must have positive duration') | |
| return speeds | |
| def relative_rates(track, target, members): | |
| """Exact extrema of (r dot v)/(r dot r) on each linear relative segment.""" | |
| track = prepared(track) | |
| times, _ = validate_track(track) | |
| if isinstance(target, dict): | |
| target = prepared(target) | |
| times = sorted(set(times+validate_track(target)[0])) | |
| rates = [] | |
| for lo, hi in intervals(members, False): | |
| knots = [lo]+[t for t in times if lo < t < hi]+[hi] | |
| for a, b in zip(knots, knots[1:]): | |
| if a == b: | |
| continue | |
| p, end = relative(track, target, a), relative(track, target, b) | |
| v = [(y-x)/(b-a) for x, y in zip(p, end)] | |
| vv, n, c = sum(x*x for x in v), sum(x*y for x, y in zip(p, v)), sum(x*x for x in p) | |
| offsets = [0, b-a] | |
| if vv: | |
| offsets.append(-n/vv) | |
| aa, bb, cc = -vv*vv, -2*n*vv, vv*c-2*n*n | |
| disc = bb*bb-4*aa*cc | |
| if disc >= 0: | |
| offsets.extend([(-bb-math.sqrt(disc))/(2*aa), (-bb+math.sqrt(disc))/(2*aa)]) | |
| for u in offsets: | |
| if not 0 <= u <= b-a: | |
| continue | |
| denominator = sum((x+u*y)**2 for x,y in zip(p,v)) | |
| if denominator == 0: | |
| raise SharedContractError('relative rate is undefined at zero distance') | |
| rates.append((n+vv*u)/denominator) | |
| return rates | |
| def _polygon(vertices): | |
| if not isinstance(vertices,list) or len(vertices)<3:raise SharedContractError('public room polygon required') | |
| pts=[point(p) for p in vertices] | |
| if len(set(map(tuple,pts)))!=len(pts):raise SharedContractError('room polygon has duplicate vertices') | |
| if abs(sum(a[0]*b[1]-a[1]*b[0] for a,b in zip(pts,pts[1:]+pts[:1])))<1e-12:raise SharedContractError('room polygon has zero area') | |
| def cross(a,b,c):return (b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]) | |
| edges=list(zip(pts,pts[1:]+pts[:1])) | |
| for i,(a,b) in enumerate(edges): | |
| for j,(c,d) in enumerate(edges): | |
| if j<=i+1 or i==0 and j==len(edges)-1:continue | |
| if cross(a,b,c)*cross(a,b,d)<=0 and cross(c,d,a)*cross(c,d,b)<=0 and max(min(a[0],b[0]),min(c[0],d[0]))<=min(max(a[0],b[0]),max(c[0],d[0])) and max(min(a[1],b[1]),min(c[1],d[1]))<=min(max(a[1],b[1]),max(c[1],d[1])): | |
| raise SharedContractError('public room polygon intersects itself') | |
| return pts | |
| def signed_distance(points, polygon): | |
| """点到房间地面多边形边的最短距离,奇偶规则定内部为正;points 是 (n,2)。证明器和 semantics 都调这里。""" | |
| points, polygon = np.asarray(points, float), np.asarray(polygon, float) | |
| if polygon.ndim != 2 or polygon.shape[1] != 2 or len(polygon) < 3: | |
| raise ValueError('invalid_floor_polygon') | |
| if np.isinf(points).any() or not np.isfinite(polygon).all(): # NaN 点(轨迹外,methods.at 无值)照算,距离也是 NaN | |
| raise ValueError('nonfinite_room_geometry') | |
| a, b = polygon, np.roll(polygon, -1, axis=0) | |
| d = b-a | |
| lengths = np.sum(d*d, axis=1) | |
| if np.any(lengths <= 1e-18): | |
| raise ValueError('degenerate_polygon_edge') | |
| offsets = points[:, None, :]-a | |
| projection = np.clip(np.sum(offsets*d, axis=2)/lengths, 0, 1) | |
| nearest = offsets-projection[:, :, None]*d | |
| distance = np.sqrt(np.min(np.sum(nearest*nearest, axis=2), axis=1)) | |
| x, y = points[:, 0, None], points[:, 1, None] | |
| dy = b[:, 1]-a[:, 1] | |
| crosses = ((a[:, 1] > y) != (b[:, 1] > y)) & ( | |
| x < a[:, 0]+(y-a[:, 1])*(b[:, 0]-a[:, 0])/np.where(dy == 0, 1, dy)) | |
| return np.where(np.sum(crosses, axis=1) % 2 == 1, distance, -distance) | |
| def room_side(signed_distance, margin): | |
| """房间边界有符号距离(室内为正,可逐行批量)→ +1 稳在里面、-1 稳在外面、0 离边界不到 margin(room_membership_offset 上端)。 | |
| semantics 的 room_margin 和证明器的房间题共用这一处,避免恰等于 margin 时判定相反。""" | |
| d = np.asarray(signed_distance, float) | |
| return np.where(np.abs(d) >= margin, np.sign(d), 0) | |
| def _membership(position,vertices): | |
| """(是否在房间内, 离边界多远):signed_distance 的标量适配。边界上 +0 是内、-0 是外,同奇偶判。""" | |
| try:d=signed_distance(np.array([point(position)],float),np.asarray(vertices,float))[0] | |
| except ValueError as e:raise SharedContractError(str(e)) from e | |
| return not np.signbit(d),abs(float(d)) | |
| def score(alternative, truth, scoring): | |
| kind = scoring.get('kind') | |
| if kind == 'exact': | |
| return type(alternative) == type(truth) and alternative == truth | |
| if kind == 'list': | |
| if not isinstance(truth, list) or not truth: | |
| raise SharedContractError('original complete list must be nonempty') | |
| scorers = item_scorers(scoring, len(truth)) | |
| return isinstance(alternative, list) and len(alternative) == len(truth) and all( | |
| score(a, b, item) for a, b, item in zip(alternative, truth, scorers)) | |
| if kind == 'log_ratio': | |
| return bool(ratio_accepts(alternative, truth, scoring['factor'])) | |
| if kind == 'numeric': | |
| true_value = finite(truth, 'truth answer') | |
| tolerance = scoring_radius(true_value, scoring) | |
| domain = answer_domain(scoring) | |
| if domain is not None and not domain[0] <= true_value <= domain[1]: | |
| raise SharedContractError('truth outside original answer domain') | |
| try: | |
| submitted = finite(alternative, 'alternative answer') | |
| except SharedContractError: | |
| return False | |
| return (domain is None or domain[0] <= submitted <= domain[1]) and abs(submitted-true_value) <= tolerance | |
| if kind in {'vector', 'coordinate'}: | |
| true_point = point(truth) | |
| tolerance = scoring_radius(truth, scoring) | |
| try: | |
| submitted = point(alternative) | |
| except SharedContractError: | |
| return False | |
| return math.dist(submitted, true_point) <= tolerance | |
| if kind == 'angle': | |
| true_angle = finite(truth, 'truth angle') | |
| tolerance = scoring_radius(0, scoring) | |
| try: | |
| submitted = finite(alternative, 'alternative angle') | |
| except SharedContractError: | |
| return False | |
| return abs((submitted-true_angle+180) % 360-180) <= tolerance | |
| if kind == 'time_pair': | |
| tolerance = scoring_radius(0, scoring) | |
| if not isinstance(truth, list) or len(truth) != 2 or finite(truth[0], 'true start') > finite(truth[1], 'true end'): | |
| raise SharedContractError('original time answer must be an ordered pair') | |
| if not isinstance(alternative, list) or len(alternative) != 2: | |
| return False | |
| try: | |
| submitted = [finite(x, 'alternative time') for x in alternative] | |
| except SharedContractError: | |
| return False | |
| return submitted[0] <= submitted[1] and all(abs(a-b) <= tolerance for a, b in zip(submitted, truth)) | |
| raise SharedContractError('undeclared original scorer') | |