#!/usr/bin/env python3
"""Reproduce the 2025-26 Evidence Lab analyses from public school-level data.

START HERE: this is the entry point for the downloaded two-file Python bundle.
Keep income_education_model_common.py and source_references.json beside it.
See README.txt for dependencies and links to the public release inputs. Example:
    python3 release_2025_26_analyses.py --data-dir ./release-inputs/2025-26 \
        --output-dir ./reproduced-results --audit-dir ./reproduced-audit
Use fresh output directories: same-name result files are replaced. No API key,
private input or network request is needed. In a repository checkout, the
command without options uses the repository-relative defaults below.

Reading order:
1. load_release checks the frozen manifest and joins public school records.
2. build_points selects a school sample and makes model rows with explicit units.
3. model_result and two_factor_result fit the SES models and check their results.
4. threshold_analysis compares the four achievement-level distributions.
5. build writes CSVs, figures and reports; bundle_scripts supplies these sources.

Each outcome is an official Total Population / All Grades school-subject total,
not a student record. The model weight is the number of scored students (Level
1-4), not participants. School/district IDs identify institutions; source_refs
identify archived source rows. CSV field definitions are in data_dictionary.json
beside the result CSVs and in this edition's Analysis downloads guide.

The common module supplies numerical and school-policy helpers. Its historical
2024-25 loader, defaults and attendance models are NOT used by this entry point.
--refresh-companions updates documentation from verified existing results;
it does not refit models or rewrite the result CSVs.
"""
from __future__ import annotations
import argparse
import collections
import csv
import hashlib
import json
import math
import os
from pathlib import Path
import sys
from fractions import Fraction

# Generic plotting cache, not an input path or a user-specific home directory.
os.environ.setdefault('MPLCONFIGDIR', '/tmp/orschool_2025_26_models_mpl')
import numpy as np
import pandas as pd
import income_education_model_common as common

ROOT = Path(__file__).resolve().parents[1]
DATE = '2026-10-13'
MANIFEST_SHA = 'c3d56482b1e792da9fbcd3cc6a6b99c0d069a4f407a40637cb3e5960afc7e5de'
RELEASE_ID = 'ode-2025-26-acs2024-sep2025-26-v5'
YEAR = '2025-2026'
SUBJECTS = {'english': 'English', 'math': 'Math', 'science': 'Science'}
TOTAL = 'Total Population (All Students)'
DATA_DIR = ROOT / 'data/processed/releases/2025-26'
OUT_DIR = ROOT / 'site/releases/2025-26/analysis'
AUDIT_DIR = ROOT / 'artifacts/analysis/ode_2025_26_coordinated_release_exploratory/models'
FOLDS, REPEATS, SEED = 5, 20, 20260910
LEVELS = [f'Number Level {x}' for x in range(1, 5)]
SOURCES = [
 'scripts/income_education_model_common.py',
 'artifacts/analysis/oregon_ba_school_poverty_joint_model_exploratory/build_oregon_ba_school_poverty_joint_model.py',
 'artifacts/analysis/oregon_ba_school_poverty_residuals_exploratory/build_oregon_ba_school_poverty_residuals.py',
 'artifacts/analysis/ho_proficiency_thresholds_exploratory/build_ho_proficiency_thresholds.py',
]
# Hypothetical level weights test how summaries depend on the chosen spacing.
# These are not ODE scale scores, student-level test scores or growth measures.
STRESS = {'Percent proficient': (0,0,1,1), 'Equal 1-4': (1,2,3,4), 'Level 4 premium': (1,2,3,5), 'Strong Level 4 premium': (1,2,3,6), 'Level 1 penalty': (0,2,3,4), 'Compressed middle': (1,1.7,2.3,4), 'Near-pass friendly': (1,2.5,3,4), 'Level 4 only': (0,0,0,1), 'Avoid Level 1': (0,1,1,1)}


def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def key(row):
    if not row.get('District ID') or not row.get('School ID'): raise ValueError('Missing composite school key')
    return row['District ID'] + '::' + row['School ID']
def num(value):
    try:
        n=float(str(value).strip().replace(',',''))
        return n if math.isfinite(n) else None
    except (ValueError, TypeError): return None

def read_asset(base, entry, csv_rows=True):
    rel=Path(entry['path'])
    if rel.is_absolute() or '..' in rel.parts: raise ValueError('Unsafe asset path')
    path=base/rel
    if path.stat().st_size != entry['bytes'] or sha(path) != entry['sha256']: raise ValueError(f'Asset integrity mismatch: {rel}')
    if not csv_rows: return json.loads(path.read_text())
    with path.open(newline='',encoding='utf-8-sig') as f: rows=list(csv.DictReader(f))
    if len(rows) != entry['rows']: raise ValueError(f'Asset row count mismatch: {rel}')
    return rows

def load_release(data_dir=DATA_DIR):
    """Verify frozen hashes, every release row key, profiles, and exact context join."""
    if sha(data_dir/'manifest.json') != MANIFEST_SHA: raise ValueError('Unapproved release manifest; review data changes before fitting')
    manifest=json.loads((data_dir/'manifest.json').read_text())
    if manifest['release_id'] != RELEASE_ID or manifest['assessment_year'] != YEAR: raise ValueError('Release/year mismatch')
    contexts=read_asset(data_dir,manifest['context'])
    context={key(r):r for r in contexts}
    if len(context)!=len(contexts): raise ValueError('Duplicate school-context key')
    profiles=read_asset(data_dir,manifest['school_profile'],False)
    published={r['key']:set(r['grades']) for r in profiles['schools']}
    if len(published)!=len(profiles['schools']): raise ValueError('Duplicate school-profile key')
    observed=collections.defaultdict(set); grade_statuses=collections.defaultdict(set); rows_by_subject={}; receipts=[]
    for subject,entry in manifest['subjects'].items():
        seen=set(); totals=[]; count=0
        for part in entry['parts']:
            rows=read_asset(data_dir,part); count+=len(rows)
            receipts.append({'subject':subject,**part})
            for row in rows:
                row_key=(key(row),row['Grade Level'],row['Student Group'])
                if row_key in seen: raise ValueError(f'Duplicate assessment key: {subject} {row_key}')
                seen.add(row_key)
                if row['Academic Year']!=YEAR or row['Grade Level']!=part['grade']: raise ValueError('Year/grade/official-row mismatch')
                expected={'english':'English Language Arts','math':'Mathematics','science':'Science'}[subject]
                if row['Subject']!=expected: raise ValueError('Subject mismatch')
                if key(row) not in context or row['Context Key']!=key(row).replace('::',':'): raise ValueError('Missing/mismatched context key')
                if row['Record Origin'] not in {'direct_ode','derived_total_minus_sep'}: raise ValueError('Unknown record origin')
                if row['Record Origin']=='derived_total_minus_sep' and row['Student Group']!='Students Not Experiencing Poverty': raise ValueError('Unexpected derived assessment population')
                if row['Student Group'] != TOTAL: continue
                if row['Record Origin']!='direct_ode': raise ValueError('Total population must use official direct ODE rows')
                if row['Grade Level'] != 'All Grades':
                    observed[key(row)].add(row['Grade Level'])
                    grade_statuses[(key(row),row['Grade Level'])].add(row['Observation Status'])
                else: totals.append({**context[key(row)],**row})
        if count != entry['rows']: raise ValueError('Subject row total mismatch')
        rows_by_subject[subject]=sorted(totals,key=key)
    apply_reviewed_grade_profiles(profiles,observed,grade_statuses)
    if dict(observed)!=published: raise ValueError('Packaged profiles differ from independent cross-subject grade union')
    universes={'elementary_primary':{k for k,g in observed.items() if g and g<={'Grade 3','Grade 4','Grade 5'}},
               'middle_sensitivity':{k for k,g in observed.items() if g and g<={'Grade 6','Grade 7','Grade 8'}},
               'all_ordinary_sensitivity':set(observed)}
    for p in profiles['schools']:
        if p['elementary'] != (p['key'] in universes['elementary_primary']): raise ValueError('Elementary profile mismatch')
    return rows_by_subject,universes,manifest,receipts

