"""Export traceable comparisons under the author's current inclusion rule."""

import argparse
import csv
from hashlib import sha256
import json
from pathlib import Path
import shutil

import numpy as np

ROOT = Path(__file__).resolve().parent
OUT = ROOT / 'staged/08_补充材料/20261023_完整结果配对核对'
NUMERIC = ROOT / 'numeric'
parser = argparse.ArgumentParser()
parser.add_argument('--percentile', choices=('pending', 'linear'), default='linear')
args = parser.parse_args()
OUT.mkdir(parents=True, exist_ok=True)
pairs = json.loads((NUMERIC / 'pair_differences.json').read_text(encoding='utf-8'))
vectors = json.loads((NUMERIC / 'case_vectors.json').read_text(encoding='utf-8'))
summary = json.loads((NUMERIC / 'summary.json').read_text(encoding='utf-8'))


def export_csv(name, rows):
    assert rows
    with (OUT / name).open('w', encoding='utf-8-sig', newline='') as stream:
        writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def aggregate(rows, model, a, b, category):
    output = []
    for metric in ('dInf', 'TV', 'd2', 'dH'):
        values = np.asarray([r[metric] for r in rows])
        output.append({'model': model, 'method_a': a, 'method_b': b,
            'sensitivity_category': category, 'metric': metric, 'n': len(rows),
            'median': float(np.median(values)),
            'p95': float(np.quantile(values, .95, method='linear')) if args.percentile == 'linear' else 'Pending author confirmation',
            'p95_method': 'linear (R type 7)' if args.percentile == 'linear' else 'Not adopted',
            'maximum': float(values.max()),
            'maximum_cases': ';'.join(r['scenario_id'] for r in rows if r[metric] == values.max()),
            'highest_changed_exact': sum(r['exact']['highest_changed'] for r in rows),
            'highest_changed_tolerance': sum(r['tolerance']['highest_changed'] for r in rows),
            'full_order_changed_exact': sum(r['exact']['full_order_changed'] for r in rows),
            'full_order_changed_tolerance': sum(r['tolerance']['full_order_changed'] for r in rows)})
    return output


overall, categories = [], []
for model, a, b in sorted({(r['model'], r['method_a'], r['method_b']) for r in pairs}):
    rows = [r for r in pairs if (r['model'], r['method_a'], r['method_b']) == (model, a, b) and r['role'] == 'sensitivity']
    overall.extend(aggregate(rows, model, a, b, 'All sensitivity'))
    for category in sorted({r['category'] for r in rows}):
        categories.extend(aggregate([r for r in rows if r['category'] == category], model, a, b, category))
export_csv('between_route_summary.csv', overall)
export_csv('between_route_by_category.csv', categories)
export_csv('scenario_pair_differences.csv', [{
    **{k: r[k] for k in ('model', 'scenario_id', 'role', 'category', 'category_title', 'description', 'method_a', 'method_b', 'dInf', 'TV', 'd2', 'dH')},
    **{f'{rule}_{name}': r[rule][name] for rule in ('exact', 'tolerance') for name in ('highest_changed', 'full_order_changed')},
    'source_sha256_a': r['source_sha256_a'], 'source_sha256_b': r['source_sha256_b']} for r in pairs])
export_csv('posterior_means.csv', [{
    'model': r['model'], 'scenario_id': r['scenario_id'], 'role': r['role'],
    'method': r['method'], 'state': r['state_labels'][state], 'state_fingerprint': state,
    'n_runs': r['n_runs'], 'mean_normalized_probability': r['mean_normalized_vector'][state],
    'design_fingerprint': r['design_fingerprint'], 'source_path': r['source_path'],
    'source_sha256': r['source_sha256']} for r in vectors for state in r['state_order']])
export_csv('within_route_metrics.csv', [{
    'model': r['model'], 'scenario_id': r['scenario_id'], 'role': r['role'],
    'method': r['method'], 'n_runs': r['n_runs'], 'Pmax': r['distribution']['Pmax'],
    'G': r['distribution']['top_two_gap'], 'HN': r['distribution']['HN'],
    'repeatability_record': json.dumps(r['repeatability'], separators=(',', ':')),
    'source_sha256': r['source_sha256']} for r in vectors])
