"""Population statistics for optimization and independent canonical replay. ``Engine`` consumes physical answer matrices keyed by condition. Final replay uses ``score_population`` with option-ID answer matrices or materialized population records. The latter uses the source-defined R methods where a canonical backend is declared; the optimization Engine is not a replacement for final replay. Python dependencies: NumPy, SciPy, pandas and patsy. Canonical R jobs require Rscript on PATH and the R packages jsonlite, car, DescTools and emmeans. """ from __future__ import annotations import collections import importlib.util import json import math import re import shutil import subprocess import tempfile from collections import defaultdict from pathlib import Path from typing import Any, Mapping import numpy as np import pandas as pd from patsy import dmatrix from scipy import stats, special try: from . import _inference except ImportError: import _inference def _make_scorer(): """Keep wrapper state private to one engine/replay, including missingness.""" path = Path(__file__).with_name("_scorer.py") spec = importlib.util.spec_from_file_location("_population_scorer_instance", path) if spec is None or spec.loader is None: raise RuntimeError(f"Cannot load population scorer: {path}") scorer = importlib.util.module_from_spec(spec) spec.loader.exec_module(scorer) _inference.install_inference_wrappers(scorer) return scorer def finite(value: Any) -> float | None: try: result = float(value) except (TypeError, ValueError): return None return result if math.isfinite(result) else None def predicted_direction(contrast: float | None) -> str | None: if contrast is None: return None return "pos" if contrast > 0 else "neg" if contrast < 0 else "zero" def analysis_width(effect: dict[str, Any]) -> tuple[float, str]: declared = finite(effect["human_target"].get("response_scale_width")) or finite( effect["statistic_spec"].get("outcome_scale_width") ) if declared is not None and declared > 0: return declared, "declared_response_scale_width" by_item: dict[str, list[float]] = defaultdict(list) for cell in effect["cells"]: by_item[str(cell["prediction_id"])].extend( float(option["analysis_value"]) for option in cell["analysis_options"] ) mapping = (effect["identifiability"].get("outcome_mapping") or {}).get("mapping") or {} if mapping.get("type") == "single_item_lookup": values = [float(value) for value in (mapping.get("values") or {}).values()] if values and max(values) > min(values): return max(values) - min(values), "inferred_lookup_range" terms = mapping.get("terms") or {} if terms: width = sum( abs(float(coefficient)) * (max(by_item[item]) - min(by_item[item])) for item, coefficient in terms.items() if item in by_item and by_item[item] ) if width > 0: return width, "inferred_affine_range" dependent = [str(item) for item in effect["identifiability"].get("dependent_prediction_ids") or []] widths = [max(by_item[item]) - min(by_item[item]) for item in dependent if item in by_item and by_item[item]] if widths and max(widths) > 0: return max(widths), "inferred_dependent_item_range" return 1.0, "unit_fallback" def signed_prediction(effect: float | None, contrast: float | None, human_direction: Any) -> float | None: if effect is None: return None if str(human_direction) in {"pos", "neg", "zero", "equal"}: if contrast is None: return None sign = 1.0 if contrast > 0 else -1.0 if contrast < 0 else 0.0 return abs(effect) * sign return abs(effect) def exact_effect_statistics( scorer: Any, effect: dict[str, Any], arrays: Mapping[str, np.ndarray], ) -> dict[str, float]: """Use the canonical calculator's exact dispatch for one effect.""" required = {str(cell["cell_id"]) for cell in effect["cells"]} missing = sorted(required - set(arrays)) if missing: raise ValueError(f"{effect['effect_key']}: missing cells {missing[:5]}") indicator = str(effect["indicator"]) spec = effect["statistic_spec"] if spec.get("canonical_backend"): raise ValueError( f"{effect['effect_key']}: this source-reviewed rule requires " "score_population (batch R backend); " "scalar dispatch would discard its method definition" ) if indicator == "d": metrics = scorer.cohen_d(effect, scorer.condition_rows(effect, arrays)) elif indicator in {"eta-square", "f"}: rows = scorer.condition_rows(effect, arrays) if spec.get("mixed_two_level"): metrics = scorer.mixed_two_level(effect, arrays) elif spec.get("long_outcomes"): metrics = scorer.repeated_long_anova(effect, rows) else: metrics = scorer.generic_anova(effect, rows) try: metrics.update(scorer.direction_statistics(effect, rows)) except (KeyError, ValueError): pass elif indicator == "b": metrics = _inference.regression_with_inference(scorer, effect, arrays) elif indicator == "chi-square": metrics = scorer.chi_square(effect, arrays) else: raise ValueError(f"Unsupported indicator {indicator!r}") output = {} for name, value in metrics.items(): number = finite(value) if number is not None: output[name] = number if finite(output.get("effect")) is None or finite(output.get("p_value")) is None: raise ValueError(f"{effect['effect_key']}: calculator omitted effect or p_value") return output def build_job(scorer,e,arrays): """Keep joint respondent indices intact; apply subgroup selectors only in backend.""" cfg=e['statistic_spec']['canonical_backend'];bycondition=collections.defaultdict(dict) for cell in e['cells']:bycondition[cell['condition_id']][cell['prediction_id']]=cell output=collections.defaultdict(list) for condition,cells in sorted(bycondition.items()): cov=dict(next(iter(cells.values()))['condition_covariates']) y=scorer.affine_array(cells,arrays,scorer.resolve_outcome_mapping(e)) if not np.all(np.isfinite(y)):raise ValueError('Non-finite mapped answers; source missingness must be explicit') output['y'].extend(y.tolist()) for k,v in cov.items():output[k].extend([v]*len(y)) if cfg.get('covariate_mapping'): cv=scorer.affine_array(cells,arrays,cfg['covariate_mapping']) if not np.all(np.isfinite(cv)):raise ValueError('Non-finite covariate') output['cov'].extend(cv.tolist()) if len({len(v) for v in output.values()})!=1:raise ValueError('Inconsistent condition metadata columns') return {'effect_key':e['effect_key'],'config':cfg,'data':dict(output)} def mask_unresolved(e,row): row['rule_status']=e.get('canonical_audit', {}).get('status', 'source_reviewed');row['unresolved']=e.get('canonical_audit', {}).get('unresolved',[]) if row.get('statistics',{}).get('undefined'): row['status']='partial_numerical_undefined' row['numerical_issue']=row['statistics'].pop('undefined') if row.get('statistics') is not None and row['unresolved']: row['diagnostic_statistics']=dict(row['statistics']) for issue in row['unresolved']: for field in issue['fields']:row['statistics'].pop(field,None) row['status']='partial_source_ambiguity' if row.get('statistics') is not None: source_undefined={f for issue in row['unresolved'] for f in issue['fields']} missing=[f for f in ['effect','p_value'] if f not in source_undefined and not (isinstance(row['statistics'].get(f),(float,int)) and math.isfinite(row['statistics'][f]))] if missing: row.setdefault('numerical_issue',{'fields':missing,'reason':'Declared statistic returned no finite numeric value'}) if row['status']=='ok':row['status']='partial_numerical_undefined' return row def _json_safe(value): if isinstance(value, dict): return {str(key): _json_safe(item) for key, item in value.items()} if isinstance(value, (list, tuple, np.ndarray)): return [_json_safe(item) for item in value] if isinstance(value, (float, np.floating)): return float(value) if math.isfinite(value) else None if isinstance(value, np.integer): return int(value) return value def _run_backend(jobs, rscript="Rscript"): if not jobs: return {"results": []} executable = shutil.which(str(rscript)) if executable is None: raise FileNotFoundError(f"Rscript executable not found: {rscript}") with tempfile.TemporaryDirectory(prefix="chiron_population_statistics_") as directory: input_path = Path(directory) / "input.json" output_path = Path(directory) / "output.json" input_path.write_text(json.dumps(_json_safe(jobs), allow_nan=False), encoding="utf-8") process = subprocess.run( [executable, str(Path(__file__).with_name("_canonical_backend.R")), str(input_path), str(output_path)], capture_output=True, text=True, ) if process.returncode: raise RuntimeError("Canonical R backend failed: " + process.stderr[-6000:]) result = json.loads(output_path.read_text(encoding="utf-8")) result["stderr"] = process.stderr return result def score_population(effects, prompts, respondents, *, rscript="Rscript"): """Return effects, reconstruction audit and backend metadata. ``respondents`` may be a mapping from condition keys to option-ID matrices, or a list of population records with ``condition_key`` and ``respondents``. Materialized records may include source-row multiplicities and explicit analysis-missingness provenance. Physical numeric values belong only in ``Engine``; this API decodes option IDs using each question's answer scale. """ if len({str(row["condition_key"]) for row in prompts}) != len(prompts): raise ValueError("Duplicate condition_key in prompts") if len({str(effect["effect_key"]) for effect in effects}) != len(effects): raise ValueError("Duplicate effect_key") prompt_by_key = {str(row["condition_key"]): row for row in prompts} if isinstance(respondents, Mapping): population = [] for key, matrix in respondents.items(): key = str(key) if key not in prompt_by_key: raise ValueError(f"Unknown population condition_key {key}") population.append({"condition_key": key, "questions": prompt_by_key[key]["questions"], "respondents": np.asarray(matrix).tolist()}) else: population = [] for row in respondents: item = dict(row) key = str(item["condition_key"]) if key not in prompt_by_key: raise ValueError(f"Unknown population condition_key {key}") item.setdefault("questions", prompt_by_key[key]["questions"]) population.append(item) scorer = _make_scorer() cell_arrays, audit = scorer.reconstruct_population_cells(prompts, population) results, jobs = {}, [] for effect in effects: try: if effect["statistic_spec"].get("canonical_backend"): jobs.append(build_job(scorer, effect, cell_arrays)) else: results[effect["effect_key"]] = { "status": "ok", "statistics": exact_effect_statistics(scorer, effect, cell_arrays), } except Exception as error: results[effect["effect_key"]] = { "status": "error", "error": type(error).__name__ + ": " + str(error), } backend = _run_backend(jobs, rscript) for row in backend["results"]: result = dict(row) results[result.pop("effect_key")] = result for effect in effects: results[effect["effect_key"]] = mask_unresolved(effect, results[effect["effect_key"]]) return {"effects": results, "reconstruction": audit, "backend": {key: value for key, value in backend.items() if key != "results"}} def arrays(pp,mats): return {x['cell_id']:mats[q['condition_key']][:,j] for q in pp for j,x in enumerate(q['questions'])} class Engine: def __init__(self,es,pp,base): self.sc = _make_scorer() self.es=es;self.pp=pp;self.cache={};self.static={} ar=arrays(pp,base) for e in es: cfg=e['statistic_spec'].get('canonical_backend') if not cfg:continue job=build_job(self.sc,e,ar);df=pd.DataFrame(job['data']);keep=np.ones(len(df),bool) for f,v in (cfg.get('subset') or {}).items():keep&=df[f].astype(str).values==str(v) df=df.loc[keep].reset_index(drop=True);s=cfg.get('selector') or {};sel=s.get('direction_levels') or s;group=[];sub=np.ones(len(df),bool) if s.get('subset_column'):sub&=df[s['subset_column']].astype(str).values==str(s['subset_value']) if sel.get('factor'): group=[np.flatnonzero(sub&(df[sel['factor']].astype(str).values==str(sel[f'level{g}']))) for g in [1,2]] z=dict(keep=keep,df=df,group=group,sub=sub,cfg=cfg,qr={}) if cfg.get('formula'): for f in cfg.get('factors',[]):df[f]=pd.Categorical(df[f].astype(str),categories=sorted(df[f].astype(str).unique())) rhs=cfg['formula'].split('~')[1] for f in sorted(cfg.get('factors',[]),key=len,reverse=True):rhs=re.sub(r'\b'+f+r'\b',f'C({f}, Sum)',rhs) if 'cov' in df:df['cov']=np.arange(len(df))/max(1,len(df)) dm=dmatrix(rhs,df);z['X']=np.array(dm);z['names']=dm.design_info.column_names z['terms']={re.sub(r'C\((\w+), Sum\)',r'\1',t):list(range(sl.start,sl.stop)) for t,sl in dm.design_info.term_name_slices.items()} z['covcol']=z['names'].index('cov') if 'cov' in z['names'] else None if cfg['kind']=='ancova_contrast': z['L']=z['X'][group[0][0]]-z['X'][group[1][0]];z['L'][z['covcol']]=0 self.static[e['effect_key']]=z def __call__(self,mats): ar=arrays(self.pp,mats);out={} for e in self.es: try: if e['statistic_spec'].get('canonical_backend'):s=self.backend(e,ar) else:s=exact_effect_statistics(self.sc,e,ar) if not all(np.isfinite(s.get(f,np.nan)) for f in ['effect','p_value']):raise ValueError('nonfinite statistic') out[e['effect_key']]={'status':'ok','statistics':s} except Exception as ex:out[e['effect_key']]={'status':'error','error':str(ex),'statistics':{}} return out def backend(self,e,ar): z=self.static[e['effect_key']];cfg=z['cfg'];kind=cfg['kind'];d=build_job(self.sc,e,ar)['data'];y=np.array(d['y'])[z['keep']];n=len(y);o={};groups=z['group'];s=cfg.get('selector') or {} if groups: a,b=[y[ix] for ix in groups];v1,v2=np.var(a,ddof=1),np.var(b,ddof=1);contrast=a.mean()-b.mean();pool=((len(a)-1)*v1+(len(b)-1)*v2)/(len(a)+len(b)-2) o.update(contrast=float(contrast),mean1=float(a.mean()),mean2=float(b.mean()),sd1=float(np.sqrt(v1)),sd2=float(np.sqrt(v2))) if kind=='t': o['effect']=contrast/np.sqrt(pool);method=cfg.get('p_method');equal=False if method=='subgroup_ml_normal':o['p_value']=2*special.ndtr(-abs(o['effect']*np.sqrt(len(a)*len(b)/(len(a)+len(b)-2)))) elif method=='tukey': lev=z['df'][s['factor']].astype(str).values;gs=[y[(lev==v)&z['sub']] for v in np.unique(lev[z['sub']])];df=sum(len(g) for g in gs)-len(gs);mse=sum(np.sum((g-g.mean())**2) for g in gs)/df q=abs(contrast)/np.sqrt(mse*(1/len(a)+1/len(b))/2);o['p_value']=stats.studentized_range.sf(q,len(gs),df) else: if method in ['levene_median','levene_mean']:equal=stats.levene(a,b,center='median' if method.endswith('median') else 'mean').pvalue>.05 se=np.sqrt(pool*(1/len(a)+1/len(b))) if equal else np.sqrt(v1/len(a)+v2/len(b)) df=len(a)+len(b)-2 if equal else (v1/len(a)+v2/len(b))**2/((v1/len(a))**2/(len(a)-1)+(v2/len(b))**2/(len(b)-1)) o['p_value']=2*special.stdtr(df,-abs(contrast/se)) elif kind in ['anova','factorial_d','ancova_contrast','ols_ml']: X=z['X'] if z['covcol'] is not None:X=X.copy();X[:,z['covcol']]=np.array(d['cov'])[z['keep']] cols=list(range(X.shape[1])) def sse(inds): inds=tuple(inds) if z['covcol'] is None: if inds not in z['qr']: xx=X[:,inds] if np.linalg.matrix_rank(xx)!=len(inds):raise ValueError('rank deficient') z['qr'][inds]=np.linalg.qr(xx,mode='reduced')[0] Q=z['qr'][inds];r=y-Q@(Q.T@y) else: xx=X[:,inds];coef,_,rank,_=np.linalg.lstsq(xx,y,rcond=None) if rank!=len(inds):raise ValueError('rank deficient') r=y-xx@coef return float(r@r) se=sse(cols);df=n-len(cols) if se<=1e-12:raise ValueError('zero residual') if kind=='ols_ml': coef=np.linalg.lstsq(X,y,rcond=None)[0];j=z['names'].index(cfg['term']);err=np.sqrt(np.linalg.inv(X.T@X)[j,j]*se/n);o.update(effect=coef[j],contrast=coef[j],p_value=2*special.ndtr(-abs(coef[j]/err))) elif kind=='ancova_contrast': coef=np.linalg.lstsq(X,y,rcond=None)[0];L=z['L'];err=np.sqrt(se/df*(L@np.linalg.solve(X.T@X,L)));o.update(effect=contrast/np.sqrt(pool),p_value=2*special.stdtr(df,-abs(L@coef/err))) else: term=cfg['term'];tc=z['terms'][term];typ=cfg['ss_type'] def ss2(): target=set(term.split(':'));included=[j for t,js in z['terms'].items() if not set(t.split(':'))>target for j in js] return max(0,sse([j for j in included if j not in tc])-sse(included)) if typ==1: upto=list(range(max(tc)+1));ss=max(0,sse([j for j in upto if j not in tc])-sse(upto)) elif typ==2:ss=ss2() else:ss=max(0,sse([j for j in cols if j not in tc])-se) f=ss/len(tc)/(se/df);effect=f if e['indicator']=='f' else ss/(ss+se) if cfg.get('eta_kind')=='partial_type2_replay_confirmed':ss=ss2();effect=ss/(ss+se) if kind=='factorial_d':effect=contrast/np.sqrt(pool) o.update(effect=effect,p_value=special.fdtrc(len(tc),df,f)) elif kind=='logit': x=np.array(d[cfg['numeric'][0]])[z['keep']];lev=np.unique(x);ys=np.unique(y);assert len(lev)==len(ys)==2 ct=np.array([[sum((x==a)&(y==b)) for b in ys] for a in lev],float) if (ct==0).any():raise ValueError('separation') beta=(np.log(ct[1,1]/ct[1,0])-np.log(ct[0,1]/ct[0,0]))/(lev[1]-lev[0]);err=np.sqrt((1/ct).sum())/abs(lev[1]-lev[0]);o.update(effect=beta,contrast=beta,p_value=2*special.ndtr(-abs(beta/err))) elif kind=='chisq': frame=z['df'];ids=np.flatnonzero(z['sub']);rows=[tuple(str(frame.iloc[i][f]) for f in cfg['row_factors']) for i in ids];uniq=sorted(set(rows));ys=np.unique(y[ids]);tab=np.zeros((len(uniq),len(ys)),int) for row,v in zip(rows,y[ids]):tab[uniq.index(row),np.searchsorted(ys,v)]+=1 if min(tab.shape)<2:raise ValueError('empty outcome category') f,pv,_,_=stats.chi2_contingency(tab,correction=bool(cfg.get('yates')));o.update(effect=f,p_value=pv) else:raise ValueError('unsupported '+kind) return {k:float(v) for k,v in o.items()}