def apply_reviewed_grade_profiles(profiles,observed,statuses):
    """Apply only documented no-test-only grade exceptions; never drop suppression.

    Original grade rows stay in the assessment CSVs. The reviewed profile keeps
    its original source grades and the reason for each omitted empty grade.
    """
    for review in profiles.get('grade_reviews',[]):
        key=review['key'];source=set(review['source_reported_grades'])
        kept=set(review['included_assessment_grades']);removed=set(review['no_test_grades_removed'])
        if observed.get(key)!=source or source-kept!=removed or kept|removed!=source or kept&removed:
            raise ValueError('Reviewed grade profile does not match source rows')
        if not removed or any(statuses.get((key,g))!={'no_students_tested'} for g in removed):
            raise ValueError('Reviewed grade would omit tested or suppressed students')
        observed[key]=kept

def validate_outcome(row):
    """Missing/suppressed counts omit rows; contradictory numeric counts abort."""
    vals=[num(row.get(f)) for f in LEVELS+['Scored Performance Denominator','Number Proficient']]
    if any(v is None for v in vals):
        if num(row.get('Scored Performance Denominator')) not in (None,0): raise ValueError('Missing level counts with positive scored denominator')
        return None
    if any(v<0 or not float(v).is_integer() for v in vals): raise ValueError('Noninteger or negative outcome count')
    levels=vals[:4]; scored,proficient=vals[4:]
    if sum(levels)!=scored or sum(levels[2:])!=proficient: raise ValueError('Outcome count identities failed')
    if scored==0: return None
    return scored,100*proficient/scored

def census_eligible(row): return row.get('Local Census Context Eligibility','').strip() not in {'ineligible','unresolved'}
def ordinary(row): return common.is_ordinary_regular(row)
def threshold_eligible(row):
    return not any(common._yes(row.get(f)) for f in ('Is Charter School','Is Virtual School','Is Special Enrollment School'))

def get_sep(row,sensitivity='midpoint'):
    if row.get('School Poverty Report Year')!='2025-26': raise ValueError('School SEP vintage mismatch')
    return common.sep_value(row,sensitivity)

def build_points(rows,keys,context,sensitivity):
    """Select complete school rows; return model inputs and exclusion counts.

    y = proficiency percent (0-100); w = scored-student count; ba = tract adult
    BA+ fraction (0-1). context is household income in dollars when requested,
    otherwise enrolled-student SEP percent (0-100). Neither SES measure describes
    individual tested students. Whole-school SEP and scored-student performance
    have different denominators. The returned key is district ID :: school ID.
    """
    points=[]
    d=collections.Counter(profile_schools=len(keys),candidate_all_grades=0,excluded_nonordinary=0,excluded_census_policy=0,unavailable_outcome=0,missing_ba=0,missing_context=0,bounded_sep_included=0)
    for row in rows:
        if key(row) not in keys: continue
        d['candidate_all_grades']+=1
        if not ordinary(row): d['excluded_nonordinary']+=1;continue
        if not census_eligible(row): d['excluded_census_policy']+=1;continue
        outcome=validate_outcome(row)
        if outcome is None: d['unavailable_outcome']+=1;continue
        ba=num(row.get('ACS_Ed_BA_or_Higher_Rate'))
        if ba is None: d['missing_ba']+=1;continue
        if not 0<=ba<=1 or row.get('ACS_Release_Years')!='2020-2024': raise ValueError('BA units or vintage mismatch')
        value=num(row.get('ACS_Median_Household_Income')) if context=='income' else get_sep(row,sensitivity)
        if value is None or (context=='income' and value<=0): d['missing_context']+=1;continue
        if context=='sep_percent' and row['Students Experiencing Poverty Value Status']=='left_censored_midpoint': d['bounded_sep_included']+=1
        scored,y=outcome
        points.append({'key':key(row),'school':row['School'],'district':row['District'],'y':y,'w':scored,'ba':ba,'context':value,'source_refs':row['Source Refs'],'sep_status':row['Students Experiencing Poverty Value Status'] if context=='sep_percent' else ''})
    d['complete_schools']=len(points)
    assert d['candidate_all_grades']==sum(d[x] for x in ('excluded_nonordinary','excluded_census_policy','unavailable_outcome','missing_ba','missing_context','complete_schools'))
    return points,dict(d)

def numpy_fit(points,names):
    """Independent weighted least-squares fit in the predictors' original units.

    Return intercept/slopes (in names order), fitted y values and weighted R2.
    Multiplying each row by sqrt(w) gives scored-student-weighted least squares.
    """
    x=np.array([[1]+[float(p[n]) for n in names] for p in points]); y=np.array([p['y'] for p in points]); w=np.array([p['w'] for p in points]); root=np.sqrt(w)
    coefs=np.linalg.lstsq(x*root[:,None],y*root,rcond=None)[0];pred=x@coefs
    r2=1-np.sum(w*(y-pred)**2)/np.sum(w*(y-np.average(y,weights=w))**2)
    return coefs,pred,float(r2)

def weighted_corr(x,y,w):
    x=np.asarray(x);y=np.asarray(y);w=np.asarray(w)
    xm=np.average(x,weights=w);ym=np.average(y,weights=w)
    return float(np.average((x-xm)*(y-ym),weights=w)/math.sqrt(np.average((x-xm)**2,weights=w)*np.average((y-ym)**2,weights=w)))

def model_result(subject,universe,context,sensitivity,points,diagnostics):
    """Summarize one sample/model, with refitting and held-out prediction checks.

    Standardized betas compare predictors on a common scale. Each CV repeat
    reshuffles schools into five groups and predicts each group from the other
    four. Twenty independently reshuffled half-splits produce forty additional
    fits. These repeated-split ranges describe stability, not confidence limits.
    """
    names=['context','ba']; coefs,r2=common.fit_model(points,names)
    cv=common.repeated_cv(points,names,FOLDS,REPEATS,SEED)
    split=common.split_coefficients(points,names,REPEATS,SEED)
    if len(cv)!=REPEATS or len(split)!=2*REPEATS: raise ValueError('Incomplete CV or split repetitions')
    nc,npred,nr2=numpy_fit(points,names)
    y=np.array([p['y'] for p in points]);w=np.array([p['w'] for p in points]);ysd=math.sqrt(np.average((y-np.average(y,weights=w))**2,weights=w))
    beta=[]
    for i,name in enumerate(names,1):
        x=np.array([p[name] for p in points]); beta.append(float(nc[i]*math.sqrt(np.average((x-np.average(x,weights=w))**2,weights=w))/ysd))
    if abs(r2-nr2)>1e-10 or max(abs(a-b) for a,b in zip(coefs[1:],beta))>1e-10: raise ValueError('Independent numpy WLS crosscheck failed')
    return {'subject':SUBJECTS[subject],'subject_key':subject,'universe':universe,'context':context,'sep_sensitivity':sensitivity,'n_schools':len(points),'scored_students':int(sum(p['w'] for p in points)),'beta_context':coefs[1],'beta_ba':coefs[2],'in_sample_r2':r2,'cv_r2_mean':sum(cv)/len(cv),'cv_r2_p05':common.percentile(cv,.05),'cv_r2_p95':common.percentile(cv,.95),'split_beta_context_p05':common.percentile([c[1] for c in split],.05),'split_beta_context_p95':common.percentile([c[1] for c in split],.95),'split_beta_ba_p05':common.percentile([c[2] for c in split],.05),'split_beta_ba_p95':common.percentile([c[2] for c in split],.95),'cv_folds':FOLDS,'cv_repeats':REPEATS,'cv_seed':SEED,'numpy_r2_abs_difference':abs(r2-nr2),**diagnostics}