diagnostics = [{'model': r['model'], 'scenario_id': r['scenario_id'], 'method': r['method'],
    'bridge_stability_flags': r['raw_stability_passed'],
    'original_registry_eligible': r['raw_registry_comparison_eligible'],
    'included_under_current_rule': True, 'source_path': r['source_path'],
    'source_sha256': r['source_sha256']} for r in vectors]
(OUT / 'raw_diagnostics.json').write_text(json.dumps(diagnostics, ensure_ascii=False, indent=2), encoding='utf-8')
policy = dict(summary['policy'])
policy['source_policy_snapshot'] = {key: policy.pop(key) for key in (
    'percentile_method_in_actual_supplement', 'p95_supplement', 'p95_linear_audit') if key in policy}
policy['author_decision_date'] = '2026-10-23'
policy['p95_current_export'] = args.percentile
policy['percentile_method'] = 'linear' if args.percentile == 'linear' else None
policy['percentile_probability'] = 0.95
policy['percentile_definition'] = ('R type 7; sort each summary group; zero-based h=0.95*(n-1); '
    'interpolate between floor(h) and ceil(h). A singleton returns its sole value.')
policy['percentile_author_approval'] = '采用线性插值法，补充材料注明' if args.percentile == 'linear' else None
policy['exclusions'] = summary['exclusions']
policy['source_files'] = {p.name: sha256(p.read_bytes()).hexdigest() for p in NUMERIC.glob('*.json')}
(OUT / 'comparison_policy.json').write_text(json.dumps(policy, ensure_ascii=False, indent=2), encoding='utf-8')
for name in ('source_hashes.json', 'case_vectors.json', 'pair_differences.json'):
    shutil.copy2(NUMERIC / name, OUT / name)

zh_percentile = (r'各指标的95百分位数采用线性插值法（R type 7、NumPy linear）。将同一汇总组内的场景指标升序排列，以零基索引\(h=0.95(n-1)\)在相邻值间插值，其中\(n\)为该组场景数；仅有一个场景时取其值。' if args.percentile == 'linear'
                 else '95百分位数的计算方式尚待作者确认，本轮表格暂不填写该列数值。')
en_percentile = (r'The 95th percentile uses linear interpolation (R type 7; NumPy linear). Scenario-level values within each summary group are sorted in ascending order, and interpolation is performed at the zero-based index \(h=0.95(n-1)\), where \(n\) is the number of scenarios. For a single scenario, its value is returned.' if args.percentile == 'linear'
                 else 'The 95th-percentile convention remains pending; values are not supplied in this export.')
