loop-measurement-supplement / code /historical_mark_control.py
nnat03's picture
Release Loop numerical tables and analysis code v1.0.0
97b0f0e verified
Raw History Blame Contribute Delete
2.94 kB
import json, glob, math, random, statistics as st
random.seed(7)
def load(p):
d=json.load(open(p))
if d.get("formatVersion")==2:
i={c:k for k,c in enumerate(d["channels"])}; c=d["columns"]; t=c[i["t"]]
mag=[math.sqrt(c[i["rx"]][k]**2+c[i["ry"]][k]**2+c[i["rz"]][k]**2) for k in range(len(t))]
m=[x["t"] for x in d.get("stitchMarks",[])]
else:
ss=d["samples"]; t=[s["elapsedSeconds"] for s in ss]
mag=[math.sqrt(s["rotationRate"]["x"]**2+s["rotationRate"]["y"]**2+s["rotationRate"]["z"]**2) for s in ss]
m=[x["elapsedSeconds"] for x in d.get("stitchMarks",[])]
return t, mag, sorted(m)
HZ=25.0; HALF=int(2.5*HZ); SEARCH=int(1.5*HZ); L=2*HALF
def z(v):
m=sum(v)/len(v); s=math.sqrt(sum((x-m)**2 for x in v)/len(v)) or 1.0
return [(x-m)/s for x in v]
grids={}
for p in sorted(glob.glob("crochet-motion_*.json")):
t,mag,marks=load(p)
if len(marks)<5: continue
n=int((t[-1]-t[0])*HZ); g=[0.0]*n; j=0
for k in range(n):
want=t[0]+k/HZ
while j+1<len(t) and t[j+1]<want: j+=1
g[k]=mag[j]
dd=[marks[0]]
for x in marks[1:]:
if x-dd[-1]>=2.0: dd.append(x)
grids[p]=(g,[int((mk-t[0])*HZ) for mk in dd],n)
def run(centres_by_file):
wins=[]
for p,(g,_,n) in grids.items():
for c in centres_by_file[p]:
if c-HALF-SEARCH<0 or c+HALF+SEARCH>=n: continue
wins.append(g[c-HALF-SEARCH:c+HALF+SEARCH])
if len(wins)<30: return None
tmpl=[sum(w[SEARCH+k] for w in wins)/len(wins) for k in range(L)]
shifts=[0]*len(wins)
for _ in range(8):
tz=z(tmpl); new=[]
for wi,w in enumerate(wins):
best,bo=-9e9,0
for off in range(0,2*SEARCH):
seg=z(w[off:off+L]); r=sum(seg[k]*tz[k] for k in range(L))/L
if r>best: best,bo=r,off
shifts[wi]=bo-SEARCH; new.append(w[bo:bo+L])
tmpl=[sum(s[k] for s in new)/len(new) for k in range(L)]
# how well do the aligned windows actually agree with the template?
tz=z(tmpl); rs=[]
for w,sh in zip(wins,shifts):
seg=z(w[sh+SEARCH:sh+SEARCH+L]); rs.append(sum(seg[k]*tz[k] for k in range(L))/L)
return st.mean(rs), st.pstdev(shifts)/HZ
real=run({p:c for p,(g,c,n) in grids.items()})
print(f"REAL marks mean agreement r = {real[0]:.3f} shift sd = {real[1]:.2f}s")
nulls=[]
for trial in range(20):
fake={}
for p,(g,c,n) in grids.items():
lo,hi=HALF+SEARCH, n-HALF-SEARCH-1
fake[p]=sorted(random.randint(lo,hi) for _ in c) if hi>lo else []
r=run(fake)
if r: nulls.append(r[0])
print(f"RANDOM marks mean agreement r = {st.mean(nulls):.3f} +- {st.pstdev(nulls):.3f} (20 trials)")
zsc=(real[0]-st.mean(nulls))/(st.pstdev(nulls) or 1e-9)
print(f"\nreal marks beat random by {zsc:+.1f} standard deviations")
print("VERDICT:", "structure is real" if zsc>2 else "NOT distinguishable from random")