def two_factor_result(subject,universe,sensitivity,points):
    """Compare BA+, SEP and their joint model using exactly the same schools.

    A BA residual is observed proficiency minus its BA-only fitted value, in
    percentage points. Regressing that residual on raw SEP is a descriptive
    follow-up; its slope is NOT the SEP coefficient from the joint model.
    """
    ba_coef,ba_pred,ba_r2=numpy_fit(points,['ba']);pov_coef,pov_pred,pov_r2=numpy_fit(points,['context']);joint_coef,joint_pred,joint_r2=numpy_fit(points,['context','ba'])
    y=np.array([p['y'] for p in points]);w=np.array([p['w'] for p in points]);ba=np.array([p['ba'] for p in points]);pov=np.array([p['context'] for p in points]);res=y-ba_pred
    residual_points=[{**p,'y':float(r)} for p,r in zip(points,res)]
    _,_,res_fit=numpy_fit(residual_points,['context']);res_coef,_,_=numpy_fit(residual_points,['context'])
    low=pov<20;high=pov>=40
    mean_low=float(np.average(res[low],weights=w[low])) if low.any() else None
    mean_high=float(np.average(res[high],weights=w[high])) if high.any() else None
    # BA is a fraction: +10 percentage points is +0.1; SEP is percent: it is +10.
    result={'subject':SUBJECTS[subject],'subject_key':subject,'universe':universe,'sep_sensitivity':sensitivity,'n_schools':len(points),'scored_students':int(w.sum()),'r2_ba_only':ba_r2,'r2_poverty_only':pov_r2,'r2_joint':joint_r2,'delta_r2_ba_after_poverty':joint_r2-pov_r2,'delta_r2_poverty_after_ba':joint_r2-ba_r2,'joint_slope_ba_per_10_percentage_points':float(joint_coef[2]*.1),'joint_slope_poverty_per_10_percentage_points':float(joint_coef[1]*10),'ba_poverty_r':weighted_corr(ba,pov,w),'residual_vs_poverty_r':weighted_corr(pov,res,w),'residual_vs_poverty_slope_per_10_percentage_points':float(res_coef[1]*10),'ba_only_slope_per_10_percentage_points':float(ba_coef[1]*.1),'residual_sd':float(math.sqrt(np.average(res**2,weights=w))),'mean_residual_low_poverty_lt20':mean_low,'mean_residual_high_poverty_ge40':mean_high,'high_minus_low_residual':None if mean_low is None or mean_high is None else mean_high-mean_low,'weighted_mean_residual':float(np.average(res,weights=w))}
    if abs(result['weighted_mean_residual'])>1e-8: raise ValueError('Residual centering check failed')
    detail=[{'subject':SUBJECTS[subject],'universe':universe,'sep_sensitivity':sensitivity,**p,'predicted_from_ba':float(pred),'ba_residual':float(r)} for p,pred,r in zip(points,ba_pred,res)]
    return result,detail

def exact_ranks(values):
    """Average ranks with rational equality; float ordering must not split ties."""
    counts=collections.Counter(values);ranks={};before=0
    for value in sorted(counts):
        ranks[value]=before+(counts[value]+1)/2;before+=counts[value]
    return np.array([ranks[v] for v in values],dtype=float)

def threshold_analysis(rows_by_subject,universes):
    """Ask what proficiency (Level 3+4) conceals about the full distribution.

    Core displays need >=30 scored students and no charter, virtual or special-
    enrollment flag, but do not require census context. The 1-4 index averages
    hypothetical equally spaced values over the four level counts. near_cut_pct
    is the share in Levels 2+3; it is not distance from a test-score cut point.
    """
    records=[];diagnostics=[]
    for subject,rows in rows_by_subject.items():
        d=collections.Counter(subject=SUBJECTS[subject],candidate_all_grades=len(rows),excluded_flags=0,unavailable_outcome=0,under_30_scored=0,included=0)
        for row in rows:
            if not threshold_eligible(row):d['excluded_flags']+=1;continue
            outcome=validate_outcome(row)
            if outcome is None:d['unavailable_outcome']+=1;continue
            w,y=outcome
            if w<30:d['under_30_scored']+=1;continue
            d['included']+=1
            levels=[int(row[f]) for f in LEVELS]
            allowed=census_eligible(row)
            ba=num(row.get('ACS_Ed_BA_or_Higher_Rate')) if allowed else None
            sep=get_sep(row)
            rec={'subject':SUBJECTS[subject],'key':key(row),'school':row['School'],'district':row['District'],'w':w,'pct_proficient':y,'level_index':sum((i+1)*v for i,v in enumerate(levels))/w,'near_cut_pct':100*(levels[1]+levels[2])/w,'ba':ba,'sep':sep,'census_eligible':allowed,'ordinary_regular':ordinary(row),'elementary':key(row) in universes['elementary_primary'],'middle':key(row) in universes['middle_sensitivity'],'source_refs':row['Source Refs']}
            rec.update({f'count_l{i+1}':v for i,v in enumerate(levels)});rec.update({f'pct_l{i+1}':100*v/w for i,v in enumerate(levels)})
            records.append(rec)
        diagnostics.append(dict(d))
    summary=[];pairs=[];correlations=[];stress=[]
    for subject in SUBJECTS.values():
        rs=[r for r in records if r['subject']==subject]; weights=np.array([r['w'] for r in rs]); n=weights.sum()
        agg={'subject':subject,'n_schools':len(rs),'scored_students':int(n)}
        for f in ['pct_proficient','level_index','near_cut_pct']+[f'pct_l{i}' for i in range(1,5)]:agg[f]=float(np.average([r[f] for r in rs],weights=weights))
        agg['median_school_near_cut_pct']=float(np.median([r['near_cut_pct'] for r in rs]));agg['share_schools_near_cut_ge50']=100*sum(r['near_cut_pct']>=50 for r in rs)/len(rs);agg['weighted_corr_proficient_index']=weighted_corr([r['pct_proficient'] for r in rs],[r['level_index'] for r in rs],weights)
        summary.append(agg)
        # Among schools with >=80 scored students, find the largest index gap
        # within one proficiency percentage point. These are illustrative extremes.
        candidates=sorted([r for r in rs if r['w']>=80],key=lambda r:(r['pct_proficient'],r['key'])); best=None
        for i,a in enumerate(candidates):
            close=[r for r in candidates[i:] if r['pct_proficient']<=a['pct_proficient']+1]
            if len(close)<2:continue
            low=min(close,key=lambda r:r['level_index']);high=max(close,key=lambda r:r['level_index']);diff=high['level_index']-low['level_index']
            if best is None or diff>best[0]:best=(diff,low,high)
        if best:
            for role,r in zip(['lower_index','higher_index'],best[1:]):pairs.append({**r,'comparison_role':role,'index_difference_with_pair':best[0]})
        for scope in ['elementary_primary','middle_sensitivity','all_school_sensitivity']:
            scoped=[r for r in rs if scope=='all_school_sensitivity' or (r['ordinary_regular'] and r['elementary' if scope=='elementary_primary' else 'middle'])]
            for predictor in ['ba','sep']:
                use=[r for r in scoped if r[predictor] is not None]
                if len(use)<3:continue
                for outcome in ['pct_proficient','level_index','pct_l4','pct_l1','near_cut_pct']:
                    correlations.append({'subject':subject,'universe':scope,'predictor':predictor,'outcome':outcome,'n_schools':len(use),'scored_students':int(sum(r['w'] for r in use)),'weighted_r':weighted_corr([r[predictor] for r in use],[r[outcome] for r in use],[r['w'] for r in use])})
        equal=np.array([r['level_index'] for r in rs]);counts=np.array([[r[f'count_l{i}'] for i in range(1,5)] for r in rs]);equal_ranks=exact_ranks([Fraction(sum(i*r[f'count_l{i}'] for i in range(1,5)),int(r['w'])) for r in rs])
        # Exact rational ranks keep ties intact. Rank correlation weights schools
        # equally; the synthetic-score mean still weights by scored students.
        for label,scores in STRESS.items():
            rational_values=[sum(Fraction(str(scores[i-1]))*r[f'count_l{i}'] for i in range(1,5))/int(r['w']) for r in rs]
            values=np.array([float(v) for v in rational_values])
            stress.append({'subject':subject,'scheme':label,'level_scores':';'.join(map(str,scores)),'weighted_mean':float(np.average(values,weights=weights)),'rank_corr_vs_equal_index':weighted_corr(equal_ranks,exact_ranks(rational_values),np.ones(len(rs)))})
    return {'summary':summary,'pairs':pairs,'correlations':correlations,'stress':stress,'coverage':diagnostics,'school_rows':records}