rules = r'''# 输出纳入与路线比较

## 中文审读稿

每次运行的后验概率须与候选状态逐一对应，完整、有限且位于0至1之间，总和与1的绝对差不超过\(10^{-6}\)。通过检查后，将各状态概率除以该次运行的总和。各路线的比较向量为五次正式运行的归一化概率按对应状态取均值。重复性分别由归一化前、后的各状态样本标准差和极差描述。

每对路线分别纳入双方均有五次完整输出的场景。参考场景单独报告，不计入敏感性汇总。R aghq桥接程序的阶数稳定性标记保留为数值诊断，不作为本次比较的排除条件。无后验输出的OXC C026（R aghq）和TAC c078（三条路线）不进入相应配对比较。

排序分别采用严格相等和\(10^{-6}\)容差并列规则。最高概率状态集合包括距该向量最大概率不超过容差的全部状态。完整排序将概率降序排列后依次分组，各组成员与该组最大概率的差均不超过容差，不按相邻概率差连续合并。最高概率状态集合和完整排序分别比较；只有状态成员及组间顺序完全相同才判为一致。两套规则的结果分别保留。

最大绝对差、总变差、欧氏距离和Hellinger距离均按表3定义计算。敏感性场景按模型、路线配对及六类输入设置汇总。ZH_PERCENTILE

虚拟患者网页输出维持其显示精度，不强行归一化。网页可见输入匹配与后台模型等价性是不同事项，相关比较与解释仍按单独的虚拟患者核对记录处理，不纳入本文件的三条计算路线汇总。

## English

### Output Inclusion and Route Comparisons

Posterior probabilities must correspond one-to-one to the candidate states, be complete and finite, lie between 0 and 1, and sum to within \(10^{-6}\) of 1. Each valid run is normalized by its sum. The comparison vector is the mean normalized probability for each state across five formal runs. Statewise sample standard deviations and ranges are retained before and after normalization.

Each route pair includes scenarios with five complete outputs from both routes. Reference scenarios are reported separately from sensitivity summaries. Quadrature-order stability flags from the R aghq bridge are retained as numerical diagnostics, not exclusion criteria for this comparison. OXC C026 has no R aghq posterior output, and TAC c078 has no posterior output from any of the three routes; these outputs are excluded from the corresponding comparisons.

Rankings are compared under exact equality and a tie tolerance of \(10^{-6}\). The highest-probability set includes every state within the applicable tolerance of the vector maximum. Complete rankings are formed by sorting probabilities in descending order and grouping states relative to each group's maximum, rather than by chaining adjacent differences. Agreement requires identical state membership and group order. Highest-probability-set and complete-ranking results are retained separately under both rules.

Maximum absolute difference, total variation, Euclidean distance and Hellinger distance follow Table 3. Sensitivity summaries are grouped by model, route pair and the six input-setting categories. EN_PERCENTILE

Virtual-patient web outputs retain their displayed precision without forced renormalization. Matching visible inputs does not establish equivalence of backend models. Those comparisons are documented separately and are not part of the three-route summaries in this file.
'''.replace('ZH_PERCENTILE', zh_percentile).replace('EN_PERCENTILE', en_percentile)
(OUT / '输出纳入与排序比较_中英文_20261023.md').write_text(rules, encoding='utf-8')
lines = ['# 完整结果配对核对', '',
    '本目录与2026-10-23更新的中文稿及图1使用相同的五轮结果和纳入范围。原附件工作版的原始结果、运行回执及诊断不作修改。', '',
    '## 当前汇总', '', '| 模型 | 路线配对 | 敏感性n | 最大绝对差中位数 | 最大值 | 最高状态变化 | 完整排序变化 |',
    '|---|---|---:|---:|---:|---:|---:|']
names = {'python_laplace': 'Python', 'nonmem_laplace': 'NONMEM', 'r_aghq': 'R aghq'}
for r in overall:
    if r['metric'] == 'dInf':
        lines.append(f"| {r['model']} | {names[r['method_a']]} / {names[r['method_b']]} | {r['n']} | {r['median']:.9g} | {r['maximum']:.9g} | {r['highest_changed_tolerance']} | {r['full_order_changed_tolerance']} |")
lines.extend(['', '## 文件', '',
    '- `输出纳入与排序比较_中英文_20261023.md`：本轮规则，供合并至Online Resource 1。',
    '- `posterior_means.csv`、`within_route_metrics.csv`：候选状态概率及路线内指标。',
    '- `scenario_pair_differences.csv`：逐场景的四种距离及两套排序判据。',
    '- `between_route_summary.csv`、`between_route_by_category.csv`：总体及六类敏感性汇总。',
    '- `case_vectors.json`、`pair_differences.json`：五次向量、状态映射及完整比较记录。',
    '- `raw_diagnostics.json`、`comparison_policy.json`、`source_hashes.json`：原始诊断、纳入决定及来源哈希。', '',
    '- `selected_environment_builds.json`：逐运行环境、源构建及文件哈希。原构建与TAC边界修复构建分别保留。',
    '- `软件环境与源码构建_20261023.md`：所选正式运行的软件版本表及源码对应说明。',
    '- `原工作版口径衔接.md`：旧筛选汇总的准确位置及最终组包核对项目。', '',
    '## 与附件工作版的衔接', '',
    '工作版的RESULT_INDEX、DIAGNOSTIC_SUMMARIES和R_AGHQ_RESULTS仍使用旧稳定性筛选口径。本目录按作者本轮决定提供替换汇总，不将旧“comparison-eligible”计数与现稿混用。正式外投包的组装入口还须吸收本目录；本次未覆盖其他对话负责的共享附件工作版，也未重新打包其PDF/ZIP。', '',
    '95百分位数状态：' + zh_percentile,
    '摘要排序措辞、虚拟患者可比性及科学解释继续留待作者审定。'])
(OUT / 'README.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print(json.dumps({'output': str(OUT), 'pairs': len(pairs), 'vectors': len(vectors), 'summary_rows': len(overall),
                  'category_rows': len(categories), 'percentile': args.percentile}))
