@tangle-network/agent-eval 1.0.19 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -27
- package/dist/adapters/http.d.ts +2 -2
- package/dist/{agent-profile-CPv4tENR.d.ts → agent-profile-BO8ruI6R.d.ts} +3 -3
- package/dist/{agent-profile-CPv4tENR.d.ts.map → agent-profile-BO8ruI6R.d.ts.map} +1 -1
- package/dist/analyst/index.d.ts +14 -14
- package/dist/analyst/index.js +11 -12
- package/dist/analyst/index.js.map +1 -1
- package/dist/{analyze-runs-pJ4fhnYg.d.ts → analyze-runs-DYYe18Gw.d.ts} +4 -4
- package/dist/{analyze-runs-pJ4fhnYg.d.ts.map → analyze-runs-DYYe18Gw.d.ts.map} +1 -1
- package/dist/{analyze-runs-C7vWBDhl.js → analyze-runs-jLTRKuoK.js} +6 -110
- package/dist/analyze-runs-jLTRKuoK.js.map +1 -0
- package/dist/app-grade/index.d.ts +4 -4
- package/dist/app-grade/index.js +3 -3
- package/dist/{benchmark-command-DSJQeYom.js → benchmark-command-CoNndRCk.js} +13 -14
- package/dist/benchmark-command-CoNndRCk.js.map +1 -0
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +4 -5
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/builder-eval/index.js +1 -1
- package/dist/{calibration-CbZPApIO.js → calibration-Cf-wpqqO.js} +2 -2
- package/dist/{calibration-CbZPApIO.js.map → calibration-Cf-wpqqO.js.map} +1 -1
- package/dist/campaign/index.d.ts +7 -7
- package/dist/campaign/index.js +10 -10
- package/dist/{campaign-BABipFel.js → campaign-Bl07uIaf.js} +14 -15
- package/dist/{campaign-BABipFel.js.map → campaign-Bl07uIaf.js.map} +1 -1
- package/dist/{campaign-evidence-DONEWvVY.js → campaign-evidence-NtH29ctt.js} +3 -3
- package/dist/{campaign-evidence-DONEWvVY.js.map → campaign-evidence-NtH29ctt.js.map} +1 -1
- package/dist/{chat-client-D0me8iwq.js → chat-client-Zz97O3NB.js} +2 -2
- package/dist/{chat-client-D0me8iwq.js.map → chat-client-Zz97O3NB.js.map} +1 -1
- package/dist/{chat-json-call-C473CwTt.js → chat-json-call-Dgi7-RH-.js} +2 -2
- package/dist/{chat-json-call-C473CwTt.js.map → chat-json-call-Dgi7-RH-.js.map} +1 -1
- package/dist/cli.js +7 -7
- package/dist/{types-0KglnQ9o.d.ts → cluster-Cd0MRbr9.d.ts} +44 -2
- package/dist/cluster-Cd0MRbr9.d.ts.map +1 -0
- package/dist/cluster-bootstrap-B0MTOBRU.js +24 -0
- package/dist/cluster-bootstrap-B0MTOBRU.js.map +1 -0
- package/dist/{completion-verifier-7KEfroqx.d.ts → completion-verifier-BEpsr3N4.d.ts} +2 -2
- package/dist/{completion-verifier-7KEfroqx.d.ts.map → completion-verifier-BEpsr3N4.d.ts.map} +1 -1
- package/dist/{completion-verifier-ClmJV_Yc.js → completion-verifier-DFyYFezn.js} +3 -3
- package/dist/{completion-verifier-ClmJV_Yc.js.map → completion-verifier-DFyYFezn.js.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +14 -15
- package/dist/contract/index.js.map +1 -1
- package/dist/{cost-ledger-CS8R3IZj.js → cost-ledger-DfhStGcZ.js} +2 -2
- package/dist/{cost-ledger-CS8R3IZj.js.map → cost-ledger-DfhStGcZ.js.map} +1 -1
- package/dist/{decision-point-CNyoKOkz.js → decision-point-Di2LATNH.js} +4 -4
- package/dist/{decision-point-CNyoKOkz.js.map → decision-point-Di2LATNH.js.map} +1 -1
- package/dist/{default-registry-BB9_jzyH.js → default-registry-CdFbxPnr.js} +5 -5
- package/dist/{default-registry-BB9_jzyH.js.map → default-registry-CdFbxPnr.js.map} +1 -1
- package/dist/{default-registry-BbXr18AT.d.ts → default-registry-aPvwtzEM.d.ts} +7 -7
- package/dist/{default-registry-BbXr18AT.d.ts.map → default-registry-aPvwtzEM.d.ts.map} +1 -1
- package/dist/{define-agent-eval-Q4FdXGj7.js → define-agent-eval-BROmIwn1.js} +6 -6
- package/dist/{define-agent-eval-Q4FdXGj7.js.map → define-agent-eval-BROmIwn1.js.map} +1 -1
- package/dist/{define-agent-eval-D_DQMH04.d.ts → define-agent-eval-Bx3b9B01.d.ts} +7 -7
- package/dist/{define-agent-eval-D_DQMH04.d.ts.map → define-agent-eval-Bx3b9B01.d.ts.map} +1 -1
- package/dist/diagnosis/index.d.ts +2 -2
- package/dist/diagnosis/index.js +1 -1
- package/dist/{dspy-rlm-engine-CqQc0R2l.js → dspy-rlm-engine-cWyn8G1a.js} +4 -4
- package/dist/{dspy-rlm-engine-CqQc0R2l.js.map → dspy-rlm-engine-cWyn8G1a.js.map} +1 -1
- package/dist/{engine-rfV8Ff8V.d.ts → engine-BF8naBn7.d.ts} +2 -2
- package/dist/{engine-rfV8Ff8V.d.ts.map → engine-BF8naBn7.d.ts.map} +1 -1
- package/dist/{eval-campaign-CZSCjxVb.js → eval-campaign-Dq8DEKmy.js} +2 -2
- package/dist/{eval-campaign-CZSCjxVb.js.map → eval-campaign-Dq8DEKmy.js.map} +1 -1
- package/dist/{evaluation-SDXKL6Fx.d.ts → evaluation-CFKj_IlJ.d.ts} +4 -4
- package/dist/{evaluation-SDXKL6Fx.d.ts.map → evaluation-CFKj_IlJ.d.ts.map} +1 -1
- package/dist/{evaluation-BBI37mRe.js → evaluation-bU_bhlv-.js} +2 -2
- package/dist/{evaluation-BBI37mRe.js.map → evaluation-bU_bhlv-.js.map} +1 -1
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -1
- package/dist/{exact-types-CaLLU1Pz.d.ts → exact-types-VAFjtOQN.d.ts} +2 -2
- package/dist/{exact-types-CaLLU1Pz.d.ts.map → exact-types-VAFjtOQN.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +3 -5
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +7 -12
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-BYBG9b1n.d.ts → exporters-dQKYD_Zo.d.ts} +2 -2
- package/dist/{exporters-BYBG9b1n.d.ts.map → exporters-dQKYD_Zo.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-CfrY-nJT.js → external-optimizer-process-2ImGH_LR.js} +2 -2
- package/dist/{external-optimizer-process-CfrY-nJT.js.map → external-optimizer-process-2ImGH_LR.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-BtJk8UcU.js → external-optimizer-subprocess-_C_2yriN.js} +3 -3
- package/dist/{external-optimizer-subprocess-BtJk8UcU.js.map → external-optimizer-subprocess-_C_2yriN.js.map} +1 -1
- package/dist/{feedback-trajectory-P37ju-gW.d.ts → feedback-trajectory-DTj8eVTR.d.ts} +3 -3
- package/dist/{feedback-trajectory-P37ju-gW.d.ts.map → feedback-trajectory-DTj8eVTR.d.ts.map} +1 -1
- package/dist/{findings-store-BnYN57-h.js → findings-store-BSuaV3dN.js} +7 -24
- package/dist/findings-store-BSuaV3dN.js.map +1 -0
- package/dist/fuzz.js +2 -2
- package/dist/{index-D4lT7aFu.d.ts → index-7tWvC0aW.d.ts} +28 -128
- package/dist/index-7tWvC0aW.d.ts.map +1 -0
- package/dist/{index-C3t17kHu.d.ts → index-B62BaRzH.d.ts} +7 -100
- package/dist/index-B62BaRzH.d.ts.map +1 -0
- package/dist/{index-HuSMvqR2.d.ts → index-BlTbxHlY.d.ts} +5 -5
- package/dist/{index-HuSMvqR2.d.ts.map → index-BlTbxHlY.d.ts.map} +1 -1
- package/dist/{index-AmfM3usI.d.ts → index-CM12lr9E.d.ts} +8 -8
- package/dist/{index-AmfM3usI.d.ts.map → index-CM12lr9E.d.ts.map} +1 -1
- package/dist/{index-DLVbfss9.d.ts → index-DFso1b2W.d.ts} +8 -8
- package/dist/{index-DLVbfss9.d.ts.map → index-DFso1b2W.d.ts.map} +1 -1
- package/dist/index-DNXFzSpc.d.ts +1101 -0
- package/dist/index-DNXFzSpc.d.ts.map +1 -0
- package/dist/{index-BPmj-_ta.d.ts → index-DfqAy8ct.d.ts} +10 -9
- package/dist/index-DfqAy8ct.d.ts.map +1 -0
- package/dist/index.d.ts +29 -31
- package/dist/index.js +28 -164
- package/dist/index.js.map +1 -1
- package/dist/{integrity-BAdVzT8u.d.ts → integrity-CrmnGB2T.d.ts} +2 -2
- package/dist/{integrity-BAdVzT8u.d.ts.map → integrity-CrmnGB2T.d.ts.map} +1 -1
- package/dist/{judge-gate-CIlBrn6q.js → judge-gate-CrN0PaAL.js} +3 -3
- package/dist/{judge-gate-CIlBrn6q.js.map → judge-gate-CrN0PaAL.js.map} +1 -1
- package/dist/{kind-factory-Cfz8DUCc.js → kind-factory-CV0FNCMM.js} +2 -2
- package/dist/{kind-factory-Cfz8DUCc.js.map → kind-factory-CV0FNCMM.js.map} +1 -1
- package/dist/{llm-client-BdSiZ4qz.js → llm-client-DMMSg-Ro.js} +2 -2
- package/dist/{llm-client-BdSiZ4qz.js.map → llm-client-DMMSg-Ro.js.map} +1 -1
- package/dist/{llm-judge-VD_MI6kd.js → llm-judge-C813vmpc.js} +13 -14
- package/dist/{llm-judge-VD_MI6kd.js.map → llm-judge-C813vmpc.js.map} +1 -1
- package/dist/{matrix-Yg1lHIGI.d.ts → matrix-C-GxIgeJ.d.ts} +2 -2
- package/dist/{matrix-Yg1lHIGI.d.ts.map → matrix-C-GxIgeJ.d.ts.map} +1 -1
- package/dist/meta-eval/index.d.ts +2 -2
- package/dist/meta-eval/index.js +7 -7
- package/dist/{metrics-DNCAUtuB.js → metrics-zALlR17s.js} +16 -17
- package/dist/metrics-zALlR17s.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -1
- package/dist/multishot/index.d.ts +2 -2
- package/dist/multishot/index.js +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{outcome-observations-DZu5hLYF.js → outcome-observations-DPkH-LHQ.js} +2 -3
- package/dist/{outcome-observations-DZu5hLYF.js.map → outcome-observations-DPkH-LHQ.js.map} +1 -1
- package/dist/paired-arms-DjMEtYI9.js +338 -0
- package/dist/paired-arms-DjMEtYI9.js.map +1 -0
- package/dist/{paired-promotion-decision-CiueaTTj.js → paired-promotion-decision-Bi9__RQS.js} +2 -3
- package/dist/{paired-promotion-decision-CiueaTTj.js.map → paired-promotion-decision-Bi9__RQS.js.map} +1 -1
- package/dist/{paired-promotion-decision-BDnqepZ1.d.ts → paired-promotion-decision-DJU3fZxH.d.ts} +3 -113
- package/dist/paired-promotion-decision-DJU3fZxH.d.ts.map +1 -0
- package/dist/{pareto-a3EOmjfe.js → pareto-fJZg8pXm.js} +3 -6
- package/dist/{pareto-a3EOmjfe.js.map → pareto-fJZg8pXm.js.map} +1 -1
- package/dist/pipelines/index.js +1 -1
- package/dist/{prime-protocol-DKRk4l4U.d.ts → prime-protocol-D1NkJRuD.d.ts} +2 -2
- package/dist/{prime-protocol-DKRk4l4U.d.ts.map → prime-protocol-D1NkJRuD.d.ts.map} +1 -1
- package/dist/{promotion-gate-DOkgJcLW.d.ts → promotion-gate-Da0xV4sa.d.ts} +3 -67
- package/dist/promotion-gate-Da0xV4sa.d.ts.map +1 -0
- package/dist/{promotion-policy-DLPcEnCf.js → promotion-policy-DCgftbnd.js} +4 -4
- package/dist/{promotion-policy-DLPcEnCf.js.map → promotion-policy-DCgftbnd.js.map} +1 -1
- package/dist/{proposal-findings-BfzzZ_lN.js → proposal-findings-DWs94yT8.js} +2 -2
- package/dist/{proposal-findings-BfzzZ_lN.js.map → proposal-findings-DWs94yT8.js.map} +1 -1
- package/dist/{registry-Ck7w-rr5.d.ts → registry-BAcEbzKm.d.ts} +4 -4
- package/dist/{registry-Ck7w-rr5.d.ts.map → registry-BAcEbzKm.d.ts.map} +1 -1
- package/dist/{release-confidence-nfQNh3eb.js → release-confidence-DGtuPDxJ.js} +2 -2
- package/dist/{release-confidence-nfQNh3eb.js.map → release-confidence-DGtuPDxJ.js.map} +1 -1
- package/dist/reporting.d.ts +4 -5
- package/dist/reporting.d.ts.map +1 -1
- package/dist/reporting.js +5 -7
- package/dist/reporting.js.map +1 -1
- package/dist/{researcher-CLnNJ7Or.d.ts → researcher-CSlc84Bp.d.ts} +4 -4
- package/dist/{researcher-CLnNJ7Or.d.ts.map → researcher-CSlc84Bp.d.ts.map} +1 -1
- package/dist/{reward-hacking-B88f-Kh7.js → reward-hacking-BYiDFbIl.js} +2 -3
- package/dist/{reward-hacking-B88f-Kh7.js.map → reward-hacking-BYiDFbIl.js.map} +1 -1
- package/dist/rl.d.ts +9 -8
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +8 -10
- package/dist/rl.js.map +1 -1
- package/dist/rollout/index.d.ts +4 -4
- package/dist/rollout/index.js +1 -1
- package/dist/{rollout-Cu7kHGIe.js → rollout-DKa54qer.js} +2 -2
- package/dist/{rollout-Cu7kHGIe.js.map → rollout-DKa54qer.js.map} +1 -1
- package/dist/{rubric-predictive-validity-D_6ZPTNR.js → rubric-predictive-validity-DL7gJ51F.js} +2 -2
- package/dist/{rubric-predictive-validity-D_6ZPTNR.js.map → rubric-predictive-validity-DL7gJ51F.js.map} +1 -1
- package/dist/{run-record-CbUi2adH.js → run-record-CFbnkE1K.js} +2 -2
- package/dist/{run-record-CbUi2adH.js.map → run-record-CFbnkE1K.js.map} +1 -1
- package/dist/{runtime-rollouts-kGn1K5ut.js → runtime-rollouts-BNrm5nC_.js} +2 -2
- package/dist/{runtime-rollouts-kGn1K5ut.js.map → runtime-rollouts-BNrm5nC_.js.map} +1 -1
- package/dist/{schema-CfoA9U_U.d.ts → schema-PDKQ_iNE.d.ts} +2 -131
- package/dist/schema-PDKQ_iNE.d.ts.map +1 -0
- package/dist/search/index.d.ts +2 -2
- package/dist/search/index.js +2 -2
- package/dist/{search-kernel-DjqaPJqL.d.ts → search-kernel-CQGLbmgn.d.ts} +3 -3
- package/dist/{search-kernel-DjqaPJqL.d.ts.map → search-kernel-CQGLbmgn.d.ts.map} +1 -1
- package/dist/{search-summary-RJ5zXjHN.js → search-summary-sPWiYtSl.js} +4 -4
- package/dist/{search-summary-RJ5zXjHN.js.map → search-summary-sPWiYtSl.js.map} +1 -1
- package/dist/{sequential-BPbvgzfe.js → sequential-9TVb5Nu5.js} +3 -3
- package/dist/{sequential-BPbvgzfe.js.map → sequential-9TVb5Nu5.js.map} +1 -1
- package/dist/{sequential-Bb_pdTqG.d.ts → sequential-B9p6uoV8.d.ts} +9 -2
- package/dist/{sequential-Bb_pdTqG.d.ts.map → sequential-B9p6uoV8.d.ts.map} +1 -1
- package/dist/{sequential-Bjs5roiK.js → sequential-CAksw6EU.js} +32 -2
- package/dist/{sequential-Bjs5roiK.js.map → sequential-CAksw6EU.js.map} +1 -1
- package/dist/{server-CPKyf3bz.js → server-DFVwfoZq.js} +3 -3
- package/dist/{server-CPKyf3bz.js.map → server-DFVwfoZq.js.map} +1 -1
- package/dist/{skillopt-optimization-method-D9Hlmhjg.js → skillopt-optimization-method-QO1nU8Kz.js} +9 -9
- package/dist/{skillopt-optimization-method-D9Hlmhjg.js.map → skillopt-optimization-method-QO1nU8Kz.js.map} +1 -1
- package/dist/{statistical-heldout-C-tgpUuu.d.ts → statistical-heldout-CvOwNqt9.d.ts} +6 -282
- package/dist/statistical-heldout-CvOwNqt9.d.ts.map +1 -0
- package/dist/{statistical-heldout-NBxC7jGo.js → statistical-heldout-DLO4Ebos.js} +3 -3
- package/dist/{statistical-heldout-NBxC7jGo.js.map → statistical-heldout-DLO4Ebos.js.map} +1 -1
- package/dist/statistics-CvvC-MPv.js +2634 -0
- package/dist/statistics-CvvC-MPv.js.map +1 -0
- package/dist/statistics.d.ts +3 -0
- package/dist/statistics.js +3 -0
- package/dist/{store-otlp-BfPRa2p8.js → store-otlp-C-jyj3WX.js} +2 -2
- package/dist/{store-otlp-BfPRa2p8.js.map → store-otlp-C-jyj3WX.js.map} +1 -1
- package/dist/{store-tool-spans-BgwVHXma.d.ts → store-tool-spans-B3z_Qb5u.d.ts} +5 -5
- package/dist/{store-tool-spans-BgwVHXma.d.ts.map → store-tool-spans-B3z_Qb5u.d.ts.map} +1 -1
- package/dist/{store-tool-spans-BrSWHB9O.js → store-tool-spans-DalWlKY8.js} +3 -3
- package/dist/{store-tool-spans-BrSWHB9O.js.map → store-tool-spans-DalWlKY8.js.map} +1 -1
- package/dist/{summary-report-C3IJvp0i.js → summary-report-BEhqoxrA.js} +4 -52
- package/dist/summary-report-BEhqoxrA.js.map +1 -0
- package/dist/{summary-report-0La5vejY.d.ts → summary-report-DyZquTaH.d.ts} +2 -2
- package/dist/{summary-report-0La5vejY.d.ts.map → summary-report-DyZquTaH.d.ts.map} +1 -1
- package/dist/supervisor-run/index.d.ts +2 -2
- package/dist/supervisor-run/index.js +1 -1
- package/dist/{systemone-CpDppX8s.d.ts → systemone-DVk-Crtu.d.ts} +7 -7
- package/dist/{systemone-CpDppX8s.d.ts.map → systemone-DVk-Crtu.d.ts.map} +1 -1
- package/dist/{systemone-review-nbuMxxmi.d.ts → systemone-review-CToBl1oa.d.ts} +2 -2
- package/dist/{systemone-review-nbuMxxmi.d.ts.map → systemone-review-CToBl1oa.d.ts.map} +1 -1
- package/dist/systemone.d.ts +3 -3
- package/dist/systemone.js +2 -2
- package/dist/{tool-groups-BQsjZD9F.d.ts → tool-groups-R5RO9OHn.d.ts} +3 -3
- package/dist/tool-groups-R5RO9OHn.d.ts.map +1 -0
- package/dist/{tool-waste-Czt3aWID.js → tool-waste-BqSmmPUz.js} +2 -3
- package/dist/{tool-waste-Czt3aWID.js.map → tool-waste-BqSmmPUz.js.map} +1 -1
- package/dist/{trace-questions-CpTrtEcm.d.ts → trace-questions-BY6taxnl.d.ts} +3 -3
- package/dist/{trace-questions-CpTrtEcm.d.ts.map → trace-questions-BY6taxnl.d.ts.map} +1 -1
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/trace-repair/index.js +1 -2
- package/dist/trace-repair/index.js.map +1 -1
- package/dist/traces.d.ts +5 -5
- package/dist/traces.js +3 -3
- package/dist/{tree-DIHp6UQ0.js → tree-C-N2kP-8.js} +4 -6
- package/dist/{tree-DIHp6UQ0.js.map → tree-C-N2kP-8.js.map} +1 -1
- package/dist/{types-DsuOcYsE.d.ts → types-BsdcSWnf.d.ts} +2 -2
- package/dist/{types-DsuOcYsE.d.ts.map → types-BsdcSWnf.d.ts.map} +1 -1
- package/dist/{types-DNB9hIXa.d.ts → types-DUVhW5V1.d.ts} +3 -2
- package/dist/types-DUVhW5V1.d.ts.map +1 -0
- package/dist/{types-wDBk14lj.d.ts → types-ip2D3-Ib.d.ts} +5 -4
- package/dist/types-ip2D3-Ib.d.ts.map +1 -0
- package/dist/{types-B9s9Xo5_.d.ts → types-kBMNdo1X.d.ts} +3 -9
- package/dist/types-kBMNdo1X.d.ts.map +1 -0
- package/dist/wire/index.d.ts +4 -4
- package/dist/wire/index.js +1 -1
- package/docs/design/statistics-decisions.md +45 -364
- package/docs/design.md +1 -1
- package/docs/research-report-methodology.md +1 -1
- package/package.json +6 -1
- package/dist/agreement-irr-DXcXEt4I.js +0 -182
- package/dist/agreement-irr-DXcXEt4I.js.map +0 -1
- package/dist/analyze-runs-C7vWBDhl.js.map +0 -1
- package/dist/benchmark-command-DSJQeYom.js.map +0 -1
- package/dist/cluster-bootstrap-BteuR1hg.js +0 -65
- package/dist/cluster-bootstrap-BteuR1hg.js.map +0 -1
- package/dist/descriptive-B3Eb7tX0.js +0 -229
- package/dist/descriptive-B3Eb7tX0.js.map +0 -1
- package/dist/findings-store-BnYN57-h.js.map +0 -1
- package/dist/index-BPmj-_ta.d.ts.map +0 -1
- package/dist/index-C3t17kHu.d.ts.map +0 -1
- package/dist/index-D4lT7aFu.d.ts.map +0 -1
- package/dist/judge-calibration-DKR6Xi-w.js +0 -319
- package/dist/judge-calibration-DKR6Xi-w.js.map +0 -1
- package/dist/judge-calibration-DnrbQaXI.d.ts +0 -144
- package/dist/judge-calibration-DnrbQaXI.d.ts.map +0 -1
- package/dist/mean-D1d6gedE.js +0 -284
- package/dist/mean-D1d6gedE.js.map +0 -1
- package/dist/metrics-DNCAUtuB.js.map +0 -1
- package/dist/multiplicity-DAd4xaDC.js +0 -100
- package/dist/multiplicity-DAd4xaDC.js.map +0 -1
- package/dist/multiplicity-D_SEsc5j.d.ts +0 -41
- package/dist/multiplicity-D_SEsc5j.d.ts.map +0 -1
- package/dist/paired-arms-3-tsXvvC.js +0 -740
- package/dist/paired-arms-3-tsXvvC.js.map +0 -1
- package/dist/paired-binary-CMzmSSd5.js +0 -372
- package/dist/paired-binary-CMzmSSd5.js.map +0 -1
- package/dist/paired-promotion-decision-BDnqepZ1.d.ts.map +0 -1
- package/dist/paired-tests-Buh6feJ4.js +0 -211
- package/dist/paired-tests-Buh6feJ4.js.map +0 -1
- package/dist/power-and-mde-g3vOn0XK.js +0 -99
- package/dist/power-and-mde-g3vOn0XK.js.map +0 -1
- package/dist/promotion-gate-DOkgJcLW.d.ts.map +0 -1
- package/dist/random-BN150Q_X.d.ts +0 -79
- package/dist/random-BN150Q_X.d.ts.map +0 -1
- package/dist/schema-CfoA9U_U.d.ts.map +0 -1
- package/dist/sequential-eprocess-C1YLwFaz.js +0 -129
- package/dist/sequential-eprocess-C1YLwFaz.js.map +0 -1
- package/dist/statistical-heldout-C-tgpUuu.d.ts.map +0 -1
- package/dist/summary-report-C3IJvp0i.js.map +0 -1
- package/dist/tool-groups-BQsjZD9F.d.ts.map +0 -1
- package/dist/types-0KglnQ9o.d.ts.map +0 -1
- package/dist/types-B9s9Xo5_.d.ts.map +0 -1
- package/dist/types-DNB9hIXa.d.ts.map +0 -1
- package/dist/types-wDBk14lj.d.ts.map +0 -1
|
@@ -0,0 +1,2634 @@
|
|
|
1
|
+
import { s as ValidationError } from "./errors-DeEEV9Vx.js";
|
|
2
|
+
import { t as interpolatedQuantile } from "./quantile-CncXP-Ss.js";
|
|
3
|
+
import { t as mulberry32 } from "./random-DrzcgC7F.js";
|
|
4
|
+
// src/math/special-functions.ts
|
|
5
|
+
/** Lanczos approximation to ln Gamma(z). */
|
|
6
|
+
function lnGamma(z) {
|
|
7
|
+
const g = 7;
|
|
8
|
+
const coefficients = [
|
|
9
|
+
.9999999999998099,
|
|
10
|
+
676.5203681218851,
|
|
11
|
+
-1259.1392167224028,
|
|
12
|
+
771.3234287776531,
|
|
13
|
+
-176.6150291621406,
|
|
14
|
+
12.507343278686905,
|
|
15
|
+
-.13857109526572012,
|
|
16
|
+
9984369578019572e-21,
|
|
17
|
+
1.5056327351493116e-7
|
|
18
|
+
];
|
|
19
|
+
if (z < .5) return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z);
|
|
20
|
+
z -= 1;
|
|
21
|
+
let x = coefficients[0];
|
|
22
|
+
for (let i = 1; i < 9; i++) x += coefficients[i] / (z + i);
|
|
23
|
+
const t = z + g + .5;
|
|
24
|
+
return .5 * Math.log(2 * Math.PI) + (z + .5) * Math.log(t) - t + Math.log(x);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Regularized incomplete beta function I_x(a, b).
|
|
28
|
+
*
|
|
29
|
+
* The Lentz continued fraction converges only for `x < (a+1)/(a+b+2)`; outside
|
|
30
|
+
* that domain it must be reached through the symmetry `I_x(a,b) = 1 −
|
|
31
|
+
* I_{1−x}(b,a)`. `studentTCdf` drives `x → 1` as `|t| → 0`, so the mirrored
|
|
32
|
+
* branch is the one every near-null t-statistic takes.
|
|
33
|
+
*/
|
|
34
|
+
function regularizedIncompleteBeta(x, a, b) {
|
|
35
|
+
if (x <= 0) return 0;
|
|
36
|
+
if (x >= 1) return 1;
|
|
37
|
+
const logBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b);
|
|
38
|
+
const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - logBeta);
|
|
39
|
+
if (x < (a + 1) / (a + b + 2)) return front * betaContinuedFraction(x, a, b) / a;
|
|
40
|
+
return 1 - front * betaContinuedFraction(1 - x, b, a) / b;
|
|
41
|
+
}
|
|
42
|
+
/** Modified Lentz evaluation of the beta continued fraction at `x`. */
|
|
43
|
+
function betaContinuedFraction(x, a, b) {
|
|
44
|
+
const maxIterations = 300;
|
|
45
|
+
const epsilon = 3e-15;
|
|
46
|
+
let c = 1;
|
|
47
|
+
let d = 1 - (a + b) * x / (a + 1);
|
|
48
|
+
if (Math.abs(d) < 1e-30) d = 1e-30;
|
|
49
|
+
d = 1 / d;
|
|
50
|
+
let fraction = d;
|
|
51
|
+
for (let m = 1; m <= maxIterations; m++) {
|
|
52
|
+
const m2 = 2 * m;
|
|
53
|
+
let numerator = m * (b - m) * x / ((a + m2 - 1) * (a + m2));
|
|
54
|
+
d = 1 + numerator * d;
|
|
55
|
+
if (Math.abs(d) < 1e-30) d = 1e-30;
|
|
56
|
+
c = 1 + numerator / c;
|
|
57
|
+
if (Math.abs(c) < 1e-30) c = 1e-30;
|
|
58
|
+
d = 1 / d;
|
|
59
|
+
fraction *= d * c;
|
|
60
|
+
numerator = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));
|
|
61
|
+
d = 1 + numerator * d;
|
|
62
|
+
if (Math.abs(d) < 1e-30) d = 1e-30;
|
|
63
|
+
c = 1 + numerator / c;
|
|
64
|
+
if (Math.abs(c) < 1e-30) c = 1e-30;
|
|
65
|
+
d = 1 / d;
|
|
66
|
+
const delta = d * c;
|
|
67
|
+
fraction *= delta;
|
|
68
|
+
if (Math.abs(delta - 1) < epsilon) break;
|
|
69
|
+
}
|
|
70
|
+
return fraction;
|
|
71
|
+
}
|
|
72
|
+
// src/math/student-t.ts
|
|
73
|
+
/**
|
|
74
|
+
* Student-t CDF via the regularized incomplete beta function.
|
|
75
|
+
*/
|
|
76
|
+
function studentTCdf(t, degreesOfFreedom) {
|
|
77
|
+
if (degreesOfFreedom <= 0) return .5;
|
|
78
|
+
const beta = regularizedIncompleteBeta(degreesOfFreedom / (degreesOfFreedom + t * t), degreesOfFreedom / 2, .5);
|
|
79
|
+
return t >= 0 ? 1 - .5 * beta : .5 * beta;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Inverse Student-t CDF, solved against {@link studentTCdf}.
|
|
83
|
+
*
|
|
84
|
+
* The CDF is monotone, so bracket expansion followed by bisection is stable
|
|
85
|
+
* across fractional degrees of freedom and does not need a separate
|
|
86
|
+
* approximation with a different error profile.
|
|
87
|
+
*/
|
|
88
|
+
function studentTQuantile(probability, degreesOfFreedom) {
|
|
89
|
+
if (!Number.isFinite(probability) || probability < 0 || probability > 1) throw new RangeError(`studentTQuantile: probability must be in [0,1], got ${probability}`);
|
|
90
|
+
if (!Number.isFinite(degreesOfFreedom) || degreesOfFreedom <= 0) throw new RangeError(`studentTQuantile: degreesOfFreedom must be positive and finite, got ${degreesOfFreedom}`);
|
|
91
|
+
if (probability === 0) return Number.NEGATIVE_INFINITY;
|
|
92
|
+
if (probability === 1) return Number.POSITIVE_INFINITY;
|
|
93
|
+
if (probability === .5) return 0;
|
|
94
|
+
if (probability < .5) return -studentTQuantile(1 - probability, degreesOfFreedom);
|
|
95
|
+
let low = 0;
|
|
96
|
+
let high = 1;
|
|
97
|
+
while (studentTCdf(high, degreesOfFreedom) < probability) high *= 2;
|
|
98
|
+
for (let iteration = 0; iteration < 64; iteration++) {
|
|
99
|
+
const middle = (low + high) / 2;
|
|
100
|
+
if (studentTCdf(middle, degreesOfFreedom) < probability) low = middle;
|
|
101
|
+
else high = middle;
|
|
102
|
+
}
|
|
103
|
+
return (low + high) / 2;
|
|
104
|
+
}
|
|
105
|
+
// src/statistics/cluster.ts
|
|
106
|
+
const DEFAULT_BOOTSTRAP_SEED = 12648430;
|
|
107
|
+
/** Percentile bootstrap; degenerate resamples are omitted, with NaN bounds if none remain. */
|
|
108
|
+
function clusterBootstrap(items, cluster, statistic, { resamples = 2e3, seed = DEFAULT_BOOTSTRAP_SEED, level = .95, strata } = {}) {
|
|
109
|
+
if (!Number.isSafeInteger(resamples) || resamples < 0 || !(level > 0 && level < 1)) throw new ValidationError("clusterBootstrap: requires nonnegative resamples and level in (0,1)");
|
|
110
|
+
const groups = /* @__PURE__ */ new Map();
|
|
111
|
+
items.forEach((item, index) => {
|
|
112
|
+
const key = cluster(item, index), stratum = strata?.(item, index) ?? "";
|
|
113
|
+
if (typeof key !== "string" || !key || typeof stratum !== "string") throw new ValidationError("clusterBootstrap: requires string cluster id and stratum");
|
|
114
|
+
const group = groups.get(key) ?? {
|
|
115
|
+
stratum,
|
|
116
|
+
rows: []
|
|
117
|
+
};
|
|
118
|
+
if (group.stratum !== stratum) throw new ValidationError("clusterBootstrap: cluster crosses strata");
|
|
119
|
+
group.rows.push(item);
|
|
120
|
+
groups.set(key, group);
|
|
121
|
+
});
|
|
122
|
+
const cells = /* @__PURE__ */ new Map();
|
|
123
|
+
for (const { stratum, rows } of groups.values()) {
|
|
124
|
+
if (!cells.has(stratum)) cells.set(stratum, []);
|
|
125
|
+
cells.get(stratum).push(rows);
|
|
126
|
+
}
|
|
127
|
+
const rng = mulberry32(seed), values = [];
|
|
128
|
+
for (let b = 0; b < resamples; b++) {
|
|
129
|
+
const value = statistic([...cells.values()].flatMap((clusters) => Array.from({ length: clusters.length }, () => clusters[Math.floor(rng() * clusters.length)]).flat()));
|
|
130
|
+
if (Number.isFinite(value)) values.push(value);
|
|
131
|
+
}
|
|
132
|
+
values.sort((a, b) => a - b);
|
|
133
|
+
return {
|
|
134
|
+
low: interpolatedQuantile(values, (1 - level) / 2),
|
|
135
|
+
high: interpolatedQuantile(values, (1 + level) / 2),
|
|
136
|
+
resamples,
|
|
137
|
+
clusters: groups.size
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function placeboBand(history, options) {
|
|
141
|
+
const { timestamp, cluster, statistic, clustersPerArm, delta, steps = [] } = options;
|
|
142
|
+
if (!Number.isSafeInteger(clustersPerArm) || clustersPerArm < 1 || !Number.isFinite(delta) || steps.some((t) => !Number.isFinite(t))) throw new ValidationError("placeboBand: invalid cluster count, delta or step");
|
|
143
|
+
const groups = /* @__PURE__ */ new Map();
|
|
144
|
+
for (const row of history) {
|
|
145
|
+
const ts = timestamp(row), key = cluster(row);
|
|
146
|
+
if (!Number.isFinite(ts) || typeof key !== "string" || !key) throw new ValidationError("placeboBand: invalid timestamp or cluster");
|
|
147
|
+
const group = groups.get(key) ?? {
|
|
148
|
+
start: ts,
|
|
149
|
+
end: ts,
|
|
150
|
+
rows: []
|
|
151
|
+
};
|
|
152
|
+
group.start = Math.min(group.start, ts);
|
|
153
|
+
group.end = Math.max(group.end, ts);
|
|
154
|
+
group.rows.push(row);
|
|
155
|
+
groups.set(key, group);
|
|
156
|
+
}
|
|
157
|
+
const ordered = [...groups.values()].sort((a, b) => a.start - b.start);
|
|
158
|
+
const start = ordered[0]?.start ?? 0, end = Math.max(start, ...ordered.map((g) => g.end));
|
|
159
|
+
const hour = 36e5;
|
|
160
|
+
const candidates = [...options.boundaries ?? Array.from({ length: Math.max(0, Math.floor(end / hour) - Math.ceil(start / hour) + 1) }, (_, i) => (Math.ceil(start / hour) + i) * hour)].sort((a, b) => a - b);
|
|
161
|
+
if (candidates.some((t, i) => !Number.isFinite(t) || i > 0 && t - candidates[i - 1] < hour)) throw new ValidationError("placeboBand: boundaries must be at least one hour apart");
|
|
162
|
+
const deltas = [], boundaries = [];
|
|
163
|
+
if (end - start >= 72 * hour) for (const boundary of candidates) {
|
|
164
|
+
if (ordered.some((g) => g.start < boundary && g.end >= boundary)) continue;
|
|
165
|
+
const before = ordered.filter((g) => g.end < boundary).slice(-clustersPerArm);
|
|
166
|
+
const after = ordered.filter((g) => g.start >= boundary).slice(0, clustersPerArm);
|
|
167
|
+
if (before.length !== clustersPerArm || after.length !== clustersPerArm) continue;
|
|
168
|
+
const windowEnd = Math.max(...after.map((g) => g.end));
|
|
169
|
+
if (steps.some((t) => t >= before[0].start && t <= windowEnd)) continue;
|
|
170
|
+
const value = statistic(before.flatMap((g) => g.rows), after.flatMap((g) => g.rows));
|
|
171
|
+
if (!Number.isFinite(value)) throw new ValidationError("placeboBand: statistic must be finite");
|
|
172
|
+
boundaries.push(boundary);
|
|
173
|
+
deltas.push(value);
|
|
174
|
+
}
|
|
175
|
+
const calibrated = deltas.length >= 39, sorted = [...deltas].sort((a, b) => a - b);
|
|
176
|
+
const q025 = calibrated ? interpolatedQuantile(sorted, .025) : null, q975 = calibrated ? interpolatedQuantile(sorted, .975) : null;
|
|
177
|
+
return {
|
|
178
|
+
status: calibrated ? "calibrated" : "uncalibrated",
|
|
179
|
+
n: history.length,
|
|
180
|
+
K: deltas.length,
|
|
181
|
+
clustersPerArm,
|
|
182
|
+
boundaries,
|
|
183
|
+
deltas,
|
|
184
|
+
q025,
|
|
185
|
+
q975,
|
|
186
|
+
low: q975 === null ? null : delta - q975,
|
|
187
|
+
high: q025 === null ? null : delta - q025
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
// src/statistics/internal.ts
|
|
191
|
+
/**
|
|
192
|
+
* Shared internals for the statistics modules. Nothing here is part of the
|
|
193
|
+
* public statistics surface — `./index` does not re-export this module.
|
|
194
|
+
*/
|
|
195
|
+
/** Every rank test refuses non-finite input. Beyond the arithmetic being
|
|
196
|
+
* undefined, the tie-grouping scan compares values with `===`, and
|
|
197
|
+
* `NaN === NaN` is false, so a NaN would leave the group boundary unable to
|
|
198
|
+
* advance and spin the loop forever. */
|
|
199
|
+
function assertFiniteSample(fn, label, xs) {
|
|
200
|
+
for (let i = 0; i < xs.length; i++) if (!Number.isFinite(xs[i])) throw new ValidationError(`${fn}: ${label}[${i}] must be finite, got ${xs[i]}`);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —
|
|
204
|
+
* the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No
|
|
205
|
+
* discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it
|
|
206
|
+
* stays exact at large discordant counts without overflow.
|
|
207
|
+
*/
|
|
208
|
+
function binomialSignTwoSided(b, c) {
|
|
209
|
+
const nd = b + c;
|
|
210
|
+
if (nd === 0) return 1;
|
|
211
|
+
return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd));
|
|
212
|
+
}
|
|
213
|
+
/** P(X >= successes) for X ~ Binomial(n, 0.5). */
|
|
214
|
+
function binomialHalfUpperTail(successes, n) {
|
|
215
|
+
if (successes <= 0) return 1;
|
|
216
|
+
if (successes > n) return 0;
|
|
217
|
+
if (successes <= n / 2) return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n));
|
|
218
|
+
return binomialHalfLowerTail(n - successes, n);
|
|
219
|
+
}
|
|
220
|
+
/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */
|
|
221
|
+
function binomialHalfLowerTail(maxSuccesses, n) {
|
|
222
|
+
if (maxSuccesses < 0) return 0;
|
|
223
|
+
if (maxSuccesses >= n) return 1;
|
|
224
|
+
if (maxSuccesses === 0) return 2 ** -n;
|
|
225
|
+
const logHalfN = n * Math.log(.5);
|
|
226
|
+
let logTail = Number.NEGATIVE_INFINITY;
|
|
227
|
+
for (let i = 0; i <= maxSuccesses; i++) {
|
|
228
|
+
const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1);
|
|
229
|
+
logTail = logAddExp(logTail, logChoose + logHalfN);
|
|
230
|
+
}
|
|
231
|
+
return Math.min(1, Math.exp(logTail));
|
|
232
|
+
}
|
|
233
|
+
function logAddExp(a, b) {
|
|
234
|
+
if (a === Number.NEGATIVE_INFINITY) return b;
|
|
235
|
+
if (b === Number.NEGATIVE_INFINITY) return a;
|
|
236
|
+
const max = Math.max(a, b);
|
|
237
|
+
return max + Math.log1p(Math.exp(Math.min(a, b) - max));
|
|
238
|
+
}
|
|
239
|
+
/** Standard-normal inverse CDF (Acklam approximation). */
|
|
240
|
+
function zQuantile(p) {
|
|
241
|
+
if (p <= 0 || p >= 1) {
|
|
242
|
+
if (p === 0) return -Infinity;
|
|
243
|
+
if (p === 1) return Infinity;
|
|
244
|
+
return NaN;
|
|
245
|
+
}
|
|
246
|
+
const a = [
|
|
247
|
+
-39.69683028665376,
|
|
248
|
+
220.9460984245205,
|
|
249
|
+
-275.9285104469687,
|
|
250
|
+
138.357751867269,
|
|
251
|
+
-30.66479806614716,
|
|
252
|
+
2.506628277459239
|
|
253
|
+
];
|
|
254
|
+
const b = [
|
|
255
|
+
-54.47609879822406,
|
|
256
|
+
161.5858368580409,
|
|
257
|
+
-155.6989798598866,
|
|
258
|
+
66.80131188771972,
|
|
259
|
+
-13.28068155288572
|
|
260
|
+
];
|
|
261
|
+
const c = [
|
|
262
|
+
-.007784894002430293,
|
|
263
|
+
-.3223964580411365,
|
|
264
|
+
-2.400758277161838,
|
|
265
|
+
-2.549732539343734,
|
|
266
|
+
4.374664141464968,
|
|
267
|
+
2.938163982698783
|
|
268
|
+
];
|
|
269
|
+
const d = [
|
|
270
|
+
.007784695709041462,
|
|
271
|
+
.3224671290700398,
|
|
272
|
+
2.445134137142996,
|
|
273
|
+
3.754408661907416
|
|
274
|
+
];
|
|
275
|
+
const pLow = .02425;
|
|
276
|
+
const pHigh = .97575;
|
|
277
|
+
let q;
|
|
278
|
+
let r;
|
|
279
|
+
if (p < pLow) {
|
|
280
|
+
q = Math.sqrt(-2 * Math.log(p));
|
|
281
|
+
return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
282
|
+
}
|
|
283
|
+
if (p <= pHigh) {
|
|
284
|
+
q = p - .5;
|
|
285
|
+
r = q * q;
|
|
286
|
+
return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1);
|
|
287
|
+
}
|
|
288
|
+
q = Math.sqrt(-2 * Math.log(1 - p));
|
|
289
|
+
return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1);
|
|
290
|
+
}
|
|
291
|
+
function medianInPlace(xs) {
|
|
292
|
+
if (xs.length === 0) return 0;
|
|
293
|
+
xs.sort((a, b) => a - b);
|
|
294
|
+
return interpolatedQuantile(xs, .5);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* PRNG for every resampling path in this module.
|
|
298
|
+
*
|
|
299
|
+
* With no caller seed the seed is DERIVED FROM THE DATA rather than taken from
|
|
300
|
+
* `Math.random`, so re-running the same input reproduces the same interval —
|
|
301
|
+
* a gate verdict that cannot be re-derived is not evidence. Distinct data
|
|
302
|
+
* still gets a distinct stream. Same pattern as `promotion-gate.ts`.
|
|
303
|
+
*/
|
|
304
|
+
function makeRng(seed, ...series) {
|
|
305
|
+
return mulberry32(seed ?? seedFromData(series));
|
|
306
|
+
}
|
|
307
|
+
/** FNV-1a over the IEEE-754 bytes of every observation. */
|
|
308
|
+
function seedFromData(series) {
|
|
309
|
+
const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
|
|
310
|
+
let hash = 2166136261;
|
|
311
|
+
for (const xs of series) {
|
|
312
|
+
for (const x of xs) {
|
|
313
|
+
view.setFloat64(0, x);
|
|
314
|
+
for (let byte = 0; byte < 8; byte++) hash = Math.imul(hash ^ view.getUint8(byte), 16777619);
|
|
315
|
+
}
|
|
316
|
+
hash = Math.imul(hash ^ 255, 16777619);
|
|
317
|
+
}
|
|
318
|
+
return hash | 0;
|
|
319
|
+
}
|
|
320
|
+
/** Order-independent seed for a symmetric two-sample statistic. */
|
|
321
|
+
function symmetricTwoSampleSeed(a, b) {
|
|
322
|
+
const sortedA = [...a].sort((left, right) => left - right);
|
|
323
|
+
const sortedB = [...b].sort((left, right) => left - right);
|
|
324
|
+
const forward = seedFromData([sortedA, sortedB]) >>> 0;
|
|
325
|
+
const reversed = seedFromData([sortedB, sortedA]) >>> 0;
|
|
326
|
+
return Math.min(forward, reversed);
|
|
327
|
+
}
|
|
328
|
+
// src/statistics/mean.ts
|
|
329
|
+
/** Arithmetic mean. An empty input has no mean and returns NaN. */
|
|
330
|
+
function mean(values) {
|
|
331
|
+
return values.reduce((sum, value) => sum + value, 0) / values.length;
|
|
332
|
+
}
|
|
333
|
+
/** Arithmetic mean, or null for an empty input. */
|
|
334
|
+
function meanOrNull(values) {
|
|
335
|
+
return values.length === 0 ? null : mean(values);
|
|
336
|
+
}
|
|
337
|
+
/** Arithmetic mean, or 0 for an empty input. */
|
|
338
|
+
function meanOrZero(values) {
|
|
339
|
+
return values.length === 0 ? 0 : mean(values);
|
|
340
|
+
}
|
|
341
|
+
// src/statistics/descriptive.ts
|
|
342
|
+
/**
|
|
343
|
+
* Descriptive statistics: means, bootstrap spread, correlation, and the
|
|
344
|
+
* weighted judge-dimension composite. Nothing here is a significance test.
|
|
345
|
+
*/
|
|
346
|
+
/** Weighted mean — falls back to uniform weights when omitted */
|
|
347
|
+
function weightedMean(scores) {
|
|
348
|
+
if (scores.length === 0) return 0;
|
|
349
|
+
let totalWeight = 0;
|
|
350
|
+
let weightedSum = 0;
|
|
351
|
+
for (const { score, weight } of scores) {
|
|
352
|
+
const w = weight ?? 1;
|
|
353
|
+
weightedSum += score * w;
|
|
354
|
+
totalWeight += w;
|
|
355
|
+
}
|
|
356
|
+
return totalWeight > 0 ? weightedSum / totalWeight : 0;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Percentile bootstrap confidence interval on the mean of `scores`.
|
|
360
|
+
*
|
|
361
|
+
* Descriptive spread. It is not a significance test, and at small n its bounds
|
|
362
|
+
* are anti-conservative in the same way {@link pairedBootstrap}'s are — see
|
|
363
|
+
* {@link BOOTSTRAP_GATE_MIN_N}. With no `seed` the resampling is seeded from
|
|
364
|
+
* the scores themselves, so the interval is reproducible either way.
|
|
365
|
+
*/
|
|
366
|
+
function confidenceInterval(scores, confidence = .95, opts = {}) {
|
|
367
|
+
if (scores.length === 0) return {
|
|
368
|
+
mean: 0,
|
|
369
|
+
lower: 0,
|
|
370
|
+
upper: 0
|
|
371
|
+
};
|
|
372
|
+
if (scores.length === 1) return {
|
|
373
|
+
mean: scores[0],
|
|
374
|
+
lower: scores[0],
|
|
375
|
+
upper: scores[0]
|
|
376
|
+
};
|
|
377
|
+
const n = scores.length;
|
|
378
|
+
const mean = scores.reduce((a, b) => a + b, 0) / n;
|
|
379
|
+
const B = opts.resamples ?? 1e3;
|
|
380
|
+
const rng = makeRng(opts.seed, scores);
|
|
381
|
+
const bootstrapMeans = [];
|
|
382
|
+
for (let i = 0; i < B; i++) {
|
|
383
|
+
let sum = 0;
|
|
384
|
+
for (let j = 0; j < n; j++) sum += scores[Math.floor(rng() * n)];
|
|
385
|
+
bootstrapMeans.push(sum / n);
|
|
386
|
+
}
|
|
387
|
+
bootstrapMeans.sort((a, b) => a - b);
|
|
388
|
+
const alpha = 1 - confidence;
|
|
389
|
+
const lowerIdx = Math.floor(alpha / 2 * B);
|
|
390
|
+
const upperIdx = Math.floor((1 - alpha / 2) * B) - 1;
|
|
391
|
+
return {
|
|
392
|
+
mean,
|
|
393
|
+
lower: bootstrapMeans[lowerIdx],
|
|
394
|
+
upper: bootstrapMeans[Math.min(upperIdx, B - 1)]
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Two-sided Student-t critical value: the `t` with `P(|T| ≤ t) = confidence`
|
|
399
|
+
* for `df` degrees of freedom. Exact, from {@link studentTQuantile}, so any
|
|
400
|
+
* confidence in (0, 1) and fractional `df` are supported.
|
|
401
|
+
*/
|
|
402
|
+
function studentTCritical(df, confidence = .95) {
|
|
403
|
+
if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError(`studentTCritical: confidence must be in (0, 1), got ${confidence}`);
|
|
404
|
+
if (!Number.isFinite(df) || df <= 0) throw new ValidationError(`studentTCritical: df must be positive and finite, got ${df}`);
|
|
405
|
+
return studentTQuantile(1 - (1 - confidence) / 2, df);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Student-t confidence interval on the mean of one sample:
|
|
409
|
+
* `mean ± t(df = n − 1) · s / √n`. Below two samples there is no spread to
|
|
410
|
+
* estimate, so the bounds are null rather than a zero-width interval that
|
|
411
|
+
* would read as certainty. Unlike {@link confidenceInterval} (a percentile
|
|
412
|
+
* bootstrap), the width keeps the small-n t penalty that z = 1.96 drops.
|
|
413
|
+
*/
|
|
414
|
+
function meanConfidenceInterval(samples, confidence = .95) {
|
|
415
|
+
assertFiniteSample("meanConfidenceInterval", "samples", samples);
|
|
416
|
+
const n = samples.length;
|
|
417
|
+
if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError(`meanConfidenceInterval: confidence must be in (0, 1), got ${confidence}`);
|
|
418
|
+
if (n < 2) return {
|
|
419
|
+
n,
|
|
420
|
+
mean: n === 0 ? null : samples[0],
|
|
421
|
+
stdev: null,
|
|
422
|
+
low: null,
|
|
423
|
+
high: null,
|
|
424
|
+
criticalValue: null
|
|
425
|
+
};
|
|
426
|
+
const center = mean(samples);
|
|
427
|
+
const sumSquares = samples.reduce((sum, value) => sum + (value - center) ** 2, 0);
|
|
428
|
+
const stdev = Math.sqrt(sumSquares / (n - 1));
|
|
429
|
+
const criticalValue = studentTCritical(n - 1, confidence);
|
|
430
|
+
const halfWidth = criticalValue * stdev / Math.sqrt(n);
|
|
431
|
+
return {
|
|
432
|
+
n,
|
|
433
|
+
mean: center,
|
|
434
|
+
stdev,
|
|
435
|
+
low: center - halfWidth,
|
|
436
|
+
high: center + halfWidth,
|
|
437
|
+
criticalValue
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
/** Partial credit: returns 0-1 ratio of current toward target */
|
|
441
|
+
function partialCredit(current, target) {
|
|
442
|
+
if (target <= 0) return 1;
|
|
443
|
+
return Math.min(1, Math.max(0, current / target));
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Fold a number series into its distribution summary. Quantiles use the
|
|
447
|
+
* nearest-rank definition — the `ceil(q·n)`-th order statistic — so every
|
|
448
|
+
* reported quantile is a value from the series. Returns `null` for an empty
|
|
449
|
+
* series: an empty series has no distribution, and a zero-filled summary
|
|
450
|
+
* would read as a measured all-zero series.
|
|
451
|
+
*/
|
|
452
|
+
function summarizeNumberSeries(values, options) {
|
|
453
|
+
const criticalValue = options?.medianInterval?.criticalValue;
|
|
454
|
+
if (options) {
|
|
455
|
+
assertFiniteSample("summarizeNumberSeries", "values", values);
|
|
456
|
+
for (const percentile of options.percentiles ?? []) if (!Number.isFinite(percentile) || percentile < 0 || percentile > 100) throw new ValidationError("summarizeNumberSeries: percentiles must be finite and between 0 and 100");
|
|
457
|
+
if (options.medianInterval && (criticalValue === void 0 || !Number.isFinite(criticalValue) || criticalValue < 0)) throw new ValidationError("summarizeNumberSeries: median criticalValue must be finite and nonnegative");
|
|
458
|
+
}
|
|
459
|
+
if (values.length === 0) return null;
|
|
460
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
461
|
+
const n = sorted.length;
|
|
462
|
+
const rank = (q) => sorted[Math.min(n - 1, Math.max(0, Math.ceil(q * n) - 1))];
|
|
463
|
+
const sum = sorted.reduce((a, b) => a + b, 0);
|
|
464
|
+
if (options && !Number.isFinite(sum)) throw new ValidationError("summarizeNumberSeries: sample sum exceeded finite range");
|
|
465
|
+
const spread = criticalValue === void 0 ? void 0 : criticalValue / 2 * Math.sqrt(n);
|
|
466
|
+
const lowRank = spread === void 0 ? 1 : Math.max(1, Math.floor(n / 2 - spread));
|
|
467
|
+
const highRank = spread === void 0 ? n : Math.min(n, Math.ceil(n / 2 + 1 + spread));
|
|
468
|
+
return {
|
|
469
|
+
n,
|
|
470
|
+
min: sorted[0],
|
|
471
|
+
p50: rank(.5),
|
|
472
|
+
p90: rank(.9),
|
|
473
|
+
max: sorted[sorted.length - 1],
|
|
474
|
+
sum,
|
|
475
|
+
...options?.percentiles === void 0 ? {} : { percentiles: Object.fromEntries(options.percentiles.map((percentile) => [percentile, rank(percentile / 100)])) },
|
|
476
|
+
...criticalValue === void 0 ? {} : { medianInterval: {
|
|
477
|
+
method: "normal-order-statistics",
|
|
478
|
+
criticalValue,
|
|
479
|
+
sampleSize: n,
|
|
480
|
+
lowRank,
|
|
481
|
+
highRank,
|
|
482
|
+
low: sorted[lowRank - 1],
|
|
483
|
+
high: sorted[highRank - 1]
|
|
484
|
+
} }
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Average-rank-with-ties transform (1-indexed). Tied values receive the mean
|
|
489
|
+
* of the ranks they span, the standard correction for Spearman's ρ.
|
|
490
|
+
*/
|
|
491
|
+
function ranks(xs) {
|
|
492
|
+
const indexed = xs.map((v, i) => ({
|
|
493
|
+
v,
|
|
494
|
+
i
|
|
495
|
+
})).sort((a, b) => a.v - b.v);
|
|
496
|
+
const r = new Array(xs.length);
|
|
497
|
+
let i = 0;
|
|
498
|
+
while (i < indexed.length) {
|
|
499
|
+
let j = i;
|
|
500
|
+
while (j + 1 < indexed.length && indexed[j + 1].v === indexed[i].v) j++;
|
|
501
|
+
const avg = (i + j) / 2 + 1;
|
|
502
|
+
for (let k = i; k <= j; k++) r[indexed[k].i] = avg;
|
|
503
|
+
i = j + 1;
|
|
504
|
+
}
|
|
505
|
+
return r;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Pearson product-moment correlation coefficient r ∈ [-1, 1] between two
|
|
509
|
+
* equal-length series. See the edge-case contract above: NaN for n < 2 or
|
|
510
|
+
* unequal lengths, 1 when both series are constant, 0 when exactly one is.
|
|
511
|
+
*/
|
|
512
|
+
function pearsonR(a, b) {
|
|
513
|
+
if (a.length !== b.length || a.length < 2) return NaN;
|
|
514
|
+
const n = a.length;
|
|
515
|
+
const meanA = a.reduce((s, v) => s + v, 0) / n;
|
|
516
|
+
const meanB = b.reduce((s, v) => s + v, 0) / n;
|
|
517
|
+
let num = 0;
|
|
518
|
+
let varA = 0;
|
|
519
|
+
let varB = 0;
|
|
520
|
+
for (let i = 0; i < n; i++) {
|
|
521
|
+
const da = a[i] - meanA;
|
|
522
|
+
const db = b[i] - meanB;
|
|
523
|
+
num += da * db;
|
|
524
|
+
varA += da * da;
|
|
525
|
+
varB += db * db;
|
|
526
|
+
}
|
|
527
|
+
if (varA === 0 || varB === 0) return varA === 0 && varB === 0 ? 1 : 0;
|
|
528
|
+
return num / Math.sqrt(varA * varB);
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Spearman's rank correlation ρ — Pearson over the average-rank-with-ties
|
|
532
|
+
* transform of each series. Same edge-case contract as {@link pearsonR}.
|
|
533
|
+
*/
|
|
534
|
+
function spearmanR(a, b) {
|
|
535
|
+
if (a.length !== b.length || a.length < 2) return NaN;
|
|
536
|
+
return pearsonR(ranks(a), ranks(b));
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Weighted composite over judge dimensions: `Σ(score_d · w_d) / Σ(w_d)` across
|
|
540
|
+
* the weighted dimensions. The canonical replacement for the per-consumer
|
|
541
|
+
* hand-rolled composite math (tax/legal/creative/gtm each ship a copy).
|
|
542
|
+
*
|
|
543
|
+
* Fail-loud: throws if a weighted dimension is missing from `dims`, if any
|
|
544
|
+
* weight is negative, or if the weights sum to 0 — none of which can produce
|
|
545
|
+
* a meaningful composite.
|
|
546
|
+
*/
|
|
547
|
+
function weightedComposite(input) {
|
|
548
|
+
const entries = Object.entries(input.weights);
|
|
549
|
+
if (entries.length === 0) throw new Error("weightedComposite: `weights` is empty — nothing to combine");
|
|
550
|
+
let weightedSum = 0;
|
|
551
|
+
let weightTotal = 0;
|
|
552
|
+
for (const [dim, weight] of entries) {
|
|
553
|
+
if (weight < 0) throw new Error(`weightedComposite: weight for '${dim}' is negative (${weight})`);
|
|
554
|
+
if (!(dim in input.dims)) throw new Error(`weightedComposite: weighted dimension '${dim}' is absent from \`dims\` — refusing to renormalise onto a different denominator`);
|
|
555
|
+
weightedSum += input.dims[dim] * weight;
|
|
556
|
+
weightTotal += weight;
|
|
557
|
+
}
|
|
558
|
+
if (weightTotal === 0) throw new Error("weightedComposite: weights sum to 0 — composite is undefined");
|
|
559
|
+
const composite = weightedSum / weightTotal;
|
|
560
|
+
return input.threshold === void 0 ? { composite } : {
|
|
561
|
+
composite,
|
|
562
|
+
pass: composite >= input.threshold
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
// src/judge-calibration.ts
|
|
566
|
+
/**
|
|
567
|
+
* Judge calibration — measure judge quality against human gold + bias.
|
|
568
|
+
*
|
|
569
|
+
* Workflow:
|
|
570
|
+
* 1. Build a golden set: {itemId, humanScore}[].
|
|
571
|
+
* 2. Run candidate judges; each produces {itemId, score}.
|
|
572
|
+
* 3. `calibrateJudge(golden, candidate)` reports κ + Pearson + MAE.
|
|
573
|
+
* 4. `calibrateJudgeContinuous(golden, candidate)` adds quadratic-weighted
|
|
574
|
+
* κ over the un-rounded [0,1] scores plus ICC(2,1), Pearson, Spearman,
|
|
575
|
+
* and bootstrap CIs — use this for fine-grained judges where rounding
|
|
576
|
+
* to int discards information (e.g. 0.78 vs 0.81 both round to 1 and
|
|
577
|
+
* look "perfectly agreed" to integer κ).
|
|
578
|
+
* 5. Run bias probes (positional, verbosity, self-preference) to
|
|
579
|
+
* detect systematic score inflation.
|
|
580
|
+
* 6. For N≥2 judges on the same items, `continuousAgreement(scores)`
|
|
581
|
+
* reports ICC(2,1) + κ_w + Pearson + Spearman with bootstrap CIs.
|
|
582
|
+
*
|
|
583
|
+
* Returns actionable diagnostics, not a single number. Consumers then
|
|
584
|
+
* decide whether to trust the judge, retrain it, or add a tie-breaker.
|
|
585
|
+
*/
|
|
586
|
+
/**
|
|
587
|
+
* Measure judge quality against human gold labels: computes Cohen's κ, Pearson correlation, and MAE over matched item ids.
|
|
588
|
+
*/
|
|
589
|
+
function calibrateJudge(golden, candidate) {
|
|
590
|
+
const map = /* @__PURE__ */ new Map();
|
|
591
|
+
for (const g of golden) map.set(g.itemId, {
|
|
592
|
+
h: g.humanScore,
|
|
593
|
+
j: NaN
|
|
594
|
+
});
|
|
595
|
+
for (const c of candidate) {
|
|
596
|
+
const entry = map.get(c.itemId);
|
|
597
|
+
if (entry) entry.j = c.score;
|
|
598
|
+
}
|
|
599
|
+
const common = [...map.values()].filter((v) => Number.isFinite(v.j));
|
|
600
|
+
const n = common.length;
|
|
601
|
+
if (n < 2) return {
|
|
602
|
+
n,
|
|
603
|
+
pearson: NaN,
|
|
604
|
+
kappa: NaN,
|
|
605
|
+
mae: NaN,
|
|
606
|
+
worstItems: []
|
|
607
|
+
};
|
|
608
|
+
const humans = common.map((c) => c.h);
|
|
609
|
+
const judges = common.map((c) => c.j);
|
|
610
|
+
return {
|
|
611
|
+
n,
|
|
612
|
+
pearson: pearsonR(humans, judges),
|
|
613
|
+
kappa: weightedKappa(humans.map(Math.round), judges.map(Math.round)),
|
|
614
|
+
mae: common.map((c) => Math.abs(c.j - c.h)).reduce((a, b) => a + b, 0) / n,
|
|
615
|
+
worstItems: [...map.entries()].filter(([, v]) => Number.isFinite(v.j)).map(([itemId, v]) => ({
|
|
616
|
+
itemId,
|
|
617
|
+
judge: v.j,
|
|
618
|
+
human: v.h,
|
|
619
|
+
delta: Math.abs(v.j - v.h)
|
|
620
|
+
})).sort((a, b) => b.delta - a.delta).slice(0, 5)
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Feed the same items to the judge twice with A/B swapped and pass all
|
|
625
|
+
* results here. Items that don't appear in both positions are ignored.
|
|
626
|
+
*/
|
|
627
|
+
function positionalBias(scores) {
|
|
628
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
629
|
+
for (const s of scores) {
|
|
630
|
+
const slot = pairs.get(s.itemId) ?? {};
|
|
631
|
+
if (s.positionOfAInput === "first") slot.first = s.score;
|
|
632
|
+
else if (s.positionOfAInput === "second") slot.second = s.score;
|
|
633
|
+
pairs.set(s.itemId, slot);
|
|
634
|
+
}
|
|
635
|
+
const deltas = [];
|
|
636
|
+
for (const { first, second } of pairs.values()) if (first !== void 0 && second !== void 0) deltas.push(first - second);
|
|
637
|
+
if (deltas.length === 0) return {
|
|
638
|
+
avgDelta: 0,
|
|
639
|
+
n: 0
|
|
640
|
+
};
|
|
641
|
+
return {
|
|
642
|
+
avgDelta: deltas.reduce((a, b) => a + b, 0) / deltas.length,
|
|
643
|
+
n: deltas.length
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
function verbosityBias(samples) {
|
|
647
|
+
const n = samples.length;
|
|
648
|
+
if (n < 3) return {
|
|
649
|
+
pearson: NaN,
|
|
650
|
+
n
|
|
651
|
+
};
|
|
652
|
+
return {
|
|
653
|
+
pearson: pearsonR(samples.map((s) => s.outputLen), samples.map((s) => s.score)),
|
|
654
|
+
n
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Pass the same scenarios scored with judge-model X grading outputs from
|
|
659
|
+
* model X (in-family) and model Y (out-of-family). Non-zero delta
|
|
660
|
+
* indicates self-preference.
|
|
661
|
+
*/
|
|
662
|
+
function selfPreference(samples) {
|
|
663
|
+
const inF = samples.filter((s) => s.inFamily).map((s) => s.score);
|
|
664
|
+
const outF = samples.filter((s) => !s.inFamily).map((s) => s.score);
|
|
665
|
+
if (inF.length === 0 || outF.length === 0) return {
|
|
666
|
+
inFamilyMean: 0,
|
|
667
|
+
outOfFamilyMean: 0,
|
|
668
|
+
deltaMean: 0,
|
|
669
|
+
n: 0
|
|
670
|
+
};
|
|
671
|
+
const inMean = inF.reduce((a, b) => a + b, 0) / inF.length;
|
|
672
|
+
const outMean = outF.reduce((a, b) => a + b, 0) / outF.length;
|
|
673
|
+
return {
|
|
674
|
+
inFamilyMean: inMean,
|
|
675
|
+
outOfFamilyMean: outMean,
|
|
676
|
+
deltaMean: inMean - outMean,
|
|
677
|
+
n: samples.length
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
/** Quadratic weighted Cohen's κ over bounded integer scores. */
|
|
681
|
+
function weightedKappa(a, b) {
|
|
682
|
+
if (a.length !== b.length || a.length === 0) return NaN;
|
|
683
|
+
const min = Math.min(...a, ...b);
|
|
684
|
+
const K = Math.max(...a, ...b) - min + 1;
|
|
685
|
+
if (K < 2) return 1;
|
|
686
|
+
const observed = Array.from({ length: K }, () => new Array(K).fill(0));
|
|
687
|
+
const rowMarg = new Array(K).fill(0);
|
|
688
|
+
const colMarg = new Array(K).fill(0);
|
|
689
|
+
for (let i = 0; i < a.length; i++) {
|
|
690
|
+
const ai = a[i] - min;
|
|
691
|
+
const bi = b[i] - min;
|
|
692
|
+
const row = observed[ai];
|
|
693
|
+
row[bi] = (row[bi] ?? 0) + 1;
|
|
694
|
+
rowMarg[ai]++;
|
|
695
|
+
colMarg[bi]++;
|
|
696
|
+
}
|
|
697
|
+
let num = 0;
|
|
698
|
+
let den = 0;
|
|
699
|
+
for (let i = 0; i < K; i++) for (let j = 0; j < K; j++) {
|
|
700
|
+
const w = (i - j) ** 2 / (K - 1) ** 2;
|
|
701
|
+
const expected = rowMarg[i] * colMarg[j] / a.length;
|
|
702
|
+
num += w * observed[i][j];
|
|
703
|
+
den += w * expected;
|
|
704
|
+
}
|
|
705
|
+
if (den === 0) return 1;
|
|
706
|
+
return 1 - num / den;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Inter-rater agreement on continuous (typically [0,1]) scores.
|
|
710
|
+
*
|
|
711
|
+
* `scores` has shape [n_items][n_raters]. Rows with any non-finite entry
|
|
712
|
+
* are dropped. Returns NaN metrics if fewer than 2 raters or 2 complete
|
|
713
|
+
* items remain.
|
|
714
|
+
*/
|
|
715
|
+
function continuousAgreement(scores, opts = {}) {
|
|
716
|
+
const bootstrap = opts.bootstrap ?? 1e3;
|
|
717
|
+
const weights = opts.weights ?? "quadratic";
|
|
718
|
+
const seed = opts.seed ?? 12648430;
|
|
719
|
+
const ciLevel = opts.ciLevel ?? .95;
|
|
720
|
+
const matrix = scores.filter((row) => row.length >= 2 && row.every((v) => Number.isFinite(v)));
|
|
721
|
+
const raters = matrix[0]?.length ?? 0;
|
|
722
|
+
const clean = matrix.filter((row) => row.length === raters);
|
|
723
|
+
const nClean = clean.length;
|
|
724
|
+
if (nClean < 2 || raters < 2) return {
|
|
725
|
+
weightedKappa: NaN,
|
|
726
|
+
icc: NaN,
|
|
727
|
+
pearson: NaN,
|
|
728
|
+
spearman: NaN,
|
|
729
|
+
ci: {
|
|
730
|
+
icc: [NaN, NaN],
|
|
731
|
+
weightedKappa: [NaN, NaN]
|
|
732
|
+
},
|
|
733
|
+
n: nClean,
|
|
734
|
+
raters
|
|
735
|
+
};
|
|
736
|
+
const kappa = continuousWeightedKappa(clean, weights);
|
|
737
|
+
const icc = icc21(clean);
|
|
738
|
+
const pearson = avgPairwise(clean, pearsonR);
|
|
739
|
+
const spearman = avgPairwise(clean, spearmanR);
|
|
740
|
+
const interval = (statistic) => {
|
|
741
|
+
const ci = clusterBootstrap(clean, (_, i) => String(i), statistic, {
|
|
742
|
+
resamples: bootstrap,
|
|
743
|
+
seed,
|
|
744
|
+
level: ciLevel
|
|
745
|
+
});
|
|
746
|
+
return [ci.low, ci.high];
|
|
747
|
+
};
|
|
748
|
+
return {
|
|
749
|
+
weightedKappa: kappa,
|
|
750
|
+
icc,
|
|
751
|
+
pearson,
|
|
752
|
+
spearman,
|
|
753
|
+
ci: {
|
|
754
|
+
icc: interval(icc21),
|
|
755
|
+
weightedKappa: interval((sample) => continuousWeightedKappa(sample, weights))
|
|
756
|
+
},
|
|
757
|
+
n: nClean,
|
|
758
|
+
raters
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Extends `calibrateJudge` with continuous-value agreement metrics while
|
|
763
|
+
* retaining its base calibration summary.
|
|
764
|
+
*/
|
|
765
|
+
function calibrateJudgeContinuous(golden, candidate, opts = {}) {
|
|
766
|
+
const base = calibrateJudge(golden, candidate);
|
|
767
|
+
const map = /* @__PURE__ */ new Map();
|
|
768
|
+
for (const g of golden) map.set(g.itemId, {
|
|
769
|
+
h: g.humanScore,
|
|
770
|
+
j: NaN
|
|
771
|
+
});
|
|
772
|
+
for (const c of candidate) {
|
|
773
|
+
const entry = map.get(c.itemId);
|
|
774
|
+
if (entry) entry.j = c.score;
|
|
775
|
+
}
|
|
776
|
+
const rows = [];
|
|
777
|
+
for (const v of map.values()) if (Number.isFinite(v.j)) rows.push([v.h, v.j]);
|
|
778
|
+
const agreement = continuousAgreement(rows, opts);
|
|
779
|
+
return {
|
|
780
|
+
...base,
|
|
781
|
+
weightedKappaContinuous: agreement.weightedKappa,
|
|
782
|
+
icc: agreement.icc,
|
|
783
|
+
spearman: agreement.spearman,
|
|
784
|
+
ci: agreement.ci
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Quadratic-weighted κ on continuous scores. With weights w(x,y) = (x-y)^2
|
|
789
|
+
* (or |x-y| for linear) the formula collapses to:
|
|
790
|
+
*
|
|
791
|
+
* κ_w = 1 − E_obs[w] / E_exp[w]
|
|
792
|
+
*
|
|
793
|
+
* where E_obs averages w over paired (a_i, b_i) and E_exp averages w over
|
|
794
|
+
* the independent product distribution (sum_{i,j} w(a_i, b_j) / n^2).
|
|
795
|
+
* The normalisation by (max-min)^2 in the integer version cancels in the
|
|
796
|
+
* ratio, so we don't need it here. Generalises to N raters by averaging κ_w
|
|
797
|
+
* over all rater pairs (mean pairwise weighted agreement).
|
|
798
|
+
*/
|
|
799
|
+
function continuousWeightedKappa(rows, scheme) {
|
|
800
|
+
if (rows.length === 0) return NaN;
|
|
801
|
+
const raters = rows[0].length;
|
|
802
|
+
if (raters < 2) return NaN;
|
|
803
|
+
const wFn = scheme === "linear" ? (x, y) => Math.abs(x - y) : (x, y) => (x - y) ** 2;
|
|
804
|
+
let sum = 0;
|
|
805
|
+
let pairs = 0;
|
|
806
|
+
for (let r1 = 0; r1 < raters; r1++) for (let r2 = r1 + 1; r2 < raters; r2++) {
|
|
807
|
+
const a = rows.map((row) => row[r1]);
|
|
808
|
+
const b = rows.map((row) => row[r2]);
|
|
809
|
+
const n = a.length;
|
|
810
|
+
let obs = 0;
|
|
811
|
+
for (let i = 0; i < n; i++) obs += wFn(a[i], b[i]);
|
|
812
|
+
obs /= n;
|
|
813
|
+
let exp = 0;
|
|
814
|
+
for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) exp += wFn(a[i], b[j]);
|
|
815
|
+
exp /= n * n;
|
|
816
|
+
if (exp === 0) sum += obs === 0 ? 1 : 0;
|
|
817
|
+
else sum += 1 - obs / exp;
|
|
818
|
+
pairs++;
|
|
819
|
+
}
|
|
820
|
+
return pairs === 0 ? NaN : sum / pairs;
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* ICC(2,1) — two-way random effects, absolute agreement, single rater.
|
|
824
|
+
*
|
|
825
|
+
* ICC(2,1) = (MSR − MSE) / (MSR + (k−1)·MSE + k·(MSC − MSE)/n)
|
|
826
|
+
*
|
|
827
|
+
* where MSR = between-rows MS, MSC = between-columns MS, MSE = residual MS,
|
|
828
|
+
* n = rows (items), k = columns (raters).
|
|
829
|
+
*/
|
|
830
|
+
function icc21(rows) {
|
|
831
|
+
const n = rows.length;
|
|
832
|
+
if (n < 2) return NaN;
|
|
833
|
+
const k = rows[0].length;
|
|
834
|
+
if (k < 2) return NaN;
|
|
835
|
+
const rowMeans = rows.map((row) => row.reduce((s, v) => s + v, 0) / k);
|
|
836
|
+
const colMeans = new Array(k).fill(0);
|
|
837
|
+
for (let j = 0; j < k; j++) {
|
|
838
|
+
let s = 0;
|
|
839
|
+
for (let i = 0; i < n; i++) s += rows[i][j];
|
|
840
|
+
colMeans[j] = s / n;
|
|
841
|
+
}
|
|
842
|
+
let grand = 0;
|
|
843
|
+
for (let i = 0; i < n; i++) grand += rowMeans[i];
|
|
844
|
+
grand /= n;
|
|
845
|
+
let ssR = 0;
|
|
846
|
+
for (let i = 0; i < n; i++) ssR += (rowMeans[i] - grand) ** 2;
|
|
847
|
+
ssR *= k;
|
|
848
|
+
let ssC = 0;
|
|
849
|
+
for (let j = 0; j < k; j++) ssC += (colMeans[j] - grand) ** 2;
|
|
850
|
+
ssC *= n;
|
|
851
|
+
let ssT = 0;
|
|
852
|
+
for (let i = 0; i < n; i++) for (let j = 0; j < k; j++) ssT += (rows[i][j] - grand) ** 2;
|
|
853
|
+
const ssE = ssT - ssR - ssC;
|
|
854
|
+
const dfR = n - 1;
|
|
855
|
+
const dfC = k - 1;
|
|
856
|
+
const dfE = (n - 1) * (k - 1);
|
|
857
|
+
const msR = ssR / dfR;
|
|
858
|
+
const msC = ssC / dfC;
|
|
859
|
+
const msE = dfE > 0 ? ssE / dfE : 0;
|
|
860
|
+
const denom = msR + (k - 1) * msE + k * (msC - msE) / n;
|
|
861
|
+
if (denom === 0) return msR === 0 && msE === 0 ? 1 : 0;
|
|
862
|
+
return (msR - msE) / denom;
|
|
863
|
+
}
|
|
864
|
+
/** Average pairwise statistic over all rater pairs. */
|
|
865
|
+
function avgPairwise(rows, fn) {
|
|
866
|
+
const k = rows[0]?.length ?? 0;
|
|
867
|
+
if (k < 2) return NaN;
|
|
868
|
+
let sum = 0;
|
|
869
|
+
let pairs = 0;
|
|
870
|
+
for (let i = 0; i < k; i++) for (let j = i + 1; j < k; j++) {
|
|
871
|
+
const r = fn(rows.map((row) => row[i]), rows.map((row) => row[j]));
|
|
872
|
+
if (Number.isFinite(r)) {
|
|
873
|
+
sum += r;
|
|
874
|
+
pairs++;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
return pairs === 0 ? NaN : sum / pairs;
|
|
878
|
+
}
|
|
879
|
+
// src/statistics/agreement-irr.ts
|
|
880
|
+
/**
|
|
881
|
+
* Inter-rater reliability — Krippendorff's α under the squared-difference
|
|
882
|
+
* metric, pooled across dimensions.
|
|
883
|
+
*
|
|
884
|
+
* Each inner array is one judge's scores. Items are matched by position
|
|
885
|
+
* WITHIN a dimension: the k-th score a judge supplies carrying dimension
|
|
886
|
+
* `d` is item k of `d`, and the ratings compared against each other are
|
|
887
|
+
* the ones different judges gave to the same item. Every judge that scores
|
|
888
|
+
* a dimension at all must supply the same number of scores for it —
|
|
889
|
+
* ragged input cannot be aligned into items and throws rather than
|
|
890
|
+
* comparing mismatched items.
|
|
891
|
+
*
|
|
892
|
+
* α = 1 − D_observed / D_expected: D_observed averages the squared
|
|
893
|
+
* difference over within-item judge pairs, D_expected over every pair of
|
|
894
|
+
* ratings irrespective of item. α = 1 is perfect agreement, 0 is chance,
|
|
895
|
+
* negative is systematic disagreement.
|
|
896
|
+
*/
|
|
897
|
+
function interRaterReliability(judgeScores) {
|
|
898
|
+
if (judgeScores.length < 2) return 1;
|
|
899
|
+
const perDimension = /* @__PURE__ */ new Map();
|
|
900
|
+
for (let judgeIndex = 0; judgeIndex < judgeScores.length; judgeIndex++) for (const s of judgeScores[judgeIndex]) {
|
|
901
|
+
let byJudge = perDimension.get(s.dimension);
|
|
902
|
+
if (byJudge === void 0) {
|
|
903
|
+
byJudge = Array.from({ length: judgeScores.length }, () => []);
|
|
904
|
+
perDimension.set(s.dimension, byJudge);
|
|
905
|
+
}
|
|
906
|
+
byJudge[judgeIndex].push(s.score);
|
|
907
|
+
}
|
|
908
|
+
const allValues = [];
|
|
909
|
+
const pairDiffs = [];
|
|
910
|
+
for (const [dimension, byJudge] of perDimension) {
|
|
911
|
+
const scoring = byJudge.filter((scores) => scores.length > 0);
|
|
912
|
+
if (scoring.length < 2) continue;
|
|
913
|
+
const itemCount = scoring[0].length;
|
|
914
|
+
if (scoring.some((scores) => scores.length !== itemCount)) throw new ValidationError(`interRaterReliability: dimension '${dimension}' has judges supplying ${scoring.map((scores) => scores.length).join("/")} scores — items cannot be aligned`);
|
|
915
|
+
for (let item = 0; item < itemCount; item++) {
|
|
916
|
+
const ratings = scoring.map((scores) => scores[item]);
|
|
917
|
+
for (const v of ratings) allValues.push(v);
|
|
918
|
+
for (let i = 0; i < ratings.length; i++) for (let j = i + 1; j < ratings.length; j++) pairDiffs.push((ratings[i] - ratings[j]) ** 2);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (pairDiffs.length === 0 || allValues.length < 2) return 1;
|
|
922
|
+
const observedDisagreement = pairDiffs.reduce((a, b) => a + b, 0) / pairDiffs.length;
|
|
923
|
+
let expectedDisagreement = 0;
|
|
924
|
+
let expectedCount = 0;
|
|
925
|
+
for (let i = 0; i < allValues.length; i++) for (let j = i + 1; j < allValues.length; j++) {
|
|
926
|
+
expectedDisagreement += (allValues[i] - allValues[j]) ** 2;
|
|
927
|
+
expectedCount++;
|
|
928
|
+
}
|
|
929
|
+
expectedDisagreement = expectedCount > 0 ? expectedDisagreement / expectedCount : 0;
|
|
930
|
+
if (expectedDisagreement === 0) return 1;
|
|
931
|
+
return 1 - observedDisagreement / expectedDisagreement;
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Corpus-wide inter-rater agreement across N items × M judges × D dimensions, the
|
|
935
|
+
* question `interRaterReliability`'s within-item α cannot answer.
|
|
936
|
+
*
|
|
937
|
+
* For each dimension, builds the [n_items][n_judges] matrix of scores
|
|
938
|
+
* (keeping only items every judge rated on that dimension), then runs
|
|
939
|
+
* `continuousAgreement` to get ICC(2,1), κ_w, Pearson, Spearman, and
|
|
940
|
+
* bootstrap CIs. Reports a pooled mean across dimensions as a single
|
|
941
|
+
* "is this judge panel reliable on this corpus?" number. Empty input, fewer than 2 judges or
|
|
942
|
+
* items, a judge without scores on a dimension and duplicate records all throw: a silently
|
|
943
|
+
* shrunk matrix would corrupt the overall metric.
|
|
944
|
+
*/
|
|
945
|
+
function corpusInterRaterAgreement(records, opts = {}) {
|
|
946
|
+
if (records.length === 0) throw new ValidationError("corpusInterRaterAgreement: no score records supplied");
|
|
947
|
+
const judgesSeen = /* @__PURE__ */ new Set();
|
|
948
|
+
const dimsSeen = /* @__PURE__ */ new Set();
|
|
949
|
+
const grid = /* @__PURE__ */ new Map();
|
|
950
|
+
for (const r of records) {
|
|
951
|
+
if (!Number.isFinite(r.score)) throw new ValidationError(`corpusInterRaterAgreement: non-finite score for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`);
|
|
952
|
+
judgesSeen.add(r.judgeName);
|
|
953
|
+
dimsSeen.add(r.dimension);
|
|
954
|
+
const byJudge = grid.get(r.dimension) ?? /* @__PURE__ */ new Map();
|
|
955
|
+
const byItem = byJudge.get(r.judgeName) ?? /* @__PURE__ */ new Map();
|
|
956
|
+
if (byItem.has(r.itemId)) throw new ValidationError(`corpusInterRaterAgreement: duplicate record for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`);
|
|
957
|
+
byItem.set(r.itemId, r.score);
|
|
958
|
+
byJudge.set(r.judgeName, byItem);
|
|
959
|
+
grid.set(r.dimension, byJudge);
|
|
960
|
+
}
|
|
961
|
+
const targetDims = opts.dimensions ?? [...dimsSeen].sort();
|
|
962
|
+
for (const d of targetDims) if (!dimsSeen.has(d)) throw new ValidationError(`corpusInterRaterAgreement: dimension '${d}' was requested but no records carry it`);
|
|
963
|
+
const targetJudges = opts.judges ? [...opts.judges] : [...judgesSeen].sort();
|
|
964
|
+
for (const j of targetJudges) if (!judgesSeen.has(j)) throw new ValidationError(`corpusInterRaterAgreement: judge '${j}' was requested but produced no records`);
|
|
965
|
+
if (targetJudges.length < 2) throw new ValidationError(`corpusInterRaterAgreement: need ≥2 judges, got ${targetJudges.length}`);
|
|
966
|
+
const perDimension = [];
|
|
967
|
+
const iccs = [];
|
|
968
|
+
const kappas = [];
|
|
969
|
+
for (const dim of targetDims) {
|
|
970
|
+
const byJudge = grid.get(dim);
|
|
971
|
+
const judgeItemCounts = Object.fromEntries(targetJudges.map((j) => [j, byJudge.get(j)?.size ?? 0]));
|
|
972
|
+
const emptyJudges = targetJudges.filter((j) => judgeItemCounts[j] === 0);
|
|
973
|
+
if (emptyJudges.length > 0) throw new ValidationError(`corpusInterRaterAgreement: dimension '${dim}' has no scores from judge(s) ${emptyJudges.join(", ")} (counts: ${JSON.stringify(judgeItemCounts)})`);
|
|
974
|
+
const sortedItems = targetJudges.map((j) => [...byJudge.get(j).keys()]).reduce((common, ids) => common.filter((x) => ids.includes(x))).sort();
|
|
975
|
+
if (sortedItems.length < 2) throw new ValidationError(`corpusInterRaterAgreement: dimension '${dim}' has ${sortedItems.length} item(s) rated by all ${targetJudges.length} judges (need ≥2)`);
|
|
976
|
+
const agreement = continuousAgreement(sortedItems.map((itemId) => targetJudges.map((j) => byJudge.get(j).get(itemId))), opts);
|
|
977
|
+
perDimension.push({
|
|
978
|
+
...agreement,
|
|
979
|
+
dimension: dim,
|
|
980
|
+
itemIds: sortedItems,
|
|
981
|
+
judgeIds: [...targetJudges]
|
|
982
|
+
});
|
|
983
|
+
if (Number.isFinite(agreement.icc)) iccs.push(agreement.icc);
|
|
984
|
+
if (Number.isFinite(agreement.weightedKappa)) kappas.push(agreement.weightedKappa);
|
|
985
|
+
}
|
|
986
|
+
const mean = (xs) => xs.length === 0 ? NaN : xs.reduce((a, b) => a + b, 0) / xs.length;
|
|
987
|
+
return {
|
|
988
|
+
perDimension,
|
|
989
|
+
overallIcc: mean(iccs),
|
|
990
|
+
overallWeightedKappa: mean(kappas),
|
|
991
|
+
dimensions: targetDims,
|
|
992
|
+
judgeIds: targetJudges
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Convenience adapter for `DimensionJudgeScore[]` data keyed externally by item.
|
|
997
|
+
*
|
|
998
|
+
* Use when you have per-item arrays of `DimensionJudgeScore[]` (e.g. one
|
|
999
|
+
* `ScenarioResult.judgeScores` per scenario) and want corpus-wide
|
|
1000
|
+
* agreement without manually flattening. `itemId` must be unique per
|
|
1001
|
+
* row of `itemsScores`.
|
|
1002
|
+
*/
|
|
1003
|
+
function corpusInterRaterAgreementFromJudgeScores(itemsScores, opts = {}) {
|
|
1004
|
+
const records = [];
|
|
1005
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1006
|
+
for (const { itemId, scores } of itemsScores) {
|
|
1007
|
+
if (seen.has(itemId)) throw new ValidationError(`corpusInterRaterAgreementFromJudgeScores: duplicate itemId '${itemId}'`);
|
|
1008
|
+
seen.add(itemId);
|
|
1009
|
+
for (const s of scores) records.push({
|
|
1010
|
+
itemId,
|
|
1011
|
+
judgeName: s.judgeName,
|
|
1012
|
+
dimension: s.dimension,
|
|
1013
|
+
score: s.score
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
return corpusInterRaterAgreement(records, opts);
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* Unweighted Cohen's κ for paired nominal labels. Labels carry no order, so a
|
|
1020
|
+
* near miss counts as a miss; use `calibrateJudge` for ordinal scores.
|
|
1021
|
+
*/
|
|
1022
|
+
function nominalAgreement(pairs, options = {}) {
|
|
1023
|
+
if (options.clusters && options.clusters.length !== pairs.length) throw new ValidationError("nominalAgreement: one cluster per pair");
|
|
1024
|
+
const kappaCi = clusterBootstrap(pairs, (_, index) => options.clusters?.[index] ?? String(index), (sample) => cohenKappa(sample).kappa, options);
|
|
1025
|
+
return {
|
|
1026
|
+
n: pairs.length,
|
|
1027
|
+
...cohenKappa(pairs),
|
|
1028
|
+
kappaCi
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
function cohenKappa(pairs) {
|
|
1032
|
+
const n = pairs.length;
|
|
1033
|
+
if (n === 0) return {
|
|
1034
|
+
agreement: NaN,
|
|
1035
|
+
kappa: NaN
|
|
1036
|
+
};
|
|
1037
|
+
const left = /* @__PURE__ */ new Map();
|
|
1038
|
+
const right = /* @__PURE__ */ new Map();
|
|
1039
|
+
let same = 0;
|
|
1040
|
+
for (const [a, b] of pairs) {
|
|
1041
|
+
if (typeof a !== "string" || typeof b !== "string") throw new ValidationError("nominalAgreement: every label must be a string");
|
|
1042
|
+
if (a === b) same += 1;
|
|
1043
|
+
left.set(a, (left.get(a) ?? 0) + 1);
|
|
1044
|
+
right.set(b, (right.get(b) ?? 0) + 1);
|
|
1045
|
+
}
|
|
1046
|
+
const observed = same / n;
|
|
1047
|
+
let expected = 0;
|
|
1048
|
+
for (const [label, count] of left) expected += count / n * ((right.get(label) ?? 0) / n);
|
|
1049
|
+
return {
|
|
1050
|
+
agreement: observed,
|
|
1051
|
+
kappa: expected === 1 ? NaN : (observed - expected) / (1 - expected)
|
|
1052
|
+
};
|
|
1053
|
+
}
|
|
1054
|
+
// src/statistics/comparison-effects.ts
|
|
1055
|
+
function binary(values, name) {
|
|
1056
|
+
if (values.some((value) => value !== 0 && value !== 1)) throw new ValidationError(`${name}: expected binary 0/1 values`);
|
|
1057
|
+
}
|
|
1058
|
+
/** Mann–Whitney ROC area: ties count half; no observed member of either class means unknown. */
|
|
1059
|
+
function rocAuc(scores, labels) {
|
|
1060
|
+
assertFiniteSample("rocAuc", "scores", scores);
|
|
1061
|
+
binary(labels, "rocAuc.labels");
|
|
1062
|
+
if (scores.length !== labels.length) throw new ValidationError("rocAuc: scores and labels must have equal lengths");
|
|
1063
|
+
const ranked = ranks(scores);
|
|
1064
|
+
const positive = labels.reduce((sum, label) => sum + label, 0);
|
|
1065
|
+
const sum = labels.reduce((total, label, index) => total + label * ranked[index], 0);
|
|
1066
|
+
const negative = labels.length - positive;
|
|
1067
|
+
return positive && negative ? (sum - positive * (positive + 1) / 2) / (positive * negative) : null;
|
|
1068
|
+
}
|
|
1069
|
+
// src/statistics/distribution-summary.ts
|
|
1070
|
+
/** Nearest-rank percentile on a sorted, non-empty sample (0-100 scale). */
|
|
1071
|
+
function nearestRank(sorted, percentile) {
|
|
1072
|
+
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(percentile / 100 * sorted.length) - 1))];
|
|
1073
|
+
}
|
|
1074
|
+
/**
|
|
1075
|
+
* Nearest-rank percentile on an arbitrary sample, `percentile` on a 0-100
|
|
1076
|
+
* scale — the same rule `summarizeDistribution` applies, exposed for a single
|
|
1077
|
+
* percentile the summary struct does not carry (e.g. p99.9). Returns NaN for
|
|
1078
|
+
* an empty sample; callers that need a numeric floor guard it.
|
|
1079
|
+
*/
|
|
1080
|
+
function percentileNearestRank(values, percentile) {
|
|
1081
|
+
if (!Array.isArray(values)) throw new ValidationError("percentileNearestRank: values must be an array");
|
|
1082
|
+
if (values.length === 0) return NaN;
|
|
1083
|
+
return nearestRank([...values].sort((a, b) => a - b), percentile);
|
|
1084
|
+
}
|
|
1085
|
+
function summarizeDistribution(values, options = {}) {
|
|
1086
|
+
if (values.some((value) => !Number.isFinite(value))) throw new ValidationError("summarizeDistribution: samples must be finite");
|
|
1087
|
+
const finite = options.lowerBound === void 0 ? values : values.filter((value) => value >= options.lowerBound);
|
|
1088
|
+
if (finite.length === 0) return {
|
|
1089
|
+
min: NaN,
|
|
1090
|
+
p50: NaN,
|
|
1091
|
+
p90: NaN,
|
|
1092
|
+
p95: NaN,
|
|
1093
|
+
p99: NaN,
|
|
1094
|
+
max: NaN,
|
|
1095
|
+
mean: NaN,
|
|
1096
|
+
n: 0,
|
|
1097
|
+
values: []
|
|
1098
|
+
};
|
|
1099
|
+
const sorted = [...finite].sort((a, b) => a - b);
|
|
1100
|
+
const n = sorted.length;
|
|
1101
|
+
const mean = sorted.reduce((sum, value) => sum + value / n, 0);
|
|
1102
|
+
const sumSquares = sorted.map((value) => value - mean).reduce((sum, value) => sum + value ** 2, 0);
|
|
1103
|
+
const summary = {
|
|
1104
|
+
min: sorted[0],
|
|
1105
|
+
p50: nearestRank(sorted, 50),
|
|
1106
|
+
p90: nearestRank(sorted, 90),
|
|
1107
|
+
p95: nearestRank(sorted, 95),
|
|
1108
|
+
p99: nearestRank(sorted, 99),
|
|
1109
|
+
max: sorted[n - 1],
|
|
1110
|
+
mean,
|
|
1111
|
+
n,
|
|
1112
|
+
values: sorted
|
|
1113
|
+
};
|
|
1114
|
+
if (n >= 2) {
|
|
1115
|
+
const stddev = Math.sqrt(sumSquares / (n - 1));
|
|
1116
|
+
const margin = studentTCritical(n - 1, .95) * stddev / Math.sqrt(n);
|
|
1117
|
+
summary.stddev = stddev;
|
|
1118
|
+
summary.ci95Low = mean - margin;
|
|
1119
|
+
summary.ci95High = mean + margin;
|
|
1120
|
+
}
|
|
1121
|
+
return summary;
|
|
1122
|
+
}
|
|
1123
|
+
// src/statistics/effect-sizes.ts
|
|
1124
|
+
/** Standardized effect sizes; undefined effects remain null. */
|
|
1125
|
+
/** Independent Cohen's d, oriented b − a; null below two samples or for an unbounded effect. */
|
|
1126
|
+
function cohensD(a, b) {
|
|
1127
|
+
if (a.length < 2 || b.length < 2) return null;
|
|
1128
|
+
const meanA = a.reduce((x, y) => x + y, 0) / a.length;
|
|
1129
|
+
const meanB = b.reduce((x, y) => x + y, 0) / b.length;
|
|
1130
|
+
const varA = a.reduce((acc, x) => acc + (x - meanA) ** 2, 0) / (a.length - 1);
|
|
1131
|
+
const varB = b.reduce((acc, x) => acc + (x - meanB) ** 2, 0) / (b.length - 1);
|
|
1132
|
+
const pooled = Math.sqrt(((a.length - 1) * varA + (b.length - 1) * varB) / (a.length + b.length - 2));
|
|
1133
|
+
if (pooled === 0) return meanB === meanA ? 0 : null;
|
|
1134
|
+
return (meanB - meanA) / pooled;
|
|
1135
|
+
}
|
|
1136
|
+
/** Paired Cohen's dz; constant nonzero deltas have no finite standardized effect. */
|
|
1137
|
+
function pairedCohensDz(before, after) {
|
|
1138
|
+
if (before.length !== after.length) throw new ValidationError(`pairedCohensDz: unequal sample sizes (${before.length} vs ${after.length})`);
|
|
1139
|
+
if (before.length < 2) return null;
|
|
1140
|
+
const deltas = before.map((value, index) => after[index] - value);
|
|
1141
|
+
if (deltas.some((value) => !Number.isFinite(value))) throw new ValidationError("pairedCohensDz: all paired values must be finite");
|
|
1142
|
+
const meanDelta = deltas.reduce((sum, value) => sum + value, 0) / deltas.length;
|
|
1143
|
+
const variance = deltas.reduce((sum, value) => sum + (value - meanDelta) ** 2, 0) / (deltas.length - 1);
|
|
1144
|
+
const standardDeviation = Math.sqrt(variance);
|
|
1145
|
+
const scale = Math.max(1, Math.abs(meanDelta), ...deltas.map(Math.abs));
|
|
1146
|
+
if (standardDeviation <= Number.EPSILON * scale) return meanDelta === 0 ? 0 : null;
|
|
1147
|
+
return meanDelta / standardDeviation;
|
|
1148
|
+
}
|
|
1149
|
+
/** Cliff's delta, oriented after − before; empty samples return zero. */
|
|
1150
|
+
function cliffsDelta(before, after) {
|
|
1151
|
+
const n = before.length * after.length;
|
|
1152
|
+
if (n === 0) return 0;
|
|
1153
|
+
let dominance = 0;
|
|
1154
|
+
for (const a of after) for (const b of before) if (a > b) dominance += 1;
|
|
1155
|
+
else if (a < b) dominance -= 1;
|
|
1156
|
+
return dominance / n;
|
|
1157
|
+
}
|
|
1158
|
+
/** Romano magnitude thresholds for the absolute Cliff's delta. */
|
|
1159
|
+
function interpretCliffs(delta) {
|
|
1160
|
+
const d = Math.abs(delta);
|
|
1161
|
+
if (d < .147) return "negligible";
|
|
1162
|
+
if (d < .33) return "small";
|
|
1163
|
+
if (d < .474) return "medium";
|
|
1164
|
+
return "large";
|
|
1165
|
+
}
|
|
1166
|
+
// src/math/normal.ts
|
|
1167
|
+
/**
|
|
1168
|
+
* Standard normal cumulative distribution using Abramowitz and Stegun 7.1.26.
|
|
1169
|
+
*
|
|
1170
|
+
* The approximation is evaluated as erf(x / sqrt(2)). Computing the negative
|
|
1171
|
+
* tail from the complementary term avoids cancellation when x is far below 0.
|
|
1172
|
+
* The maximum absolute CDF error is approximately 7.5e-8.
|
|
1173
|
+
*/
|
|
1174
|
+
function normalCdf(x) {
|
|
1175
|
+
if (x === 0) return .5;
|
|
1176
|
+
const a1 = .254829592;
|
|
1177
|
+
const a2 = -.284496736;
|
|
1178
|
+
const a3 = 1.421413741;
|
|
1179
|
+
const a4 = -1.453152027;
|
|
1180
|
+
const a5 = 1.061405429;
|
|
1181
|
+
const p = .3275911;
|
|
1182
|
+
const scaled = Math.abs(x) / Math.SQRT2;
|
|
1183
|
+
const t = 1 / (1 + p * scaled);
|
|
1184
|
+
const complement = ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-scaled * scaled);
|
|
1185
|
+
return x < 0 ? complement / 2 : 1 - complement / 2;
|
|
1186
|
+
}
|
|
1187
|
+
// src/statistics/inference.ts
|
|
1188
|
+
/** Two-sided normal tail, evaluated without subtracting a near-one CDF. */
|
|
1189
|
+
function normalTwoSidedPValue(z) {
|
|
1190
|
+
if (Number.isNaN(z)) throw new ValidationError("normalTwoSidedPValue: z must not be NaN");
|
|
1191
|
+
return Math.min(1, 2 * normalCdf(-Math.abs(z)));
|
|
1192
|
+
}
|
|
1193
|
+
/** Two-sided Student-t tail, preserving small tail probabilities. */
|
|
1194
|
+
function studentTTwoSidedPValue(t, df) {
|
|
1195
|
+
if (Number.isNaN(t) || !Number.isFinite(df) || df <= 0) throw new ValidationError("studentTTwoSidedPValue: t must not be NaN and df must be positive and finite");
|
|
1196
|
+
return regularizedIncompleteBeta(df / (df + t * t), df / 2, .5);
|
|
1197
|
+
}
|
|
1198
|
+
function table(a, b, c, d) {
|
|
1199
|
+
if (![
|
|
1200
|
+
a,
|
|
1201
|
+
b,
|
|
1202
|
+
c,
|
|
1203
|
+
d
|
|
1204
|
+
].every((value) => Number.isSafeInteger(value) && value >= 0) || !Number.isSafeInteger(a + b + c + d)) throw new ValidationError("contingency table: counts and total must be nonnegative safe integers");
|
|
1205
|
+
return a + b + c + d;
|
|
1206
|
+
}
|
|
1207
|
+
/** Pearson statistic for a 2x2 table; empty or fixed margins have statistic zero. */
|
|
1208
|
+
function chiSquared(a, b, c, d) {
|
|
1209
|
+
const n = table(a, b, c, d);
|
|
1210
|
+
if (!n) return 0;
|
|
1211
|
+
const expected = [
|
|
1212
|
+
(a + b) * (a + c) / n,
|
|
1213
|
+
(a + b) * (b + d) / n,
|
|
1214
|
+
(c + d) * (a + c) / n,
|
|
1215
|
+
(c + d) * (b + d) / n
|
|
1216
|
+
];
|
|
1217
|
+
if (expected.some((value) => value === 0)) return 0;
|
|
1218
|
+
return [
|
|
1219
|
+
a,
|
|
1220
|
+
b,
|
|
1221
|
+
c,
|
|
1222
|
+
d
|
|
1223
|
+
].reduce((sum, value, i) => sum + (value - expected[i]) ** 2 / expected[i], 0);
|
|
1224
|
+
}
|
|
1225
|
+
/** One-degree-of-freedom chi-squared survival probability. */
|
|
1226
|
+
function chiSquaredPValue(statistic) {
|
|
1227
|
+
if (Number.isNaN(statistic) || statistic < 0) throw new ValidationError("chiSquaredPValue: statistic must be nonnegative and not NaN");
|
|
1228
|
+
return normalTwoSidedPValue(Math.sqrt(statistic));
|
|
1229
|
+
}
|
|
1230
|
+
/** Fisher two-sided probability: sum all fixed-margin tables no likelier than the observed table. */
|
|
1231
|
+
function fisherExactTwoSided(a, b, c, d) {
|
|
1232
|
+
const n = table(a, b, c, d), row1 = a + b, row2 = c + d, col1 = a + c;
|
|
1233
|
+
if (!n || !row1 || !row2 || !col1 || col1 === n) return 1;
|
|
1234
|
+
const logChoose = (total, count) => lnGamma(total + 1) - lnGamma(count + 1) - lnGamma(total - count + 1);
|
|
1235
|
+
const denominator = logChoose(n, col1);
|
|
1236
|
+
const logP = (count) => logChoose(row1, count) + logChoose(row2, col1 - count) - denominator;
|
|
1237
|
+
const threshold = logP(a) + 1e-7;
|
|
1238
|
+
let p = 0;
|
|
1239
|
+
for (let k = Math.max(0, col1 - row2); k <= Math.min(row1, col1); k++) {
|
|
1240
|
+
const probability = logP(k);
|
|
1241
|
+
if (probability <= threshold) p += Math.exp(probability);
|
|
1242
|
+
}
|
|
1243
|
+
return Math.min(1, p);
|
|
1244
|
+
}
|
|
1245
|
+
/** Fisher when any expected count is below five; otherwise Pearson's chi-squared tail. */
|
|
1246
|
+
function twoByTwoPValue(a, b, c, d) {
|
|
1247
|
+
const n = table(a, b, c, d);
|
|
1248
|
+
if (!n) return 1;
|
|
1249
|
+
return Math.min((a + b) * (a + c), (a + b) * (b + d), (c + d) * (a + c), (c + d) * (b + d)) / n < 5 ? fisherExactTwoSided(a, b, c, d) : chiSquaredPValue(chiSquared(a, b, c, d));
|
|
1250
|
+
}
|
|
1251
|
+
/** Centered least-squares slope; null p-value means no slope test was possible. */
|
|
1252
|
+
function linearRegressionSlope(points) {
|
|
1253
|
+
assertFiniteSample("linearRegressionSlope", "x", points.map((point) => point.x));
|
|
1254
|
+
assertFiniteSample("linearRegressionSlope", "y", points.map((point) => point.y));
|
|
1255
|
+
if (points.length < 2) return {
|
|
1256
|
+
slope: 0,
|
|
1257
|
+
rSquared: 0,
|
|
1258
|
+
slopePValue: null
|
|
1259
|
+
};
|
|
1260
|
+
const n = points.length;
|
|
1261
|
+
const meanX = points.reduce((sum, point) => sum + point.x / n, 0);
|
|
1262
|
+
const meanY = points.reduce((sum, point) => sum + point.y / n, 0);
|
|
1263
|
+
const sxx = points.reduce((sum, point) => sum + (point.x - meanX) ** 2, 0);
|
|
1264
|
+
const syy = points.reduce((sum, point) => sum + (point.y - meanY) ** 2, 0);
|
|
1265
|
+
const sxy = points.reduce((sum, point) => sum + (point.x - meanX) * (point.y - meanY), 0);
|
|
1266
|
+
if (!sxx) return {
|
|
1267
|
+
slope: 0,
|
|
1268
|
+
rSquared: 0,
|
|
1269
|
+
slopePValue: null
|
|
1270
|
+
};
|
|
1271
|
+
const slope = sxy / sxx;
|
|
1272
|
+
const residual = points.reduce((sum, point) => sum + (point.y - meanY - slope * (point.x - meanX)) ** 2, 0);
|
|
1273
|
+
if (![
|
|
1274
|
+
slope,
|
|
1275
|
+
residual,
|
|
1276
|
+
sxx,
|
|
1277
|
+
sxy,
|
|
1278
|
+
syy
|
|
1279
|
+
].every(Number.isFinite)) throw new ValidationError("linearRegressionSlope: sample arithmetic exceeded finite range");
|
|
1280
|
+
return {
|
|
1281
|
+
slope,
|
|
1282
|
+
rSquared: syy === 0 ? 0 : Math.max(0, 1 - residual / syy),
|
|
1283
|
+
slopePValue: n < 3 ? null : residual === 0 ? slope === 0 ? 1 : 0 : studentTTwoSidedPValue(slope / Math.sqrt(residual / (n - 2) / sxx), n - 2)
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
// src/statistics/multiplicity.ts
|
|
1287
|
+
/**
|
|
1288
|
+
* Multiple-comparison corrections: family-wise error (Bonferroni, Holm) and
|
|
1289
|
+
* false discovery rate (Benjamini-Hochberg), with inclusive rejection
|
|
1290
|
+
* boundaries throughout.
|
|
1291
|
+
*/
|
|
1292
|
+
/**
|
|
1293
|
+
* Bonferroni adjustment: multiply every p-value by the test count, clamp at 1.
|
|
1294
|
+
*
|
|
1295
|
+
* Rejects at `p_adjusted ≤ alpha` — the boundary is inclusive, matching
|
|
1296
|
+
* {@link holm}, which uniformly dominates this correction and must therefore
|
|
1297
|
+
* never reject less. Validates its inputs on the same terms.
|
|
1298
|
+
*/
|
|
1299
|
+
function bonferroni(pValues, alpha = .05) {
|
|
1300
|
+
assertAlpha("bonferroni", "alpha", alpha);
|
|
1301
|
+
assertPValues("bonferroni", pValues);
|
|
1302
|
+
const k = pValues.length;
|
|
1303
|
+
const adjusted = pValues.map((p) => Math.min(1, p * k));
|
|
1304
|
+
return {
|
|
1305
|
+
adjusted,
|
|
1306
|
+
significant: adjusted.map((p) => p <= alpha)
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Holm step-down family-wise error adjustment.
|
|
1311
|
+
*
|
|
1312
|
+
* P-values are sorted from smallest to largest, multiplied by their remaining
|
|
1313
|
+
* hypothesis count, and made monotonically non-decreasing before being mapped
|
|
1314
|
+
* back to input order. This uniformly dominates plain Bonferroni while keeping
|
|
1315
|
+
* strong family-wise error control under arbitrary dependence.
|
|
1316
|
+
*/
|
|
1317
|
+
function holm(pValues, alpha = .05) {
|
|
1318
|
+
assertAlpha("holm", "alpha", alpha);
|
|
1319
|
+
assertPValues("holm", pValues);
|
|
1320
|
+
const count = pValues.length;
|
|
1321
|
+
if (count === 0) return {
|
|
1322
|
+
adjusted: [],
|
|
1323
|
+
significant: []
|
|
1324
|
+
};
|
|
1325
|
+
const ordered = pValues.map((pValue, index) => ({
|
|
1326
|
+
pValue,
|
|
1327
|
+
index
|
|
1328
|
+
})).sort((a, b) => a.pValue - b.pValue || a.index - b.index);
|
|
1329
|
+
const adjusted = new Array(count);
|
|
1330
|
+
let previous = 0;
|
|
1331
|
+
for (let rank = 0; rank < count; rank++) {
|
|
1332
|
+
const entry = ordered[rank];
|
|
1333
|
+
const stepAdjusted = Math.min(1, entry.pValue * (count - rank));
|
|
1334
|
+
previous = Math.max(previous, stepAdjusted);
|
|
1335
|
+
adjusted[entry.index] = previous;
|
|
1336
|
+
}
|
|
1337
|
+
return {
|
|
1338
|
+
adjusted,
|
|
1339
|
+
significant: adjusted.map((pValue) => pValue <= alpha)
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Benjamini–Hochberg false discovery rate. Returns adjusted q-values and
|
|
1344
|
+
* significance at the target FDR; handles ties and preserves q monotonicity.
|
|
1345
|
+
*
|
|
1346
|
+
* Rejects at `q ≤ fdr` — the BH rule is inclusive at the boundary, so an
|
|
1347
|
+
* exactly-`fdr` q-value is a discovery.
|
|
1348
|
+
*/
|
|
1349
|
+
function benjaminiHochberg(pValues, fdr = .05) {
|
|
1350
|
+
assertAlpha("benjaminiHochberg", "fdr", fdr);
|
|
1351
|
+
assertPValues("benjaminiHochberg", pValues);
|
|
1352
|
+
const n = pValues.length;
|
|
1353
|
+
if (n === 0) return {
|
|
1354
|
+
qValues: [],
|
|
1355
|
+
significant: []
|
|
1356
|
+
};
|
|
1357
|
+
const indexed = pValues.map((p, i) => ({
|
|
1358
|
+
p,
|
|
1359
|
+
i
|
|
1360
|
+
})).sort((a, b) => a.p - b.p);
|
|
1361
|
+
const q = new Array(n);
|
|
1362
|
+
let minRight = 1;
|
|
1363
|
+
for (let k = n - 1; k >= 0; k--) {
|
|
1364
|
+
const rank = k + 1;
|
|
1365
|
+
const entry = indexed[k];
|
|
1366
|
+
const raw = n / rank * entry.p;
|
|
1367
|
+
const bounded = Math.min(minRight, raw);
|
|
1368
|
+
minRight = bounded;
|
|
1369
|
+
q[entry.i] = Math.min(1, bounded);
|
|
1370
|
+
}
|
|
1371
|
+
return {
|
|
1372
|
+
qValues: q,
|
|
1373
|
+
significant: q.map((v) => v <= fdr)
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
function assertAlpha(fn, label, value) {
|
|
1377
|
+
if (!Number.isFinite(value) || value <= 0 || value >= 1) throw new ValidationError(`${fn}: ${label} must be in (0,1), got ${value}`);
|
|
1378
|
+
}
|
|
1379
|
+
function assertPValues(fn, pValues) {
|
|
1380
|
+
for (const [index, pValue] of pValues.entries()) if (!Number.isFinite(pValue) || pValue < 0 || pValue > 1) throw new ValidationError(`${fn}: pValues[${index}] must be in [0,1], got ${pValue}`);
|
|
1381
|
+
}
|
|
1382
|
+
// src/statistics/paired-binary.ts
|
|
1383
|
+
/**
|
|
1384
|
+
* Wilson score interval for a binomial proportion. Correct at small n and near
|
|
1385
|
+
* 0/1, where the normal (Wald) approximation produces bounds outside [0, 1] and
|
|
1386
|
+
* understates coverage. Use this for any pass-rate / hit-rate / realness-rate
|
|
1387
|
+
* CI — the continuous `confidenceInterval` assumes the wrong distribution for a
|
|
1388
|
+
* proportion. Counts must be finite nonnegative integers, successes cannot exceed
|
|
1389
|
+
* n, and confidence must lie strictly between zero and one. With n = 0 the
|
|
1390
|
+
* interval is the full [0, 1] support: no rate is ruled out. The estimate stays
|
|
1391
|
+
* 0 for compatibility, not as a measured failure rate; retain n alongside it.
|
|
1392
|
+
*/
|
|
1393
|
+
function wilson(successes, n, confidence = .95) {
|
|
1394
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new Error("wilson: n must be a finite nonnegative integer");
|
|
1395
|
+
if (!Number.isSafeInteger(successes) || successes < 0 || successes > n) throw new Error(`wilson: successes (${successes}) must be in [0, ${n}]`);
|
|
1396
|
+
if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new Error("wilson: confidence must be between zero and one");
|
|
1397
|
+
if (n === 0) return {
|
|
1398
|
+
estimate: 0,
|
|
1399
|
+
lower: 0,
|
|
1400
|
+
upper: 1
|
|
1401
|
+
};
|
|
1402
|
+
const z = zQuantile(1 - (1 - confidence) / 2);
|
|
1403
|
+
const p = successes / n;
|
|
1404
|
+
const z2 = z * z;
|
|
1405
|
+
const denom = 1 + z2 / n;
|
|
1406
|
+
const center = (p + z2 / (2 * n)) / denom;
|
|
1407
|
+
const half = z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n) / denom;
|
|
1408
|
+
return {
|
|
1409
|
+
estimate: p,
|
|
1410
|
+
lower: Math.max(0, center - half),
|
|
1411
|
+
upper: Math.min(1, center + half)
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
/** Independent-binomial difference: Newcombe (1998), method 10 (Wilson, no CC).
|
|
1415
|
+
* doi:10.1002/(SICI)1097-0258(19980430)17:8<873::AID-SIM779>3.0.CO;2-I
|
|
1416
|
+
* Empty arms retain full difference support; no point difference is measured. */
|
|
1417
|
+
function independentRiskDifference(beforeSuccesses, beforeN, afterSuccesses, afterN, confidence = .95) {
|
|
1418
|
+
const before = {
|
|
1419
|
+
...wilson(beforeSuccesses, beforeN, confidence),
|
|
1420
|
+
successes: beforeSuccesses,
|
|
1421
|
+
n: beforeN
|
|
1422
|
+
};
|
|
1423
|
+
const after = {
|
|
1424
|
+
...wilson(afterSuccesses, afterN, confidence),
|
|
1425
|
+
successes: afterSuccesses,
|
|
1426
|
+
n: afterN
|
|
1427
|
+
};
|
|
1428
|
+
const delta = beforeN && afterN ? after.estimate - before.estimate : null;
|
|
1429
|
+
return {
|
|
1430
|
+
before,
|
|
1431
|
+
after,
|
|
1432
|
+
delta,
|
|
1433
|
+
confidence,
|
|
1434
|
+
lower: delta === null ? -1 : Math.max(-1, delta - Math.hypot(after.estimate - after.lower, before.upper - before.estimate)),
|
|
1435
|
+
upper: delta === null ? 1 : Math.min(1, delta + Math.hypot(after.upper - after.estimate, before.estimate - before.lower))
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* McNemar's test for paired binary outcomes — the correct significance test for
|
|
1440
|
+
* "does treatment change the success rate vs control on the SAME items". Only
|
|
1441
|
+
* discordant pairs (one arm right, the other wrong) carry information; concordant
|
|
1442
|
+
* pairs are uninformative, so a paired t-test / two-proportion z-test on the raw
|
|
1443
|
+
* rates is wrong here. The p-value is exact: under H0 the b "treatment-wins" are
|
|
1444
|
+
* Binomial(b + c, 0.5), so the two-sided p is the doubled binomial tail — correct
|
|
1445
|
+
* at the small discordant counts typical of eval runs (no continuity-corrected
|
|
1446
|
+
* chi-square approximation needed, though it is returned as `statistic` for
|
|
1447
|
+
* reference). Inputs are paired 0/1 (or boolean) arrays, control first to match
|
|
1448
|
+
* the module's (before, after) convention. Throws on unequal lengths.
|
|
1449
|
+
*/
|
|
1450
|
+
function mcnemar(control, treatment) {
|
|
1451
|
+
if (control.length !== treatment.length) throw new Error(`mcnemar: unequal sample sizes (${control.length} vs ${treatment.length})`);
|
|
1452
|
+
const n = control.length;
|
|
1453
|
+
let b = 0;
|
|
1454
|
+
let c = 0;
|
|
1455
|
+
for (let i = 0; i < n; i++) {
|
|
1456
|
+
const ctrl = control[i] ? 1 : 0;
|
|
1457
|
+
const treat = treatment[i] ? 1 : 0;
|
|
1458
|
+
if (treat === 1 && ctrl === 0) b++;
|
|
1459
|
+
else if (treat === 0 && ctrl === 1) c++;
|
|
1460
|
+
}
|
|
1461
|
+
const nDiscordant = b + c;
|
|
1462
|
+
const statistic = nDiscordant === 0 ? 0 : (Math.abs(b - c) - 1) ** 2 / nDiscordant;
|
|
1463
|
+
return {
|
|
1464
|
+
n,
|
|
1465
|
+
nDiscordant,
|
|
1466
|
+
b,
|
|
1467
|
+
c,
|
|
1468
|
+
statistic,
|
|
1469
|
+
pValue: binomialSignTwoSided(b, c)
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Paired risk difference (the effect-size companion to {@link mcnemar}): the
|
|
1474
|
+
* change in success rate p(treatment) − p(control) on matched items, which for
|
|
1475
|
+
* paired binary data equals (b − c) / n. The CI uses the paired variance from
|
|
1476
|
+
* the discordant counts, not the independent-samples formula (which overstates
|
|
1477
|
+
* the interval by ignoring the pairing). Inputs are paired 0/1 (or boolean)
|
|
1478
|
+
* arrays, control first. Throws on unequal lengths. With no pairs, returns the
|
|
1479
|
+
* full [-1, 1] support and a compatibility point estimate of 0, not equivalence.
|
|
1480
|
+
*
|
|
1481
|
+
* REPORTING ONLY — do NOT decide a promotion on this interval. The CI is a Wald
|
|
1482
|
+
* normal approximation, which badly UNDERCOVERS when only a handful of pairs are
|
|
1483
|
+
* discordant: at n = 3 with b = 2, c = 0 it returns [0.133, 1.000], excluding 0,
|
|
1484
|
+
* while McNemar's exact test on the same data gives p = 0.50. A gate keying on
|
|
1485
|
+
* `lower > 0` would promote noise. Use {@link pairedRiskDifferenceExact}, whose
|
|
1486
|
+
* interval is dual to the exact test by construction, for any decision.
|
|
1487
|
+
*/
|
|
1488
|
+
function pairedRiskDifference(control, treatment, confidence = .95) {
|
|
1489
|
+
if (control.length !== treatment.length) throw new Error(`pairedRiskDifference: unequal sample sizes (${control.length} vs ${treatment.length})`);
|
|
1490
|
+
const n = control.length;
|
|
1491
|
+
if (n === 0) return {
|
|
1492
|
+
n: 0,
|
|
1493
|
+
b: 0,
|
|
1494
|
+
c: 0,
|
|
1495
|
+
riskDifference: 0,
|
|
1496
|
+
lower: -1,
|
|
1497
|
+
upper: 1,
|
|
1498
|
+
confidence
|
|
1499
|
+
};
|
|
1500
|
+
let b = 0;
|
|
1501
|
+
let c = 0;
|
|
1502
|
+
for (let i = 0; i < n; i++) {
|
|
1503
|
+
const ctrl = control[i] ? 1 : 0;
|
|
1504
|
+
const treat = treatment[i] ? 1 : 0;
|
|
1505
|
+
if (treat === 1 && ctrl === 0) b++;
|
|
1506
|
+
else if (treat === 0 && ctrl === 1) c++;
|
|
1507
|
+
}
|
|
1508
|
+
const rd = (b - c) / n;
|
|
1509
|
+
const variance = (b + c - (b - c) ** 2 / n) / (n * n);
|
|
1510
|
+
const half = zQuantile(1 - (1 - confidence) / 2) * Math.sqrt(Math.max(0, variance));
|
|
1511
|
+
return {
|
|
1512
|
+
n,
|
|
1513
|
+
b,
|
|
1514
|
+
c,
|
|
1515
|
+
riskDifference: rd,
|
|
1516
|
+
lower: Math.max(-1, rd - half),
|
|
1517
|
+
upper: Math.min(1, rd + half),
|
|
1518
|
+
confidence
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Paired risk difference with the EXACT CONDITIONAL interval — the estimator a
|
|
1523
|
+
* promotion gate may decide on.
|
|
1524
|
+
*
|
|
1525
|
+
* Conditional on the number of discordant pairs m = b + c, the treatment-win
|
|
1526
|
+
* count b is Binomial(m, π) with π = P(treatment wins | discordant), and the
|
|
1527
|
+
* risk difference is an exact reparameterisation: RD = (2π − 1)·m/n. So a
|
|
1528
|
+
* Clopper-Pearson exact interval for π maps straight onto RD. This buys the
|
|
1529
|
+
* property the Wald interval in {@link pairedRiskDifference} does not have:
|
|
1530
|
+
*
|
|
1531
|
+
* **`lower > 0` ⟺ McNemar's exact test rejects at α = 1 − confidence.**
|
|
1532
|
+
*
|
|
1533
|
+
* Clopper-Pearson excludes π = 0.5 exactly when the two-sided exact binomial
|
|
1534
|
+
* test of π = 0.5 rejects, and that test IS {@link mcnemar}'s p-value — so the
|
|
1535
|
+
* interval and the test can never disagree, and a gate keyed on `lower` cannot
|
|
1536
|
+
* promote what the exact test refuses. The exact p is returned in the same
|
|
1537
|
+
* object so the two are impossible to compute apart.
|
|
1538
|
+
*
|
|
1539
|
+
* The interval is conservative (exact intervals over-cover; conditioning on m
|
|
1540
|
+
* discards the concordant pairs' information about m itself). That is the
|
|
1541
|
+
* correct direction for a promotion gate: it refuses more often, never less.
|
|
1542
|
+
*
|
|
1543
|
+
* With n = 0, returns the full [-1, 1] support, p = 1, and a compatibility
|
|
1544
|
+
* point estimate of 0. With n > 0 and m = 0, π is not identified: the result
|
|
1545
|
+
* is the degenerate [0, 0] with p = 1. That is NOT evidence of equivalence —
|
|
1546
|
+
* callers must treat a zero-width interval as "cannot decide", not as "no
|
|
1547
|
+
* difference". Inputs are paired 0/1 (or boolean) arrays, control first.
|
|
1548
|
+
* Throws on unequal lengths.
|
|
1549
|
+
*/
|
|
1550
|
+
function pairedRiskDifferenceExact(control, treatment, confidence = .95) {
|
|
1551
|
+
if (control.length !== treatment.length) throw new Error(`pairedRiskDifferenceExact: unequal sample sizes (${control.length} vs ${treatment.length})`);
|
|
1552
|
+
if (confidence <= 0 || confidence >= 1) throw new Error(`pairedRiskDifferenceExact: confidence must be in (0,1), got ${confidence}`);
|
|
1553
|
+
const n = control.length;
|
|
1554
|
+
if (n === 0) return {
|
|
1555
|
+
n: 0,
|
|
1556
|
+
b: 0,
|
|
1557
|
+
c: 0,
|
|
1558
|
+
nDiscordant: 0,
|
|
1559
|
+
riskDifference: 0,
|
|
1560
|
+
lower: -1,
|
|
1561
|
+
upper: 1,
|
|
1562
|
+
confidence,
|
|
1563
|
+
pValue: 1
|
|
1564
|
+
};
|
|
1565
|
+
let b = 0;
|
|
1566
|
+
let c = 0;
|
|
1567
|
+
for (let i = 0; i < n; i++) {
|
|
1568
|
+
const ctrl = control[i] ? 1 : 0;
|
|
1569
|
+
const treat = treatment[i] ? 1 : 0;
|
|
1570
|
+
if (treat === 1 && ctrl === 0) b++;
|
|
1571
|
+
else if (treat === 0 && ctrl === 1) c++;
|
|
1572
|
+
}
|
|
1573
|
+
const m = b + c;
|
|
1574
|
+
const riskDifference = (b - c) / n;
|
|
1575
|
+
const pValue = binomialSignTwoSided(b, c);
|
|
1576
|
+
if (m === 0) return {
|
|
1577
|
+
n,
|
|
1578
|
+
b,
|
|
1579
|
+
c,
|
|
1580
|
+
nDiscordant: 0,
|
|
1581
|
+
riskDifference: 0,
|
|
1582
|
+
lower: 0,
|
|
1583
|
+
upper: 0,
|
|
1584
|
+
confidence,
|
|
1585
|
+
pValue
|
|
1586
|
+
};
|
|
1587
|
+
const alpha = 1 - confidence;
|
|
1588
|
+
const piLow = b === 0 ? 0 : betaQuantile(alpha / 2, b, m - b + 1);
|
|
1589
|
+
const piHigh = b === m ? 1 : betaQuantile(1 - alpha / 2, b + 1, m - b);
|
|
1590
|
+
const scale = m / n;
|
|
1591
|
+
return {
|
|
1592
|
+
n,
|
|
1593
|
+
b,
|
|
1594
|
+
c,
|
|
1595
|
+
nDiscordant: m,
|
|
1596
|
+
riskDifference,
|
|
1597
|
+
lower: Math.max(-1, (2 * piLow - 1) * scale),
|
|
1598
|
+
upper: Math.min(1, (2 * piHigh - 1) * scale),
|
|
1599
|
+
confidence,
|
|
1600
|
+
pValue
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
/** Inverse regularized incomplete beta by bisection on
|
|
1604
|
+
* {@link regularizedIncompleteBeta}, which is monotone increasing in x. 80
|
|
1605
|
+
* halvings of [0,1] resolve to ~8e-25, far past the continued fraction's own
|
|
1606
|
+
* 3e-15 tolerance, so the quantile is as exact as the CDF it inverts. */
|
|
1607
|
+
function betaQuantile(p, a, b) {
|
|
1608
|
+
if (p <= 0) return 0;
|
|
1609
|
+
if (p >= 1) return 1;
|
|
1610
|
+
let lo = 0;
|
|
1611
|
+
let hi = 1;
|
|
1612
|
+
for (let i = 0; i < 80; i++) {
|
|
1613
|
+
const mid = (lo + hi) / 2;
|
|
1614
|
+
if (regularizedIncompleteBeta(mid, a, b) < p) lo = mid;
|
|
1615
|
+
else hi = mid;
|
|
1616
|
+
}
|
|
1617
|
+
return (lo + hi) / 2;
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Constrained MLE of q = P(treatment loses) under the hypothesis RD = `delta`.
|
|
1621
|
+
*
|
|
1622
|
+
* Profiling the two concordant cells out of the multinomial leaves
|
|
1623
|
+
* `L(q) = b·log(q+delta) + c·log(q) + e·log(1 − 2q − delta)` with `e = n − b − c`,
|
|
1624
|
+
* whose stationary point is the positive root of
|
|
1625
|
+
* `2n·q² − [(b + c) − delta·(b + 3c + 2e)]·q − c·delta·(1 − delta) = 0`.
|
|
1626
|
+
* At `delta = 0` this returns `(b + c) / 2n`, the familiar null.
|
|
1627
|
+
*/
|
|
1628
|
+
function constrainedLossRate(b, c, n, delta) {
|
|
1629
|
+
const e = n - b - c;
|
|
1630
|
+
const quadratic = 2 * n;
|
|
1631
|
+
const linear = -(b + c - delta * (b + 3 * c + 2 * e));
|
|
1632
|
+
const constant = -c * delta * (1 - delta);
|
|
1633
|
+
const discriminant = linear * linear - 4 * quadratic * constant;
|
|
1634
|
+
const root = discriminant > 0 ? Math.sqrt(discriminant) : 0;
|
|
1635
|
+
const q = (-linear + root) / (2 * quadratic);
|
|
1636
|
+
return Math.min(Math.max(q, Math.max(0, -delta)), Math.max(0, (1 - delta) / 2));
|
|
1637
|
+
}
|
|
1638
|
+
/** Tango's score statistic for H0: RD = `delta`. `Var(b − c) = n·(2q + delta −
|
|
1639
|
+
* delta²)` under that hypothesis, evaluated at the constrained MLE of q. */
|
|
1640
|
+
function tangoScore(b, c, n, delta) {
|
|
1641
|
+
const numerator = b - c - n * delta;
|
|
1642
|
+
const variance = n * (2 * constrainedLossRate(b, c, n, delta) + delta * (1 - delta));
|
|
1643
|
+
if (!(variance > 0)) {
|
|
1644
|
+
if (numerator === 0) return 0;
|
|
1645
|
+
return numerator > 0 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
|
|
1646
|
+
}
|
|
1647
|
+
return numerator / Math.sqrt(variance);
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* Paired risk difference with TANGO'S (1998) SCORE INTERVAL — the estimator a
|
|
1651
|
+
* promotion gate may decide on **at a nonzero margin**.
|
|
1652
|
+
*
|
|
1653
|
+
* {@link pairedRiskDifferenceExact} conditions on the observed discordant count
|
|
1654
|
+
* `m = b + c`, builds a Clopper-Pearson interval for the win share among those
|
|
1655
|
+
* `m` pairs, and multiplies by the observed `m/n`. That is exact for testing
|
|
1656
|
+
* RD = 0 — it is dual to McNemar — but it is NOT a confidence interval for the
|
|
1657
|
+
* population risk difference at a nonzero margin, because the sampling
|
|
1658
|
+
* variability of `m/n` itself is discarded. The gap is not academic: with the
|
|
1659
|
+
* production caller's `pairedDeltaThreshold: -0.05`, a process whose true risk
|
|
1660
|
+
* difference sits exactly on that margin clears a nominal-95 % `lower > margin`
|
|
1661
|
+
* check 24.75 % of the time at n = 40 and 43.95 % at n = 76 (2000 replicates
|
|
1662
|
+
* each) when the conditional interval decides.
|
|
1663
|
+
*
|
|
1664
|
+
* Tango's interval inverts the score test of RD = delta, which estimates the
|
|
1665
|
+
* nuisance loss rate under each hypothesised delta instead of fixing it at the
|
|
1666
|
+
* observed value, so `m` contributes its own uncertainty. It is the method
|
|
1667
|
+
* `ratesci::scorepairci` uses for paired risk-difference noninferiority, and it
|
|
1668
|
+
* is not conditional, so it stays valid as the margin moves away from zero.
|
|
1669
|
+
*
|
|
1670
|
+
* The bounds are found by bisecting `tangoScore(delta) = ±z` — the score is
|
|
1671
|
+
* monotone decreasing in delta, so each crossing is unique. Inputs are paired
|
|
1672
|
+
* 0/1 (or boolean) arrays, control first. Throws on unequal lengths.
|
|
1673
|
+
*/
|
|
1674
|
+
function pairedRiskDifferenceScore(control, treatment, confidence = .95) {
|
|
1675
|
+
if (control.length !== treatment.length) throw new Error(`pairedRiskDifferenceScore: unequal sample sizes (${control.length} vs ${treatment.length})`);
|
|
1676
|
+
if (confidence <= 0 || confidence >= 1) throw new Error(`pairedRiskDifferenceScore: confidence must be in (0,1), got ${confidence}`);
|
|
1677
|
+
const n = control.length;
|
|
1678
|
+
if (n === 0) return {
|
|
1679
|
+
n: 0,
|
|
1680
|
+
b: 0,
|
|
1681
|
+
c: 0,
|
|
1682
|
+
nDiscordant: 0,
|
|
1683
|
+
riskDifference: 0,
|
|
1684
|
+
lower: -1,
|
|
1685
|
+
upper: 1,
|
|
1686
|
+
confidence
|
|
1687
|
+
};
|
|
1688
|
+
let b = 0;
|
|
1689
|
+
let c = 0;
|
|
1690
|
+
for (let i = 0; i < n; i++) {
|
|
1691
|
+
const ctrl = control[i] ? 1 : 0;
|
|
1692
|
+
const treat = treatment[i] ? 1 : 0;
|
|
1693
|
+
if (treat === 1 && ctrl === 0) b++;
|
|
1694
|
+
else if (treat === 0 && ctrl === 1) c++;
|
|
1695
|
+
}
|
|
1696
|
+
const riskDifference = (b - c) / n;
|
|
1697
|
+
const z = zQuantile(1 - (1 - confidence) / 2);
|
|
1698
|
+
let lo = -1;
|
|
1699
|
+
let hi = riskDifference;
|
|
1700
|
+
for (let i = 0; i < 64; i++) {
|
|
1701
|
+
const mid = (lo + hi) / 2;
|
|
1702
|
+
if (tangoScore(b, c, n, mid) > z) lo = mid;
|
|
1703
|
+
else hi = mid;
|
|
1704
|
+
}
|
|
1705
|
+
const lower = (lo + hi) / 2;
|
|
1706
|
+
let ulo = riskDifference;
|
|
1707
|
+
let uhi = 1;
|
|
1708
|
+
for (let i = 0; i < 64; i++) {
|
|
1709
|
+
const mid = (ulo + uhi) / 2;
|
|
1710
|
+
if (tangoScore(b, c, n, mid) > -z) ulo = mid;
|
|
1711
|
+
else uhi = mid;
|
|
1712
|
+
}
|
|
1713
|
+
const upper = (ulo + uhi) / 2;
|
|
1714
|
+
return {
|
|
1715
|
+
n,
|
|
1716
|
+
b,
|
|
1717
|
+
c,
|
|
1718
|
+
nDiscordant: b + c,
|
|
1719
|
+
riskDifference,
|
|
1720
|
+
lower: Math.max(-1, lower),
|
|
1721
|
+
upper: Math.min(1, upper),
|
|
1722
|
+
confidence
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
/** Common positive level of paired {0, s} outcomes; divide by s before binary tests.
|
|
1726
|
+
* Returns null for non-finite, negative, mixed-scale or all-zero data. */
|
|
1727
|
+
function pairedBinaryScale(before, after) {
|
|
1728
|
+
let level = null;
|
|
1729
|
+
for (const arm of [before, after]) for (let i = 0; i < arm.length; i++) {
|
|
1730
|
+
const v = arm[i];
|
|
1731
|
+
if (!Number.isFinite(v)) return null;
|
|
1732
|
+
if (v === 0) continue;
|
|
1733
|
+
if (v < 0) return null;
|
|
1734
|
+
if (level === null) level = v;
|
|
1735
|
+
else if (v !== level) return null;
|
|
1736
|
+
}
|
|
1737
|
+
return level;
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* Unbiased pass@k for code generation (Chen et al. 2021, "Evaluating Large
|
|
1741
|
+
* Language Models Trained on Code"). Given `n` independent samples for one
|
|
1742
|
+
* problem of which `c` pass, the probability that at least one of a random k of
|
|
1743
|
+
* them passes is 1 − C(n−c, k) / C(n, k). Estimating pass@k as "did any of the
|
|
1744
|
+
* first k pass" is biased high at small n; this is the variance-reduced estimator
|
|
1745
|
+
* averaged implicitly over all k-subsets. Average the per-problem values across
|
|
1746
|
+
* the suite for the corpus pass@k. Computed in the numerically stable product
|
|
1747
|
+
* form. Requires 1 ≤ k ≤ n and 0 ≤ c ≤ n.
|
|
1748
|
+
*/
|
|
1749
|
+
function passAtK(n, c, k) {
|
|
1750
|
+
if (!Number.isInteger(n) || !Number.isInteger(c) || !Number.isInteger(k)) throw new Error(`passAtK: n, c, k must be integers (got n=${n}, c=${c}, k=${k})`);
|
|
1751
|
+
if (k < 1 || k > n || c < 0 || c > n) throw new Error(`passAtK: require 1 ≤ k ≤ n and 0 ≤ c ≤ n (got n=${n}, c=${c}, k=${k})`);
|
|
1752
|
+
if (n - c < k) return 1;
|
|
1753
|
+
let prob = 1;
|
|
1754
|
+
for (let i = n - c + 1; i <= n; i++) prob *= 1 - k / i;
|
|
1755
|
+
return 1 - prob;
|
|
1756
|
+
}
|
|
1757
|
+
// src/statistics/paired-tests.ts
|
|
1758
|
+
/**
|
|
1759
|
+
* Paired significance tests on continuous scores: the paired t-test, the
|
|
1760
|
+
* promotion-gate paired bootstrap, the exact sign test, and the package-wide
|
|
1761
|
+
* paired-delta decision statistic.
|
|
1762
|
+
*/
|
|
1763
|
+
/**
|
|
1764
|
+
* Paired t-test — before/after measurements on the SAME items.
|
|
1765
|
+
* Pairing removes inter-item variance, giving tighter significance than
|
|
1766
|
+
* an unpaired test when comparing prompt v1 vs prompt v2 on identical
|
|
1767
|
+
* scenarios.
|
|
1768
|
+
*
|
|
1769
|
+
* Returns `t = p = null` where the statistic is undefined: fewer than two
|
|
1770
|
+
* pairs, or a non-zero constant delta whose observed variance is zero. A
|
|
1771
|
+
* constant shift carries no information about the variance it would have to
|
|
1772
|
+
* be compared against, so the honest answer is "undefined", not `p = 0` —
|
|
1773
|
+
* three observations cannot buy absolute certainty. This is the same contract
|
|
1774
|
+
* {@link pairedCohensDz} states for the same condition. An all-zero delta is
|
|
1775
|
+
* different: it is a measured null, and returns `t = 0, p = 1`.
|
|
1776
|
+
*/
|
|
1777
|
+
function pairedTTest(before, after) {
|
|
1778
|
+
if (before.length !== after.length) throw new ValidationError(`pairedTTest: unequal sample sizes (${before.length} vs ${after.length})`);
|
|
1779
|
+
assertFiniteSample("pairedTTest", "before", before);
|
|
1780
|
+
assertFiniteSample("pairedTTest", "after", after);
|
|
1781
|
+
const n = before.length;
|
|
1782
|
+
if (n < 2) return {
|
|
1783
|
+
t: null,
|
|
1784
|
+
df: 0,
|
|
1785
|
+
p: null
|
|
1786
|
+
};
|
|
1787
|
+
const diffs = before.map((b, i) => after[i] - b);
|
|
1788
|
+
const mean = diffs.reduce((a, b) => a + b, 0) / n;
|
|
1789
|
+
const variance = diffs.reduce((acc, d) => acc + (d - mean) ** 2, 0) / (n - 1);
|
|
1790
|
+
const se = Math.sqrt(variance / n);
|
|
1791
|
+
if (se === 0) return mean === 0 ? {
|
|
1792
|
+
t: 0,
|
|
1793
|
+
df: n - 1,
|
|
1794
|
+
p: 1
|
|
1795
|
+
} : {
|
|
1796
|
+
t: null,
|
|
1797
|
+
df: n - 1,
|
|
1798
|
+
p: null
|
|
1799
|
+
};
|
|
1800
|
+
const t = mean / se;
|
|
1801
|
+
const df = n - 1;
|
|
1802
|
+
return {
|
|
1803
|
+
t,
|
|
1804
|
+
df,
|
|
1805
|
+
p: 2 * (1 - studentTCdf(Math.abs(t), df))
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* Pairs below which a percentile bootstrap interval is descriptive spread only.
|
|
1810
|
+
*
|
|
1811
|
+
* `P(low > 0)` under a true null, against a nominal 2.5 %, measured over 4000
|
|
1812
|
+
* seeded trials: 13.53 % at n = 3, 3.52 % at n = 10, 3.10 % at n = 20 on the
|
|
1813
|
+
* median; 13.85 %, 4.90 %, 3.80 % on the mean. This is intrinsic to resampling
|
|
1814
|
+
* three points, not an implementation error — scipy's BCa gives 16.0 % on the
|
|
1815
|
+
* same n = 3 data — so no change to the estimator moves it. Below this floor
|
|
1816
|
+
* the decision belongs to the exact sign test or exact signed-rank test.
|
|
1817
|
+
*/
|
|
1818
|
+
const BOOTSTRAP_GATE_MIN_N = 20;
|
|
1819
|
+
/**
|
|
1820
|
+
* Paired bootstrap on (after − before) deltas. Returns a CI on the chosen
|
|
1821
|
+
* statistic (median by default); pairs are resampled with replacement. Throws
|
|
1822
|
+
* on unequal sample sizes.
|
|
1823
|
+
*
|
|
1824
|
+
* `low > threshold` carries the stated confidence ONLY at `n ≥
|
|
1825
|
+
* {@link BOOTSTRAP_GATE_MIN_N}`, which `gateEligible` reports. Below it the
|
|
1826
|
+
* check fires under a true null several times more often than nominal, so the
|
|
1827
|
+
* interval is descriptive spread and a promotion must not turn on it.
|
|
1828
|
+
*/
|
|
1829
|
+
function pairedBootstrap(before, after, opts = {}) {
|
|
1830
|
+
if (before.length !== after.length) throw new Error(`pairedBootstrap: unequal sample sizes (${before.length} vs ${after.length})`);
|
|
1831
|
+
const confidence = opts.confidence ?? .95;
|
|
1832
|
+
const resamples = opts.resamples ?? 2e3;
|
|
1833
|
+
const statistic = opts.statistic ?? "median";
|
|
1834
|
+
if (confidence <= 0 || confidence >= 1) throw new Error(`pairedBootstrap: confidence must be in (0,1), got ${confidence}`);
|
|
1835
|
+
const n = before.length;
|
|
1836
|
+
const deltas = before.map((b, i) => after[i] - b);
|
|
1837
|
+
const gateEligible = n >= 20;
|
|
1838
|
+
if (n === 0) return {
|
|
1839
|
+
n: 0,
|
|
1840
|
+
median: 0,
|
|
1841
|
+
mean: 0,
|
|
1842
|
+
low: 0,
|
|
1843
|
+
high: 0,
|
|
1844
|
+
confidence,
|
|
1845
|
+
resamples,
|
|
1846
|
+
gateEligible
|
|
1847
|
+
};
|
|
1848
|
+
if (n === 1) {
|
|
1849
|
+
const d = deltas[0];
|
|
1850
|
+
return {
|
|
1851
|
+
n: 1,
|
|
1852
|
+
median: d,
|
|
1853
|
+
mean: d,
|
|
1854
|
+
low: d,
|
|
1855
|
+
high: d,
|
|
1856
|
+
confidence,
|
|
1857
|
+
resamples,
|
|
1858
|
+
gateEligible
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1861
|
+
const rng = makeRng(opts.seed, deltas);
|
|
1862
|
+
const samples = new Array(resamples);
|
|
1863
|
+
for (let b = 0; b < resamples; b++) if (statistic === "mean") {
|
|
1864
|
+
let sum = 0;
|
|
1865
|
+
for (let k = 0; k < n; k++) sum += deltas[Math.floor(rng() * n)];
|
|
1866
|
+
samples[b] = sum / n;
|
|
1867
|
+
} else {
|
|
1868
|
+
const acc = new Array(n);
|
|
1869
|
+
for (let k = 0; k < n; k++) acc[k] = deltas[Math.floor(rng() * n)];
|
|
1870
|
+
samples[b] = medianInPlace(acc);
|
|
1871
|
+
}
|
|
1872
|
+
samples.sort((a, b) => a - b);
|
|
1873
|
+
const alpha = 1 - confidence;
|
|
1874
|
+
const lowIdx = Math.floor(alpha / 2 * resamples);
|
|
1875
|
+
const highIdx = Math.min(resamples - 1, Math.ceil((1 - alpha / 2) * resamples) - 1);
|
|
1876
|
+
return {
|
|
1877
|
+
n,
|
|
1878
|
+
median: medianInPlace([...deltas]),
|
|
1879
|
+
mean: deltas.reduce((s, x) => s + x, 0) / n,
|
|
1880
|
+
low: samples[lowIdx],
|
|
1881
|
+
high: samples[Math.max(highIdx, lowIdx)],
|
|
1882
|
+
confidence,
|
|
1883
|
+
resamples,
|
|
1884
|
+
gateEligible
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Exact one-sided sign test over paired differences.
|
|
1889
|
+
*
|
|
1890
|
+
* Pass `after[i] - before[i]` for each matched item. `alternative = 'greater'`
|
|
1891
|
+
* tests whether positive signs are more likely than negative signs and returns
|
|
1892
|
+
* `P(Binomial(nNonTies, 0.5) >= positive)`. `alternative = 'less'` treats
|
|
1893
|
+
* negative signs as successes instead. With a continuous difference
|
|
1894
|
+
* distribution this is the usual directional median test. Exact zero
|
|
1895
|
+
* differences are ties and do not enter the binomial denominator. All-tie and
|
|
1896
|
+
* empty inputs return p = 1. Every input difference must be finite, and the
|
|
1897
|
+
* direction must be chosen explicitly so a caller cannot select it after
|
|
1898
|
+
* seeing the signs.
|
|
1899
|
+
*/
|
|
1900
|
+
function pairedSignTest(differences, alternative) {
|
|
1901
|
+
if (alternative !== "greater" && alternative !== "less") throw new ValidationError(`pairedSignTest: alternative must be 'greater' or 'less', got ${alternative}`);
|
|
1902
|
+
let positive = 0;
|
|
1903
|
+
let negative = 0;
|
|
1904
|
+
let ties = 0;
|
|
1905
|
+
for (let i = 0; i < differences.length; i++) {
|
|
1906
|
+
const difference = differences[i];
|
|
1907
|
+
if (!Number.isFinite(difference)) throw new ValidationError(`pairedSignTest: difference at index ${i} must be finite, got ${difference}`);
|
|
1908
|
+
if (difference > 0) positive++;
|
|
1909
|
+
else if (difference < 0) negative++;
|
|
1910
|
+
else ties++;
|
|
1911
|
+
}
|
|
1912
|
+
const nNonTies = positive + negative;
|
|
1913
|
+
const successes = alternative === "greater" ? positive : negative;
|
|
1914
|
+
return {
|
|
1915
|
+
n: differences.length,
|
|
1916
|
+
positive,
|
|
1917
|
+
negative,
|
|
1918
|
+
ties,
|
|
1919
|
+
nNonTies,
|
|
1920
|
+
alternative,
|
|
1921
|
+
pValue: binomialHalfUpperTail(successes, nNonTies)
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
/** Fraction of paired observations whose delta is an exact tie (|after − before|
|
|
1925
|
+
* < 1e-9). Throws on unequal sample sizes; 0 pairs ⇒ 0. */
|
|
1926
|
+
function pairedDeltaTieFraction(before, after) {
|
|
1927
|
+
if (before.length !== after.length) throw new Error(`pairedDeltaTieFraction: unequal sample sizes (${before.length} vs ${after.length})`);
|
|
1928
|
+
const n = before.length;
|
|
1929
|
+
if (n === 0) return 0;
|
|
1930
|
+
let ties = 0;
|
|
1931
|
+
for (let i = 0; i < n; i++) if (Math.abs(after[i] - before[i]) < 1e-9) ties++;
|
|
1932
|
+
return ties / n;
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* The paired-delta statistic a DECISION is computed on, package-wide.
|
|
1936
|
+
*
|
|
1937
|
+
* The mean paired delta is the estimator that answers the question a promotion
|
|
1938
|
+
* gate asks — "by how much did the candidate move the score" — in the caller's
|
|
1939
|
+
* own units, and it equals the aggregate lift everyone quotes. The MEDIAN
|
|
1940
|
+
* answers a different question and loses the answer to this one in every regime
|
|
1941
|
+
* eval data actually lands in:
|
|
1942
|
+
* - TWO-POINT (pass/fail) outcomes on any encoding: the delta vector lives in
|
|
1943
|
+
* {−s, 0, +s} dominated by zeros, so the median and its whole bootstrap CI
|
|
1944
|
+
* are pinned at exactly 0 however large the shift. (Decide these on
|
|
1945
|
+
* {@link pairedRiskDifferenceExact} instead — same estimand, exact interval.)
|
|
1946
|
+
* - TIE-DOMINATED outcomes: at half the pairs tied the sample median is 0 by
|
|
1947
|
+
* construction, and `ci.low > threshold` then answers "no" forever at a
|
|
1948
|
+
* non-negative threshold and "yes" forever at a negative one.
|
|
1949
|
+
* - LOW-CARDINALITY outcomes, even well below half ties: judge dimensions on
|
|
1950
|
+
* integer 0-100, and block scores like {⅔, 1} from averaging pass/fail
|
|
1951
|
+
* leaves, put the median on a coarse lattice whose bootstrap percentiles
|
|
1952
|
+
* land on atoms. Measured: 26 blocks of 3 pass/fail leaves carrying a real
|
|
1953
|
+
* +12.8pp lift, only 23% of pairs tied, gives a median CI of [0, 0.333] —
|
|
1954
|
+
* lower bound exactly 0, so a gate at threshold 0 refuses a real lift.
|
|
1955
|
+
* That last case is why there is no tie-fraction threshold here: any cutoff on
|
|
1956
|
+
* ties leaves the lattice case open on the other side of it.
|
|
1957
|
+
*
|
|
1958
|
+
* `heldoutSignificance` has defaulted to the mean since #316 for the same
|
|
1959
|
+
* reason. The median remains available per call site for callers who
|
|
1960
|
+
* specifically want outlier robustness and accept the blindness.
|
|
1961
|
+
*/
|
|
1962
|
+
const DECISION_PAIRED_DELTA_STATISTIC = "mean";
|
|
1963
|
+
// src/statistics/power-and-mde.ts
|
|
1964
|
+
/**
|
|
1965
|
+
* Required N per arm for a two-sample comparison at target effect size,
|
|
1966
|
+
* alpha, and power. Normal-approximation formula:
|
|
1967
|
+
* n = 2 * ( (z_{1-α/2} + z_{1-β}) / d )^2
|
|
1968
|
+
* where d is Cohen's d. Returns Infinity for effect ≤ 0.
|
|
1969
|
+
*/
|
|
1970
|
+
function requiredSampleSize(opts) {
|
|
1971
|
+
const effect = opts.effect;
|
|
1972
|
+
if (!Number.isFinite(effect) || effect <= 0) return Infinity;
|
|
1973
|
+
const alpha = opts.alpha ?? .05;
|
|
1974
|
+
const power = opts.power ?? .8;
|
|
1975
|
+
const n = 2 * ((zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha) + zQuantile(power)) / effect) ** 2;
|
|
1976
|
+
return Math.ceil(n);
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Required number of paired observations for a target Cohen's dz.
|
|
1980
|
+
* Unlike the independent-groups formula, this has no two-arm factor of two.
|
|
1981
|
+
*
|
|
1982
|
+
* Normal quantiles with no t correction, so treat the result as a LOWER bound:
|
|
1983
|
+
* it returns 32 where the exact t-based answer is 34 at dz = 0.5, and 13 where
|
|
1984
|
+
* it is 15 at dz = 0.8 — a 6–13 % shortfall precisely in the range a caller
|
|
1985
|
+
* consults to decide whether 3–10 repetitions suffice.
|
|
1986
|
+
*/
|
|
1987
|
+
function requiredPairedSampleSize(opts) {
|
|
1988
|
+
const effect = opts.effect;
|
|
1989
|
+
if (!Number.isFinite(effect) || effect <= 0) return Infinity;
|
|
1990
|
+
const alpha = opts.alpha ?? .05;
|
|
1991
|
+
const power = opts.power ?? .8;
|
|
1992
|
+
const zAlpha = zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha);
|
|
1993
|
+
const zBeta = zQuantile(power);
|
|
1994
|
+
return Math.ceil(((zAlpha + zBeta) / effect) ** 2);
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Minimum detectable paired effect (standardised units) for a target paired
|
|
1998
|
+
* sample size: d_min = (z_{1-α/2} + z_β) / sqrt(n_paired). Multiply by
|
|
1999
|
+
* sd(deltas) for score units; treat as a lower bound — Wilcoxon and bootstrap
|
|
2000
|
+
* have asymptotic relative efficiency below 1 vs the t-test on heavy tails.
|
|
2001
|
+
*/
|
|
2002
|
+
function pairedMde(opts) {
|
|
2003
|
+
if (!Number.isFinite(opts.nPaired) || opts.nPaired <= 0) return Infinity;
|
|
2004
|
+
const alpha = opts.alpha ?? .05;
|
|
2005
|
+
const power = opts.power ?? .8;
|
|
2006
|
+
return (zQuantile(opts.twoSided ?? true ? 1 - alpha / 2 : 1 - alpha) + zQuantile(power)) / Math.sqrt(opts.nPaired);
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Number of paired observations needed for a McNemar test to reach a target
|
|
2010
|
+
* power — the pre-registration companion to {@link mcnemar}. Parametrised by the
|
|
2011
|
+
* expected discordant-cell probabilities `p10` (P[treatment wins on a pair]) and
|
|
2012
|
+
* `p01` (P[control wins]); concordant pairs carry no information, so the count
|
|
2013
|
+
* is driven entirely by the discordant rate. Lachin's (1992) asymptotic normal
|
|
2014
|
+
* approximation: with discordant rate `pDisc = p10 + p01` and marginal effect
|
|
2015
|
+
* `δ = p10 − p01`,
|
|
2016
|
+
* n = ( z_{1-α/2}·√pDisc + z_{1-β}·√(pDisc − δ²) )² / δ².
|
|
2017
|
+
* Returns Infinity when there is no effect (p10 === p01). Asymptotic — at the
|
|
2018
|
+
* tiny discordant counts where the exact {@link mcnemar} differs from the normal
|
|
2019
|
+
* approximation, treat the result as a lower bound and prefer the discordant-pair
|
|
2020
|
+
* floor.
|
|
2021
|
+
*/
|
|
2022
|
+
function mcnemarRequiredN(opts) {
|
|
2023
|
+
const { p10, p01 } = opts;
|
|
2024
|
+
if (p10 < 0 || p01 < 0 || p10 + p01 > 1) throw new Error(`mcnemarRequiredN: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`);
|
|
2025
|
+
const delta = p10 - p01;
|
|
2026
|
+
if (delta === 0) return Infinity;
|
|
2027
|
+
const alpha = opts.alpha ?? .05;
|
|
2028
|
+
const power = opts.power ?? .8;
|
|
2029
|
+
const twoSided = opts.twoSided ?? true;
|
|
2030
|
+
const pDisc = p10 + p01;
|
|
2031
|
+
const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha);
|
|
2032
|
+
const zBeta = zQuantile(power);
|
|
2033
|
+
const n = (zAlpha * Math.sqrt(pDisc) + zBeta * Math.sqrt(Math.max(0, pDisc - delta * delta))) ** 2 / (delta * delta);
|
|
2034
|
+
return Math.ceil(n);
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* Power of a McNemar test at a given number of paired observations, the inverse
|
|
2038
|
+
* of {@link mcnemarRequiredN} (same Lachin asymptotic model, same parameters).
|
|
2039
|
+
* Returns a value in [0, 1]; equals `alpha` when there is no effect.
|
|
2040
|
+
*/
|
|
2041
|
+
function mcnemarPower(opts) {
|
|
2042
|
+
const { p10, p01, nPairs } = opts;
|
|
2043
|
+
if (p10 < 0 || p01 < 0 || p10 + p01 > 1) throw new Error(`mcnemarPower: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`);
|
|
2044
|
+
const alpha = opts.alpha ?? .05;
|
|
2045
|
+
const twoSided = opts.twoSided ?? true;
|
|
2046
|
+
const delta = p10 - p01;
|
|
2047
|
+
if (delta === 0 || nPairs <= 0) return alpha;
|
|
2048
|
+
const pDisc = p10 + p01;
|
|
2049
|
+
const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha);
|
|
2050
|
+
const denom = Math.sqrt(Math.max(1e-12, pDisc - delta * delta));
|
|
2051
|
+
const zBeta = (Math.sqrt(nPairs) * Math.abs(delta) - zAlpha * Math.sqrt(pDisc)) / denom;
|
|
2052
|
+
return Math.min(1, Math.max(0, normalCdf(zBeta)));
|
|
2053
|
+
}
|
|
2054
|
+
// src/statistics/rank-tests.ts
|
|
2055
|
+
/** Maximum dynamic-programming cells used by an exact two-sample rank test. */
|
|
2056
|
+
const MANN_WHITNEY_EXACT_MAX_STATES = 8192;
|
|
2057
|
+
/** Maximum inner-loop transitions used by an exact two-sample rank test. */
|
|
2058
|
+
const MANN_WHITNEY_EXACT_MAX_WORK = 25e4;
|
|
2059
|
+
/** Non-zero differences up to which the signed-rank null is enumerated exactly. */
|
|
2060
|
+
const WILCOXON_EXACT_MAX_N = 20;
|
|
2061
|
+
/** Resamples used when a rank test falls back to Monte Carlo permutation. */
|
|
2062
|
+
const DEFAULT_PERMUTATIONS = 1e5;
|
|
2063
|
+
/**
|
|
2064
|
+
* Mann-Whitney U — two independent samples, no distributional assumption.
|
|
2065
|
+
*
|
|
2066
|
+
* Exact conditional (permutation) p by default when the dynamic program fits
|
|
2067
|
+
* {@link MANN_WHITNEY_EXACT_MAX_STATES} cells and
|
|
2068
|
+
* {@link MANN_WHITNEY_EXACT_MAX_WORK} transitions, seeded Monte Carlo
|
|
2069
|
+
* permutation above those limits. This keeps imbalanced designs such as 1+24
|
|
2070
|
+
* exact without admitting expensive balanced designs merely because they have
|
|
2071
|
+
* the same total size. Throws on non-finite input and on `method:
|
|
2072
|
+
* 'asymptotic'` where an exact answer is available. Empty input yields `p = 1,
|
|
2073
|
+
* pFloor = 1` — no design, no attainable evidence.
|
|
2074
|
+
*/
|
|
2075
|
+
function mannWhitneyU(a, b, opts = {}) {
|
|
2076
|
+
assertFiniteSample("mannWhitneyU", "a", a);
|
|
2077
|
+
assertFiniteSample("mannWhitneyU", "b", b);
|
|
2078
|
+
const n1 = a.length;
|
|
2079
|
+
const n2 = b.length;
|
|
2080
|
+
if (n1 === 0 || n2 === 0) return {
|
|
2081
|
+
u: 0,
|
|
2082
|
+
uA: 0,
|
|
2083
|
+
p: 1,
|
|
2084
|
+
method: "exact",
|
|
2085
|
+
pFloor: 1
|
|
2086
|
+
};
|
|
2087
|
+
const total = n1 + n2;
|
|
2088
|
+
const combined = [...a.map((v) => ({
|
|
2089
|
+
v,
|
|
2090
|
+
fromA: true
|
|
2091
|
+
})), ...b.map((v) => ({
|
|
2092
|
+
v,
|
|
2093
|
+
fromA: false
|
|
2094
|
+
}))].sort((x, y) => x.v - y.v);
|
|
2095
|
+
const { midranks, tieTerm } = midranksWithTieTerm(combined.map((entry) => entry.v));
|
|
2096
|
+
let rankSumA = 0;
|
|
2097
|
+
for (let k = 0; k < total; k++) if (combined[k].fromA) rankSumA += midranks[k];
|
|
2098
|
+
const uA = rankSumA - n1 * (n1 + 1) / 2;
|
|
2099
|
+
const u = Math.min(uA, n1 * n2 - uA);
|
|
2100
|
+
const doubled = midranks.map((rank) => Math.round(rank * 2));
|
|
2101
|
+
const doubledDeviation = Math.abs(2 * uA - n1 * n2);
|
|
2102
|
+
const selectedN = Math.min(n1, n2);
|
|
2103
|
+
const otherN = total - selectedN;
|
|
2104
|
+
const exactCost = exactTwoSampleCost(doubled, selectedN);
|
|
2105
|
+
const designFloor = exactTwoSampleFloor(doubled, selectedN);
|
|
2106
|
+
const method = selectRankTestMethod("mannWhitneyU", opts.method ?? "auto", `n1=${n1}, n2=${n2}`, exactCost.states <= MANN_WHITNEY_EXACT_MAX_STATES && exactCost.work <= MANN_WHITNEY_EXACT_MAX_WORK, designFloor, `${MANN_WHITNEY_EXACT_MAX_STATES.toLocaleString("en-US")} states and ${MANN_WHITNEY_EXACT_MAX_WORK.toLocaleString("en-US")} transitions`);
|
|
2107
|
+
if (method === "exact") {
|
|
2108
|
+
const { p, pFloor } = exactTwoSampleP(doubled, selectedN, otherN, doubledDeviation);
|
|
2109
|
+
return {
|
|
2110
|
+
u,
|
|
2111
|
+
uA,
|
|
2112
|
+
p,
|
|
2113
|
+
method,
|
|
2114
|
+
pFloor
|
|
2115
|
+
};
|
|
2116
|
+
}
|
|
2117
|
+
if (method === "asymptotic") return {
|
|
2118
|
+
u,
|
|
2119
|
+
uA,
|
|
2120
|
+
p: asymptoticTwoSidedP(doubledDeviation / 2, twoSampleSigma(n1, n2, total, tieTerm)),
|
|
2121
|
+
method,
|
|
2122
|
+
pFloor: designFloor
|
|
2123
|
+
};
|
|
2124
|
+
const permutations = resolvePermutations("mannWhitneyU", opts.permutations);
|
|
2125
|
+
const rng = opts.seed === void 0 ? makeRng(symmetricTwoSampleSeed(a, b)) : makeRng(opts.seed);
|
|
2126
|
+
let atLeastAsExtreme = 0;
|
|
2127
|
+
const pool = [...doubled];
|
|
2128
|
+
for (let iteration = 0; iteration < permutations; iteration++) {
|
|
2129
|
+
let doubledRankSum = 0;
|
|
2130
|
+
for (let k = 0; k < selectedN; k++) {
|
|
2131
|
+
const pick = k + Math.floor(rng() * (total - k));
|
|
2132
|
+
const swapped = pool[pick];
|
|
2133
|
+
pool[pick] = pool[k];
|
|
2134
|
+
pool[k] = swapped;
|
|
2135
|
+
doubledRankSum += swapped;
|
|
2136
|
+
}
|
|
2137
|
+
if (Math.abs(doubledRankSum - selectedN * (selectedN + 1) - selectedN * otherN) >= doubledDeviation) atLeastAsExtreme++;
|
|
2138
|
+
}
|
|
2139
|
+
const pFloor = Math.max(1 / (permutations + 1), designFloor);
|
|
2140
|
+
return {
|
|
2141
|
+
u,
|
|
2142
|
+
uA,
|
|
2143
|
+
p: Math.max((1 + atLeastAsExtreme) / (permutations + 1), pFloor),
|
|
2144
|
+
method,
|
|
2145
|
+
pFloor
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Wilcoxon signed-rank — paired, no distributional assumption on the deltas.
|
|
2150
|
+
*
|
|
2151
|
+
* Exact conditional (sign-flip) p by default at `n ≤
|
|
2152
|
+
* {@link WILCOXON_EXACT_MAX_N}` non-zero differences, seeded Monte Carlo
|
|
2153
|
+
* permutation above it. Throws on non-finite input and on `method:
|
|
2154
|
+
* 'asymptotic'` where an exact answer is available.
|
|
2155
|
+
*
|
|
2156
|
+
* `n` is the count of NON-ZERO differences: exact ties are dropped before
|
|
2157
|
+
* ranking, so a run of tied pairs shrinks the design and raises `pFloor`.
|
|
2158
|
+
* All-tied input yields `p = 1, pFloor = 1` — no attainable evidence, which
|
|
2159
|
+
* `pFloor` states rather than leaving `p = 1` to be read as a measured null.
|
|
2160
|
+
*/
|
|
2161
|
+
function wilcoxonSignedRank(before, after, opts = {}) {
|
|
2162
|
+
if (before.length !== after.length) throw new ValidationError(`wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`);
|
|
2163
|
+
assertFiniteSample("wilcoxonSignedRank", "before", before);
|
|
2164
|
+
assertFiniteSample("wilcoxonSignedRank", "after", after);
|
|
2165
|
+
const diffs = before.map((b, i) => after[i] - b).filter((d) => d !== 0);
|
|
2166
|
+
const n = diffs.length;
|
|
2167
|
+
if (n === 0) return {
|
|
2168
|
+
w: 0,
|
|
2169
|
+
p: 1,
|
|
2170
|
+
method: "exact",
|
|
2171
|
+
pFloor: 1,
|
|
2172
|
+
nNonZero: 0
|
|
2173
|
+
};
|
|
2174
|
+
const abs = Math.abs(diffs[0]);
|
|
2175
|
+
const allEqualAbs = diffs.every((d) => Math.abs(d) === abs);
|
|
2176
|
+
if ((opts.method === void 0 || opts.method === "auto") && allEqualAbs) {
|
|
2177
|
+
const positive = diffs.filter((d) => d > 0).length;
|
|
2178
|
+
const negative = n - positive;
|
|
2179
|
+
return {
|
|
2180
|
+
w: positive * (n + 1) / 2,
|
|
2181
|
+
p: binomialSignTwoSided(positive, negative),
|
|
2182
|
+
method: "exact",
|
|
2183
|
+
pFloor: Math.min(1, 2 ** (1 - n)),
|
|
2184
|
+
nNonZero: n
|
|
2185
|
+
};
|
|
2186
|
+
}
|
|
2187
|
+
const order = diffs.map((d, i) => ({
|
|
2188
|
+
abs: Math.abs(d),
|
|
2189
|
+
i
|
|
2190
|
+
})).sort((x, y) => x.abs - y.abs);
|
|
2191
|
+
const { midranks, tieTerm } = midranksWithTieTerm(order.map((entry) => entry.abs));
|
|
2192
|
+
const ranks = new Array(n);
|
|
2193
|
+
for (let k = 0; k < n; k++) ranks[order[k].i] = midranks[k];
|
|
2194
|
+
let wPlus = 0;
|
|
2195
|
+
for (let k = 0; k < n; k++) if (diffs[k] > 0) wPlus += ranks[k];
|
|
2196
|
+
const doubled = midranks.map((rank) => Math.round(rank * 2));
|
|
2197
|
+
const doubledDeviation = Math.abs(2 * wPlus - n * (n + 1) / 2);
|
|
2198
|
+
const designFloor = Math.min(1, 2 ** (1 - n));
|
|
2199
|
+
const method = selectRankTestMethod("wilcoxonSignedRank", opts.method ?? "auto", `n=${n} non-zero differences`, n <= WILCOXON_EXACT_MAX_N, designFloor, `${WILCOXON_EXACT_MAX_N} non-zero differences`);
|
|
2200
|
+
if (method === "exact") {
|
|
2201
|
+
const { p, pFloor } = exactSignedRankP(doubled, doubledDeviation);
|
|
2202
|
+
return {
|
|
2203
|
+
w: wPlus,
|
|
2204
|
+
p,
|
|
2205
|
+
method,
|
|
2206
|
+
pFloor,
|
|
2207
|
+
nNonZero: n
|
|
2208
|
+
};
|
|
2209
|
+
}
|
|
2210
|
+
if (method === "asymptotic") {
|
|
2211
|
+
const variance = n * (n + 1) * (2 * n + 1) / 24 - tieTerm / 48;
|
|
2212
|
+
return {
|
|
2213
|
+
w: wPlus,
|
|
2214
|
+
p: asymptoticTwoSidedP(doubledDeviation / 2, Math.sqrt(variance)),
|
|
2215
|
+
method,
|
|
2216
|
+
pFloor: designFloor,
|
|
2217
|
+
nNonZero: n
|
|
2218
|
+
};
|
|
2219
|
+
}
|
|
2220
|
+
const permutations = resolvePermutations("wilcoxonSignedRank", opts.permutations);
|
|
2221
|
+
const rng = makeRng(opts.seed, before, after);
|
|
2222
|
+
const doubledCentre = n * (n + 1) / 2;
|
|
2223
|
+
let atLeastAsExtreme = 0;
|
|
2224
|
+
for (let iteration = 0; iteration < permutations; iteration++) {
|
|
2225
|
+
let doubledWPlus = 0;
|
|
2226
|
+
for (let k = 0; k < n; k++) if (rng() < .5) doubledWPlus += doubled[k];
|
|
2227
|
+
if (Math.abs(doubledWPlus - doubledCentre) >= doubledDeviation) atLeastAsExtreme++;
|
|
2228
|
+
}
|
|
2229
|
+
return {
|
|
2230
|
+
w: wPlus,
|
|
2231
|
+
p: (1 + atLeastAsExtreme) / (permutations + 1),
|
|
2232
|
+
method,
|
|
2233
|
+
pFloor: Math.max(1 / (permutations + 1), designFloor),
|
|
2234
|
+
nNonZero: n
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
/**
|
|
2238
|
+
* Average ranks over an ASCENDING-sorted array, plus `Σ(t³ − t)` over tie
|
|
2239
|
+
* groups of size `t` — the correction term both asymptotic rank-test variances
|
|
2240
|
+
* need.
|
|
2241
|
+
*/
|
|
2242
|
+
function midranksWithTieTerm(sorted) {
|
|
2243
|
+
const midranks = new Array(sorted.length);
|
|
2244
|
+
let tieTerm = 0;
|
|
2245
|
+
let i = 0;
|
|
2246
|
+
while (i < sorted.length) {
|
|
2247
|
+
let j = i;
|
|
2248
|
+
while (j < sorted.length && sorted[j] === sorted[i]) j++;
|
|
2249
|
+
const average = (i + 1 + j) / 2;
|
|
2250
|
+
for (let k = i; k < j; k++) midranks[k] = average;
|
|
2251
|
+
const groupSize = j - i;
|
|
2252
|
+
if (groupSize > 1) tieTerm += groupSize ** 3 - groupSize;
|
|
2253
|
+
i = j;
|
|
2254
|
+
}
|
|
2255
|
+
return {
|
|
2256
|
+
midranks,
|
|
2257
|
+
tieTerm
|
|
2258
|
+
};
|
|
2259
|
+
}
|
|
2260
|
+
function selectRankTestMethod(fn, request, design, exactFeasible, designFloor, threshold) {
|
|
2261
|
+
if (request === "auto") return exactFeasible ? "exact" : "permutation";
|
|
2262
|
+
if (request === "exact") {
|
|
2263
|
+
if (exactFeasible) return "exact";
|
|
2264
|
+
throw new ValidationError(`${fn}: method 'exact' is out of range at ${design} — enumeration is bounded by ${threshold}. Use 'auto' for the seeded Monte Carlo permutation, which converges to the same answer.`);
|
|
2265
|
+
}
|
|
2266
|
+
if (exactFeasible) throw new ValidationError(`${fn}: method 'asymptotic' is refused at ${design} — the exact p-grid at this design starts at ${formatProbability(designFloor)}, so an asymptotic p below it describes no attainable outcome. Use method 'exact' (the default) or add repetitions past ${threshold}.`);
|
|
2267
|
+
return "asymptotic";
|
|
2268
|
+
}
|
|
2269
|
+
function resolvePermutations(fn, permutations) {
|
|
2270
|
+
if (permutations === void 0) return DEFAULT_PERMUTATIONS;
|
|
2271
|
+
if (!Number.isInteger(permutations) || permutations < 1) throw new ValidationError(`${fn}: permutations must be a positive integer, got ${permutations}`);
|
|
2272
|
+
return permutations;
|
|
2273
|
+
}
|
|
2274
|
+
/** Two-sided normal-approximation tail with the continuity correction. */
|
|
2275
|
+
function asymptoticTwoSidedP(deviation, sigma) {
|
|
2276
|
+
if (!(sigma > 0)) return 1;
|
|
2277
|
+
return Math.min(1, 2 * (1 - normalCdf(Math.max(0, deviation - .5) / sigma)));
|
|
2278
|
+
}
|
|
2279
|
+
/** SD of U under the permutation null, corrected for the realised ties. The
|
|
2280
|
+
* tie term reduces (N+1) and reaches it exactly when every value is tied, so
|
|
2281
|
+
* the variance floors at 0 rather than going negative. */
|
|
2282
|
+
function twoSampleSigma(n1, n2, total, tieTerm) {
|
|
2283
|
+
if (total < 2) return 0;
|
|
2284
|
+
const variance = n1 * n2 / 12 * (total + 1 - tieTerm / (total * (total - 1)));
|
|
2285
|
+
return Math.sqrt(Math.max(0, variance));
|
|
2286
|
+
}
|
|
2287
|
+
function logChoose(n, k) {
|
|
2288
|
+
return lnGamma(n + 1) - lnGamma(k + 1) - lnGamma(n - k + 1);
|
|
2289
|
+
}
|
|
2290
|
+
function formatProbability(value) {
|
|
2291
|
+
return value >= 1e-4 || value === 0 ? value.toFixed(4) : value.toExponential(3);
|
|
2292
|
+
}
|
|
2293
|
+
/**
|
|
2294
|
+
* Exact DP allocation and loop count for this observed rank vector.
|
|
2295
|
+
*
|
|
2296
|
+
* The smaller arm is sufficient because selecting its complement produces the
|
|
2297
|
+
* same two-sided U deviation while using fewer rows in the state table.
|
|
2298
|
+
*/
|
|
2299
|
+
function exactTwoSampleCost(doubledRanks, selectedN) {
|
|
2300
|
+
const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
|
|
2301
|
+
let work = 0;
|
|
2302
|
+
for (let placed = 0; placed < doubledRanks.length; placed++) work += Math.min(selectedN, placed + 1) * (maxSum - doubledRanks[placed] + 1);
|
|
2303
|
+
return {
|
|
2304
|
+
states: (selectedN + 1) * (maxSum + 1),
|
|
2305
|
+
work
|
|
2306
|
+
};
|
|
2307
|
+
}
|
|
2308
|
+
/**
|
|
2309
|
+
* Smallest attainable two-sided p under the observed ties.
|
|
2310
|
+
*
|
|
2311
|
+
* Only subsets with the minimum or maximum rank sum can attain the largest
|
|
2312
|
+
* deviation. Their multiplicity is the number of ways to choose within the
|
|
2313
|
+
* tie group at each boundary, so this calculation is exact without allocating
|
|
2314
|
+
* the full null distribution.
|
|
2315
|
+
*/
|
|
2316
|
+
function exactTwoSampleFloor(doubledRanks, selectedN) {
|
|
2317
|
+
const total = doubledRanks.length;
|
|
2318
|
+
const otherN = total - selectedN;
|
|
2319
|
+
const minimumSum = doubledRanks.slice(0, selectedN).reduce((sum, rank) => sum + rank, 0);
|
|
2320
|
+
const maximumSum = doubledRanks.slice(total - selectedN).reduce((sum, rank) => sum + rank, 0);
|
|
2321
|
+
if (minimumSum === maximumSum) return 1;
|
|
2322
|
+
const centre = selectedN * (selectedN + 1) + selectedN * otherN;
|
|
2323
|
+
const minimumDeviation = Math.abs(minimumSum - centre);
|
|
2324
|
+
const maximumDeviation = Math.abs(maximumSum - centre);
|
|
2325
|
+
const totalLogWays = logChoose(total, selectedN);
|
|
2326
|
+
const minimumMass = Math.exp(logExtremeSubsetWays(doubledRanks, selectedN, "minimum") - totalLogWays);
|
|
2327
|
+
const maximumMass = Math.exp(logExtremeSubsetWays(doubledRanks, selectedN, "maximum") - totalLogWays);
|
|
2328
|
+
if (minimumDeviation > maximumDeviation) return minimumMass;
|
|
2329
|
+
if (maximumDeviation > minimumDeviation) return maximumMass;
|
|
2330
|
+
return Math.min(1, minimumMass + maximumMass);
|
|
2331
|
+
}
|
|
2332
|
+
function logExtremeSubsetWays(sortedRanks, selectedN, side) {
|
|
2333
|
+
const boundaryIndex = side === "minimum" ? selectedN - 1 : sortedRanks.length - selectedN;
|
|
2334
|
+
const boundary = sortedRanks[boundaryIndex];
|
|
2335
|
+
let first = boundaryIndex;
|
|
2336
|
+
let afterLast = boundaryIndex + 1;
|
|
2337
|
+
while (first > 0 && sortedRanks[first - 1] === boundary) first--;
|
|
2338
|
+
while (afterLast < sortedRanks.length && sortedRanks[afterLast] === boundary) afterLast++;
|
|
2339
|
+
return logChoose(afterLast - first, selectedN - (side === "minimum" ? first : sortedRanks.length - afterLast));
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* Exact conditional two-sided p for the two-sample rank test.
|
|
2343
|
+
*
|
|
2344
|
+
* Convolves the observed doubled midranks into the null distribution of group
|
|
2345
|
+
* a's rank sum over every `C(n₁+n₂, n₁)` split — identical to enumerating the
|
|
2346
|
+
* splits, but `O(N·n₁·ΣR)` instead of `O(C(N,n₁)·n₁n₂)`. Conditioning on the
|
|
2347
|
+
* realised multiset makes the tie handling exact rather than a correction.
|
|
2348
|
+
*
|
|
2349
|
+
* The null is symmetric about `n₁n₂/2` (negating every value maps `U → n₁n₂ −
|
|
2350
|
+
* U` and permutes the split set onto itself), so the two-sided p is the mass
|
|
2351
|
+
* at least as far from the centre as the observation.
|
|
2352
|
+
*/
|
|
2353
|
+
function exactTwoSampleP(doubledRanks, n1, n2, doubledDeviation) {
|
|
2354
|
+
const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
|
|
2355
|
+
const width = maxSum + 1;
|
|
2356
|
+
const ways = Array.from({ length: n1 + 1 }, () => new Float64Array(width));
|
|
2357
|
+
ways[0][0] = 1;
|
|
2358
|
+
let placed = 0;
|
|
2359
|
+
for (const rank of doubledRanks) {
|
|
2360
|
+
for (let k = Math.min(n1, placed + 1); k >= 1; k--) {
|
|
2361
|
+
const from = ways[k - 1];
|
|
2362
|
+
const into = ways[k];
|
|
2363
|
+
for (let sum = maxSum - rank; sum >= 0; sum--) {
|
|
2364
|
+
const count = from[sum];
|
|
2365
|
+
if (count !== 0) into[sum + rank] += count;
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
placed++;
|
|
2369
|
+
}
|
|
2370
|
+
const shift = n1 * (n1 + 1) + n1 * n2;
|
|
2371
|
+
const chosen = ways[n1];
|
|
2372
|
+
let totalWays = 0;
|
|
2373
|
+
let extremeWays = 0;
|
|
2374
|
+
let tailWays = 0;
|
|
2375
|
+
let maxDeviation = -1;
|
|
2376
|
+
for (let sum = 0; sum < width; sum++) {
|
|
2377
|
+
const count = chosen[sum];
|
|
2378
|
+
if (count === 0) continue;
|
|
2379
|
+
totalWays += count;
|
|
2380
|
+
const deviation = Math.abs(sum - shift);
|
|
2381
|
+
if (deviation >= doubledDeviation) tailWays += count;
|
|
2382
|
+
if (deviation > maxDeviation) {
|
|
2383
|
+
maxDeviation = deviation;
|
|
2384
|
+
extremeWays = count;
|
|
2385
|
+
} else if (deviation === maxDeviation) extremeWays += count;
|
|
2386
|
+
}
|
|
2387
|
+
return {
|
|
2388
|
+
p: tailWays / totalWays,
|
|
2389
|
+
pFloor: extremeWays / totalWays
|
|
2390
|
+
};
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* Exact conditional two-sided p for the paired signed-rank test.
|
|
2394
|
+
*
|
|
2395
|
+
* Convolves the observed doubled absolute midranks over all `2ⁿ` sign
|
|
2396
|
+
* assignments in `O(n·ΣR)`. Probabilities rather than counts keep `2ⁿ` off the
|
|
2397
|
+
* arithmetic. The null is symmetric about `n(n+1)/4`.
|
|
2398
|
+
*/
|
|
2399
|
+
function exactSignedRankP(doubledRanks, doubledDeviation) {
|
|
2400
|
+
const maxSum = doubledRanks.reduce((sum, rank) => sum + rank, 0);
|
|
2401
|
+
const width = maxSum + 1;
|
|
2402
|
+
let mass = new Float64Array(width);
|
|
2403
|
+
mass[0] = 1;
|
|
2404
|
+
for (const rank of doubledRanks) {
|
|
2405
|
+
const next = new Float64Array(width);
|
|
2406
|
+
for (let sum = 0; sum < width; sum++) {
|
|
2407
|
+
const probability = mass[sum];
|
|
2408
|
+
if (probability === 0) continue;
|
|
2409
|
+
next[sum] += probability * .5;
|
|
2410
|
+
next[sum + rank] += probability * .5;
|
|
2411
|
+
}
|
|
2412
|
+
mass = next;
|
|
2413
|
+
}
|
|
2414
|
+
const centre = maxSum / 2;
|
|
2415
|
+
let tail = 0;
|
|
2416
|
+
let extreme = 0;
|
|
2417
|
+
let maxDeviation = -1;
|
|
2418
|
+
for (let sum = 0; sum < width; sum++) {
|
|
2419
|
+
const probability = mass[sum];
|
|
2420
|
+
if (probability === 0) continue;
|
|
2421
|
+
const deviation = Math.abs(sum - centre);
|
|
2422
|
+
if (deviation >= doubledDeviation) tail += probability;
|
|
2423
|
+
if (deviation > maxDeviation) {
|
|
2424
|
+
maxDeviation = deviation;
|
|
2425
|
+
extreme = probability;
|
|
2426
|
+
} else if (deviation === maxDeviation) extreme += probability;
|
|
2427
|
+
}
|
|
2428
|
+
return {
|
|
2429
|
+
p: Math.min(1, tail),
|
|
2430
|
+
pFloor: Math.min(1, extreme)
|
|
2431
|
+
};
|
|
2432
|
+
}
|
|
2433
|
+
// src/statistics/samples.ts
|
|
2434
|
+
/** Interpolated sample median; an empty population has no measured median. */
|
|
2435
|
+
function sampleMedian(values) {
|
|
2436
|
+
assertFiniteSample("sampleMedian", "values", values);
|
|
2437
|
+
return values.length ? medianInPlace([...values]) : null;
|
|
2438
|
+
}
|
|
2439
|
+
/** Descriptive facts, not stability policy or a significance test. */
|
|
2440
|
+
function summarizeSample(values, options = {}) {
|
|
2441
|
+
assertFiniteSample("summarizeSample", "values", values);
|
|
2442
|
+
const confidence = options.confidence ?? .95;
|
|
2443
|
+
const resamples = options.resamples ?? 1e3;
|
|
2444
|
+
if (!Number.isFinite(confidence) || confidence <= 0 || confidence >= 1) throw new ValidationError("summarizeSample: confidence must be between zero and one");
|
|
2445
|
+
if (!Number.isSafeInteger(resamples) || resamples < 1) throw new ValidationError("summarizeSample: resamples must be a positive safe integer");
|
|
2446
|
+
const rng = makeRng(options.seed, [...values]);
|
|
2447
|
+
if (!values.length) return null;
|
|
2448
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
2449
|
+
const n = sorted.length;
|
|
2450
|
+
const mean = sorted.reduce((sum, value) => sum + value / n, 0);
|
|
2451
|
+
const centered = sorted.map((value) => value - mean);
|
|
2452
|
+
const sumSquares = centered.reduce((sum, value) => sum + value ** 2, 0);
|
|
2453
|
+
const stddev = n > 1 ? Math.sqrt(sumSquares / (n - 1)) : 0;
|
|
2454
|
+
const median = interpolatedQuantile(sorted, .5);
|
|
2455
|
+
const q1 = interpolatedQuantile(sorted, .25);
|
|
2456
|
+
const q3 = interpolatedQuantile(sorted, .75);
|
|
2457
|
+
const iqr = q3 - q1;
|
|
2458
|
+
const deviations = sorted.map((value) => Math.abs(value - median)).sort((a, b) => a - b);
|
|
2459
|
+
const skewness = n >= 3 && stddev > 0 ? n * centered.reduce((sum, value) => sum + (value / stddev) ** 3, 0) / ((n - 1) * (n - 2)) : null;
|
|
2460
|
+
const kurtosis = n >= 4 && stddev > 0 ? n * (n + 1) * centered.reduce((sum, value) => sum + (value / stddev) ** 4, 0) / ((n - 1) * (n - 2) * (n - 3)) - 3 * (n - 1) ** 2 / ((n - 2) * (n - 3)) : null;
|
|
2461
|
+
const bootstrap = [];
|
|
2462
|
+
if (n >= 3) {
|
|
2463
|
+
for (let i = 0; i < resamples; i++) {
|
|
2464
|
+
const sample = Array.from({ length: n }, () => sorted[Math.floor(rng() * n)]);
|
|
2465
|
+
bootstrap.push(medianInPlace(sample));
|
|
2466
|
+
}
|
|
2467
|
+
bootstrap.sort((a, b) => a - b);
|
|
2468
|
+
}
|
|
2469
|
+
const alpha = (1 - confidence) / 2;
|
|
2470
|
+
const summary = {
|
|
2471
|
+
n,
|
|
2472
|
+
median,
|
|
2473
|
+
mean,
|
|
2474
|
+
stddev,
|
|
2475
|
+
q1,
|
|
2476
|
+
q3,
|
|
2477
|
+
iqr,
|
|
2478
|
+
min: sorted[0],
|
|
2479
|
+
max: sorted[n - 1],
|
|
2480
|
+
range: sorted[n - 1] - sorted[0],
|
|
2481
|
+
cv: mean === 0 ? null : stddev / Math.abs(mean),
|
|
2482
|
+
skewness,
|
|
2483
|
+
kurtosis,
|
|
2484
|
+
mad: interpolatedQuantile(deviations, .5),
|
|
2485
|
+
outliers: sorted.filter((value) => value < q1 - 1.5 * iqr || value > q3 + 1.5 * iqr),
|
|
2486
|
+
medianInterval: n < 3 ? null : {
|
|
2487
|
+
low: interpolatedQuantile(bootstrap, alpha),
|
|
2488
|
+
high: interpolatedQuantile(bootstrap, 1 - alpha),
|
|
2489
|
+
confidence,
|
|
2490
|
+
resamples
|
|
2491
|
+
}
|
|
2492
|
+
};
|
|
2493
|
+
if ([
|
|
2494
|
+
mean,
|
|
2495
|
+
stddev,
|
|
2496
|
+
iqr,
|
|
2497
|
+
summary.range,
|
|
2498
|
+
summary.mad,
|
|
2499
|
+
summary.cv,
|
|
2500
|
+
skewness,
|
|
2501
|
+
kurtosis,
|
|
2502
|
+
summary.medianInterval?.low ?? null,
|
|
2503
|
+
summary.medianInterval?.high ?? null
|
|
2504
|
+
].some((value) => value !== null && !Number.isFinite(value))) throw new ValidationError("summarizeSample: sample arithmetic exceeded finite range");
|
|
2505
|
+
return summary;
|
|
2506
|
+
}
|
|
2507
|
+
// src/statistics/sequential-eprocess.ts
|
|
2508
|
+
/**
|
|
2509
|
+
* Betting test-martingale for bounded observations — the e-process core of
|
|
2510
|
+
* anytime-valid sequential testing (Waudby-Smith & Ramdas, "Estimating means
|
|
2511
|
+
* of bounded random variables by betting", JRSS-B 2024).
|
|
2512
|
+
*
|
|
2513
|
+
* Observations x_i ∈ [0,1]; H0: E[x] ≤ m₀ (`nullMean`, default 1/2). Wealth
|
|
2514
|
+
*
|
|
2515
|
+
* W_t = Π_{i≤t} (1 + λ_i (x_i − m₀)), W_0 = 1
|
|
2516
|
+
*
|
|
2517
|
+
* with the truncated GROW-style plug-in bet computed from PRIOR observations:
|
|
2518
|
+
*
|
|
2519
|
+
* λ_i = clamp((μ̂_{i−1} − m₀) / (σ̂²_{i−1} + (μ̂_{i−1} − m₀)²), 0, maxBet)
|
|
2520
|
+
*
|
|
2521
|
+
* where μ̂/σ̂² are the shrunk running estimates μ̂_t = (1/2 + Σx_i)/(t+1),
|
|
2522
|
+
* σ̂²_t = (1/4 + Σ(x_i − μ̂_i)²)/(t+1).
|
|
2523
|
+
*
|
|
2524
|
+
* PREDICTABILITY INVARIANT (load-bearing): λ_i is a function of x_1..x_{i−1}
|
|
2525
|
+
* ONLY — it may never see x_i. With λ_i ≥ 0 predictable, each factor has
|
|
2526
|
+
* E[1 + λ_i(x_i − m₀) | past] ≤ 1 under H0, so W is a nonnegative
|
|
2527
|
+
* supermartingale and Ville's inequality gives P(∃t: W_t ≥ 1/α) ≤ α — the
|
|
2528
|
+
* type-I guarantee holds at ANY data-dependent stopping time. λ_1 is always 0
|
|
2529
|
+
* (no prior evidence), so the first observation never moves wealth.
|
|
2530
|
+
*
|
|
2531
|
+
* `decided` latches at the first crossing W_t ≥ 1/α and never un-latches;
|
|
2532
|
+
* wealth keeps updating after the crossing (the e-process remains valid), but
|
|
2533
|
+
* the decision time is the first crossing.
|
|
2534
|
+
*/
|
|
2535
|
+
function eProcess(opts = {}) {
|
|
2536
|
+
const alpha = opts.alpha ?? .05;
|
|
2537
|
+
const maxBet = opts.maxBet ?? .5;
|
|
2538
|
+
const nullMean = opts.nullMean ?? .5;
|
|
2539
|
+
if (!Number.isFinite(alpha) || alpha <= 0 || alpha >= 1) throw new ValidationError(`eProcess: alpha must be in (0,1), got ${alpha}`);
|
|
2540
|
+
if (!Number.isFinite(nullMean) || nullMean <= 0 || nullMean >= 1) throw new ValidationError(`eProcess: nullMean must be in (0,1), got ${nullMean}`);
|
|
2541
|
+
if (!Number.isFinite(maxBet) || maxBet <= 0 || maxBet >= 1 / nullMean) throw new ValidationError(`eProcess: maxBet must be in (0, 1/nullMean=${(1 / nullMean).toFixed(4)}) so wealth factors stay positive, got ${maxBet}`);
|
|
2542
|
+
const threshold = 1 / alpha;
|
|
2543
|
+
let wealth = 1;
|
|
2544
|
+
let n = 0;
|
|
2545
|
+
let decided = false;
|
|
2546
|
+
let decidedAtN;
|
|
2547
|
+
let sumX = 0;
|
|
2548
|
+
let varSum = 0;
|
|
2549
|
+
if (opts.resume !== void 0) {
|
|
2550
|
+
const r = assertResumable(opts.resume, {
|
|
2551
|
+
alpha,
|
|
2552
|
+
maxBet,
|
|
2553
|
+
nullMean,
|
|
2554
|
+
threshold
|
|
2555
|
+
});
|
|
2556
|
+
wealth = r.wealth;
|
|
2557
|
+
n = r.n;
|
|
2558
|
+
decided = r.decided;
|
|
2559
|
+
decidedAtN = r.decidedAtN;
|
|
2560
|
+
sumX = r.sumX;
|
|
2561
|
+
varSum = r.varSum;
|
|
2562
|
+
}
|
|
2563
|
+
return {
|
|
2564
|
+
update(x) {
|
|
2565
|
+
if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new ValidationError(`eProcess: observation must be a finite number in [0,1], got ${x}`);
|
|
2566
|
+
const muPrev = (.5 + sumX) / (n + 1);
|
|
2567
|
+
const varPrev = (.25 + varSum) / (n + 1);
|
|
2568
|
+
const edge = muPrev - nullMean;
|
|
2569
|
+
const lambda = Math.min(maxBet, Math.max(0, edge / (varPrev + edge * edge)));
|
|
2570
|
+
wealth *= 1 + lambda * (x - nullMean);
|
|
2571
|
+
n += 1;
|
|
2572
|
+
sumX += x;
|
|
2573
|
+
const muNow = (.5 + sumX) / (n + 1);
|
|
2574
|
+
varSum += (x - muNow) ** 2;
|
|
2575
|
+
if (!decided && wealth >= threshold) {
|
|
2576
|
+
decided = true;
|
|
2577
|
+
decidedAtN = n;
|
|
2578
|
+
}
|
|
2579
|
+
return {
|
|
2580
|
+
wealth,
|
|
2581
|
+
n,
|
|
2582
|
+
decided
|
|
2583
|
+
};
|
|
2584
|
+
},
|
|
2585
|
+
state() {
|
|
2586
|
+
return {
|
|
2587
|
+
wealth,
|
|
2588
|
+
n,
|
|
2589
|
+
decided,
|
|
2590
|
+
alpha,
|
|
2591
|
+
maxBet,
|
|
2592
|
+
nullMean,
|
|
2593
|
+
threshold,
|
|
2594
|
+
decidedAtN,
|
|
2595
|
+
sumX,
|
|
2596
|
+
varSum
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
};
|
|
2600
|
+
}
|
|
2601
|
+
/**
|
|
2602
|
+
* Refuse a snapshot that was not produced by an e-process with exactly these
|
|
2603
|
+
* parameters, or whose fields cannot all be true at once. Every check names
|
|
2604
|
+
* the field, so a refused restart reports what disagrees.
|
|
2605
|
+
*/
|
|
2606
|
+
function assertResumable(resume, params) {
|
|
2607
|
+
const fail = (detail) => {
|
|
2608
|
+
throw new ValidationError(`eProcess: cannot resume — ${detail}`);
|
|
2609
|
+
};
|
|
2610
|
+
if (typeof resume !== "object" || resume === null) fail(`resume must be an EProcessState object, got ${String(resume)}`);
|
|
2611
|
+
for (const key of [
|
|
2612
|
+
"alpha",
|
|
2613
|
+
"maxBet",
|
|
2614
|
+
"nullMean",
|
|
2615
|
+
"threshold"
|
|
2616
|
+
]) if (resume[key] !== params[key]) fail(`snapshot ${key}=${resume[key]} differs from the process ${key}=${params[key]}; a snapshot continues only the process it was taken from`);
|
|
2617
|
+
const { wealth, n, decided, decidedAtN, sumX, varSum } = resume;
|
|
2618
|
+
if (!Number.isInteger(n) || n < 0) fail(`n must be a non-negative integer, got ${n}`);
|
|
2619
|
+
if (!Number.isFinite(wealth) || wealth <= 0) fail(`wealth must be a finite positive number, got ${wealth}`);
|
|
2620
|
+
if (!Number.isFinite(sumX) || sumX < 0 || sumX > n) fail(`sumX must lie in [0, n=${n}] for observations in [0,1], got ${sumX}`);
|
|
2621
|
+
if (!Number.isFinite(varSum) || varSum < 0) fail(`varSum must be a finite non-negative number, got ${varSum}`);
|
|
2622
|
+
if (typeof decided !== "boolean") fail(`decided must be a boolean, got ${String(decided)}`);
|
|
2623
|
+
if (n === 0 && (wealth !== 1 || sumX !== 0 || varSum !== 0 || decided)) fail("n=0 requires wealth=1, sumX=0, varSum=0, decided=false");
|
|
2624
|
+
if (decided) {
|
|
2625
|
+
if (decidedAtN === void 0 || !Number.isInteger(decidedAtN) || decidedAtN < 1 || decidedAtN > n) fail(`decided requires decidedAtN to be an integer in [1, n=${n}], got ${decidedAtN}`);
|
|
2626
|
+
} else {
|
|
2627
|
+
if (decidedAtN !== void 0) fail(`decidedAtN=${decidedAtN} is set while decided=false`);
|
|
2628
|
+
if (wealth >= params.threshold) fail(`wealth ${wealth} ≥ threshold ${params.threshold} while decided=false; decided latches at the first crossing`);
|
|
2629
|
+
}
|
|
2630
|
+
return resume;
|
|
2631
|
+
}
|
|
2632
|
+
export { meanConfidenceInterval as $, fisherExactTwoSided as A, summarizeDistribution as B, passAtK as C, holm as D, bonferroni as E, cliffsDelta as F, nominalAgreement as G, corpusInterRaterAgreement as H, cohensD as I, continuousAgreement as J, calibrateJudge as K, interpretCliffs as L, normalTwoSidedPValue as M, studentTTwoSidedPValue as N, chiSquared as O, twoByTwoPValue as P, confidenceInterval as Q, pairedCohensDz as R, pairedRiskDifferenceScore as S, benjaminiHochberg as T, corpusInterRaterAgreementFromJudgeScores as U, rocAuc as V, interRaterReliability as W, selfPreference as X, positionalBias as Y, verbosityBias as Z, independentRiskDifference as _, placeboBand as _t, wilcoxonSignedRank as a, summarizeNumberSeries as at, pairedRiskDifference as b, pairedMde as c, mean as ct, BOOTSTRAP_GATE_MIN_N as d, makeRng as dt, partialCredit as et, DECISION_PAIRED_DELTA_STATISTIC as f, medianInPlace as ft, pairedTTest as g, clusterBootstrap as gt, pairedSignTest as h, DEFAULT_BOOTSTRAP_SEED as ht, mannWhitneyU as i, studentTCritical as it, linearRegressionSlope as j, chiSquaredPValue as k, requiredPairedSampleSize as l, meanOrNull as lt, pairedDeltaTieFraction as m, zQuantile as mt, sampleMedian as n, ranks as nt, mcnemarPower as o, weightedComposite as ot, pairedBootstrap as p, seedFromData as pt, calibrateJudgeContinuous as q, summarizeSample as r, spearmanR as rt, mcnemarRequiredN as s, weightedMean as st, eProcess as t, pearsonR as tt, requiredSampleSize as u, meanOrZero as ut, mcnemar as v, studentTCdf as vt, wilson as w, pairedRiskDifferenceExact as x, pairedBinaryScale as y, studentTQuantile as yt, percentileNearestRank as z };
|
|
2633
|
+
|
|
2634
|
+
//# sourceMappingURL=statistics-CvvC-MPv.js.map
|