METHODS = {
 'assessment_year':YEAR,'acs_vintage':'2020–2024','school_sep_year':'2025–26','attendance_used':False,
 'outcome':'Percent proficient = 100 × (Level 3 + Level 4) / Scored Performance Denominator; exact integer count identities required.',
 'unit':'One official Total Population All Grades school record per subject, including Science. Grade-level rows classify school span only; they are never summed into outcomes.',
 'primary_population':'Ordinary ODE Regular elementary school sites, classified from the union of observed Total Population grades across all three subjects: at least one grade 3–5 and no observed grade outside 3–5. Charter, true virtual, special-enrollment, and reviewed census-ineligible or unresolved sites are excluded.',
 'sensitivity':'Ordinary middle-only sites (observed grades 6–8) are a separate sensitivity. The BA+/SEP companion additionally shows all ordinary sites as a weaker-geographic-linkage sensitivity, including high/combined schools; it is not a replacement for the elementary results.',
 'weights':'Scored students for achievement means, regression, correlation and held-out R². Participants and enrollment are distinct populations and are never achievement weights.',
 'geography':'BA+ and household income describe adults/households in the census tract containing the school site, not necessarily enrolled students’ residences or families.',
 'sep':'Whole-school enrolled-student poverty from May 2025–26 enrollment, not the scored-cohort SEP share. Numeric SEP rates are whole-percent rounded disclosures; exact means numeric rather than interval, not unrounded truth. <5 uses a 2.5 midpoint, with lower-endpoint (0), upper-bound (5, an upper-limit sensitivity), and exact-only checks.',
 'suppression':'Unavailable/suppressed assessment counts are omitted, never zero-filled or reconstructed. Only SEP context inequalities receive documented midpoint treatment.',
 'joint_models':'Income+BA and SEP+BA use model-specific complete cases. Standardized coefficients scale both predictors and outcome. Single-factor and joint BA+/SEP fits use exactly the same complete-case school set.',
 'validation':'Twenty repeated five-fold school-row cross-validations, seed 20260910, training-only scaling. Repeat p05–p95 is descriptive split variation, not a confidence interval. These are not district-held-out tests. Random-half coefficient ranges use twenty repeats (40 half-sample fits).',
 'residual':'Observed minus BA-only predicted proficiency, in percentage points. Residual correlation with raw SEP is not a partial correlation and is not the adjusted SEP coefficient. Residuals are not school quality, individual growth or causal effects.',
 'threshold':'Core proficiency-threshold displays use all school sites with at least 30 scored students, excluding charter, virtual and special-enrollment flags. They do not require census context. Same-proficiency pairs require at least 80 scored students and at most one percentage point difference; maximum index-gap pairs are illustrative extremes, not representative schools. The four-level index and alternate spacings are synthetic sensitivity measures, not interval-scale test scores. Synthetic-score rank comparisons use exact rational arithmetic and average ranks to preserve ties.',
 'threshold_context':'SES correlations are separate from the core distributions: elementary ordinary schools are primary; middle and broad all-school scopes are sensitivities. BA+ requires usable, policy-eligible tract context; SEP remains a school measure and does not require tract context.',
 'comparability':'These are new-year descriptive analyses, not matched-school estimates of year-to-year change. Eligibility, context vintage, school composition, tested cohorts and suppression may differ from 2024–25. No attendance-adjusted claim is made.',
 'uncertainty':'No sampling confidence intervals are claimed. Cross-validation and half-split ranges assess reproducibility under school splits, not sampling, census estimate, measurement or causal uncertainty.',
}

def write_csv(path,rows):
    if not rows:raise ValueError(f'No rows: {path}')
    fields=list(dict.fromkeys(k for r in rows for k in r))
    with path.open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(rows)

