115 lines
6.9 KiB
Python
115 lines
6.9 KiB
Python
"""Scientific O1 v2: area-rank type face weights and fixed geometric gates."""
|
|
import hashlib
|
|
import itertools
|
|
import numpy as np
|
|
|
|
from o1_partition import Q, K, GeometryFailure, InputViolation, match
|
|
|
|
|
|
def array_sha(a):
|
|
return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()
|
|
|
|
|
|
def area_midrank(values, areas):
|
|
d=np.asarray(values,dtype=np.float64);a=np.asarray(areas,dtype=np.float64)
|
|
if d.shape!=a.shape or d.ndim!=1 or not len(d) or not np.isfinite(d).all() or np.any(d<0) or not np.isfinite(a).all() or np.any(a<=0):
|
|
raise GeometryFailure('INVALID_FACE_JUMP_OR_AREA')
|
|
order=np.argsort(d,kind='stable');ds=d[order];aa=a[order]
|
|
starts=np.r_[0,np.flatnonzero(ds[1:]!=ds[:-1])+1]
|
|
group_area=np.add.reduceat(aa,starts);before=np.r_[0,np.cumsum(group_area)[:-1]]
|
|
total=a.sum(dtype=np.float64)
|
|
rank_sorted=np.repeat((before+.5*group_area)/total,np.diff(np.r_[starts,len(d)]))
|
|
ranks=np.empty(len(d));ranks[order]=rank_sorted
|
|
qindex=min(int(np.searchsorted(np.cumsum(aa),.9*total,side='left')),len(d)-1)
|
|
return ranks,float(ds[qindex])
|
|
|
|
|
|
def common_scale_quantize(weights, area_total):
|
|
w=np.asarray(weights,dtype=np.float64)
|
|
if (w.ndim!=1 or not 0<len(w)<=Q or not np.isfinite(w).all() or np.any(w<=0)
|
|
or not np.isfinite(area_total) or area_total<=0):
|
|
raise GeometryFailure('INT_WEIGHT_RANGE')
|
|
# Preserve original G's operation order exactly; no per-arm renormalization.
|
|
integer=1+np.floor(Q*(w/area_total)).astype(np.int64)
|
|
if integer.sum()>2*Q or integer.max()>np.iinfo(np.int32).max or integer.min()<=0:
|
|
raise GeometryFailure('INT_WEIGHT_RANGE')
|
|
return integer.astype(np.int32)
|
|
|
|
|
|
def face_weights(g,z,shuffled):
|
|
e=g['edges'];a=g['area'];total=float(a.sum(dtype=np.float64))
|
|
dz=np.linalg.norm(z[e[:,0]]-z[e[:,1]],axis=1)
|
|
dc=np.linalg.norm(shuffled[e[:,0]]-shuffled[e[:,1]],axis=1)
|
|
rt,q90=area_midrank(dz,a);rc,_=area_midrank(dc,a)
|
|
strength=min(1.,q90/.05)
|
|
factors=dict(G=np.ones(len(a)),T=np.exp(-np.log(4)*strength*rt**2),C=np.exp(-np.log(4)*strength*rc**2))
|
|
arrays={arm:common_scale_quantize(a*f,total) for arm,f in factors.items()}
|
|
if any(np.any(f<.25-1e-15) or np.any(f>1) for f in factors.values()):
|
|
raise GeometryFailure('FACE_FACTOR_RANGE')
|
|
diagnostics=dict(g_p=strength,true_q90_area=q90,scale_numerator=Q,scale_denominator_G_total_area=total,
|
|
integer_equal_G_area_fraction={arm:float(a[arrays[arm]==arrays['G']].sum()/total) for arm in ['T','C']},
|
|
factor_quantiles={arm:np.quantile(f,[0,.25,.5,.75,.9,1]).tolist() for arm,f in factors.items()},
|
|
integer_face_sha256={arm:array_sha(v) for arm,v in arrays.items()},shared_real_field_strength=True,
|
|
factor_quantiles_weighting='face-count descriptive quantiles; g_p uses the prescribed area-weighted q90')
|
|
return arrays,diagnostics,dict(true_jump=dz,shuffled_jump=dc,true_rank=rt,shuffled_rank=rc,**{'factor_'+k:v for k,v in factors.items()})
|
|
|
|
|
|
def reweighted_graph(g, face_integer):
|
|
e=g['edges'];directed=np.concatenate((e,e[:,::-1]))
|
|
order=np.lexsort((directed[:,1],directed[:,0]));weights=np.tile(face_integer,2)[order]
|
|
if weights.dtype!=np.int32 or np.any(weights<=0) or weights.astype(np.int64).sum()>4*Q:
|
|
raise GeometryFailure('DIRECTED_INTEGER_WEIGHT_RANGE')
|
|
# Each unordered face receives exactly the same integer in its two directions.
|
|
original=np.empty(len(weights),dtype=weights.dtype);original[order]=weights
|
|
if not np.array_equal(original[:len(e)],original[len(e):]):raise InputViolation('Asymmetric weights')
|
|
out=dict(g);out['adjwgt']=weights
|
|
return out
|
|
|
|
|
|
def triple_match(metrics):
|
|
arms=['G','T','C']
|
|
fractions=np.array([metrics[a]['fractions'] for a in arms])
|
|
area=np.array([metrics[a]['cut_area'] for a in arms])
|
|
diameter=np.array([metrics[a]['diameters'] for a in arms])
|
|
if np.any(area<=0) or np.any(diameter<=0):raise GeometryFailure('DEGENERATE_MATCH_MEASURE')
|
|
deviations={a+'/'+b:float(K*np.abs(fractions[arms.index(a)]-fractions[arms.index(b)]).max()) for a,b in itertools.combinations(arms,2)}
|
|
area_ratio=float(area.max()/area.min());size_ratio=diameter.max(axis=0)/diameter.min(axis=0)
|
|
old=(match(metrics['T'],metrics['G'])['passed'] and match(metrics['C'],metrics['G'])['passed']
|
|
and match(metrics['T'],metrics['C'],mutual=True)['passed'])
|
|
return dict(passed=bool(max(deviations.values())<=.025 and area_ratio<=1.25 and np.all(size_ratio<=1.25)),
|
|
volume_pair_scaled_max=deviations,cut_area_max_min=area_ratio,sorted_diameter_max_min=size_ratio.tolist(),
|
|
old_five_percent_matching_pass=bool(old))
|
|
|
|
|
|
def feasibility(parts, results, panel_ids, *, full=False):
|
|
by={p['case']:p for p in parts};panel=[by[case] for case in panel_ids]
|
|
groups=sorted({p['component_id'] for p in panel});group_rows=[]
|
|
if full and len(groups)!=209:
|
|
raise InputViolation('Full gate must retain original 209-component denominator')
|
|
qualified=[p for p in panel if results.get(p['case'],{}).get('status')=='PASS']
|
|
def differences(p):
|
|
d=results[p['case']]['diagnostics']
|
|
return d['T/G']['interface']['value'],d['T/C']['interface']['value']
|
|
strong=sum(x>=.1 and y>=.1 for x,y in map(differences,qualified))
|
|
for group in groups:
|
|
included=[p for p in panel if p['component_id']==group]
|
|
good=all(results.get(p['case'],{}).get('status')=='PASS' for p in included)
|
|
tg=tc=None
|
|
if good:
|
|
ds=np.array([differences(p) for p in included]);tg=float(ds[:,0].mean());tc=float(ds[:,1].mean())
|
|
group_rows.append(dict(component_id=group,paired=good,panel_cases=[p['case'] for p in included],
|
|
non_panel_cases=[p['case'] for p in parts if p['component_id']==group and p['case'] not in panel_ids],
|
|
interface_TG_mean=tg,interface_TC_mean=tc,strong=bool(good and tg>=.1 and tc>=.1)))
|
|
paired=sum(r['paired'] for r in group_rows);cg_strong=sum(r['strong'] for r in group_rows)
|
|
n=len(panel);e=len(qualified);h=strong;g=len(groups)
|
|
part_gate=bool(n and 5*e>=4*n and e and 10*h>7*e)
|
|
component_gate=bool(g and 5*paired>=4*g and paired and (10*cg_strong>=7*paired if full else 10*cg_strong>7*paired))
|
|
return dict(passed=component_gate if full else part_gate and component_gate,full_roster=full,
|
|
total_parts=n,eligible_parts=e,strong_eligible_parts=h,E_over_N=e/n if n else None,H_over_E=h/e if e else None,H_over_N=h/n if n else None,
|
|
part_coverage_pass=bool(n and 5*e>=4*n),part_strict_intervention_pass=bool(e and 10*h>7*e),
|
|
total_components=g,paired_components=paired,strong_paired_components=cg_strong,
|
|
component_coverage=paired/g if g else None,component_intervention=cg_strong/paired if paired else None,
|
|
component_gate_pass=component_gate,component_rows=group_rows,
|
|
original_full_component_denominator=209,strict_70_percent=not full,
|
|
interpretation='Operational label-free panel, not random sampling or full-corpus success-rate estimate' if not full else 'Original full component gate')
|