"""Concrete geometry/time measurements from decoded RGB and typed observations. No learned judge, color-area reward proxy or invented reference tolerance. Exact criteria use task facts; reference-relative measurements feed calibrated rules. """ import math, subprocess, json from collections import deque from pathlib import Path def decode_video(path, width=160, height=120): """Decode all frames with preserved PTS; analysis scale is caller-controlled. Matching dimensions/aspect ratio is the caller's responsibility. Geometry errors are normalized; output contracts use original probe metadata. """ from media import probe as inspect_media, decode_rgb, MediaError inspected=inspect_media(path) if inspected.get('status')!='ok': raise ValueError('Video inspection failed: '+str(inspected.get('error',inspected['status']))) decoded=decode_rgb(path,(width,height),max_frames=3000,timeout=120) frames=[frame.tobytes() for frame in decoded] pts=inspected['pts'] if len(pts)!=len(frames):raise ValueError('PTS/frame mismatch') return {'frames':frames,'pts':pts,'analysis_width':width,'analysis_height':height, 'width':inspected['width'],'height':inspected['height'],'fps':inspected['fps'], 'frame_count':len(frames),'decoded':True} def binary_mask(frame,width,height,color,threshold=10): if len(frame)!=width*height*3:raise ValueError('RGB dimensions mismatch') values=[] for i in range(width*height): r,g,b=frame[3*i:3*i+3] if color=='light':hit=min(r,g,b)>threshold elif color=='teal':hit=min(g,b)>threshold and min(g,b)>r*1.15 elif color=='orange':hit=r>threshold and r>g*1.2 and g>b*1.2 elif color=='blue':hit=b>threshold and b>r*1.2 else:raise ValueError('Unsupported mask class') values.append(bool(hit)) return values def components(bitmap,width,height,min_area=1): if len(bitmap)!=width*height:raise ValueError('Mask dimensions mismatch') seen=set();out=[] for seed in range(len(bitmap)): if not bitmap[seed] or seed in seen:continue q=deque([seed]);seen.add(seed);pts=[] while q: p=q.popleft();x,y=p%width,p//width;pts.append((x,y)) for nx,ny in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]: j=ny*width+nx if 0<=nxthreshold for v in peak],width,height,min_area=2) if len(cs)<3:continue try: fit=fit_ring([(c['cx'],c['cy']) for c in cs]) except ValueError:continue # Compare dimensionless circularity without forcing count or target radius. quality=fit['radial_error']/max(1,fit['radius']) + math.sqrt(variance([c['area'] for c in cs]))/max(1,sum(c['area'] for c in cs)/len(cs)) candidates.append((quality,threshold,cs)) if not candidates: raise ValueError('Temporal support cannot resolve separate geometrical dots') _,selected_threshold,dots=min(candidates,key=lambda x:x[0]) centers=[(d['cx'],d['cy']) for d in dots] ring=fit_ring(centers) if len(centers)>=3 else None luminance=[] for f in frames: luminance.append([sum(min(f[3*(y*width+x):3*(y*width+x)+3]) for x,y in d['pixels'])/d['area']/255 for d in dots]) if ring: order=sorted(range(len(dots)),key=lambda i:math.atan2(dots[i]['cy']-ring['cy'],dots[i]['cx']-ring['cx'])) luminance=[[r[i] for i in order] for r in luminance] return {'dot_count':len(dots),'center_error':math.hypot(ring['cx']-width/2,ring['cy']-height/2)/math.hypot(width,height) if ring else None, 'angular_spacing_error':ring['angular_spacing_error'] if ring else None, 'ring_radius':ring['radius']/min(width,height) if ring else None, 'dot_radius_variance':variance([math.sqrt(d['area']/math.pi) for d in dots]), 'dot_rois':dots,'brightness_series':luminance,'pts':pts,'support_threshold':selected_threshold, 'brightest_sequence':[max(range(len(r)),key=lambda i:r[i]) for r in luminance] if dots else []} def variance(values): if not values:return 0 mean=sum(values)/len(values) return sum((v-mean)**2 for v in values)/len(values) def rmse(actual,expected): if len(actual)!=len(expected) or not actual:raise ValueError('Comparable nonempty series required') return math.sqrt(sum((a-b)**2 for a,b in zip(actual,expected))/len(actual)) def interpolate(pts,values,query): if len(pts)!=len(values) or len(pts)<2 or any(b<=a for a,b in zip(pts,pts[1:])):raise ValueError('Strictly increasing PTS required') if querypts[-1]:raise ValueError('No extrapolated missing frames') for i in range(1,len(pts)): if query<=pts[i]: frac=(query-pts[i-1])/(pts[i]-pts[i-1]);return values[i-1]*(1-frac)+values[i]*frac return values[-1] def temporal_curve_error(pts,values,reference_pts,reference_values): return rmse([interpolate(pts,values,t) for t in reference_pts],reference_values) def fill_frontier(fill_mask,track_mask,width,height): if len(fill_mask)!=len(track_mask) or len(fill_mask)!=width*height:raise ValueError('Mask mismatch') inside=[(i%width,i//width) for i,v in enumerate(fill_mask) if v and track_mask[i]] total=sum(bool(v) for v in fill_mask);outside=sum(bool(f and not t) for f,t in zip(fill_mask,track_mask)) return {'frontier_x':max((x for x,y in inside),default=None),'outside_fill_fraction':outside/max(1,total)} def prefix_reveal(visible_mask,path_points,width,height,tolerance_px): """Project visible stroke onto ordered sampled centerline, not bbox right edge.""" if not path_points:raise ValueError('Empty path') pixels=[(i%width,i//width) for i,v in enumerate(visible_mask) if v] present=[any(math.hypot(x-px,y-py)<=tolerance_px for px,py in pixels) for x,y in path_points] active=[i for i,v in enumerate(present) if v] if not active:return {'tip_arc_fraction':0,'prefix_gap':0,'ahead_islands':0,'connected_prefix':True} last=max(active);gaps=sum(not v for v in present[:last+1]);runs=sum(v and (i==0 or not present[i-1]) for i,v in enumerate(present)) return {'tip_arc_fraction':last/max(1,len(present)-1),'prefix_gap':gaps/(last+1),'ahead_islands':max(0,runs-1),'connected_prefix':gaps==0} def contour_distance(a,b,normalizer=1): if not a or not b or normalizer<=0:raise ValueError('Nonempty contours and positive normalizer required') def directed(x,y):return sum(min(math.hypot(px-qx,py-qy) for qx,qy in y) for px,py in x)/len(x) return max(directed(a,b),directed(b,a))/normalizer def phase_direction(sequence,n): steps=[(b-a)%n for a,b in zip(sequence,sequence[1:]) if b!=a] if not steps:return {'visits':len(set(sequence)),'direction_consistent':False,'direction':None} forward=sum(0reverse else 'reverse'} def native_loader_geometry(native): """Count evaluated geometric instances, not number of native layers. Requires inspector-owned render_geometry_instances with role confidence. Authored layer fields are not promoted to rendered/effective facts. """ if native.get('status')!='loaded':return {'_status':'verifier_error','_reason':'Native load incomplete'} instances=native.get('render_geometry_instances') if instances is None:return {'_status':'unsupported','_reason':'Evaluated render geometry unavailable'} dots=[o for o in instances if o.get('role')=='loader_dot' and o.get('visible_support') is True] if any(o.get('role')=='unknown' for o in instances):return {'_status':'unsupported','_reason':'Unclassified render geometry could affect count'} return {'dot_count':len(dots)} def collect_observations(task_id, observations, reference=None): """Extract concrete features from frozen candidate media/reference annotations. Reference arrays/path roles are accepted only as measurements, with final grading additionally requiring verified-cut criterion rules in task engine. No role guessing is silently scored for complex scenes. """ import copy obs=dict(observations) obs['metrics']=copy.deepcopy(observations.get('metrics',{})) obs['extraction_evidence']=copy.deepcopy(observations.get('extraction_evidence',{})) task=task_id.split('/')[-1].split('-')[0] files=obs.get('media',{}).get('files') or [obs.get('media',{})] path=files[0].get('path') if files else None if task=='t52' and path and Path(path).is_file(): try: decoded=decode_video(path,320,240) m=loader_metrics(decoded['frames'],320,240,decoded['pts']) obs.setdefault('metrics',{})['dot_count']={'dot_count':m['dot_count']} obs['metrics']['eight_dot_geometry']={'angular_spacing_error':m['angular_spacing_error'],'dot_radius_variance':m['dot_radius_variance']} obs['metrics'].setdefault('centering_spacing',{}).update(center_error=m['center_error']) direction=cyclic_sequence_semantics(m['brightest_sequence'],max(1,m['dot_count'])) obs['metrics'].setdefault('travelling_phase',{}).update(phase_order_matches=direction['phase_order_matches']) obs['metrics'].setdefault('periodic_cycle',{}).update(repeated_ordered_cycle=direction['repeated_ordered_cycle']) obs.setdefault('extraction_evidence',{})['loader']={k:v for k,v in m.items() if k not in ['dot_rois','brightness_series']} except FileNotFoundError as exc: obs.setdefault('metrics',{})['dot_count']={'_status':'verifier_error','_reason':str(exc)} except (ValueError,subprocess.CalledProcessError,KeyError,StopIteration) as exc: # Probe already differentiates corrupt submission/tool failure; do not invent missing-dot zero. obs.setdefault('metrics',{})['dot_count']={'_status':'unsupported','_reason':'Geometry extraction unavailable: '+str(exc)} # Dense native evaluated role samples, generated by the inspector. Avoid trusting # authored keys as effective visibility or forcing a single construction method. role_samples=obs.get('native',{}).get('evaluated_role_samples',{}) ref_samples=(reference or {}).get('role_samples',{}) for cid,role in [('bounce_trajectory','ball'),('orbital_trajectory','orbiter'),('relative_motion','button')]: candidate=role_samples.get(role);expected=ref_samples.get(role) if candidate and expected: try: err=temporal_curve_error(candidate['pts'],candidate['centroid_x'],expected['pts'],expected['centroid_x']) yerr=temporal_curve_error(candidate['pts'],candidate['centroid_y'],expected['pts'],expected['centroid_y']) obs.setdefault('metrics',{}).setdefault(cid,{})['trajectory_error']=math.hypot(err,yerr) except (ValueError,KeyError):pass ref=reference or {} if ref.get('local_cut_verified') is True and ref.get('source_hash') and ref.get('render_roles') and path and Path(path).is_file(): try: size=ref.get('analysis_size',[320,240]) decoded=decode_video(path,*size) derived,evidence=collect_role_render_metrics(task,decoded,ref) for cid,values in derived.items():obs.setdefault('metrics',{}).setdefault(cid,{}).update(values) obs.setdefault('extraction_evidence',{})['render_roles']=evidence except FileNotFoundError as exc:obs.setdefault('extraction_evidence',{})['render_error']={'status':'verifier_error','reason':str(exc)} except (ValueError,KeyError,subprocess.CalledProcessError) as exc:obs.setdefault('extraction_evidence',{})['render_error']={'status':'needs_review','reason':str(exc)} if ref.get('local_cut_verified') is True and ref.get('source_hash') and ref.get('native_roles') and obs.get('native',{}).get('scenes'): try: derived,evidence=collect_native_role_metrics(task,obs['native'],ref) for cid,values in derived.items():obs.setdefault('metrics',{}).setdefault(cid,{}).update(values) obs.setdefault('extraction_evidence',{})['native_roles']=evidence except (ValueError,KeyError) as exc:obs.setdefault('extraction_evidence',{})['native_role_error']={'status':'needs_review','reason':str(exc)} return obs def ordered_polyline_samples(points,count=128): if len(points)<2:raise ValueError('Need polyline') lengths=[0] for a,b in zip(points,points[1:]):lengths.append(lengths[-1]+math.dist(a,b)) if lengths[-1]<=0:raise ValueError('Degenerate polyline') out=[] for j in range(count): distance=lengths[-1]*j/(count-1) for i in range(1,len(lengths)): if distance<=lengths[i]: ratio=(distance-lengths[i-1])/max(1e-12,lengths[i]-lengths[i-1]);out.append([points[i-1][k]*(1-ratio)+points[i][k]*ratio for k in [0,1]]);break return out def shape_signature(mask,width,height): cs=components(mask,width,height,1) if not cs:return {'area':0,'centroid':None,'bbox':None,'component_count':0,'contour':[]} pts=[(i%width,i//width) for i,v in enumerate(mask) if v];xs=[x for x,y in pts];ys=[y for x,y in pts] contour=[] for x,y in pts: if any(nx<0 or ny<0 or nx>=width or ny>=height or not mask[ny*width+nx] for nx,ny in [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]):contour.append((x,y)) return {'area':len(pts),'centroid':[sum(xs)/len(xs),sum(ys)/len(ys)],'bbox':[min(xs),min(ys),max(xs),max(ys)],'component_count':len(cs),'contour':contour} def radial_coverage(mask,width,height,center,inner,outer,sectors=360): bins=[0]*sectors for i,hit in enumerate(mask): if not hit:continue x,y=i%width-center[0],i//width-center[1];r=math.hypot(x,y) if inner<=r<=outer:bins[int((math.atan2(y,x)%(2*math.pi))/(2*math.pi)*sectors)%sectors]+=1 lit=[v>0 for v in bins];runs=sum(v and not lit[(i-1)%sectors] for i,v in enumerate(lit)) endpoints=[i/sectors for i,v in enumerate(lit) if v and not lit[(i+1)%sectors]] return {'coverage':sum(lit)/sectors,'connected_arc':runs<=1,'visible_intervals':runs,'end_angles':endpoints,'bins':bins} def motion_signature(signatures,pts): if len(signatures)!=len(pts):raise ValueError('PTS mismatch') result={'centroid_x':[],'centroid_y':[],'width':[],'height':[],'area':[],'aspect':[],'blank_frames':[]} for i,s in enumerate(signatures): if not s['centroid']: result['blank_frames'].append(i) for k in ['centroid_x','centroid_y','width','height','area','aspect']:result[k].append(None) continue b=s['bbox'];w=b[2]-b[0]+1;h=b[3]-b[1]+1 for k,v in [('centroid_x',s['centroid'][0]),('centroid_y',s['centroid'][1]),('width',w),('height',h),('area',s['area']),('aspect',w/h)]:result[k].append(v) speeds=[] for i in range(1,len(pts)): if result['centroid_x'][i] is None or result['centroid_x'][i-1] is None:speeds.append(None) else:speeds.append(math.hypot(result['centroid_x'][i]-result['centroid_x'][i-1],result['centroid_y'][i]-result['centroid_y'][i-1])/(pts[i]-pts[i-1])) result['speeds']=speeds return result def painted_role_mask(frame,width,height,role): """Reference-authored paint classes/ROI; not an assumed task palette.""" paint=role.get('paint') if not paint or 'rgb' not in paint or 'tolerance' not in paint:raise ValueError('Missing calibrated role paint') rgb=paint['rgb'];tol=paint['tolerance'];roi=role.get('roi',[0,0,width,height]) out=[] for i in range(width*height): x,y=i%width,i//width;p=frame[3*i:3*i+3] out.append(roi[0]<=x=a for a,b in zip(front,front[1:]))) r=roles['fill'] if r.get('frontier_pts'):m('fill_progression',frontier_curve_error=temporal_curve_error(pts,front,r['frontier_pts'],r['frontier_values'])/w) if task=='t49' and 'primary' in traces: t=traces['primary'];r=roles['primary'];m('continuous_morph',blank_gap=bool(t['motion']['blank_frames'])) if r.get('triangle_contour') and t['signatures'][0]['contour']:m('initial_final_pose',triangle_pose_error=contour_distance(t['signatures'][0]['contour'],r['triangle_contour'],norm)) if r.get('square_contour') and t['signatures'][-1]['contour']:m('initial_final_pose',square_pose_error=contour_distance(t['signatures'][-1]['contour'],r['square_contour'],norm)) if r.get('stretch_pts') and not t['motion']['blank_frames']:m('continuous_morph',stretch_error=rmse([interpolate(pts,t['motion']['aspect'],x) for x in r['stretch_pts']],r['stretch_aspects'])) if task=='t51' and 'line' in traces: r=roles['line'];path=ordered_polyline_samples(r['final_centerline']) reveal=[prefix_reveal(mask,path,w,h,r['stroke_tolerance_px']) for mask in traces['line']['masks']] m('sequential_reveal',prefix_gap=max(x['prefix_gap'] for x in reveal),ahead_islands=max(x['ahead_islands'] for x in reveal),connected_prefix=all(x['connected_prefix'] for x in reveal)) if r.get('reveal_pts'):m('sequential_reveal',reveal_curve_error=temporal_curve_error(pts,[x['tip_arc_fraction'] for x in reveal],r['reveal_pts'],r['reveal_values'])) # Outline boundary has stroke radius offset from centerline. Measure ordered # path support deviation separately; native centerline handles exact geometry. visible=traces['line']['signatures'][-1]['contour'] if visible: excess=max(0,contour_distance(visible,path)-r['stroke_tolerance_px'])/norm m('contour_style',centerline_distance_error=excess) if task=='t50': orbiters=[name for name,r in roles.items() if r.get('orbit_role') is True and name in traces and any(s['area']>0 for s in traces[name]['signatures'])] m('arrangement',orbiter_count=len(orbiters)) errors=[];tail_errors=[];depth_results=[] for name in orbiters: r=roles[name];trace=traces[name];motion=trace['motion'] if r.get('trajectory_pts') and not motion['blank_frames']: errors.append(math.hypot(temporal_curve_error(pts,motion['centroid_x'],r['trajectory_pts'],r['x']),temporal_curve_error(pts,motion['centroid_y'],r['trajectory_pts'],r['y']))/norm) if r.get('tail_contours'): for pose in r['tail_contours']: i=min(range(len(pts)),key=lambda i:abs(pts[i]-pose['time'])) if trace['signatures'][i]['contour']:tail_errors.append(contour_distance(trace['signatures'][i]['contour'],pose['contour'],norm)) # Annotated front/back witness masks grade actual composited overlap, # not proximity to center or static stack order. if r.get('occlusion_witnesses'): for pose in r['occlusion_witnesses']: i=min(range(len(pts)),key=lambda i:abs(pts[i]-pose['time'])) if len(pose['expected_visible_mask'])==w*h: depth_results.append(mask_iou(trace['masks'][i],pose['expected_visible_mask'])>=pose['minimum_iou']) if errors:m('orbital_trajectory',path_error=max(errors)) if tail_errors:m('trailing_shape',tail_attachment_error=max(tail_errors)) if depth_results:m('depth',head_occlusion_order_matches=all(depth_results)) # Role-specific contour targets and motion curves cover button/bubble scenes # without mistaking pixels for text semantics. OCR/native glyphs below. for name,t in traces.items(): r=roles[name];cid=r.get('criterion') if cid and r.get('reference_contour') and t['signatures'][-1]['contour']: m(cid,**{r.get('contour_metric','bubble_contour_error'):contour_distance(t['signatures'][-1]['contour'],r['reference_contour'],norm)}) if cid and r.get('trajectory_pts') and not t['motion']['blank_frames']: err=math.hypot(temporal_curve_error(pts,t['motion']['centroid_x'],r['trajectory_pts'],r['x']),temporal_curve_error(pts,t['motion']['centroid_y'],r['trajectory_pts'],r['y']))/norm m(cid,**{r.get('motion_metric','entrance_curve_error'):err}) return metrics,{'pts':pts,'roles':{name:{'motion':t['motion'],'component_counts':[s['component_count'] for s in t['signatures']]} for name,t in traces.items()}} def mask_iou(a,b): if len(a)!=len(b):raise ValueError('Mask mismatch') union=sum(x or y for x,y in zip(a,b));return sum(x and y for x,y in zip(a,b))/max(1,union) def walk_tree(node, child_keys=('children','objects')): if not isinstance(node,dict):return yield node for key in child_keys: for child in node.get(key,[]):yield from walk_tree(child,child_keys) def flatten_path(records,steps=12): """Convert inspector's SkPath verbs into sampled editable geometry.""" out=[];cursor=None;start=None;move_count=0 for record in records or []: verb=str(record.get('verb','')).lower();p=record.get('points',[]) if verb in ['move','moveto','0'] and p: move_count+=1 if move_count>1:raise ValueError('Multiple contours need separate contour evaluation') cursor=p[-1];start=cursor;out.append(cursor) elif verb in ['line','lineto','1'] and p:cursor=p[-1];out.append(cursor) elif verb in ['quad','quadto','2'] and len(p)>=2 and cursor is not None: control,end=p[-2:] for i in range(1,steps+1): t=i/steps;out.append([(1-t)**2*cursor[k]+2*(1-t)*t*control[k]+t*t*end[k] for k in [0,1]]) cursor=end elif verb in ['cubic','cubicto','4'] and len(p)>=3 and cursor is not None: c1,c2,end=p[-3:] for i in range(1,steps+1): t=i/steps;out.append([(1-t)**3*cursor[k]+3*(1-t)**2*t*c1[k]+3*(1-t)*t*t*c2[k]+t**3*end[k] for k in [0,1]]) cursor=end elif verb in ['close','5'] and start is not None:out.append(start);cursor=start elif verb in ['conic','3']: raise ValueError('Conic weight required for accurate sampling') return out def transformed(points,matrix): if len(matrix)!=6:raise ValueError('Expected Qt affine matrix6') a,b,c,d,tx,ty=matrix return [[a*x+c*y+tx,b*x+d*y+ty] for x,y in points] def native_role_observations(native,reference): """Extract typed inspector paths/evaluated strings through explicit role IDs. Uses authored structure only for mapping. Per-frame geometry/properties are taken from evaluated dumps. Composited occlusion remains rendered evidence. """ roles=reference.get('native_roles',{});results={};evidence={} scenes=native.get('scenes',[]) for role,config in roles.items(): ids=set(config.get('object_ids',[]));scene=next((s for s in scenes if s.get('id')==config.get('scene_id')),None) if scene is None:continue samples=[] for frame in scene.get('frames',[]): from native_bridge import frame_evidence frame=frame_evidence(frame) entries=[n for n in walk_tree(frame.get('data',{}),('children','objects','compositor_entries')) if n.get('object_id') in ids] paths=[];opacity=[] for e in entries: path=e.get(config.get('path_field','stroke_centerline')) or e.get('post_effect_path') if path: local=flatten_path(path);world=transformed(local,e['world_matrix']);paths.extend(world) opacity.append(e.get('opacity_percent')) xs=[p[0] for p in paths];ys=[p[1] for p in paths] props=list(walk_tree(frame.get('evaluated_properties',{}))) # Text extraction targets explicit evaluated property IDs, never label guessing. strings=[p.get('value') for p in props if p.get('id') in config.get('text_property_ids',[]) and isinstance(p.get('value'),str)] if not paths and not strings:continue samples.append({'frame':frame['frame'],'time':frame['frame']/scene['fps'],'centroid_x':sum(xs)/len(xs) if xs else None,'centroid_y':sum(ys)/len(ys) if ys else None,'width':max(xs)-min(xs) if xs else None,'height':max(ys)-min(ys) if ys else None,'world_path':paths,'local_opacity_percent':opacity,'texts':strings}) results[role]=samples evidence[role]={'scene_id':scene['id'],'object_ids':sorted(ids),'samples':len(samples)} return results,evidence def collect_native_role_metrics(task_id,native,reference): roles,evidence=native_role_observations(native,reference);metrics={} for role,samples in roles.items(): config=reference['native_roles'][role];cid=config.get('criterion') if not cid or not samples:continue row=metrics.setdefault(cid,{}) if config.get('reference_contour'): row[config.get('contour_metric','contour_error')]=contour_distance(samples[-1]['world_path'],config['reference_contour'],config.get('normalizer',1)) if config.get('trajectory_pts'): pts=[s['time'] for s in samples] xerr=temporal_curve_error(pts,[s['centroid_x'] for s in samples],config['trajectory_pts'],config['x']) yerr=temporal_curve_error(pts,[s['centroid_y'] for s in samples],config['trajectory_pts'],config['y']) row[config.get('motion_metric','trajectory_error')]=math.hypot(xerr,yerr)/config.get('normalizer',1) if config.get('label_states'): matches=[] for state in config['label_states']: sample=min(samples,key=lambda s:abs(s['time']-state['time']));matches.append(state['text'] in sample['texts']) row['labels_match']=all(matches) return metrics,evidence def cyclic_sequence_semantics(sequence,count): """Exact ordered-phase predicate, independent of a guessed period/tolerance. Adjacent repeated samples collapse; each transition must advance exactly one ring position in a consistent direction. Sparse/ambiguous observations are reviewable rather than affirmative. Two full cycles require at least2count nonstationary adjacent transitions; no equality-of-export-endpoints assumption. """ collapsed=[] for x in sequence: if not collapsed or x!=collapsed[-1]:collapsed.append(x) if count<3 or len(collapsed)<2:return {'phase_order_matches':False,'repeated_ordered_cycle':False,'direction':None,'transitions':len(collapsed)-1} steps=[(b-a)%count for a,b in zip(collapsed,collapsed[1:])] forward=all(s==1 for s in steps);reverse=all(s==count-1 for s in steps);ordered=forward or reverse return {'phase_order_matches':ordered and len(set(collapsed))==count,'repeated_ordered_cycle':ordered and len(steps)>=2*count, 'direction':'forward' if forward else ('reverse' if reverse else None),'transitions':len(steps)}