def plots(out,results,two,threshold,residuals):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    plt.rcParams.update({'font.size':15,'axes.titlesize':19,'axes.labelsize':16,'legend.fontsize':13})
    assets=[]
    primary=[r for r in two if r['universe']=='elementary_primary' and r['sep_sensitivity']=='midpoint']
    fig,ax=plt.subplots(figsize=(11,6.5));x=np.arange(3);width=.25
    for i,(field,label,color) in enumerate([('r2_ba_only','Tract BA+','#287f78'),('r2_poverty_only','School enrollment SEP','#bb7931'),('r2_joint','BA+ and SEP together','#466d9a')]):
        vals=[r[field] for r in primary];bars=ax.bar(x+(i-1)*width,vals,width,label=label,color=color)
        ax.bar_label(bars,labels=[f'{v:.3f}' for v in vals],padding=5,fontsize=13)
    ax.set_xticks(x,[r['subject'] for r in primary]);ax.set_ylim(0,1);ax.set_ylabel('In-sample weighted R²');ax.set_title('2025–26: two SES measures and school proficiency',pad=20);ax.legend(loc='upper left');ax.spines[['top','right']].set_visible(False)
    fig.text(.12,.02,'Ordinary elementary schools · same schools in all three fits · scored-student weights\nDescriptive association; no causal interpretation. ACS 2020–2024; school SEP 2025–26.',fontsize=12);fig.subplots_adjust(bottom=.2,top=.87)
    fig.savefig(out/'two_factor_r2.svg');plt.close(fig);assets.append({'file':'two_factor_r2.svg','alt':'In-sample R-squared for BA+, school enrollment poverty, and their joint model, by subject; ordinary elementary schools.'})
    fig,axs=plt.subplots(1,3,figsize=(14,5.4),sharex=True,sharey=True)
    for ax,subject in zip(axs,SUBJECTS.values()):
        rs=[r for r in residuals if r['subject']==subject and r['universe']=='elementary_primary' and r['sep_sensitivity']=='midpoint']
        ax.scatter([r['context'] for r in rs],[r['ba_residual'] for r in rs],s=[min(55,max(9,math.sqrt(r['w'])*1.5)) for r in rs],alpha=.4,c='#26796e',edgecolors='none');ax.axhline(0,c='#777',lw=1);ax.set_title(subject);ax.set_xlabel('School enrollment SEP (%)');ax.spines[['top','right']].set_visible(False)
    axs[0].set_ylabel('BA-only residual (percentage points)');fig.suptitle('2025–26: poverty and differences from the BA-only line',fontsize=20);fig.text(.09,.02,'Ordinary elementary schools · dots are schools; size reflects scored students · residuals are descriptive, not school quality.',fontsize=12);fig.subplots_adjust(top=.8,bottom=.23,wspace=.1);fig.savefig(out/'ba_residuals.svg');plt.close(fig);assets.append({'file':'ba_residuals.svg','alt':'School proficiency residuals from the BA-only line plotted against school enrollment poverty, separately by subject.'})
    fig,ax=plt.subplots(figsize=(11,6.5));left=np.zeros(3);ys=np.arange(3);colors=['#b84b51','#d8a16a','#79a691','#287b68']
    for i in range(1,5):
        vals=[r[f'pct_l{i}'] for r in threshold['summary']];ax.barh(ys,vals,left=left,color=colors[i-1],label=f'Level {i}')
        for j,v in enumerate(vals):ax.text(101.5 if v<8 else left[j]+v/2,j,f'{v:.1f}%',ha='left' if v<8 else 'center',va='center',color='#172923' if v<8 else ('white' if i in (1,4) else '#172923'),fontsize=15)
        left+=vals
    ax.set_yticks(ys,[r['subject'] for r in threshold['summary']]);ax.invert_yaxis();ax.set_xlim(0,110);ax.set_xticks(np.arange(0,101,20));ax.set_xlabel('Share of scored students (%)');ax.set_title('2025–26 achievement: proficiency combines Levels 3 and 4',pad=22);ax.legend(ncol=4,bbox_to_anchor=(.5,-.18),loc='upper center',frameon=False);ax.spines[['top','right']].set_visible(False)
    fig.text(.14,.02,'All eligible school sites with ≥30 scored students · charter, virtual and special-enrollment excluded\nScored-student weighted; subjects have separate samples. Attendance is not used.',fontsize=12);fig.subplots_adjust(left=.15,bottom=.29,top=.84);fig.savefig(out/'threshold_level_shares.svg');plt.close(fig);assets.append({'file':'threshold_level_shares.svg','alt':'Four achievement-level shares by subject in the eligible 2025–26 all-school sample.'})
    fig,ax=plt.subplots(figsize=(11,7))
    for subject,color in zip(SUBJECTS.values(),['#287f78','#466d9a','#b84b51']):
        rs=[r for r in threshold['school_rows'] if r['subject']==subject]
        ax.scatter([r['pct_proficient'] for r in rs],[r['level_index'] for r in rs],s=[min(65,max(8,math.sqrt(r['w'])*1.2)) for r in rs],alpha=.28,c=color,edgecolors='none',label=subject)
    ax.set_xlim(0,100);ax.set_ylim(1,4);ax.set_xlabel('Percent proficient');ax.set_ylabel('Synthetic four-level index');ax.set_title('2025–26: similar proficiency can conceal different distributions',pad=20);ax.legend();ax.spines[['top','right']].set_visible(False)
    fig.text(.12,.02,'Index assigns Levels 1–4 the scores 1, 2, 3, 4; these are assumed spacings, not test scores.\nSame all-school eligibility as level-share chart; dots are schools and size reflects scored students.',fontsize=12);fig.subplots_adjust(bottom=.2,top=.86);fig.savefig(out/'threshold_proficiency_vs_index.svg');plt.close(fig);assets.append({'file':'threshold_proficiency_vs_index.svg','alt':'School proficiency compared with a synthetic four-level index; vertical spread illustrates different level distributions at similar proficiency.'})
    return assets

