Download expansion_v2/source/src/train_cross_wave.py from Giuliocc/windtunnel-response-data: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/datasets/Giuliocc/windtunnel-response-data/resolve/main/expansion_v2/source/src/train_cross_wave.py
- Command line
-
hf download hf://datasets/Giuliocc/windtunnel-response-data/expansion_v2/source/src/train_cross_wave.py
-
curl -L -o train_cross_wave.py https://huggingface.co/datasets/Giuliocc/windtunnel-response-data/resolve/main/expansion_v2/source/src/train_cross_wave.py
11.5 kB
| """Additional exact-instrument 2022->2024 transport; label-assisted offsets remain separate.""" | |
| import os | |
| for k in ['OMP_NUM_THREADS','MKL_NUM_THREADS','OPENBLAS_NUM_THREADS']:os.environ[k]='1' | |
| import datetime,json,re,hashlib | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.optimize import minimize | |
| from scipy.special import softmax | |
| from train_known import load_data,evaluate,bootstrap | |
| from windtunnel_response.sources import read,write,digest,object_hash,CELLS,STATES | |
| from windtunnel_response.baseline import fitted_model,by_cell,probabilities,DESIGN,FEATURES | |
| ROOT=Path(__file__).resolve().parents[1] | |
| SPECS=[ | |
| ('CC22_332b','CC24_324b',40,[29537,30412]),('CC22_333c','CC24_326c',42,[36536,23459]), | |
| ('CC22_340a','CC24_330a',44,[7703,8771,5638,14777,5283,8011,6322,3453]), | |
| ('CC22_340c','CC24_330c',44,[18835,10919,10183,8508,2366,1482,1105,6513]), | |
| ('CC22_340d','CC24_330e',44,[2462,1044,963,2864,5618,11893,24711,10400]), | |
| ('CC22_340e','CC24_330f',44,[20310,11842,10037,6453,2243,1400,985,6699]), | |
| ('CC22_340f','CC24_330g',44,[1465,1196,1586,3282,6943,13396,24480,7637]), | |
| ('CC22_340g','CC24_330h',44,[1360,1353,2087,10988,8755,10176,14715,10557]), | |
| ] | |
| def crosswalk(items): | |
| target={q['question_id']:q for q in items};rows=[] | |
| pages=(ROOT/'raw/ces22-pre.txt').read_text().split('\f') | |
| for old,new,page,counts in SPECS: | |
| q=target[new] | |
| # The field/question hash is for the exact textual input. It is not a hash of surrounding survey pages. | |
| instrument={k:q[k] for k in ['question_text','stimulus_text','preceding_context','options','language']} | |
| record={**instrument,'question_id':old,'question_family_id':q['question_family_id'],'instrument_hash':object_hash(instrument),'ordinal_order':q['ordinal_order'],'response_type':q['response_type']} | |
| # Verify the source variable and stem in the actual corresponding page, rather than only copying a hash. | |
| sourcepage=next(t for t in pages if f'Page {page}\n' in t or f'Page {page}\r' in t) | |
| assert f'[{old}]' in sourcepage,old | |
| compact=lambda s:re.sub(r'[\s◯○]+','',s) | |
| stem=q['question_text'] | |
| assert compact(stem) in compact(sourcepage),(old,'stem') | |
| if page!=44:assert compact(q['stimulus_text']) in compact(sourcepage.split(f'[{old}]',1)[1].split('required:',1)[0]),old | |
| else: | |
| assert compact(q['stimulus_text']) in compact(sourcepage.split(f'[{old}]',1)[1].split('[CC22_',1)[0]),old | |
| assert [o['label'] for o in q['options']]==['Very Liberal','Liberal','Somewhat Liberal','Middle of the Road','Somewhat Conservative','Conservative','Very Conservative','Not sure'] | |
| rows.append({'older':old,'newer':new,'family':q['question_family_id'],'questionnaire_page':page,'older_instrument':record,'newer_instrument':q,'guide_counts':counts,'match':'same_item_text_and_options','wording_verification':'Agent transcription checked against pinned source page text; ideology option columns visually inspected from page 44. No independent human adjudication.','source_context_limitation':'Same question stem, named stimulus and answer labels; survey order, historical setting and surrounding pages differ.'}) | |
| return rows | |
| def main(): | |
| assert not (ROOT/'results/cross-wave-evaluation.json').exists(), 'Preserve first-pass results; reproduce in a fresh workspace.' | |
| items,df,receipt=load_data();rows=crosswalk(items);protocol=read(ROOT/'configs/protocol.v2.json');path=ROOT/'configs/cross-wave-instruments.v2.json' | |
| prefit={'id':'windtunnel-cross-wave-extra-eight-v2','registered_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'parent_protocol_sha256':digest(ROOT/'configs/protocol.v2.json'),'source_dates':{'2022':['2022-09-29','2022-11-08'],'2024':['2024-10-01','2024-11-04']},'pairs':[{'older':r['older'],'newer':r['newer'],'hash':r['older_instrument']['instrument_hash'],'family':r['family']} for r in rows],'exposure':'Target wave historical marginals were public; these target instruments are also in the now completed separate encoder diagnostic. This is a locked-before-fit retrospective comparison, not fresh outcome-blind/prospective validation.'} | |
| if path.exists(): | |
| existing=read(path);assert {k:v for k,v in existing.items() if k!='registered_at'}=={k:v for k,v in prefit.items() if k!='registered_at'},'Instrument registration differs' | |
| else:write(path,prefit) | |
| write(ROOT/'results/cross-wave-crosswalk.json',rows) | |
| oldkeys=[r['older'] for r in rows];fields=['caseid','cit1','commonweight','inputstate','birthyr','educ',*oldkeys] | |
| old=pd.read_csv(ROOT/'raw/ces22.csv',usecols=fields,dtype={'caseid':str},low_memory=False) | |
| assert len(old)==60000 and old.caseid.is_unique | |
| reconcile={} | |
| for r in rows: | |
| counts=[int((old[r['older']]==int(o['id'])).sum()) for o in r['older_instrument']['options']];assert counts==r['guide_counts'],(r['older'],counts,r['guide_counts']);reconcile[r['older']]={'guide_counts':r['guide_counts'],'csv_counts':counts} | |
| age=2022-old.birthyr;mask=(old.cit1==1)&old.inputstate.isin(STATES)&(age>=18)&(old.commonweight>0)&np.isfinite(old.commonweight);old=old.loc[mask].copy();a=np.searchsorted([30,45,65],age.loc[mask],side='right');ed=old.educ.map({1:0,2:0,3:1,4:1,5:2,6:2});old['cell']=np.where(ed.notna(),a*3+ed.fillna(0),-1).astype(int) | |
| dev=df[df.split=='dev'];models={};historical={};marginal={};assisted={};devmarginal={} | |
| for r in rows: | |
| k=r['newer'];q=r['newer_instrument'];m=fitted_model(old,r['older_instrument'],{'known_item':{'l2_c':1,'minimum_cell_answered':100,'minimum_cell_kish':50}});models[k]=m;historical[k]={c:probabilities(m,c,'linear').tolist() for c in [*CELLS,'unknown']};marginal[k]={c:m['marginal'] for c in [*CELLS,'unknown']} | |
| n=len(q['options']);valid=dev[k].isin(range(1,n+1));part=dev.loc[valid];labels=part[k].to_numpy().astype(int)-1;weights=part.commonweight.to_numpy();w=weights/weights.sum();base=np.asarray([np.log(historical[k][[*CELLS,'unknown'][c]]) for c in part.cell]) | |
| def objective(offset): | |
| pred=softmax(base+offset,axis=1);value=-np.dot(w,np.log(np.clip(pred[np.arange(len(labels)),labels],1e-15,1)));grad=np.sum(w[:,None]*(pred-np.eye(n)[labels]),axis=0);return value,grad | |
| fit=minimize(objective,np.zeros(n),jac=True,method='L-BFGS-B',options={'maxiter':400,'ftol':1e-12,'gtol':1e-9});assert fit.success | |
| offset=fit.x-fit.x.mean();m['intercept_offsets_from_target_dev']=offset.tolist();assisted[k]={c:softmax(np.log(historical[k][c])+offset).tolist() for c in [*CELLS,'unknown']} | |
| cells=by_cell(dev,q);masses=np.sum([np.array(o['weighted_outcome_mass']) for o in cells.values()],axis=0);devp=(masses/masses.sum()).tolist();devmarginal[k]={c:devp for c in [*CELLS,'unknown']} | |
| artifact={'method':'ces_cross_wave_research_v2','benchmark_id':'ces2022-v4-to-ces2024-v9-extra-eight-v2','registered_protocol_sha256':digest(ROOT/'configs/protocol.v2.json'),'crosswalk_sha256':digest(path),'target_frozen_split_sha256':receipt['assignment_sha256'],'feature_names':FEATURES,'cell_features':{c:DESIGN[i].tolist() for i,c in enumerate([*CELLS,'unknown'])},'source_dates':prefit['source_dates'],'items':[{'question_id':r['newer'],'older_question_id':r['older'],'instrument_hash':r['newer_instrument']['instrument_hash'],'older_instrument_hash':r['older_instrument']['instrument_hash'],'option_ids':[o['id'] for o in r['newer_instrument']['options']],**{k:models[r['newer']][k] for k in ['coefficients','intercepts','intercept_offsets_from_target_dev','training_support']},'supported_cells':[c for c,s in models[r['newer']]['training_support'].items() if s['supported']]} for r in rows]} | |
| write(ROOT/'results/cross-wave-model.json',artifact);write(ROOT/'results/cross-wave-training.json',{'source2022_sha256':digest(ROOT/'raw/ces22.csv'),'source2022_eligible':len(old),'source2024_assignment_sha256':receipt['assignment_sha256'],'cross_wave_release_local_id_matches':len(set(old.caseid)&set(df.caseid)),'real_person_panelist_overlap':'Not identifiable through release-local IDs; possible repeated panelists cannot be excluded.','source_question_roles_sha256':object_hash({r['older']:'fit_2022' for r in rows}),'target_dev_question_roles_sha256':object_hash({r['newer']:'calibration_only_dev_2024' for r in rows}),'target_test_question_roles_sha256':object_hash({r['newer']:'test_only_2024' for r in rows}),'reconciliation':reconcile,'selected_model_sha256':digest(ROOT/'results/cross-wave-model.json'),'test_opened_after_artifact_written_at':datetime.datetime.now(datetime.timezone.utc).isoformat()}) | |
| test=df[df.split=='test'];report=[];public=[] | |
| for r in rows: | |
| k=r['newer'];q=r['newer_instrument'];cells=by_cell(test,q) | |
| report.append({'question_id':k,'family':r['family'],'instrument_hash':q['instrument_hash'],'historical':evaluate(historical[k],cells,q),'historical_marginal':evaluate(marginal[k],cells,q),'label_assisted':evaluate(assisted[k],cells,q),'target_dev_marginal':evaluate(devmarginal[k],cells,q)}) | |
| oldcells=by_cell(old,r['older_instrument']);allow=cells['unknown']['human_n_eligible']==0 and oldcells['unknown']['human_n_eligible']==0 and all(min(cells[c]['human_n_selected'])>=10 and min(oldcells[c]['human_n_selected'])>=10 for c in CELLS) | |
| if allow: | |
| for c in CELLS:public.append({'question_id':k,'instrument_hash':q['instrument_hash'],'cell_id':c,'option_ids':[o['id'] for o in q['options']],'source_2022':oldcells[c]['probabilities'],'test_2024':cells[c]['probabilities'],'historical':historical[k][c],'label_assisted':assisted[k][c],'effective_n_weight_only':cells[c]['effective_n_weight_only']}) | |
| def means(field):return {scope:{metric:float(np.mean([r[field][scope][metric] for r in report])) for metric in ['half_multiclass_brier','total_variation','cross_entropy']} for scope in ['national','within_cell']} | |
| observed={field:means(field) for field in ['historical','historical_marginal','label_assisted','target_dev_marginal']};qs=[r['newer_instrument'] for r in rows];boot=bootstrap(test,qs,historical,marginal);assistboot=bootstrap(test,qs,assisted,devmarginal);gain=observed['historical_marginal']['within_cell']['half_multiclass_brier']-observed['historical']['within_cell']['half_multiclass_brier'];gate=protocol['cross_wave']['promotion_gate'];passed=len(rows)>=5 and len({r['family'] for r in rows})>=3 and gain>=.0001 and boot['interval'][1]<0 | |
| write(ROOT/'results/cross-wave-evaluation.json',{'benchmark_id':artifact['benchmark_id'],'track':'additional_historical_temporal_instruments','questions':len(rows),'families':len({r['family'] for r in rows}),'new_family_relative_to_v1':['ideological_placement'],'means':observed,'historical_gain':gain,'paired_bootstrap':boot,'label_assisted_bootstrap':assistboot,'promotion_passed':bool(passed),'gate':gate,'rows':report,'limitations':['Historical outcomes and target guide marginals were already available.','Six of eight items share one ideology battery; fixed-instrument inference dominates the equal-item mean. Family-generalization is unsupported.','No independent real-person overlap check between waves; release-local IDs are insufficient.','Opt-in panels, fixed fitted models, observed target answerer composition; no probability-sample interval or causal inference.','Label-assisted mode uses target development response labels and is not a forecast.']}) | |
| write(ROOT/'results/cross-wave-public-cells.json',public) | |
| print(json.dumps({'questions':len(rows),'families':3,'historical':observed['historical']['within_cell'],'marginal':observed['historical_marginal']['within_cell'],'gain':gain,'interval':boot['interval'],'promotion':bool(passed)})) | |
| if __name__=='__main__':main() | |