def write_reports(out,joint,two,threshold):
    """Readable companions generated from the same already-calculated results."""
    import textwrap
    scopes={'elementary_primary':'Elementary schools (main sample)', 'middle_sensitivity':'Middle schools (additional check)', 'all_ordinary_sensitivity':'All ordinary schools (additional check)'}
    treatments={'as_reported':'income as reported', 'midpoint':'SEP below 5% represented by 2.5%', 'lower_endpoint':'SEP below 5% represented by 0%', 'upper_endpoint':'SEP below 5% represented by 5% (upper-limit check)', 'exact_only':'numeric SEP disclosures only; these are still rounded'}
    def save(name,title,blocks):
        paragraphs=[title+' — 2025–26','Assessments and school enrollment poverty: 2025–26. Census ACS: 2020–2024.']+blocks+['REPRODUCTION RECORD', 'Release: '+RELEASE_ID, 'Manifest SHA-256: '+MANIFEST_SHA, 'Complete column definitions and file guidance: ../analysis-downloads.html. Numerical CSV files retain unrounded values.']
        text='\n\n'.join('\n'.join(textwrap.fill(line,width=88,break_long_words=False,break_on_hyphens=False) for line in block.splitlines()) for block in paragraphs)+'\n'
        # A UTF-8 signature lets browsers detect Unicode even on simple local servers.
        (out/(name+'.txt')).write_text(text,encoding='utf-8-sig')
        return name+'.txt'
    outcome='Proficiency is the percentage of students with reported Level 1–4 results who reached Level 3 or 4. Each school contributes its official Total Population All Grades result for the subject. The denominator and weight are the number of students with those scored results, not enrollment or test-participation counts.'
    context='BA+ is the share of adults aged 25 or older with a bachelor’s degree or higher in the census tract containing the school. Income is that tract’s median household income. These are neighborhood measures, not direct measures of students’ families. School poverty (SEP) is the percentage of all enrolled students identified by ODE as Students Experiencing Poverty.'
    samples='The main model sample is schools classified by ODE as Regular, with reported tested grades confined to 3–5 across the three subjects. Charter, virtual, special-enrollment and census-ineligible or unresolved sites are excluded. Separate middle-school checks use grades 6–8. Each model needs complete values for its own measures, so different model families can include different schools.'
    limits='These are descriptive comparisons among schools. They do not estimate the effects of changing family circumstances, school quality or individual learning. No annual attendance values are used. These analyses do not track a fixed set of schools to measure change from 2024–25.'
    validation='Prediction: for each of 20 rounds, reshuffle all schools into five groups. Fit on four groups and predict the fifth, rotating until every school has a prediction from a fit that excluded its result. Each round yields one pooled, scored-student-weighted R². Groups contain schools, not whole districts. The averages and standard deviations used to rescale the measures come only from the schools used to fit the model. Random halves: reshuffle the complete list separately for each of 20 repetitions and fit both halves, yielding 40 fits. The starting seed is 20260910. Ranges below are 5th–95th percentiles across repeats or halves, not confidence intervals.'
    glossary='R² summarizes how closely estimated proficiency matches reported proficiency across schools; higher values mean closer fit. Standardized coefficients put income, BA+ and proficiency on a common scale using the spread of their values across schools. A coefficient of 0.50 means a one-standard-deviation difference in that measure corresponds to a predicted proficiency difference of half a proficiency standard deviation, at the same value of the other measure. This is an illustrative example, not a reported result. A positive coefficient means higher estimated proficiency at higher values of that measure. Larger schools have proportionally greater influence through their scored-student counts.'
    sections={}
    for slug,title in [('income_education_joint_model','Income, adult education and school proficiency'),('income_education_split_stability','Stability of associations across school samples')]:
        question=('How closely do neighborhood income and adult education together describe school proficiency, and does the model predict schools whose results were excluded from fitting?' if 'split' not in slug else 'Does the relative size of the income and BA+ associations depend strongly on which schools are included? Repeated random halves test this dependence. The separate held-out prediction check tests prediction rather than coefficient stability.')
        main=[r for r in joint if r['universe']=='elementary_primary' and r['context']=='income']
        additional=[r for r in joint if r not in main]
        finding=('Across all three subjects, prediction for schools left out of fitting is nearly as accurate as fit to the model’s own schools. This supports the usefulness of the association within this school sample; it does not test future years or entirely new districts.' if 'split' not in slug else 'Across all three subjects, the BA+ association is larger than the income association on the common scale. The 5th–95th percentile ranges from the 40 half-sample fits do not overlap: the lower end of the BA+ range exceeds the upper end of the income range. These are repeat-split ranges, not confidence intervals.')
        blocks=['QUESTION',question,'MAIN FINDING',finding,'MEASURES AND SCHOOLS',outcome,context,samples,'HOW TO READ THE NUMBERS',glossary,validation,'MAIN RESULTS: ELEMENTARY SCHOOLS, INCOME AND BA+','The three subject results below are the main comparison. Each subject has its own eligible school sample.']
        for i,r in enumerate(main+additional):
            if i==len(main):blocks+=['ADDITIONAL CHECKS','The remaining results use school poverty instead of income, different treatments of below-5% poverty disclosures, or middle schools. Their school samples can differ. Compare model performance on the same schools before attributing a difference to the choice of measure.']
            predictor='Income' if r['context']=='income' else 'School poverty'
            lines=[f"{r['subject']} — {scopes[r['universe']]} — {predictor} and BA+",f"Disclosure treatment: {treatments[r['sep_sensitivity']]}",f"Schools: {r['n_schools']:,}; scored students: {r['scored_students']:,}.",f"Standardized coefficients: {predictor} {r['beta_context']:.3f}; BA+ {r['beta_ba']:.3f}.",f"Fit to the model’s own schools (R²): {r['in_sample_r2']:.3f}.",f"Held-out prediction R²: mean {r['cv_r2_mean']:.3f}; repeated-split range {r['cv_r2_p05']:.3f} to {r['cv_r2_p95']:.3f}."]
            if 'split' in slug:lines.append(f"Random-half coefficient ranges: {predictor} {r['split_beta_context_p05']:.3f} to {r['split_beta_context_p95']:.3f}; BA+ {r['split_beta_ba_p05']:.3f} to {r['split_beta_ba_p95']:.3f}.")
            blocks.append('\n'.join(lines))
        blocks+=['LIMITS',limits,'DATA FILES','joint_models.csv: all fits, ranges and coverage counts. model_school_rows.csv: school inputs, repeated across model variants. Filter by subject, sample, context and disclosure treatment before counting schools or students.']
        sections[slug]=save(slug,title,blocks)
    blocks=['QUESTION','Does school enrollment poverty add information beyond neighborhood adult education, and does adult education add information beyond poverty? Three fits use exactly the same schools within each comparison.','MAIN FINDING','In each subject, school poverty alone fits more closely than adult education alone, and the model using both fits more closely than either separately. Each subject’s three fits use the same schools. The two measures overlap in what they describe, so their separate R² values cannot be added.','MEASURES AND SCHOOLS',outcome,context,samples,'HOW TO READ THE NUMBERS',glossary,'A residual is reported proficiency minus the BA+-only prediction, in percentage points. Its correlation with poverty is a diagnostic of what that model misses. Because poverty is left unadjusted, this is not the poverty association holding BA+ fixed. Adjusted slopes are in two_factor.csv.','RESULTS','Elementary schools with the documented 2.5% midpoint for SEP below 5% are the main comparison. Endpoint treatments, numeric-only disclosures, middle schools and the broader ordinary-school sample are additional checks.']
    ordered=[r for r in two if r['universe']=='elementary_primary' and r['sep_sensitivity']=='midpoint']+[r for r in two if not (r['universe']=='elementary_primary' and r['sep_sensitivity']=='midpoint')]
    for i,r in enumerate(ordered):
        if i==3:blocks+=['ADDITIONAL CHECKS','The remaining fits vary the treatment of imprecise poverty disclosures or use middle schools and a broader school sample. Within each row, all three R² values still use the same schools.']
        blocks.append('\n'.join([f"{r['subject']} — {scopes[r['universe']]}",f"Disclosure treatment: {treatments[r['sep_sensitivity']]}",f"Schools: {r['n_schools']:,}; scored students: {r['scored_students']:,}.",f"R²: BA+ alone {r['r2_ba_only']:.3f}; poverty alone {r['r2_poverty_only']:.3f}; both {r['r2_joint']:.3f}.",f"Correlation of the BA+-only residual with poverty: {r['residual_vs_poverty_r']:.3f}.",f"Residual difference per 10 percentage points of school poverty: {r['residual_vs_poverty_slope_per_10_percentage_points']:.2f} proficiency percentage points."]))
    blocks+=['LIMITS',limits,'Adding both measures can describe more variation without assigning causal responsibility to either. School-site census context may be a weaker proxy at middle, high and combined-grade schools. Numeric SEP disclosures are rounded; below-5% midpoints are working estimates, not exact observations.','DATA FILES','two_factor.csv: all fits and adjusted slopes. ba_residual_school_rows.csv: observed proficiency, BA+-only predictions and residuals.']
    sections['ba_school_poverty_two_factor']=save('ba_school_poverty_two_factor','Adult education, school poverty and proficiency',blocks)
    blocks=['QUESTION','What does a single proficiency percentage leave out about the distribution of achievement across Levels 1–4?','MAIN FINDING','A single proficiency percentage can conceal quite different distributions across the four levels. The school pairs below were deliberately selected to show large contrasts at nearly the same proficiency rate; they do not tell us how common such contrasts are.','MEASURES AND SCHOOLS',outcome,'The core distribution sample includes all school types with at least 30 scored students, except charter, virtual and special-enrollment sites. It does not require census context. Each subject has its own sample; aggregate level shares pool the scored-student counts.','HOW TO READ THE NUMBERS','Proficiency combines Levels 3 and 4. The constructed index assigns Levels 1–4 the values 1, 2, 3 and 4 and averages them using scored-student counts. It helps select schools with similar proficiency but contrasting distributions. It is not an actual test-score average; equal gaps between levels are an assumption. For illustration, 50% at Level 1 and 50% at Level 3 gives 50% proficiency and an index of 2. A different distribution with 50% at Level 2 and 50% at Level 4 also gives 50% proficiency, but an index of 3. These are made-up examples to explain the index.','The Level 2+3 share counts students in the two categories adjacent to the proficiency threshold. It does not show how close their individual scores are to the cut score.','CORE DISTRIBUTIONS']
    for r in threshold['summary']:
        blocks.append('\n'.join([f"{r['subject']}: {r['n_schools']:,} schools; {r['scored_students']:,} scored students.",f"Proficient: {r['pct_proficient']:.1f}%.",'Level shares: '+', '.join(f"Level {i}: {r[f'pct_l{i}']:.1f}%" for i in range(1,5))+'.',f"Level 2+3 share: {r['near_cut_pct']:.1f}%.",f"Weighted correlation between proficiency and the four-level index: {r['weighted_corr_proficient_index']:.3f}."]))
    blocks+=['ILLUSTRATIVE SCHOOL PAIRS','One pair per subject is selected for the largest index gap among schools within one percentage point of proficiency, each with at least 80 scored students. These deliberately selected contrasts may involve different grades and school types. They are not representative pairs or rankings of school quality.']
    for r in threshold['pairs']:
        blocks.append(f"{r['subject']} — {r['school']} ({r['district']})\nScored students: {r['w']:.0f}; proficient: {r['pct_proficient']:.2f}%; constructed index: {r['level_index']:.3f}; Level 4: {r['pct_l4']:.2f}%.")
    blocks+=['ADDITIONAL CHECKS','threshold_stress.csv changes the assigned level values to test how much school ordering depends on the spacing assumption. threshold_correlations.csv compares the associations of BA+ and SEP with proficiency, the index and level shares. Those context comparisons use separate eligible school samples; they are not the pooled distribution totals.',context,'LIMITS',limits,'The attendance-correlation portion awaits detailed 2025–26 attendance data. No older attendance values are substituted.','DATA FILES','threshold_summary.csv: pooled distributions. threshold_pairs.csv: selected pairs. threshold_school_rows.csv: all eligible school inputs. threshold_coverage.csv: exclusions. threshold_correlations.csv: context comparisons. threshold_stress.csv: alternative level assignments.']
    sections['proficiency_thresholds']=save('proficiency_thresholds','What a proficiency threshold leaves out',blocks)
    return sections


def refresh_companions(out):
    """Refresh documentation only after checking the existing registered assets."""
    summary=json.loads((out/'summary.json').read_text())
    if summary['manifest_sha256']!=MANIFEST_SHA or summary['release_id']!=RELEASE_ID:
        raise ValueError('Companion refresh requires the approved numerical release')
    for entry in summary['downloads']:
        # Older refreshes could accidentally register local import bytecode.
        # It is not a scientific output or a distributable source file.
        if '__pycache__' in Path(entry['file']).parts or Path(entry['file']).suffix == '.pyc':
            continue
        p=out/entry['file']
        if not p.is_file() or sha(p)!=entry['sha256']:
            raise ValueError('Registered output changed before companion refresh: '+entry['file'])
    threshold={name:summary['threshold_'+name] for name in ['summary','pairs']}
    summary['text_reports']=write_reports(out,summary['joint_models'],summary['two_factor'],threshold)
    bundle_scripts(out)
    summary['source_scripts']=source_references()
    summary['downloads']=[{'file':str(p.relative_to(out)),'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted(out.rglob('*')) if p.is_file() and p.name!='summary.json' and '__pycache__' not in p.parts and p.suffix != '.pyc']
    (out/'summary.json').write_text(json.dumps(summary,indent=2,ensure_ascii=False,allow_nan=False)+'\n')
    print('Refreshed report text, reproduction scripts and output hashes; no models rerun.')
    return summary


def source_references():
    if all((ROOT/p).is_file() for p in SOURCES):
        return [{'path':p,'sha256':sha(ROOT/p)} for p in SOURCES]
    bundled=Path(__file__).resolve().parent/'source_references.json'
    if not bundled.is_file(): raise ValueError('Missing source reference inventory')
    return json.loads(bundled.read_text())

def bundle_scripts(out):
    dictionary=ROOT/'scripts/release_inputs/2025-26-analysis-downloads.json'
    if dictionary.is_file(): (out/'data_dictionary.json').write_bytes(dictionary.read_bytes())
    folder=out/'scripts'; folder.mkdir(exist_ok=True)
    for source in [Path(__file__),Path(common.__file__)]:
        target=folder/source.name
        if target.resolve()!=source.resolve(): target.write_bytes(source.read_bytes())
    (folder/'source_references.json').write_text(json.dumps(source_references(),indent=2)+'\n')
    (folder/'README.txt').write_text("""Reproducing the 2025–26 non-attendance analyses
================================================
Instructions revised: November 13, 2026.

Assessments and school enrollment poverty: 2025–26. Neighborhood census
context: ACS 2020–2024. This runner uses no annual attendance data.

Download both Python files and source_references.json into one directory.
Requires Python 3.10+ with numpy, pandas and matplotlib installed.

Input manifest: /data/processed/releases/2025-26/manifest.json on this site.
Open /releases/2025-26/analysis-downloads.html on this site for clickable input
links and CSV definitions. Download the public release input directory
data/processed/releases/2025-26,
retaining manifest.json, school-context.csv, school-profiles.json and every
assessment CSV part listed in manifest.json. The runner verifies the approved
manifest SHA-256 plus each input byte count, hash and row count. Tract geometry
is not needed. Use the part paths relative to the manifest directory; preserve those
subdirectories locally. The input directory is approximately 86 MB and is not duplicated
inside this source bundle. No API key, private file or network request is used.

Run (substitute your actual local directory names):
python3 release_2025_26_analyses.py --data-dir ./release-inputs/2025-26 --output-dir ./reproduced-results --audit-dir ./reproduced-audit

Outputs and report versions
---------------------------
The command creates numerical CSVs, the four original analytical TXT records
listed below, SVG plots, summary.json, a scripts folder and audit receipts.
The scripts folder contains the runner, numerical helpers, these instructions
and source_references.json. Same-name outputs in the chosen directories are
replaced. Use fresh directories to preserve an earlier run. Input files remain
unchanged.

Original 2025–26 analytical TXT records:
- ba_school_poverty_two_factor.txt
- income_education_joint_model.txt
- income_education_split_stability.txt
- proficiency_thresholds.txt

The current HTML reports and their revised TXT companions are prepared
separately. They include later editorial revisions; the consolidated threshold
report also includes separately dated 2024–25 findings, including attendance.
This runner recreates the 2025–26 analytical records, not that combined report.
The source index labels the current reports and original records separately:
/releases/2025-26/statistical-results-overview.html on this site.
The 2024–25 reproduction package is described at
/evidence-lab/analysis-downloads.html.

The optional --refresh-companions operation regenerates the original analytical
TXT records and source bundle from verified existing results, then updates
summary.json file hashes. It does not refit the models or regenerate the
current edited HTML/TXT readers or the consolidated report.

The common module's legacy loader and default 2024–25 constants are not used.
Only its functions for weighted regression, scaling, repeated prediction,
random-half comparisons and poverty-disclosure checks are called. The new runner separately validates the 2025–26 release,
source rows, populations, contexts and independent NumPy fitting identities.
References/hashes for earlier analytical methods are in source_references.json;
those earlier scripts are not runtime dependencies.

Reading the code and CSVs
-------------------------
Start with release_2025_26_analyses.py, not the common module's historical loader.
Its module header gives a function-by-function reading order. The common module
keeps older loading/report functions for historical users, but only the shared
helpers described above are used here.

Every CSV starts with a field-name header. The Analysis downloads guide explains
each file's row unit and fields. Download data_dictionary.json from that guide
for a local copy of the same definitions in machine-readable form. A school can occur in several subjects and model
variants: select one subject, universe and disclosure treatment before aggregating.

In school-level model CSVs, y is proficiency percent (0-100), w is the scored-
student count, and ba is the tract adult BA+ fraction (0-1). In model_school_rows,
context_type specifies whether context is income in dollars or SEP percent
(0-100); in ba_residual_school_rows, context is always SEP percent. In
joint_models, context is instead the model-choice label. Blank values are not zero.
A residual is observed proficiency minus the BA-only fitted value, in percentage
points. These rows describe schools, not individual students or student growth.

School and district names/IDs are public institution labels. source_refs points
to archived workbook rows, not student identifiers. Source-input addresses and
coordinates describe school sites, not students' homes. See the provenance page
for missing context, school-use exclusions and ODE disclosure treatment.

School groups are reshuffled before every prediction round and half-sample
comparison. Fixed starting seeds make the sequence repeatable. Scaling uses
only the schools used to fit each model. The reported 5th–95th percentile
ranges describe variation across the repeated splits, not confidence intervals.
No annual attendance data, attendance imputation or causal adjustment is used
by this 2025–26 runner.
""",encoding='utf-8-sig')

def build(data_dir=DATA_DIR,out=OUT_DIR,audit=AUDIT_DIR):
    out.mkdir(parents=True,exist_ok=True);audit.mkdir(parents=True,exist_ok=True)
    bundle_scripts(out)
    rows,universes,manifest,receipts=load_release(data_dir)
    joint=[];two=[];model_rows=[];residuals=[]
    for subject,source in rows.items():
        for universe,keys in universes.items():
            for context,sensitivities in [('income',['as_reported']),('sep_percent',['midpoint','lower_endpoint','upper_endpoint','exact_only'])]:
                if universe=='all_ordinary_sensitivity' and context=='income':continue
                for sensitivity in sensitivities:
                    points,d=build_points(source,keys,context,sensitivity)
                    if universe!='all_ordinary_sensitivity':
                        joint.append(model_result(subject,universe,context,sensitivity,points,d))
                        model_rows.extend({'subject':SUBJECTS[subject],'subject_key':subject,'universe':universe,'context_type':context,'sep_sensitivity':sensitivity,**p} for p in points)
                    if context=='sep_percent':
                        t,detail=two_factor_result(subject,universe,sensitivity,points);two.append(t)
                        if sensitivity=='midpoint':residuals.extend(detail)
    threshold=threshold_analysis(rows,universes)
    outputs={'joint_models.csv':joint,'two_factor.csv':two,'model_school_rows.csv':model_rows,'ba_residual_school_rows.csv':residuals,**{f'threshold_{name}.csv':threshold[name] for name in ['summary','pairs','correlations','stress','coverage','school_rows']}}
    for filename,data in outputs.items():write_csv(out/filename,data)
    text_reports=write_reports(out,joint,two,threshold);assets=plots(out,joint,two,threshold,residuals)
    findings=[]
    for r in two:
        if r['universe']=='elementary_primary' and r['sep_sensitivity']=='midpoint':findings.append(f"{r['subject']}: among {r['n_schools']} ordinary elementary schools, BA+ alone accounts for {100*r['r2_ba_only']:.1f}% of weighted between-school proficiency variation, enrollment SEP alone {100*r['r2_poverty_only']:.1f}%, and both together {100*r['r2_joint']:.1f}% in sample. These are descriptive fits, not causal shares.")
    summary={'schema_version':1,'date':DATE,'release_id':RELEASE_ID,'manifest_sha256':MANIFEST_SHA,'methods':METHODS,'findings':findings,'joint_models':joint,'two_factor':two,'threshold_summary':threshold['summary'],'threshold_pairs':threshold['pairs'],'threshold_correlations':threshold['correlations'],'threshold_stress':threshold['stress'],'threshold_coverage':threshold['coverage'],'text_reports':text_reports,'plots':assets,'source_scripts':source_references(), 'source_assets':receipts,'context_sha256':manifest['context']['sha256'],'profile_sha256':manifest['school_profile']['sha256'],'validation':{'all_release_asset_hashes_checked':True,'unique_assessment_keys':True,'cross_subject_profiles_independently_reconstructed':True,'official_all_grades_only':True,'numpy_wls_crosschecks':len(joint),'max_numpy_r2_abs_difference':max(r['numpy_r2_abs_difference'] for r in joint),'complete_cv_repeats':REPEATS,'historical_outputs_modified':False,'attendance_fallback':False},'downloads':[{'file':str(p.relative_to(out)),'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted(out.rglob('*')) if p.is_file() and p.name!='summary.json' and '__pycache__' not in p.parts and p.suffix != '.pyc']}
    (out/'summary.json').write_text(json.dumps(summary,indent=2,ensure_ascii=False,allow_nan=False)+'\n')
    evidence={'date':DATE,'command':'python3 scripts/release_2025_26_analyses.py','generator_sha256':sha(Path(__file__)),'release_id':RELEASE_ID,'manifest_sha256':MANIFEST_SHA,'validation':summary['validation'],'output_files':[{'path':str(p.relative_to(ROOT)) if p.is_relative_to(ROOT) else str(p),'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted(out.iterdir()) if p.is_file()]}
    (audit/f'build_receipt_{DATE}.json').write_text(json.dumps(evidence,indent=2)+'\n')
    (audit/f'CHECKPOINT_{DATE}.txt').write_text('Non-attendance report counterparts generated from the pinned public release.\nHistorical reports and data untouched.\nRun: python3 scripts/release_2025_26_analyses.py\nTests: python3 -m unittest discover -s tests/data -p test_2025_26_analyses.py\nScope/limitations are in site/releases/2025-26/analysis/summary.json and four TXT companions.\nNo publication, commit, push or deployment.\n')
    print(json.dumps({'joint_models':len(joint),'two_factor_models':len(two),'threshold_subjects':len(threshold['summary']),'max_numpy_r2_abs_difference':summary['validation']['max_numpy_r2_abs_difference'],'output':str(out),'findings':findings},indent=2))
    return summary

if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--data-dir',type=Path,default=DATA_DIR);parser.add_argument('--output-dir',type=Path,default=OUT_DIR);parser.add_argument('--audit-dir',type=Path,default=AUDIT_DIR);parser.add_argument('--refresh-companions',action='store_true',help='Refresh report prose and source bundle from verified existing results; do not refit models');args=parser.parse_args();refresh_companions(args.output_dir) if args.refresh_companions else build(args.data_dir,args.output_dir,args.audit_dir)
