FireWorldLab commited on
Commit
7cb8e31
·
verified ·
1 Parent(s): 5bd5c3a

Publish complete independent I50 and S50 benchmark

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. DATA_FORMAT.md +19 -0
  2. DATA_LICENSE.md +9 -0
  3. FireWorldBench-v2-I50-S50.zip +3 -0
  4. README.md +19 -18
  5. dataset_card_public.md +14 -0
  6. evaluation/FireWorldBench-ICLR/.gitignore +28 -0
  7. evaluation/FireWorldBench-ICLR/DATA_LICENSE.md +7 -0
  8. evaluation/FireWorldBench-ICLR/LICENSE +201 -0
  9. evaluation/FireWorldBench-ICLR/README.md +27 -0
  10. evaluation/FireWorldBench-ICLR/UPSTREAM.md +12 -0
  11. evaluation/FireWorldBench-ICLR/data/README.md +5 -0
  12. evaluation/FireWorldBench-ICLR/requirements.txt +1 -0
  13. evaluation/FireWorldBench-ICLR/scripts/contracts/dual_axis.json +115 -0
  14. evaluation/FireWorldBench-ICLR/scripts/contracts/l22_c06_nowcast_s.txt +8 -0
  15. evaluation/FireWorldBench-ICLR/scripts/contracts/l22_c06_s.txt +7 -0
  16. evaluation/FireWorldBench-ICLR/scripts/contracts/l22_main_nowcast_s.txt +8 -0
  17. evaluation/FireWorldBench-ICLR/scripts/contracts/l22_main_s.txt +7 -0
  18. evaluation/FireWorldBench-ICLR/scripts/contracts/three_stage_event_family.json +23 -0
  19. evaluation/FireWorldBench-ICLR/scripts/fwb_axis_schema.json +30 -0
  20. evaluation/FireWorldBench-ICLR/scripts/relabel_event_families.py +238 -0
  21. evaluation/FireWorldBench-ICLR/scripts/run_api.py +804 -0
  22. evaluation/FireWorldBench-ICLR/scripts/run_eval.py +92 -0
  23. evaluation/FireWorldBench-ICLR/scripts/score_fg9_deep_metrics_by_cell.py +51 -0
  24. evaluation/FireWorldBench-ICLR/scripts/score_fg9_gold_linked_support.py +167 -0
  25. evaluation/FireWorldBench-ICLR/scripts/score_fg9_predictions.py +600 -0
  26. evaluation/FireWorldBench-ICLR/scripts/score_six_metrics.py +172 -0
  27. evaluation/FireWorldBench-ICLR/setup.py +28 -0
  28. main_synthetic/assets/{events/FWBFR-546B1539D42C5585/smoke3d/birdseye/volume_birdseye_t060.png → final_optimized/FWBFG9-00646A8DF42ADA88C2/soot_density_t30.png} +2 -2
  29. main_synthetic/assets/final_optimized/FWBFG9-05E56EC571CF510027/soot_density_t10.png +3 -0
  30. main_synthetic/assets/final_optimized/FWBFG9-05E56EC571CF510027/soot_density_t30.png +3 -0
  31. main_synthetic/assets/final_optimized/FWBFG9-0EF2817BEC74364FEB/temperature_t60.png +3 -0
  32. main_synthetic/assets/final_optimized/FWBFG9-11D1296B6CB31957A8/temperature_t60.png +3 -0
  33. main_synthetic/assets/final_optimized/FWBFG9-17F3B1D1D364EA3150/soot_density_t30.png +3 -0
  34. main_synthetic/assets/final_optimized/FWBFG9-260BA18DDE41A73818/temperature_t60.png +3 -0
  35. main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t010.png → final_optimized/FWBFG9-2877A6954E7C9CF5C3/soot_density_t30.png} +2 -2
  36. main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t030.png → final_optimized/FWBFG9-2877A6954E7C9CF5C3/soot_density_t60.png} +2 -2
  37. main_synthetic/assets/final_optimized/FWBFG9-357CF5649A3B863AB4/soot_density_t30.png +3 -0
  38. main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t060.png → final_optimized/FWBFG9-375A6BB14314EB280B/soot_density_t10.png} +2 -2
  39. main_synthetic/assets/final_optimized/FWBFG9-375A6BB14314EB280B/soot_density_t30.png +3 -0
  40. main_synthetic/assets/final_optimized/FWBFG9-3CCFD86F74E3A9D08E/soot_density_t60.png +3 -0
  41. main_synthetic/assets/final_optimized/FWBFG9-3F4B407538BE87D948/soot_density_t30.png +3 -0
  42. main_synthetic/assets/final_optimized/FWBFG9-3F4B407538BE87D948/soot_density_t60.png +3 -0
  43. main_synthetic/assets/final_optimized/FWBFG9-451C773FBA9C30D53D/soot_density_t30.png +3 -0
  44. main_synthetic/assets/final_optimized/FWBFG9-4643D810275BF3A05C/soot_density_t60.png +3 -0
  45. main_synthetic/assets/final_optimized/FWBFG9-4AEBACEF01C0DC6826/soot_density_t30.png +3 -0
  46. main_synthetic/assets/final_optimized/FWBFG9-4AEBACEF01C0DC6826/soot_density_t60.png +3 -0
  47. main_synthetic/assets/final_optimized/FWBFG9-4EBBF51A2588AEACD3/temperature_t60.png +3 -0
  48. main_synthetic/assets/final_optimized/FWBFG9-54BD966E1831DFD38C/soot_density_t30.png +3 -0
  49. main_synthetic/assets/final_optimized/FWBFG9-56757B303A98C6E550/soot_density_t30.png +3 -0
  50. main_synthetic/assets/final_optimized/FWBFG9-56757B303A98C6E550/soot_density_t60.png +3 -0
DATA_FORMAT.md ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FireWorldBench v2 数据格式
2
+
3
+ ## 文件
4
+
5
+ `main_synthetic/full_test_A/questions.jsonl`:200 行模型输入;`gold.jsonl`:相同 `qa_id` 的 200 行源标准答案;`selection_manifest.jsonl`:独立筛选的 I50、S50 索引、来源和图片哈希。I/S **没有一对一对应关系**。所有 JSONL 为 UTF-8,每行一个 JSON 对象。
6
+
7
+ 同一道逻辑题共享 `logical_id`,有 `choice` 与 `open` 两行。`track` 为 I 或 S。`question` 是原英文题干,choice 的 `options` 保留原选项。`query_context` 给出起点时刻、预测时距及目标区域。open 的 `answer_fields` 精确列出应输出的 `prediction` 字段;点分路径表示嵌套 JSON。
8
+
9
+ ## 模型材料
10
+
11
+ I 轨 `material.assets` 顺序就是图像附件顺序;每项有 `image_index`、`field`、目标 `time_s`、实际 `actual_time_s`、固定 y 的 x-z 切面几何、`color_scale` 和相对于 `main_synthetic/` 的 `path`。R1–R8 在 `region_layout.bins` 给出沿 x 的等宽边界,x 从左至右,z 从下至上。`numeric_observations` 保存没有可见结构、因此未附图的原始切片统计值,按变量和观测时刻列出 R1–R8。模型无需从图片猜变量或色标。`task_rules` 写明区域统计、全域聚合、趋势死区或风险校准。
12
+
13
+ S 轨 `material.observations` 是按时刻排序的 R1–R8 温度 P95、烟炱 P95、能见度 P10。原源文件的速度相关三字段与原始切片多处不一致,而本版所选任务仅使用上述三变量,所以从 v2 **输入**中移除了速度三字段,原源 gold 不变。S 轨同样给出 `region_geometry`、`observation_geometry` 和 `task_rules`。
14
+
15
+ **时间隔离:**模型材料只含题目起点及之前的观测。未来原始切片只用于离线核验 gold,不能进入模型输入。Gold 只供评分器读取。
16
+
17
+ ## 输出
18
+
19
+ Choice 返回 `{"choices":["A"],"confidence":0.8}`;多选题须选出全部且仅选正确声明,完整假设题恰选一个标签。Open 返回 `conclusion`、`prediction`、`evidence`、`mechanism`、`confidence`,其中 `prediction` 只填 `answer_fields` 规定的路径。运行代码从本仓库根目录调用 `evaluation/FireWorldBench-ICLR/scripts/run_eval.py --split main_synthetic --data-dir .`。完整参数见仓库 README。
DATA_LICENSE.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # FireWorldBench v2 data license
2
+
3
+ The benchmark questions, gold answers, and associated assets in this package are distributed under the Creative Commons Attribution 4.0 International license (CC BY 4.0), following the upstream FireWorldBench data license.
4
+
5
+ This v2 package selects 50 matched I/S pairs, adds explicit I/S pairing records, and adds image-variable, time, slice, and region metadata to the I-track inputs. The original question text, options, and gold records are retained.
6
+
7
+ Attribution: FireWorldBench. Source dataset: https://huggingface.co/datasets/FireWorldBench/FireWorldBench. Source code repository: https://github.com/15628925702/FireWorldBench-ICLR.
8
+
9
+ The evaluation code copied under `evaluation/FireWorldBench-ICLR/` is licensed separately under Apache License 2.0; see that directory's `LICENSE` and `UPSTREAM.md`.
FireWorldBench-v2-I50-S50.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4938ed904fe50898dbbb7b65d855b59459be54a26519d95b78824268fb0e854f
3
+ size 9385360
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- license: other
3
  task_categories:
4
  - visual-question-answering
5
  tags:
@@ -9,27 +9,28 @@ size_categories:
9
  - n<1K
10
  ---
11
 
12
- # FireWorldBench-new
13
 
14
- 筛选后的 I 轨试做集,共 50 道逻辑题(选择题和开放题成对)。同事件、同题型的 S 轨文本题一并附上,共 145 个 S 逻辑题。问题行 390。有结构的二维场 133 张图;没有结构的场 62 处不附图,只在 `material` 里给出原切片按 R1–R8 算出的一个统计量。
15
 
16
- 三维图沿用原图。题干文字、选项和 Gold 不改。
 
 
 
 
17
 
18
- ## 数据入口
19
 
20
- - 项目主页:https://FireWorldBench.github.io/
21
- - 公开数据:https://huggingface.co/datasets/FireWorldBench/FireWorldBench (`Guaogua/FireWorldBench` 为同一仓)
22
- - 公开代码:https://github.com/15628925702/FireWorldBench-ICLR
23
- - 开发数据(私有):https://huggingface.co/datasets/Guaogua/FireWorldBench-private
24
- - 本仓:https://huggingface.co/datasets/FireWorldLab/FireWorldBench-new (筛选后的 I 轨试做集。本地目录 `代码/FireWorldBench-new/`。)
25
 
26
- ## 本仓内容
 
 
 
 
 
 
27
 
28
- - `main_synthetic/full_test_A/questions.jsonl`
29
- - `main_synthetic/full_test_A/gold.jsonl`
30
- - `main_synthetic/assets/i50/`:有结构的新图
31
- - 没有结构的场:`material` 中无 `path`,含 `statistic` 和 `regions`
32
 
33
- 区域:沿 x 从入口到出口均分 8 段,R1 为入口。温度和第 95 百分位、烟炱第 95 百分位、能见度第 10 百分位、速度第 90 百分位、纵向/竖向速度为平均值。图的底色是略浅于旧图的海军蓝,等高线 1.2 pt。
34
-
35
- 尚未做关键区域裁剪。评测尚未在这 50 题上重跑。
 
1
  ---
2
+ license: cc-by-4.0
3
  task_categories:
4
  - visual-question-answering
5
  tags:
 
9
  - n<1K
10
  ---
11
 
12
+ # FireWorldBench v2: independent I50 and S50
13
 
14
+ 本仓库是可独立运行的 FireWorldBench v2。I 轨和 S 轨分别筛选 50 道逻辑题,**不按编号配对**。每道逻辑题包含 choice 和 open 两条输入,共 200 条 question 与逐一对应的 200 条原始 gold。题干、选项、gold 均保留源记录;I 轨补充原切片图、变量/时间/区域/色标元数据与无结构场数值。S 轨只保留经过原切片核对的任务变量。
15
 
16
+ - 数据:[main_synthetic/full_test_A/questions.jsonl](main_synthetic/full_test_A/questions.jsonl)、[gold.jsonl](main_synthetic/full_test_A/gold.jsonl)、[selection_manifest.jsonl](main_synthetic/full_test_A/selection_manifest.jsonl)。
17
+ - 68 张 I 轨输入图统一采用暗蓝紫 RGB (0,0,128) 的低端与轻柔色带过渡,位于 `main_synthetic/assets/final_optimized/`,均按最终视觉标准从原切片绘制为全场图,无文字和图例。`material.assets[*].image_index` 指向实际附件顺序,路径相对 `main_synthetic/`。
18
+ - 推理与六项指标评分代码、schema、冻结合同及代码许可位于 `evaluation/FireWorldBench-ICLR/`。
19
+ - 格式见 [DATA_FORMAT.md](DATA_FORMAT.md),数据许可见 [DATA_LICENSE.md](DATA_LICENSE.md),数据卡见 [dataset_card_public.md](dataset_card_public.md)。
20
+ - 完整包:[FireWorldBench-v2-I50-S50.zip](FireWorldBench-v2-I50-S50.zip)。
21
 
22
+ ## 运行
23
 
24
+ 需要 Python 3.8+;从本仓库根目录运行:
 
 
 
 
25
 
26
+ ```powershell
27
+ python -m pip install -r evaluation/FireWorldBench-ICLR/requirements.txt
28
+ $env:OPENAI_BASE_URL = "你的 OpenAI 兼容接口地址"
29
+ $env:OPENAI_API_KEY = "你的接口密钥"
30
+ $env:OPENAI_MODEL = "模型名称"
31
+ python evaluation/FireWorldBench-ICLR/scripts/run_eval.py --split main_synthetic --data-dir .
32
+ ```
33
 
34
+ 纯文本模型加 `--track S`;视觉模型可选 I 轨或两轨。可用 `--max-requests 2` 做小规模连通检查。runner 只读 questions 和引用图片;评分器单独读取 gold。模型输入包含 query_context、区域与变量规则、每张附件编号、时间、切片和色标范围。正式题包不需要原始私有 `.sf` 才能运行。
 
 
 
35
 
36
+ 本轮筛选覆盖 I 轨 L1-2(20)、L2-2(5)、L3-1(25),S 轨 L1-2(25)、L3-1(25)。没有宣称覆盖原题库的全部任务类型。推理代码源于 FireWorldBench-ICLR 提交 `c2ed1d2c82084337cc88c901e25e27296e993233`,复制后仅为 v2 输入协议调整;代码保留 Apache 2.0 许可证。
 
 
dataset_card_public.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - visual-question-answering
5
+ tags:
6
+ - fire
7
+ - physics
8
+ size_categories:
9
+ - n<1K
10
+ ---
11
+
12
+ # FireWorldBench v2
13
+
14
+ 独立筛选的 50 道 I 轨与 50 道 S 轨逻辑题;每题 choice 和 open 两种输入。共 200 条 questions、200 条 source gold 与 180 张 I 轨最终版物理场图。两轨不作一对一配对。I 轨选择 L1-2/L2-2/L3-1,S 轨选择 L1-2/L3-1。材料只含起点之前观测;未来原始切片仅作离线 gold 核对。完整格式、评分代码和运行命令见 README 与 DATA_FORMAT。
evaluation/FireWorldBench-ICLR/.gitignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ .eggs/
11
+
12
+ # Environments
13
+ .env
14
+ .venv
15
+ venv/
16
+ env/
17
+
18
+ # IDE
19
+ .idea/
20
+ .vscode/
21
+
22
+ # FireWorldBench runtime outputs (never commit)
23
+ data/main_synthetic/ # downloaded dataset (~660MB)
24
+ data/mmodalfire_c06/ # downloaded dataset
25
+ results/ # evaluation outputs
26
+ runs/
27
+ *.jsonl.manifest.json
28
+ *.SHA256SUMS.txt
evaluation/FireWorldBench-ICLR/DATA_LICENSE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Data License
2
+
3
+ The benchmark questions, gold answers, and associated assets are licensed under the Creative Commons Attribution 4.0 International license.
4
+
5
+ The dataset itself is not distributed in this anonymous-review repository. Distribution locations and attribution details are intentionally omitted during double-blind review.
6
+
7
+ The evaluation code is licensed separately as described in `LICENSE`.
evaluation/FireWorldBench-ICLR/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ Apache License, Version 2.0
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ Apache License, Version 2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
evaluation/FireWorldBench-ICLR/README.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FireWorldBench v2 evaluation toolkit
2
+
3
+ This is a copy of the FireWorldBench-ICLR evaluation code, task contracts, and schemas. Source repository and commit are recorded in `UPSTREAM.md`. The code license is in `LICENSE`; the bundled dataset license is at `../../DATA_LICENSE.md`.
4
+
5
+ ## Install
6
+
7
+ From the FireWorldBench v2 repository root:
8
+
9
+ ```powershell
10
+ python -m pip install -r evaluation/FireWorldBench-ICLR/requirements.txt
11
+ ```
12
+
13
+ Python 3.8 or newer is required. The included runner uses an OpenAI-compatible HTTP endpoint; configure `OPENAI_BASE_URL`, `OPENAI_API_KEY`, and `OPENAI_MODEL` in the environment.
14
+
15
+ ## Run the bundled benchmark
16
+
17
+ From the FireWorldBench v2 repository root:
18
+
19
+ ```powershell
20
+ python evaluation/FireWorldBench-ICLR/scripts/run_eval.py --split main_synthetic --data-dir .
21
+ ```
22
+
23
+ The v2 package root is the data directory because it contains `main_synthetic/full_test_A/`. The runner reads questions and referenced images, never gold. After inference, the scorer reads matching gold rows by `qa_id` and writes six metrics under `results/`.
24
+
25
+ Use `--track S` for text-only models or `--track I` for vision models; omit `--track` to run both. Add `--max-requests 2` for a small endpoint connectivity check.
26
+
27
+ The scripts in `scripts/contracts/` contain the frozen task contracts. The direct API runner accepts an optional `--task-contract` file for contract-controlled runs. See `python evaluation/FireWorldBench-ICLR/scripts/run_eval.py --help` and `python evaluation/FireWorldBench-ICLR/scripts/run_api.py --help` for all options.
evaluation/FireWorldBench-ICLR/UPSTREAM.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Upstream code snapshot
2
+
3
+ The evaluation runtime in this directory is copied from the FireWorldBench-ICLR repository.
4
+
5
+ - Upstream: https://github.com/15628925702/FireWorldBench-ICLR
6
+ - Source commit: c2ed1d2c82084337cc88c901e25e27296e993233
7
+ - Copied on: 2026-09-23
8
+ - Upstream working tree was clean at copy time.
9
+ - The Apache-2.0 license for this code is retained in `LICENSE`.
10
+ - The bundled v2 dataset is at `../../main_synthetic/` from this directory.
11
+
12
+ The v2 copy keeps the upstream scoring logic. Its API runner was adapted to pass `query_context`, attach numbered images with matching variable/time metadata, and require exactly one label for complete-hypothesis questions. The v2 root README documents how to point `run_eval.py` at the bundled data.
evaluation/FireWorldBench-ICLR/data/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Bundled FireWorldBench v2 data
2
+
3
+ The v2 questions, gold records, and image assets are stored at `../../../main_synthetic/` relative to this `data/` folder.
4
+
5
+ From the repository root, run the evaluation pipeline with `--data-dir .`. The previous upstream distribution expected the full public dataset to be downloaded into this folder; this v2 package is self-contained and does not require that download script.
evaluation/FireWorldBench-ICLR/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ requests>=2.31,<3
evaluation/FireWorldBench-ICLR/scripts/contracts/dual_axis.json ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FWB-FG9-DUAL-AXIS-v20260902",
3
+ "note": "Difficulty order on main_synthetic figure Acc (25 tracks, InternVL included). P1/T1 easiest. Fire T2/T3 swapped vs 2026-08-30 so T1→T5 is also easy→hard. C06 formal test n=714.",
4
+ "axes": {
5
+ "physical": {
6
+ "P1": "Temporal Evolution Forecasting",
7
+ "P2": "Physical Field Perception and Grounding",
8
+ "P3": "Cross-Field Coupling Understanding",
9
+ "P4": "Causal Mechanism Attribution",
10
+ "P5": "Counterfactual Intervention Reasoning"
11
+ },
12
+ "physical_zh": {
13
+ "P1": "时间预测",
14
+ "P2": "场感知与落地",
15
+ "P3": "跨场耦合理解",
16
+ "P4": "机制归因",
17
+ "P5": "反事实干预推理"
18
+ },
19
+ "fire": {
20
+ "T1": "Fire Evolution Prediction",
21
+ "T2": "Fire State Assessment",
22
+ "T3": "Fire Early Warning",
23
+ "T4": "Fire Intervention Decision-Making",
24
+ "T5": "Fire Mechanism Diagnosis"
25
+ },
26
+ "fire_zh": {
27
+ "T1": "演化预测",
28
+ "T2": "状态评估",
29
+ "T3": "早期预警",
30
+ "T4": "干预决策",
31
+ "T5": "机制诊断"
32
+ }
33
+ },
34
+ "task_to_physical": {
35
+ "L1-1": "P2",
36
+ "L1-2": "P3",
37
+ "L1-3": "P4",
38
+ "L2-1": "P2",
39
+ "L2-2": "P3",
40
+ "L2-3": "P4",
41
+ "L3-1": "P1",
42
+ "L3-2": "P1",
43
+ "L3-3": "P5"
44
+ },
45
+ "task_to_fire": {
46
+ "L1-1": "T3",
47
+ "L1-2": "T1",
48
+ "L1-3": "T2",
49
+ "L2-1": "T2",
50
+ "L2-2": "T2",
51
+ "L2-3": "T5",
52
+ "L3-1": "T1",
53
+ "L3-2": "T1",
54
+ "L3-3": "T4"
55
+ },
56
+ "physical_to_tasks": {
57
+ "P1": [
58
+ "L3-1",
59
+ "L3-2"
60
+ ],
61
+ "P2": [
62
+ "L1-1",
63
+ "L2-1"
64
+ ],
65
+ "P3": [
66
+ "L1-2",
67
+ "L2-2"
68
+ ],
69
+ "P4": [
70
+ "L1-3",
71
+ "L2-3"
72
+ ],
73
+ "P5": [
74
+ "L3-3"
75
+ ]
76
+ },
77
+ "fire_to_tasks": {
78
+ "T1": [
79
+ "L1-2",
80
+ "L3-1",
81
+ "L3-2"
82
+ ],
83
+ "T2": [
84
+ "L1-3",
85
+ "L2-1",
86
+ "L2-2"
87
+ ],
88
+ "T3": [
89
+ "L1-1"
90
+ ],
91
+ "T4": [
92
+ "L3-3"
93
+ ],
94
+ "T5": [
95
+ "L2-3"
96
+ ]
97
+ },
98
+ "counts_main_synthetic": {
99
+ "physical": {
100
+ "P1": 2038,
101
+ "P2": 1824,
102
+ "P3": 1718,
103
+ "P4": 1956,
104
+ "P5": 824
105
+ },
106
+ "fire": {
107
+ "T1": 2944,
108
+ "T2": 2504,
109
+ "T3": 1044,
110
+ "T4": 824,
111
+ "T5": 1044
112
+ }
113
+ },
114
+ "c06_n": 714
115
+ }
evaluation/FireWorldBench-ICLR/scripts/contracts/l22_c06_nowcast_s.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ L2-2 operational terminal-nowcast contract for MmodalFire C06
2
+
3
+ The target is the completed-window persistent risk profile at the stated target time. Only observations strictly before that time are supplied. Infer the terminal state from the persistent spatial and temporal pattern in this history; do not assume an unobserved value was provided.
4
+
5
+ Use temperature, visibility, and soot as the three hazard channels. Higher temperature and soot indicate greater risk; lower visibility indicates greater risk. Compare channels on the benchmark's calibrated risk scale learned from exposed training examples. Aggregate each channel robustly over the target window. runner_up_region is the next persistent competitor and risk_level is the selected pair's calibrated ordinal band.
6
+
7
+ stability_phase is early, middle, late, or unstable according to when the final pair becomes persistent over the target history. winner_switch_count_bin is zero, one, or multiple. Apply this same terminal-nowcast contract to every C06 L2-2/S item.
8
+
evaluation/FireWorldBench-ICLR/scripts/contracts/l22_c06_s.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ L2-2 operational terminal-nowcast contract for MmodalFire C06
2
+
3
+ The target is the completed-window persistent risk profile at the stated target time. Only observations strictly before that time are supplied. Infer the terminal state from the persistent spatial and temporal pattern in this history; do not assume an unobserved value was provided.
4
+
5
+ Use temperature, visibility, and soot as the three hazard channels. Higher temperature and soot indicate greater risk; lower visibility indicates greater risk. Compare channels on the benchmark's calibrated risk scale learned from exposed training examples. Aggregate each channel robustly over the target window. runner_up_region is the next persistent competitor and risk_level is the selected pair's calibrated ordinal band.
6
+
7
+ stability_phase is early, middle, late, or unstable according to when the final pair becomes persistent over the target history. winner_switch_count_bin is zero, one, or multiple. Apply this same terminal-nowcast contract to every C06 L2-2/S item.
evaluation/FireWorldBench-ICLR/scripts/contracts/l22_main_nowcast_s.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ L2-2 operational terminal-nowcast contract
2
+
3
+ The target is the completed-window robust risk profile at the stated target time. Only observations strictly before that time are supplied. Infer the terminal state from the persistent spatial and temporal pattern in this history; do not assume an unobserved value was provided.
4
+
5
+ Use temperature, visibility, and soot as the three hazard channels. Higher temperature and soot indicate greater risk; lower visibility indicates greater risk. Compare channels on the benchmark's calibrated risk scale learned from exposed training examples. The main-set profile is robust to one potentially unreliable reading and represents the region-driver pair with persistent support across the target window. runner_up_region is the next persistent competitor and risk_level is the selected pair's calibrated ordinal band.
6
+
7
+ stability_phase is early, middle, late, or unstable according to when the final pair becomes persistent over the target history. winner_switch_count_bin is zero, one, or multiple. Apply this same terminal-nowcast contract to every main-set L2-2/S item.
8
+
evaluation/FireWorldBench-ICLR/scripts/contracts/l22_main_s.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ L2-2 operational terminal-nowcast contract
2
+
3
+ The target is the completed-window robust risk profile at the stated target time. Full three-channel observations for every region are supplied only before the target. At the target, a fixed sparse sensor network supplies exact temperature, visibility, and soot measurements only in R1, R3, R5, and R7; infer the other regions from their histories. This sensor placement is fixed for every item and is independent of the answer.
4
+
5
+ Use temperature, visibility, and soot as the three hazard channels. Higher temperature and soot indicate greater risk; lower visibility indicates greater risk. Compare channels on the benchmark's calibrated risk scale learned from exposed training examples. The main-set profile is robust to one potentially unreliable reading and represents the region-driver pair with persistent support across the target window. runner_up_region is the next persistent competitor and risk_level is the selected pair's calibrated ordinal band.
6
+
7
+ stability_phase is early, middle, late, or unstable according to when the final pair becomes persistent over the target history. winner_switch_count_bin is zero, one, or multiple. Apply this same terminal-nowcast contract to every main-set L2-2/S item.
evaluation/FireWorldBench-ICLR/scripts/contracts/three_stage_event_family.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FWB-FG9-THREE-STAGE-EVENT-FAMILY-v1",
3
+ "fire_axis": {
4
+ "T1 Localized Onset": {"zh": "局域起火", "definition": "Localized source, anomaly, violation, or fire-stage assessment."},
5
+ "T2 Coupled Propagation": {"zh": "耦合蔓延", "definition": "Cross-region state, transport, coupling, or risk propagation."},
6
+ "T3 Critical Transition": {"zh": "临界转变", "definition": "Future outcome, threshold crossing, intervention, or counterfactual transition."}
7
+ },
8
+ "task_mapping": {
9
+ "L1-1": "T1 Localized Onset", "L1-3": "T1 Localized Onset", "L2-1": "T1 Localized Onset",
10
+ "L1-2": "T2 Coupled Propagation", "L2-2": "T2 Coupled Propagation", "L2-3": "T2 Coupled Propagation",
11
+ "L3-1": "T3 Critical Transition", "L3-2": "T3 Critical Transition", "L3-3": "T3 Critical Transition"
12
+ },
13
+ "event_families": [
14
+ "Transportation and Infrastructure",
15
+ "Office and Digital Facilities",
16
+ "Healthcare and Education",
17
+ "Commercial and Public Spaces",
18
+ "Residential and Care Settings",
19
+ "Industry, Energy, and Logistics",
20
+ "Wildland and Wildland--Urban Interface (WUI)"
21
+ ],
22
+ "physical_axis_policy": "physical_axis is copied byte-for-byte and never used to assign fire_axis"
23
+ }
evaluation/FireWorldBench-ICLR/scripts/fwb_axis_schema.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "FWB-DUAL-AXIS-PAPER-v20260914",
3
+ "source": "Fire.pdf Section 3.1 + expert-review L-task mapping (Outcome Transition renamed Critical Transition)",
4
+ "physical": {
5
+ "P1": {"en": "Temporal Evolution Forecasting", "tasks": ["L3-1", "L3-2"]},
6
+ "P2": {"en": "Physical Field Perception and Grounding", "tasks": ["L1-1", "L2-1"]},
7
+ "P3": {"en": "Cross-Field Coupling Understanding", "tasks": ["L1-2", "L2-2"]},
8
+ "P4": {"en": "Causal Mechanism Attribution", "tasks": ["L1-3", "L2-3"]},
9
+ "P5": {"en": "Counterfactual Intervention Reasoning", "tasks": ["L3-3"]}
10
+ },
11
+ "fire": {
12
+ "T1": {"en": "Localized Onset", "tasks": ["L1-1", "L1-3", "L2-1"]},
13
+ "T2": {"en": "Coupled Propagation", "tasks": ["L1-2", "L2-2", "L2-3"]},
14
+ "T3": {"en": "Critical Transition", "tasks": ["L3-1", "L3-2", "L3-3"]}
15
+ },
16
+ "metrics": ["Acc", "F1", "Brier", "Evi-F1", "Mech", "GLS"],
17
+ "tracks": {
18
+ "S": 15,
19
+ "I": 10,
20
+ "total_paper_tracks": 25
21
+ },
22
+ "model_stems": [
23
+ "llama31_8b_S", "qwen3_8b_S", "gemma3_12b_it_S", "gemma3_27b_S", "qwen3_32b_S",
24
+ "llama33_70b_S", "qwen3next_80b_S", "glm45_air_S", "qwen3_235b_S", "deepseek_v3_S", "kimi_k2_S",
25
+ "gpt56_luna_S", "gemini25flash_S", "claude_haiku_45_S", "qwen35_plus_S",
26
+ "internvl3_8b_I", "internvl3_38b_I", "internvl3_78b_I",
27
+ "qwen3vl8b_I", "qwen3vl32b_I", "qwen3vl235b_I",
28
+ "gpt56_luna_I", "gemini25flash_I", "claude_haiku_45_I", "qwen35_plus_I"
29
+ ]
30
+ }
evaluation/FireWorldBench-ICLR/scripts/relabel_event_families.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the three-stage fire axis, event-family manifest, and grouped audits.
3
+
4
+ The input files are expected to be exported from the official HF repositories.
5
+ No source data is committed by this script. Every output row is copied with
6
+ only ``fire_axis`` changed; physical_axis and all answer fields are preserved.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import hashlib
13
+ import json
14
+ import re
15
+ from collections import Counter, defaultdict
16
+ from pathlib import Path
17
+
18
+ FIRE_AXIS = {
19
+ "T1 Localized Onset": "localized source, anomaly, violation, or fire-stage assessment",
20
+ "T2 Coupled Propagation": "cross-region state, transport, coupling, or risk propagation",
21
+ "T3 Critical Transition": "future outcome, threshold crossing, intervention, or counterfactual transition",
22
+ }
23
+ TASK_FIRE = {
24
+ "L1-1": "T1 Localized Onset", "L1-3": "T1 Localized Onset", "L2-1": "T1 Localized Onset",
25
+ "L1-2": "T2 Coupled Propagation", "L2-2": "T2 Coupled Propagation", "L2-3": "T2 Coupled Propagation",
26
+ "L3-1": "T3 Critical Transition", "L3-2": "T3 Critical Transition", "L3-3": "T3 Critical Transition",
27
+ }
28
+
29
+ FAMILIES = [
30
+ "Transportation and Infrastructure",
31
+ "Office and Digital Facilities",
32
+ "Healthcare and Education",
33
+ "Commercial and Public Spaces",
34
+ "Residential and Care Settings",
35
+ "Industry, Energy, and Logistics",
36
+ "Wildland and Wildland--Urban Interface (WUI)",
37
+ ]
38
+ FAMILY_RULES = [
39
+ (FAMILIES[6], ["wildland", "wildfire", "forest", "grassland", "wui", "wild_urban"]),
40
+ (FAMILIES[0], ["rail", "metro", "transit", "transport", "vehicle", "road", "bridge", "tunnel", "airport", "port", "bus_depot"]),
41
+ (FAMILIES[1], ["data_center", "datacenter", "server", "office", "digital", "telecom", "computer"]),
42
+ (FAMILIES[2], ["hospital", "health", "clinic", "school", "university", "college", "education", "laboratory", "laboratory_room"]),
43
+ (FAMILIES[3], ["mall", "market", "retail", "shop", "restaurant", "hotel", "stadium", "theater", "museum", "commercial", "public"]),
44
+ (FAMILIES[4], ["house", "home", "residential", "apartment", "dwelling", "nursing", "care", "dormitory"]),
45
+ (FAMILIES[5], ["industrial", "factory", "plant", "tank", "process", "pipe", "warehouse", "logistics", "loading", "energy", "battery", "charging", "refinery", "workshop"]),
46
+ ]
47
+ EXPLICIT_FAMILY = {
48
+ "aircraft_hangar": FAMILIES[0],
49
+ "canadian_townhouse_row": FAMILIES[4],
50
+ "chemical_packaging_warehouse": FAMILIES[5],
51
+ "crosswind_canyon": FAMILIES[6],
52
+ "exhibition_hall_booths": FAMILIES[3],
53
+ "fireworks_mixing_workshop": FAMILIES[5],
54
+ "fireworks_storage_magazines": FAMILIES[5],
55
+ "high_bay_rack_warehouse": FAMILIES[5],
56
+ "industrial_service_tunnel": FAMILIES[5],
57
+ "mixed_conifer_valley": FAMILIES[6],
58
+ "school_vocational_workshop": FAMILIES[2],
59
+ "semiconductor_cleanroom": FAMILIES[1],
60
+ "stepped_pine_slope": FAMILIES[6],
61
+ "switchgear_transformer_room": FAMILIES[5],
62
+ "theatre_backstage": FAMILIES[3],
63
+ "timber_heritage_courtyard": FAMILIES[3],
64
+ "two_level_underground_garage": FAMILIES[0],
65
+ "waste_sorting_recycling_hall": FAMILIES[5],
66
+ "windward_ridge_crest": FAMILIES[6],
67
+ "wui_road_edge": FAMILIES[6],
68
+ }
69
+
70
+
71
+ def read_jsonl(path: Path):
72
+ with path.open(encoding="utf-8") as handle:
73
+ for number, line in enumerate(handle, 1):
74
+ if line.strip():
75
+ yield number, json.loads(line)
76
+
77
+
78
+ def write_jsonl(path: Path, rows):
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ with path.open("w", encoding="utf-8", newline="\n") as handle:
81
+ for row in rows:
82
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
83
+
84
+
85
+ def norm(value):
86
+ return re.sub(r"[^a-z0-9]+", "_", str(value or "").lower()).strip("_")
87
+
88
+
89
+ def classify_fire(row):
90
+ task = row.get("task")
91
+ label = TASK_FIRE.get(task)
92
+ text = " ".join(str(row.get(key, "")) for key in ("question", "task"))
93
+ boundary = bool(re.search(r"\b(future|forecast|predict|threshold|intervention|counterfactual)\b", text, re.I))
94
+ return label, {"rule": f"task:{task}", "boundary_review": boundary}
95
+
96
+
97
+ def classify_family(archetype):
98
+ token = norm(archetype)
99
+ if token in EXPLICIT_FAMILY:
100
+ return EXPLICIT_FAMILY[token], [token], "matched"
101
+ hits = [(family, [word for word in words if re.search(rf"(?:^|_){re.escape(norm(word))}(?:_|$)", token)]) for family, words in FAMILY_RULES]
102
+ hits = [(family, words) for family, words in hits if words]
103
+ if not hits:
104
+ return None, [], "unmatched"
105
+ max_hits = max(len(words) for _, words in hits)
106
+ winners = [(family, words) for family, words in hits if len(words) == max_hits]
107
+ if len(winners) > 1:
108
+ return winners[0][0], [x[0] for x in winners], "ambiguous"
109
+ return winners[0][0], winners[0][1], "matched"
110
+
111
+
112
+ def main():
113
+ ap = argparse.ArgumentParser()
114
+ ap.add_argument("--gold", nargs="+", type=Path, required=True)
115
+ ap.add_argument("--questions", nargs="+", type=Path, required=True)
116
+ ap.add_argument("--item-scores", nargs="*", type=Path, default=[])
117
+ ap.add_argument("--output", type=Path, required=True)
118
+ args = ap.parse_args()
119
+ args.output.mkdir(parents=True, exist_ok=True)
120
+
121
+ gold_by_qa = {}
122
+ event_rows = defaultdict(lambda: {"event_id": None, "archetypes": set(), "sources": set(), "qa_count": 0})
123
+ audit = []
124
+ for path in args.gold:
125
+ source = path.as_posix()
126
+ for line, row in read_jsonl(path):
127
+ qa_id = row.get("qa_id")
128
+ if not qa_id:
129
+ audit.append({"kind": "gold_missing_qa_id", "source": source, "line": line})
130
+ continue
131
+ fire, fire_meta = classify_fire(row)
132
+ provenance = row.get("provenance") or {}
133
+ event_id = provenance.get("event_id") or provenance.get("world_id")
134
+ archetype = provenance.get("archetype") or (provenance.get("metadata") or {}).get("archetype")
135
+ family, matched, family_status = classify_family(archetype)
136
+ if qa_id in gold_by_qa and gold_by_qa[qa_id]["event_id"] != event_id:
137
+ audit.append({"kind": "qa_id_conflict", "qa_id": qa_id, "source": source})
138
+ gold_by_qa[qa_id] = {"fire_axis": fire, "fire_meta": fire_meta, "event_id": event_id,
139
+ "family": family, "family_status": family_status, "archetype": archetype,
140
+ "physical_axis": row.get("physical_axis"), "task": row.get("task")}
141
+ if event_id:
142
+ item = event_rows[event_id]
143
+ item["event_id"] = event_id; item["qa_count"] += 1; item["sources"].add(source)
144
+ if archetype: item["archetypes"].add(archetype)
145
+ else:
146
+ audit.append({"kind": "missing_event_id", "qa_id": qa_id, "source": source})
147
+ if family_status != "matched":
148
+ audit.append({"kind": f"family_{family_status}", "qa_id": qa_id, "event_id": event_id,
149
+ "archetype": archetype, "matched": matched})
150
+
151
+ # Enrich and rewrite question files while retaining every original field.
152
+ for path in args.questions:
153
+ out = args.output / "relabelled" / path.name
154
+ rows = []
155
+ for line, row in read_jsonl(path):
156
+ qa_id = row.get("qa_id")
157
+ info = gold_by_qa.get(qa_id)
158
+ if info is None:
159
+ audit.append({"kind": "question_unmatched_gold", "qa_id": qa_id, "source": path.as_posix(), "line": line,
160
+ "excluded_from_formal_output": True})
161
+ continue
162
+ else:
163
+ row["fire_axis"] = info["fire_axis"]
164
+ rows.append(row)
165
+ write_jsonl(out, rows)
166
+
167
+ # Also provide relabelled gold files, useful for testResult consumers.
168
+ for path in args.gold:
169
+ out = args.output / "relabelled_gold" / path.name
170
+ rows = []
171
+ for _, row in read_jsonl(path):
172
+ info = gold_by_qa.get(row.get("qa_id"))
173
+ if info: row["fire_axis"] = info["fire_axis"]
174
+ rows.append(row)
175
+ write_jsonl(out, rows)
176
+
177
+ manifest = []
178
+ for event_id, item in sorted(event_rows.items()):
179
+ archetypes = sorted(item["archetypes"])
180
+ family_results = [classify_family(x) for x in archetypes]
181
+ families = sorted({x[0] for x in family_results if x[0]})
182
+ status = "matched" if len(families) == 1 and all(x[2] == "matched" for x in family_results) else ("ambiguous" if families else "unmatched")
183
+ manifest.append({"event_id": event_id, "family": families[0] if len(families) == 1 else None,
184
+ "family_status": status, "archetypes": archetypes, "question_count": item["qa_count"],
185
+ "source_files": sorted(item["sources"])})
186
+ (args.output / "event_family_manifest.json").write_text(json.dumps({"families": FAMILIES, "events": manifest}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
187
+
188
+ # Item scores are the official deterministic scorer's per-item values.
189
+ metric_rows = []
190
+ for path in args.item_scores:
191
+ model = path.stem.removesuffix(".six")
192
+ for _, score in read_jsonl(path):
193
+ info = gold_by_qa.get(score.get("qa_id"), {})
194
+ metric_rows.append({"model": model, "track": model.rsplit("_", 1)[-1], "interface": model.rsplit("_", 1)[-1],
195
+ "split": path.parts[-3] if len(path.parts) >= 3 else "unknown",
196
+ "event_id": info.get("event_id"), "event_family": next((m["family"] for m in manifest if m["event_id"] == info.get("event_id")), None),
197
+ "fire_axis": info.get("fire_axis"), "physical_axis": info.get("physical_axis"),
198
+ "question_type": score.get("question_type"), "task": score.get("task"),
199
+ "qa_id": score.get("qa_id"), "ratio": score.get("ratio"), "item_f1": score.get("item_f1"),
200
+ "evidence_f1": score.get("evidence_f1"), "mechanism_alignment": score.get("mechanism_alignment"),
201
+ "gold_linked_support": score.get("gold_linked_support"), "confidence": score.get("confidence")})
202
+ if metric_rows:
203
+ grouped = defaultdict(list)
204
+ for row in metric_rows:
205
+ grouped[(row["model"], row["track"], row["interface"], row["split"], row["event_family"], row["question_type"])].append(row)
206
+ summaries = []
207
+ for key, rows in sorted(grouped.items(), key=lambda x: str(x[0])):
208
+ def avg(field):
209
+ vals = [r[field] for r in rows if isinstance(r.get(field), (int, float))]
210
+ return sum(vals) / len(vals) if vals else None
211
+ summaries.append(dict(zip(("model", "track", "interface", "split", "event_family", "question_type"), key),
212
+ n=len(rows), completion_accuracy=avg("ratio"), f1=avg("item_f1"), brier_score=avg("brier_component"),
213
+ evidence_f1=avg("evidence_f1"), mechanism_alignment=avg("mechanism_alignment"),
214
+ gold_linked_support=avg("gold_linked_support")))
215
+ # Brier is (confidence - completion ratio)^2 in the frozen scorer.
216
+ for row in metric_rows:
217
+ if isinstance(row.get("confidence"), (int, float)) and isinstance(row.get("ratio"), (int, float)):
218
+ row["brier_component"] = (row["confidence"] - row["ratio"]) ** 2
219
+ for summary in summaries:
220
+ rows = grouped[tuple(summary[k] for k in ("model", "track", "interface", "split", "event_family", "question_type"))]
221
+ vals = [r["brier_component"] for r in rows if "brier_component" in r]
222
+ summary["brier_score"] = sum(vals) / len(vals) if vals else None
223
+ with (args.output / "metrics_by_event_family.csv").open("w", encoding="utf-8", newline="") as handle:
224
+ fields = list(summaries[0]) if summaries else []
225
+ writer = csv.DictWriter(handle, fieldnames=fields); writer.writeheader(); writer.writerows(summaries)
226
+ write_jsonl(args.output / "metric_items.jsonl", metric_rows)
227
+ report = {"schema_version": "FWB-FG9-THREE-STAGE-EVENT-FAMILY-v1", "fire_axis": FIRE_AXIS,
228
+ "task_to_fire_axis": TASK_FIRE, "family_names": FAMILIES,
229
+ "counts": {"gold_rows": len(gold_by_qa), "events": len(manifest), "audit_rows": len(audit),
230
+ "fire_axis": dict(Counter(x["fire_axis"] for x in gold_by_qa.values())),
231
+ "physical_axis": dict(Counter(x.get("physical_axis") for x in gold_by_qa.values()))},
232
+ "audit": audit}
233
+ (args.output / "audit.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
234
+ print(json.dumps(report["counts"], ensure_ascii=False, indent=2))
235
+
236
+
237
+ if __name__ == "__main__":
238
+ main()
evaluation/FireWorldBench-ICLR/scripts/run_api.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Resumable cross-provider runner for a frozen FG9 subset.
2
+
3
+ The runner never reads gold. It records transport failures, schema fallbacks and
4
+ format-only re-asks separately so that provider protocol failures cannot be
5
+ mistaken for model capability failures.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import base64
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import random
15
+ import re
16
+ import time
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ import requests
22
+
23
+
24
+ RUNNER_VERSION = "FWB-FG9-API-RUNNER-v10.1-openai-chat-wire-null-safe"
25
+ PROMPT_VERSION = "FWB-v2-independent-context-numbered-images"
26
+ SCHEMA_VERSION = "FWB-v2-single-hypothesis-or-exact-set"
27
+
28
+ CANONICAL_MODEL_ALIASES = {
29
+ "claude-haiku-4-5": {"claude-haiku-4-5-20251001"},
30
+ }
31
+
32
+
33
+ def model_identity_matches(requested: str, reported: str | None) -> bool:
34
+ if reported is None:
35
+ return False
36
+ return reported == requested or reported in CANONICAL_MODEL_ALIASES.get(requested, set())
37
+
38
+
39
+ def completed_qa_ids(rows: list[dict], provider: str, model: str) -> set[str]:
40
+ return {
41
+ row["qa_id"]
42
+ for row in rows
43
+ if row.get("status") in {"ok", "model_mismatch"}
44
+ and (provider != "openai"
45
+ or model_identity_matches(model, row.get("response_model")))
46
+ }
47
+
48
+
49
+ TASK_FIELDS = {
50
+ "L1-1": {"event_class": ["fire", "no_fire", "ventilation_disturbance", "sensor_fault"],
51
+ "cause_region": [*[f"R{i}" for i in range(1, 9)], "global", "none"],
52
+ "dominant_signal": ["temperature", "soot", "visibility", "flow", "none"],
53
+ "secondary_signal": ["temperature", "soot", "visibility", "flow", "none"],
54
+ "affected_region_count": list(range(9))},
55
+ "L1-2": {"temperature_trend": ["up", "stable", "down"], "smoke_trend": ["up", "stable", "down"],
56
+ "visibility_trend": ["up", "stable", "down"]},
57
+ "L1-3": {"consistency": ["consistent", "inconsistent"],
58
+ "first_violation_bin": ["none", "early", "middle", "late"],
59
+ "violation_type": ["none", "reverse", "jump", "disappearance", "direction_flip", "sensor_conflict"]},
60
+ "L2-1": {"source_region": [f"R{i}" for i in range(1, 9)],
61
+ "stage": ["incipient", "growth", "developed", "decay"]},
62
+ "L2-2": {"risk_region": [f"R{i}" for i in range(1, 9)],
63
+ "risk_level": ["low", "moderate", "high", "critical"],
64
+ "risk_driver": ["temperature", "visibility", "soot"],
65
+ "runner_up_region": [f"R{i}" for i in range(1, 9)],
66
+ "stability_phase": ["early", "middle", "late", "unstable"],
67
+ "winner_switch_count_bin": ["zero", "one", "multiple"],
68
+ "winner_support_count": [f"v{i}" for i in range(16)],
69
+ "runner_up_support_count": [f"v{i}" for i in range(16)],
70
+ "winner_switch_count": [f"v{i}" for i in range(16)]},
71
+ "L2-3": {"mechanism": ["buoyant_plume", "ceiling_jet", "smoke_layer", "longitudinal_ventilation",
72
+ "backlayering", "extraction_dominated"],
73
+ "flow_direction": ["vertical", "downstream", "upstream", "bidirectional", "mixed"],
74
+ "control_regime": ["buoyancy", "ventilation", "extraction", "mixed"]},
75
+ "L3-2": {"region": [*[f"R{i}" for i in range(1, 9)], "none"],
76
+ "time_bin": ["none", "0_10s", "10_30s", "30_60s", "after_60s"],
77
+ "trigger_variable": ["none", "temperature", "visibility", "soot"]},
78
+ "L3-3": {"direction": ["A", "B", "same"],
79
+ "magnitude_bin": ["negligible", "small", "medium", "large"],
80
+ "earliest_affected_target": ["none", "temperature", "smoke", "visibility", "risk_region"]},
81
+ }
82
+
83
+
84
+ def load_jsonl(path: Path) -> list[dict]:
85
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
86
+
87
+
88
+ def load_confidential_config(path: Path) -> dict[str, str]:
89
+ values = {}
90
+ for line in path.read_text(encoding="utf-8").splitlines():
91
+ match = re.match(r"^([A-Z][A-Z0-9_]+)=(.+)$", line.strip())
92
+ if match:
93
+ values[match.group(1)] = match.group(2).strip()
94
+ return values
95
+
96
+
97
+ def enum_value_schema(values: list[object]) -> dict:
98
+ if values and all(isinstance(value, str) for value in values):
99
+ value_type = "string"
100
+ elif values and all(isinstance(value, int) and not isinstance(value, bool) for value in values):
101
+ value_type = "integer"
102
+ else:
103
+ raise ValueError(f"enum values must have one supported scalar type: {values!r}")
104
+ return {"type": value_type, "enum": values}
105
+
106
+
107
+ def enum_object(fields: dict[str, list[object]]) -> dict:
108
+ return {
109
+ "type": "object", "additionalProperties": False, "required": list(fields),
110
+ "properties": {key: enum_value_schema(values) for key, values in fields.items()},
111
+ }
112
+
113
+
114
+ def full_prediction_schema(task: str) -> dict:
115
+ if task != "L3-1":
116
+ return enum_object(TASK_FIELDS[task])
117
+ trend = enum_object({"temperature_trend": ["up", "stable", "down"],
118
+ "smoke_trend": ["up", "stable", "down"],
119
+ "visibility_trend": ["up", "stable", "down"]})
120
+ return {
121
+ "type": "object", "additionalProperties": False, "required": ["horizons"],
122
+ "properties": {"horizons": {
123
+ "type": "object", "additionalProperties": False, "required": ["10s", "30s", "60s"],
124
+ "properties": {key: trend for key in ("10s", "30s", "60s")},
125
+ }},
126
+ }
127
+
128
+
129
+ def schema_subset(schema: dict, fields: list[str]) -> dict:
130
+ selected: dict = {"type": "object", "additionalProperties": False, "required": [], "properties": {}}
131
+ for field in fields:
132
+ source = schema
133
+ target = selected
134
+ for part in field.split("."):
135
+ if source.get("type") != "object" or part not in source.get("properties", {}):
136
+ raise KeyError(f"unknown prediction field: {field}")
137
+ source = source["properties"][part]
138
+ if part not in target["properties"]:
139
+ target["required"].append(part)
140
+ target["properties"][part] = (
141
+ {"type": "object", "additionalProperties": False,
142
+ "required": [], "properties": {}}
143
+ if source.get("type") == "object" else source
144
+ )
145
+ target = target["properties"][part]
146
+ return selected
147
+
148
+
149
+ def prediction_schema(row: dict) -> dict:
150
+ schema = full_prediction_schema(row["task"])
151
+ fields = row.get("answer_fields")
152
+ return schema_subset(schema, fields) if fields else schema
153
+
154
+
155
+ def response_schema(row: dict) -> dict:
156
+ if row["question_type"] == "choice":
157
+ labels = [option["label"] for option in row.get("options", [])]
158
+ if not labels or len(labels) != len(set(labels)):
159
+ raise ValueError(f"invalid choice labels for {row.get('qa_id', '<unknown>')}")
160
+ return {
161
+ "type": "object", "additionalProperties": False, "required": ["choices", "confidence"],
162
+ "properties": {"choices": {"type": "array", "items": {"type": "string", "enum": labels},
163
+ "minItems": 1 if all('hypothesis' in o for o in row['options']) else 0,
164
+ "maxItems": 1 if all('hypothesis' in o for o in row['options']) else len(labels), "uniqueItems": True},
165
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1}},
166
+ }
167
+ return {
168
+ "type": "object", "additionalProperties": False,
169
+ "required": ["conclusion", "prediction", "evidence", "mechanism", "confidence"],
170
+ "properties": {
171
+ "conclusion": {"type": "string"}, "prediction": prediction_schema(row),
172
+ "evidence": {"type": "array", "items": {"type": "string"}},
173
+ "mechanism": {"type": "string"},
174
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1},
175
+ },
176
+ }
177
+
178
+
179
+ def strip_paths(value: Any) -> Any:
180
+ if isinstance(value, list):
181
+ return [strip_paths(item) for item in value]
182
+ if isinstance(value, dict):
183
+ return {key: strip_paths(item) for key, item in value.items() if key not in {"path", "asset_path"}}
184
+ return value
185
+
186
+
187
+ def asset_entries(value: Any) -> list[dict]:
188
+ output = []
189
+ if isinstance(value, list):
190
+ for item in value:
191
+ output.extend(asset_entries(item))
192
+ elif isinstance(value, dict):
193
+ if "path" in value or "asset_path" in value:
194
+ output.append(value)
195
+ for key, item in value.items():
196
+ if key not in {"path", "asset_path"}:
197
+ output.extend(asset_entries(item))
198
+ return output
199
+
200
+
201
+ def resolve_asset(entry: dict, source_root: Path) -> Path:
202
+ relative = entry.get("path", entry.get("asset_path"))
203
+ path = source_root / str(relative)
204
+ if not path.is_file():
205
+ raise FileNotFoundError(path)
206
+ return path
207
+
208
+
209
+ def prompt_text(row: dict, task_contract: str | None = None) -> str:
210
+ material = strip_paths(row["material"])
211
+ parts = []
212
+ if task_contract:
213
+ parts.extend(["Frozen task contract (shared across all items):", task_contract])
214
+ parts.extend([f"Task: {row['task']}", row["question"],
215
+ "Query context:", json.dumps(row.get("query_context", {}), ensure_ascii=False),
216
+ "Observation metadata/data:",
217
+ json.dumps(material, ensure_ascii=False, separators=(",", ":"))])
218
+ entries = asset_entries(row['material'])
219
+ if entries:
220
+ parts.append('Image attachment order (Image N matches image_index N):')
221
+ for index, entry in enumerate(entries, 1):
222
+ if entry.get('image_index', index) != index:
223
+ raise ValueError('Image metadata order differs from attachment order')
224
+ parts.append(f"Image {index}: " + json.dumps(strip_paths(entry), ensure_ascii=False))
225
+ if row["question_type"] == "choice":
226
+ parts.extend(["Candidate hypotheses:", json.dumps(row["options"], ensure_ascii=False, separators=(",", ":")),
227
+ ('Select exactly one complete hypothesis.' if all('hypothesis' in o for o in row['options'])
228
+ else 'Select every and only true claim.') + ' Return only JSON with choices (label array) and confidence (0..1).'])
229
+ else:
230
+ parts.append("Return only the required JSON report. Evidence must contain 1-3 concise observed facts; mechanism must explain the physical link.")
231
+ return "\n".join(parts)
232
+
233
+
234
+ def encode_images(row: dict, source_root: Path) -> list[tuple[str, str]]:
235
+ images = []
236
+ for entry in asset_entries(row["material"]):
237
+ path = resolve_asset(entry, source_root)
238
+ mime = "image/png" if path.suffix.lower() == ".png" else "image/jpeg"
239
+ images.append((mime, base64.b64encode(path.read_bytes()).decode("ascii")))
240
+ return images
241
+
242
+
243
+ def extract_text(provider: str, response: dict) -> str:
244
+ if provider in {"openai", "grok"}:
245
+ if isinstance(response.get("output_text"), str):
246
+ return response["output_text"]
247
+ chunks = []
248
+ for item in response.get("output", []):
249
+ for content in item.get("content", []):
250
+ if isinstance(content.get("text"), str):
251
+ chunks.append(content["text"])
252
+ if chunks:
253
+ return "\n".join(chunks)
254
+ choices = response.get("choices", [])
255
+ return (choices[0].get("message", {}).get("content") or "") if choices else ""
256
+ if provider == "anthropic":
257
+ return "\n".join(item.get("text", "") for item in response.get("content", []) if item.get("type") == "text")
258
+ if provider == "gemini":
259
+ candidates = response.get("candidates", [])
260
+ if not candidates:
261
+ return ""
262
+ return "\n".join(part.get("text", "") for part in candidates[0].get("content", {}).get("parts", []))
263
+ choices = response.get("choices", [])
264
+ return (choices[0].get("message", {}).get("content") or "") if choices else ""
265
+
266
+
267
+ def usage_record(provider: str, response: dict) -> dict:
268
+ if provider == "gemini":
269
+ return response.get("usageMetadata", {})
270
+ return response.get("usage", {})
271
+
272
+
273
+ def normalized_usage(provider: str, response: dict) -> dict:
274
+ usage = usage_record(provider, response)
275
+ if provider == "gemini":
276
+ return {
277
+ "input_tokens": usage.get("promptTokenCount"),
278
+ "output_tokens": usage.get("candidatesTokenCount"),
279
+ "cached_tokens": usage.get("cachedContentTokenCount"),
280
+ "reasoning_tokens": usage.get("thoughtsTokenCount"),
281
+ "total_tokens": usage.get("totalTokenCount"),
282
+ }
283
+ input_details = usage.get("input_tokens_details") or usage.get("prompt_tokens_details") or {}
284
+ output_details = usage.get("output_tokens_details") or usage.get("completion_tokens_details") or {}
285
+ return {
286
+ "input_tokens": usage.get("input_tokens", usage.get("prompt_tokens")),
287
+ "output_tokens": usage.get("output_tokens", usage.get("completion_tokens")),
288
+ "cached_tokens": usage.get("cache_read_input_tokens", input_details.get("cached_tokens")),
289
+ "reasoning_tokens": output_details.get("reasoning_tokens"),
290
+ "total_tokens": usage.get("total_tokens"),
291
+ }
292
+
293
+
294
+ def provider_cost(response: dict) -> dict:
295
+ usage = response.get("usage") if isinstance(response.get("usage"), dict) else {}
296
+ candidates = (
297
+ (response.get("cost"), "response.cost"),
298
+ (response.get("total_cost"), "response.total_cost"),
299
+ (usage.get("cost"), "response.usage.cost"),
300
+ (usage.get("total_cost"), "response.usage.total_cost"),
301
+ )
302
+ for value, source in candidates:
303
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
304
+ currency = response.get("currency") or usage.get("currency")
305
+ return {"amount": value, "currency": currency, "source": source}
306
+ return {"amount": None, "currency": None, "source": "not_returned_by_provider"}
307
+
308
+
309
+ def response_model(provider: str, response: dict) -> str | None:
310
+ if provider == "gemini":
311
+ return response.get("modelVersion")
312
+ return response.get("model")
313
+
314
+
315
+ def file_digest(path: Path) -> str:
316
+ value = hashlib.sha256()
317
+ with path.open("rb") as stream:
318
+ for block in iter(lambda: stream.read(1 << 20), b""):
319
+ value.update(block)
320
+ return value.hexdigest()
321
+
322
+
323
+ def classify_exception(exc: Exception) -> str:
324
+ text = str(exc).lower()
325
+ if isinstance(exc, KeyError):
326
+ return "tooling"
327
+ if isinstance(exc, FileNotFoundError):
328
+ return "capability"
329
+ if any(term in text for term in (
330
+ "datainspectionfailed", "data_inspection_failed", "inappropriate content",
331
+ "content safety", "content policy", "safety filter",
332
+ )):
333
+ return "content_safety"
334
+ if any(term in text for term in ("billing", "insufficient credit", "insufficient balance", "http 402")):
335
+ return "billing"
336
+ if "timeout" in text or isinstance(exc, requests.Timeout):
337
+ return "timeout"
338
+ if "proxy" in text:
339
+ return "proxy"
340
+ if "http 429" in text or "rate limit" in text:
341
+ return "rate_limit"
342
+ if re.search(r"http (?:4|5)\d\d", text):
343
+ return "http"
344
+ if any(term in text for term in ("connection", "transport")):
345
+ return "transport"
346
+ return "capability"
347
+
348
+
349
+ def write_run_manifest(path: Path, metadata: dict, records: list[dict]) -> None:
350
+ status_counts: dict[str, int] = {}
351
+ error_counts: dict[str, int] = {}
352
+ usage_totals = {key: 0 for key in ("input_tokens", "output_tokens", "cached_tokens", "reasoning_tokens", "total_tokens")}
353
+ unknown_usage = {key: 0 for key in usage_totals}
354
+ costs = []
355
+ for record in records:
356
+ status = str(record.get("status", "unknown"))
357
+ status_counts[status] = status_counts.get(status, 0) + 1
358
+ classification = record.get("error_classification")
359
+ if classification:
360
+ error_counts[classification] = error_counts.get(classification, 0) + 1
361
+ for key in usage_totals:
362
+ value = record.get("usage_normalized", {}).get(key)
363
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
364
+ usage_totals[key] += value
365
+ else:
366
+ unknown_usage[key] += 1
367
+ cost = record.get("provider_cost", {})
368
+ if cost.get("amount") is not None:
369
+ costs.append(cost)
370
+ manifest = {
371
+ **metadata,
372
+ "updated_at_utc": datetime.now(timezone.utc).isoformat(),
373
+ "record_count": len(records),
374
+ "status_counts": status_counts,
375
+ "error_classification_counts": error_counts,
376
+ "usage_totals": usage_totals,
377
+ "usage_missing_record_counts": unknown_usage,
378
+ "provider_cost_records": costs,
379
+ "provider_cost_note": "No monetary amount is inferred when the provider response omits billing data.",
380
+ }
381
+ temporary = path.with_suffix(path.suffix + ".tmp")
382
+ temporary.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
383
+ temporary.replace(path)
384
+
385
+
386
+ def numbered_image_parts(images, wire):
387
+ parts = []
388
+ for index, (mime, data) in enumerate(images, 1):
389
+ label = f"Image {index} (see corresponding observation metadata):"
390
+ if wire == "gemini":
391
+ parts.extend([{"text": label}, {"inlineData": {"mimeType": mime, "data": data}}])
392
+ elif wire == "responses":
393
+ parts.extend([{"type": "input_text", "text": label}, {"type": "input_image", "image_url": f"data:{mime};base64,{data}"}])
394
+ elif wire == "anthropic":
395
+ parts.extend([{"type": "text", "text": label}, {"type": "image", "source": {"type": "base64", "media_type": mime, "data": data}}])
396
+ else:
397
+ parts.extend([{"type": "text", "text": label}, {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{data}"}}])
398
+ return parts
399
+
400
+
401
+ def build_request(provider: str, model: str, system: str, prompt: str, images: list[tuple[str, str]],
402
+ schema: dict, mode: str, max_tokens: int, reasoning_effort: str,
403
+ wire_api: str = "responses") -> tuple[str, dict, dict]:
404
+ if provider in {"openai", "grok"}:
405
+ if provider == "openai" and wire_api == "chat_completions":
406
+ content = [{"type": "text", "text": prompt}]
407
+ content.extend(numbered_image_parts(images, "chat"))
408
+ payload = {
409
+ "model": model,
410
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": content}],
411
+ "max_tokens": max_tokens,
412
+ "reasoning_effort": reasoning_effort,
413
+ }
414
+ if mode == "json_schema":
415
+ payload["response_format"] = {
416
+ "type": "json_schema",
417
+ "json_schema": {"name": "fwb_fg9_report", "strict": True, "schema": schema},
418
+ }
419
+ elif mode == "json_object":
420
+ payload["response_format"] = {"type": "json_object"}
421
+ return "/chat/completions", {
422
+ "Authorization": "Bearer {key}", "Content-Type": "application/json",
423
+ }, payload
424
+ content = [{"type": "input_text", "text": prompt}]
425
+ content.extend(numbered_image_parts(images, "responses"))
426
+ payload = {"model": model, "input": [{"role": "system", "content": [{"type": "input_text", "text": system}]},
427
+ {"role": "user", "content": content}],
428
+ "max_output_tokens": max_tokens, "store": False, "reasoning": {"effort": reasoning_effort}}
429
+ if mode == "json_schema":
430
+ payload["text"] = {"format": {"type": "json_schema", "name": "fwb_fg9_report", "schema": schema, "strict": True}}
431
+ elif mode == "json_object":
432
+ payload["text"] = {"format": {"type": "json_object"}}
433
+ path = "/responses" if provider == "grok" else "/responses"
434
+ return path, {"Authorization": "Bearer {key}", "Content-Type": "application/json"}, payload
435
+ if provider == "anthropic":
436
+ content = [{"type": "text", "text": prompt}]
437
+ content.extend(numbered_image_parts(images, "anthropic"))
438
+ payload = {"model": model, "system": system, "messages": [{"role": "user", "content": content}],
439
+ "max_tokens": max_tokens, "temperature": 0}
440
+ if mode == "json_schema":
441
+ payload["output_config"] = {"format": {"type": "json_schema", "schema": schema}}
442
+ return "/v1/messages", {"x-api-key": "{key}", "anthropic-version": "2023-06-01", "Content-Type": "application/json"}, payload
443
+ if provider == "gemini":
444
+ parts = [{"text": system + "\n\n" + prompt}]
445
+ parts.extend(numbered_image_parts(images, "gemini"))
446
+ generation = {"temperature": 0, "maxOutputTokens": max_tokens, "responseMimeType": "application/json"}
447
+ if mode == "json_schema":
448
+ generation["responseJsonSchema"] = schema
449
+ payload = {"contents": [{"role": "user", "parts": parts}], "generationConfig": generation}
450
+ return f"/v1beta/models/{model}:generateContent", {"x-goog-api-key": "{key}",
451
+ "Content-Type": "application/json"}, payload
452
+ if provider == "gemini_openai_compat":
453
+ content = [{"type": "text", "text": prompt}]
454
+ content.extend(numbered_image_parts(images, "chat"))
455
+ payload = {
456
+ "model": model,
457
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": content}],
458
+ "temperature": 0,
459
+ "max_tokens": max_tokens,
460
+ }
461
+ if mode == "json_schema":
462
+ payload["response_format"] = {
463
+ "type": "json_schema",
464
+ "json_schema": {"name": "fwb_fg9_report", "strict": True, "schema": schema},
465
+ }
466
+ elif mode == "json_object":
467
+ payload["response_format"] = {"type": "json_object"}
468
+ return "/chat/completions", {"Authorization": "Bearer {key}", "Content-Type": "application/json"}, payload
469
+ content = [{"type": "text", "text": prompt}]
470
+ content.extend(numbered_image_parts(images, "chat"))
471
+ payload = {"model": model, "messages": [{"role": "system", "content": system}, {"role": "user", "content": content}],
472
+ "temperature": 0, "max_tokens": max_tokens, "enable_thinking": False}
473
+ if mode == "json_schema":
474
+ payload["response_format"] = {"type": "json_schema", "json_schema": {"name": "fwb_fg9_report", "strict": True, "schema": schema}}
475
+ elif mode == "json_object":
476
+ payload["response_format"] = {"type": "json_object"}
477
+ return "/chat/completions", {"Authorization": "Bearer {key}", "Content-Type": "application/json"}, payload
478
+
479
+
480
+ def parse_json(text: str) -> dict | None:
481
+ cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.IGNORECASE)
482
+ try:
483
+ value = json.loads(cleaned)
484
+ return value if isinstance(value, dict) else None
485
+ except json.JSONDecodeError:
486
+ start, end = text.find("{"), text.rfind("}")
487
+ if start >= 0 and end > start:
488
+ try:
489
+ value = json.loads(text[start:end + 1])
490
+ return value if isinstance(value, dict) else None
491
+ except json.JSONDecodeError:
492
+ pass
493
+ return None
494
+
495
+
496
+ def validation_errors(value: Any, schema: dict, path: str = "<root>") -> list[str]:
497
+ errors: list[str] = []
498
+ expected_type = schema.get("type")
499
+ type_ok = {
500
+ "object": isinstance(value, dict),
501
+ "array": isinstance(value, list),
502
+ "string": isinstance(value, str),
503
+ "integer": isinstance(value, int) and not isinstance(value, bool),
504
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
505
+ }.get(expected_type, True)
506
+ if not type_ok:
507
+ return [f"{path}: expected {expected_type}, got {type(value).__name__}"]
508
+ if "enum" in schema and value not in schema["enum"]:
509
+ errors.append(f"{path}: value {value!r} not in enum")
510
+ if expected_type == "number":
511
+ if "minimum" in schema and value < schema["minimum"]:
512
+ errors.append(f"{path}: value below minimum")
513
+ if "maximum" in schema and value > schema["maximum"]:
514
+ errors.append(f"{path}: value above maximum")
515
+ elif expected_type == "object":
516
+ required = set(schema.get("required", []))
517
+ missing = sorted(required - set(value))
518
+ if missing:
519
+ errors.append(f"{path}: missing required keys {missing}")
520
+ properties = schema.get("properties", {})
521
+ if schema.get("additionalProperties") is False:
522
+ extra = sorted(set(value) - set(properties))
523
+ if extra:
524
+ errors.append(f"{path}: additional keys {extra}")
525
+ for key, child_schema in properties.items():
526
+ if key in value:
527
+ errors.extend(validation_errors(value[key], child_schema, f"{path}.{key}"))
528
+ elif expected_type == "array":
529
+ if "minItems" in schema and len(value) < schema["minItems"]:
530
+ errors.append(f"{path}: fewer than minItems")
531
+ if "maxItems" in schema and len(value) > schema["maxItems"]:
532
+ errors.append(f"{path}: more than maxItems")
533
+ if schema.get("uniqueItems") and len({json.dumps(item, sort_keys=True) for item in value}) != len(value):
534
+ errors.append(f"{path}: duplicate items")
535
+ item_schema = schema.get("items", {})
536
+ for index, item in enumerate(value):
537
+ errors.extend(validation_errors(item, item_schema, f"{path}[{index}]"))
538
+ return errors
539
+
540
+
541
+ def post_with_retry(session: requests.Session, url: str, headers: dict, payload: dict,
542
+ timeout: float, retries: int) -> tuple[dict, int, float]:
543
+ started = time.perf_counter()
544
+ last_error = None
545
+ for attempt in range(retries + 1):
546
+ try:
547
+ response = session.post(url, headers=headers, json=payload, timeout=timeout)
548
+ if response.status_code < 400:
549
+ return response.json(), attempt, time.perf_counter() - started
550
+ error = RuntimeError(f"HTTP {response.status_code}: {response.text[:800]}")
551
+ if response.status_code not in {408, 409, 429, 500, 502, 503, 504}:
552
+ raise error
553
+ last_error = error
554
+ except (requests.Timeout, requests.ConnectionError, ValueError) as exc:
555
+ last_error = exc
556
+ if attempt < retries:
557
+ time.sleep(min(12.0, 1.5 * 2 ** attempt) + random.random() * 0.5)
558
+ raise RuntimeError(f"transport exhausted after {retries + 1} attempts: {last_error}")
559
+
560
+
561
+ def provider_config(provider: str, values: dict[str, str]) -> tuple[str, str, str]:
562
+ if provider == "openai":
563
+ return values["OPENAI_BASE_URL"], values["OPENAI_API_KEY"], values["OPENAI_MODEL"]
564
+ if provider == "grok":
565
+ return values["GROK_BASE_URL"], values["GROK_API_KEY"], values["GROK_MODEL"]
566
+ if provider == "anthropic":
567
+ return values["ANTHROPIC_BASE_URL"], values["ANTHROPIC_AUTH_TOKEN"], values["ANTHROPIC_MODEL"]
568
+ if provider == "gemini":
569
+ return values["GOOGLE_GEMINI_BASE_URL"], values["GEMINI_API_KEY"], values["GEMINI_MODEL"]
570
+ if provider == "gemini_openai_compat":
571
+ return values["GEMINI_OPENAI_BASE_URL"], values["GEMINI_API_KEY"], values["GEMINI_MODEL"]
572
+ return values["BAILIAN_BASE_URL"], values["DASHSCOPE_API_KEY"], "qwen3.5-plus-2026-02-15"
573
+
574
+
575
+ def main() -> None:
576
+ parser = argparse.ArgumentParser()
577
+ parser.add_argument(
578
+ "--provider",
579
+ choices=("openai", "grok", "anthropic", "gemini", "gemini_openai_compat", "bailian"),
580
+ required=True,
581
+ )
582
+ parser.add_argument("--questions", type=Path, required=True)
583
+ parser.add_argument("--source-root", type=Path, required=True)
584
+ parser.add_argument(
585
+ "--task-contract", type=Path,
586
+ help="Optional frozen task contract prepended identically to every selected item.",
587
+ )
588
+ parser.add_argument(
589
+ "--confidential-config", type=Path,
590
+ help="Optional KEY=VALUE file. Process environment variables take precedence.",
591
+ )
592
+ parser.add_argument("--output", type=Path, required=True)
593
+ parser.add_argument("--model")
594
+ parser.add_argument("--max-requests", type=int)
595
+ parser.add_argument("--track", choices=("S", "I"))
596
+ parser.add_argument("--question-type", choices=("choice", "open"))
597
+ parser.add_argument("--task")
598
+ parser.add_argument("--subtrack")
599
+ parser.add_argument("--timeout", type=float, default=120.0)
600
+ parser.add_argument("--retries", type=int, default=4)
601
+ parser.add_argument("--max-tokens", type=int, default=900)
602
+ parser.add_argument("--reasoning-effort", default="high")
603
+ parser.add_argument(
604
+ "--wire-api", choices=("responses", "chat_completions"), default="responses",
605
+ help="OpenAI-compatible transport. chat_completions is recorded and only valid for --provider openai.",
606
+ )
607
+ parser.add_argument("--format-reasks", type=int, default=1)
608
+ parser.add_argument(
609
+ "--format-mode", choices=("auto", "json_schema", "json_object", "prompt_only"),
610
+ default="auto", help="Use auto fallback or a recorded single response-format mode.",
611
+ )
612
+ args = parser.parse_args()
613
+ if args.provider != "openai" and args.wire_api != "responses":
614
+ parser.error("--wire-api chat_completions is only valid with --provider openai")
615
+
616
+ values = load_confidential_config(args.confidential_config) if args.confidential_config else {}
617
+ values.update(os.environ)
618
+ base_url, key, default_model = provider_config(args.provider, values)
619
+ model = args.model or default_model
620
+ rows = load_jsonl(args.questions)
621
+ if args.track:
622
+ rows = [row for row in rows if row["track"] == args.track]
623
+ if args.question_type:
624
+ rows = [row for row in rows if row["question_type"] == args.question_type]
625
+ if args.task:
626
+ rows = [row for row in rows if row["task"] == args.task]
627
+ if args.subtrack:
628
+ rows = [row for row in rows if row["subtrack"] == args.subtrack]
629
+ existing = load_jsonl(args.output) if args.output.exists() else []
630
+ completed = completed_qa_ids(existing, args.provider, model)
631
+ pending = [row for row in rows if row["qa_id"] not in completed]
632
+ if args.max_requests is not None:
633
+ pending = pending[:args.max_requests]
634
+ args.output.parent.mkdir(parents=True, exist_ok=True)
635
+ manifest_path = args.output.with_suffix(args.output.suffix + ".manifest.json")
636
+ task_contract = args.task_contract.read_text(encoding="utf-8").strip() if args.task_contract else None
637
+ manifest_metadata = {
638
+ "schema_version": "FWB-FG9-API-RUN-MANIFEST-v1",
639
+ "runner_version": RUNNER_VERSION,
640
+ "prompt_version": PROMPT_VERSION,
641
+ "response_schema_version": SCHEMA_VERSION,
642
+ "provider": args.provider,
643
+ "requested_model": model,
644
+ "questions": str(args.questions.resolve()),
645
+ "questions_sha256": file_digest(args.questions),
646
+ "source_root": str(args.source_root.resolve()),
647
+ "task_contract": str(args.task_contract.resolve()) if args.task_contract else None,
648
+ "task_contract_sha256": file_digest(args.task_contract) if args.task_contract else None,
649
+ "filters": {key: value for key, value in {
650
+ "track": args.track, "question_type": args.question_type,
651
+ "task": args.task, "subtrack": args.subtrack,
652
+ }.items() if value is not None},
653
+ "selected_question_count": len(rows),
654
+ "pending_question_count_at_start": len(pending),
655
+ "selected_qa_ids_sha256": hashlib.sha256(
656
+ "\n".join(row["qa_id"] for row in rows).encode()
657
+ ).hexdigest(),
658
+ "reasoning_effort": args.reasoning_effort,
659
+ "max_output_tokens": args.max_tokens,
660
+ "transport_retry_limit": args.retries,
661
+ "format_reask_limit": args.format_reasks,
662
+ "requested_format_mode": args.format_mode,
663
+ "wire_api": args.wire_api,
664
+ }
665
+ all_records = list(existing)
666
+ write_run_manifest(manifest_path, manifest_metadata, all_records)
667
+ system = ("You are evaluating a fire-physics benchmark. Use only the supplied observation. "
668
+ "Return one JSON object matching the requested schema, without markdown or commentary.")
669
+ session = requests.Session()
670
+ with args.output.open("a", encoding="utf-8") as stream:
671
+ for position, row in enumerate(pending, 1):
672
+ record = {"qa_id": row["qa_id"], "provider": args.provider,
673
+ "requested_model": model, "model": model,
674
+ "runner_version": RUNNER_VERSION, "prompt_version": PROMPT_VERSION,
675
+ "response_schema_version": SCHEMA_VERSION,
676
+ "question_type": row["question_type"], "task": row["task"], "status": "error",
677
+ "started_at_utc": datetime.now(timezone.utc).isoformat(),
678
+ "attempts": [], "format_reasks": 0}
679
+ final_raw_response = None
680
+ try:
681
+ images = encode_images(row, args.source_root)
682
+ prompt = prompt_text(row, task_contract)
683
+ schema = response_schema(row)
684
+ prompt += "\nRequired JSON Schema:\n" + json.dumps(schema, separators=(",", ":"))
685
+ record["request_fingerprint"] = {
686
+ "prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
687
+ "schema_sha256": hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest(),
688
+ "image_count": len(images),
689
+ }
690
+ parsed = None
691
+ schema_valid = False
692
+ raw_text = ""
693
+ received_response = False
694
+ modes = (("json_schema", "json_object", "prompt_only")
695
+ if args.format_mode == "auto" else (args.format_mode,))
696
+ for mode in modes:
697
+ path, headers, payload = build_request(args.provider, model, system, prompt, images, schema, mode,
698
+ args.max_tokens, args.reasoning_effort, args.wire_api)
699
+ url = base_url.rstrip("/") + path
700
+ headers = {name: value.replace("{key}", key) for name, value in headers.items()}
701
+ try:
702
+ response, transport_retries, latency = post_with_retry(
703
+ session, url, headers, payload, args.timeout, args.retries)
704
+ except RuntimeError as exc:
705
+ record["attempts"].append({
706
+ "mode": mode, "status": "request_error",
707
+ "error": str(exc)[:1000],
708
+ "error_classification": classify_exception(exc),
709
+ })
710
+ if "HTTP 400" in str(exc) or "HTTP 404" in str(exc) or "HTTP 422" in str(exc):
711
+ continue
712
+ raise
713
+ raw_text = extract_text(args.provider, response)
714
+ final_raw_response = response
715
+ received_response = True
716
+ parsed = parse_json(raw_text)
717
+ schema_issues = validation_errors(parsed, schema)
718
+ schema_valid = not schema_issues
719
+ record["attempts"].append({"mode": mode, "status": "response", "latency_s": latency,
720
+ "transport_retries": transport_retries,
721
+ "usage": usage_record(args.provider, response),
722
+ "usage_normalized": normalized_usage(args.provider, response),
723
+ "provider_cost": provider_cost(response),
724
+ "response_model": response_model(args.provider, response),
725
+ "raw_response": response,
726
+ "parsed_json": parsed is not None, "schema_valid": schema_valid,
727
+ "schema_errors": schema_issues[:12]})
728
+ record["format_mode"] = mode
729
+ record["usage"] = usage_record(args.provider, response)
730
+ record["usage_normalized"] = normalized_usage(args.provider, response)
731
+ record["provider_cost"] = provider_cost(response)
732
+ record["response_model"] = response_model(args.provider, response)
733
+ if schema_valid:
734
+ break
735
+ if not received_response:
736
+ raise RuntimeError("all response-format modes were rejected before model inference")
737
+ for _ in range(args.format_reasks):
738
+ if schema_valid:
739
+ break
740
+ record["format_reasks"] += 1
741
+ reask = prompt + "\nYour previous output was not valid JSON. Return only one valid JSON object now."
742
+ path, headers, payload = build_request(args.provider, model, system, reask, images, schema,
743
+ "json_object", args.max_tokens, args.reasoning_effort,
744
+ args.wire_api)
745
+ headers = {name: value.replace("{key}", key) for name, value in headers.items()}
746
+ response, transport_retries, latency = post_with_retry(
747
+ session, base_url.rstrip("/") + path, headers, payload, args.timeout, args.retries)
748
+ final_raw_response = response
749
+ raw_text = extract_text(args.provider, response)
750
+ parsed = parse_json(raw_text)
751
+ schema_issues = validation_errors(parsed, schema)
752
+ schema_valid = not schema_issues
753
+ record["attempts"].append({"mode": "format_reask", "status": "response", "latency_s": latency,
754
+ "transport_retries": transport_retries,
755
+ "usage": usage_record(args.provider, response),
756
+ "usage_normalized": normalized_usage(args.provider, response),
757
+ "provider_cost": provider_cost(response),
758
+ "response_model": response_model(args.provider, response),
759
+ "raw_response": response,
760
+ "parsed_json": parsed is not None, "schema_valid": schema_valid,
761
+ "schema_errors": schema_issues[:12]})
762
+ record["format_mode"] = "format_reask"
763
+ record["usage"] = usage_record(args.provider, response)
764
+ record["usage_normalized"] = normalized_usage(args.provider, response)
765
+ record["provider_cost"] = provider_cost(response)
766
+ record["response_model"] = response_model(args.provider, response)
767
+ record["response"] = parsed if parsed is not None else raw_text
768
+ record["raw_text"] = raw_text
769
+ record["raw_response"] = final_raw_response
770
+ record["status"] = "ok" if schema_valid else ("schema_error" if parsed is not None else "format_error")
771
+ if not schema_valid:
772
+ record["error_classification"] = "format" if parsed is not None else "parse"
773
+ reported_model = record.get("response_model")
774
+ if (args.provider == "openai" and reported_model is not None
775
+ and not model_identity_matches(model, reported_model)):
776
+ record["status"] = "model_mismatch"
777
+ record["error_classification"] = "model_identity"
778
+ except Exception as exc: # Each item is checkpointed; one provider failure does not discard the gate.
779
+ record["error_type"] = type(exc).__name__
780
+ record["error"] = str(exc)[:1200]
781
+ attempt_classes = {
782
+ attempt["error_classification"]
783
+ for attempt in record["attempts"]
784
+ if attempt.get("error_classification")
785
+ }
786
+ record["error_classification"] = (
787
+ next(iter(attempt_classes)) if len(attempt_classes) == 1
788
+ else classify_exception(exc)
789
+ )
790
+ record["attempt_count"] = len(record["attempts"])
791
+ record["transport_retries"] = sum(
792
+ attempt.get("transport_retries", 0) for attempt in record["attempts"]
793
+ )
794
+ record["finished_at_utc"] = datetime.now(timezone.utc).isoformat()
795
+ stream.write(json.dumps(record, separators=(",", ":")) + "\n")
796
+ stream.flush()
797
+ all_records.append(record)
798
+ write_run_manifest(manifest_path, manifest_metadata, all_records)
799
+ print(json.dumps({"finished": position, "selected": len(pending), "qa_id": row["qa_id"],
800
+ "status": record["status"], "provider": args.provider, "model": model}))
801
+
802
+
803
+ if __name__ == "__main__":
804
+ main()
evaluation/FireWorldBench-ICLR/scripts/run_eval.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run a model on a FireWorldBench split and compute the six metrics.
3
+
4
+ Usage (from the repo root):
5
+ python scripts/run_eval.py --split main_synthetic
6
+ python scripts/run_eval.py --split mmodalfire_c06 --group-by physical
7
+
8
+ Requires the OpenAI-compatible endpoint env vars:
9
+ OPENAI_BASE_URL, OPENAI_API_KEY, OPENAI_MODEL
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ SPLITS = {
19
+ "main_synthetic": ("main_synthetic/full_test_A", "main_synthetic"),
20
+ "mmodalfire_c06": ("mmodalfire_c06/full_test_A", "mmodalfire_c06"),
21
+ }
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser(description=__doc__)
26
+ parser.add_argument("--split", choices=tuple(SPLITS), required=True)
27
+ parser.add_argument("--group-by", choices=("task", "physical", "fire"), default="physical",
28
+ help="report cells by physical axis P1-P5 (default), fire axis T1-T3, "
29
+ "or fine-grained task (36)")
30
+ parser.add_argument("--provider", default="openai")
31
+ parser.add_argument("--model", default=None, help="default: $OPENAI_MODEL")
32
+ parser.add_argument("--max-requests", type=int, default=None,
33
+ help="run only the first N questions (for a quick test)")
34
+ parser.add_argument("--track", choices=("S", "I"), default=None,
35
+ help="run only text track S or vision track I. Text-only models MUST use --track S "
36
+ "(I-track items carry images and will fail on a text model); vision models may use --track I.")
37
+ parser.add_argument("--data-dir", default=None, help="default: ./data")
38
+ parser.add_argument("--out-dir", default="results")
39
+ args = parser.parse_args()
40
+
41
+ root = Path(__file__).resolve().parent.parent
42
+ data_dir = Path(args.data_dir) if args.data_dir else root / "data"
43
+ split, source = SPLITS[args.split]
44
+ questions = data_dir / split / "questions.jsonl"
45
+ gold = data_dir / split / "gold.jsonl"
46
+ if not questions.exists():
47
+ sys.exit(f"Data not found at {questions}\nRun: cd scripts && bash download.sh")
48
+ if not gold.exists():
49
+ sys.exit(f"Gold not found at {gold}")
50
+
51
+ model = args.model or os.environ.get("OPENAI_MODEL")
52
+ if not model:
53
+ sys.exit("Missing model. Set OPENAI_MODEL or pass --model.")
54
+
55
+ out_dir = Path(args.out_dir)
56
+ out_dir.mkdir(parents=True, exist_ok=True)
57
+ preds = out_dir / f"{args.split}.jsonl"
58
+ result = out_dir / f"{args.split}-{args.group_by}.json"
59
+
60
+ # Step 1: run inference (resumable; never reads Gold)
61
+ cmd = [sys.executable, str(root / "scripts" / "run_api.py"),
62
+ "--provider", args.provider,
63
+ "--questions", str(questions),
64
+ "--source-root", str(data_dir / source),
65
+ "--output", str(preds),
66
+ "--model", model]
67
+ if args.max_requests:
68
+ cmd += ["--max-requests", str(args.max_requests)]
69
+ if args.track:
70
+ cmd += ["--track", args.track]
71
+ if args.track == "I":
72
+ print("[track I] vision track: ensure your model endpoint supports images.", flush=True)
73
+ elif args.track == "S":
74
+ print("[track S] text track: running text-only items.", flush=True)
75
+ else:
76
+ print("[track all] running S+I together. Text-only model? pass --track S (I items carry images).", flush=True)
77
+ print(">", " ".join(cmd), flush=True)
78
+ subprocess.run(cmd, check=True)
79
+
80
+ # Step 2: compute the six metrics
81
+ cmd = [sys.executable, str(root / "scripts" / "score_six_metrics.py"),
82
+ "--gold", str(gold), "--predictions", str(preds),
83
+ "--output", str(result), "--group-by", args.group_by]
84
+ print(">", " ".join(cmd), flush=True)
85
+ subprocess.run(cmd, check=True)
86
+
87
+ print(f"\nDone. Six metrics written to {result}")
88
+ print(json.dumps(json.load(open(result))["overall"], ensure_ascii=False, indent=2))
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
evaluation/FireWorldBench-ICLR/scripts/score_fg9_deep_metrics_by_cell.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, re
2
+ from pathlib import Path
3
+ from collections import defaultdict
4
+
5
+ ROOT=Path('/root/autodl-tmp/FireWorldBench/2/5.项目实现/v1')
6
+ BASE=ROOT/'artifacts/validation/fg9_dual_model_n40_final_20260812'
7
+ RUNS={
8
+ 'main_grok':('模拟数据主集',['main_gate_C/gold.jsonl','main_gate_B/gold.jsonl']),
9
+ 'main_claude':('模拟数据主集',['main_gate_C/gold.jsonl','main_gate_B/gold.jsonl']),
10
+ 'c06_grok':('真实事件模拟',['c06_candidate/build_A/gold.jsonl','c06_gate_A/gold.jsonl','c06_pool80/build_A/gold.jsonl','c06_pool80/build_B/gold.jsonl']),
11
+ 'c06_claude':('真实事件模拟',['c06_candidate/build_A/gold.jsonl','c06_gate_A/gold.jsonl','c06_pool80/build_A/gold.jsonl','c06_pool80/build_B/gold.jsonl'])}
12
+ VARS={'temperature','visibility','soot','flow','velocity','risk','fire','smoke','sensor','ventilation'}
13
+ def text(v):
14
+ if isinstance(v,str):return v.lower()
15
+ if isinstance(v,list):return ' '.join(text(x) for x in v)
16
+ if isinstance(v,dict):return ' '.join(text(x) for x in v.values())
17
+ return str(v).lower()
18
+ def toks(s):return set(re.findall(r'[a-z][a-z0-9_]+',s.lower()))
19
+ def ece(rows,bins=10):
20
+ if not rows:return None
21
+ z=0
22
+ for i in range(bins):
23
+ b=[r for r in rows if i/bins<=r[0]<(i+1)/bins or (i==bins-1 and r[0]==1)]
24
+ if b:z+=len(b)/len(rows)*abs(sum(x[0] for x in b)/len(b)-sum(x[1] for x in b)/len(b))
25
+ return z
26
+ def main():
27
+ out=[]
28
+ for run,(dataset,grels) in RUNS.items():
29
+ gold={}
30
+ for grel in grels:
31
+ for x in map(json.loads,(BASE/grel).open(encoding='utf-8')):
32
+ if x.get('question_type')=='open':gold[x['qa_id']]=x
33
+ cells=defaultdict(list)
34
+ for x in map(json.loads,(BASE/'runs'/run/'merged_responses.jsonl').open(encoding='utf-8')):
35
+ if x.get('question_type')!='open' or x.get('qa_id') not in gold:continue
36
+ g=gold[x['qa_id']]; raw=x.get('response'); r=raw if isinstance(raw,dict) else {}; pred=r.get('prediction') or {}; free=text([r.get('conclusion',''),r.get('evidence',[]),r.get('mechanism','')]); ft=toks(free)
37
+ anchors=[]
38
+ for c in g.get('evidence_claims') or []:
39
+ obs=(c.get('observation') or '').lower(); var=next((v for v in VARS if v in obs),None); anchors.append((str(c.get('region','')).lower(),var))
40
+ rec=sum(((reg in free)+(var in free if var else 0))/(2 if var else 1) for reg,var in anchors)/max(1,len(anchors))
41
+ claims=set(z.lower() for z in re.findall(r'\bR\d+\b',free,re.I))|(ft&VARS); supported={z for a in anchors for z in a if z}; prec=len(claims&supported)/len(claims) if claims else 0
42
+ gt=toks(' '.join(c.get('statement','') for c in g.get('mechanism_claims') or []))-{'the','and','with','that','this','from','into','first'}; mech=toks(text(r.get('mechanism',''))); align=len(gt&mech)/len(gt) if gt else 0
43
+ cons=sum(str(v).lower() in free for v in pred.values())/max(1,len(pred)); conf=r.get('confidence'); conf=float(conf) if isinstance(conf,(int,float)) else 0; correct=int(pred==g.get('prediction')); valid=int(x.get('status')=='ok')
44
+ cells[(g.get('task'),g.get('track'))].append((rec,prec,align,cons,conf,correct,valid))
45
+ for (task,track),rs in cells.items():
46
+ valid=[r for r in rs if r[6]]; cal=[(r[4],r[5]) for r in valid]
47
+ def avg(i):return sum(r[i] for r in valid)/len(valid) if valid else 0
48
+ out.append({'dataset':dataset,'model':'Grok' if run.endswith('grok') else 'Claude','task':task,'track':track,'cell':f'{task}-{track}','n':len(rs),'valid_n':len(valid),'format_valid_rate':len(valid)/len(rs),'evidence_anchor_recall':avg(0),'evidence_precision_proxy':avg(1),'mechanism_alignment':avg(2),'prediction_explanation_consistency':avg(3),'brier_score':sum((c-y)**2 for c,y in cal)/len(cal) if cal else None,'ece_10bin':ece(cal)})
49
+ out.sort(key=lambda x:(x['dataset'],x['task'],x['track'],x['model']))
50
+ dest=BASE/'final_report_20260813/n40_open_deep_metrics_18cells.json'; dest.write_text(json.dumps({'schema_version':'FWB-FG9-DEEP-CELL-METRICS-v1','open_only':True,'rows':out},ensure_ascii=False,indent=2),encoding='utf-8'); print(dest,len(out))
51
+ if __name__=='__main__':main()
evaluation/FireWorldBench-ICLR/scripts/score_fg9_gold_linked_support.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import re
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+
7
+ ROOT = Path(__file__).resolve().parent.parent
8
+ BASE = ROOT / "artifacts/validation/fg9_dual_model_n40_final_20260812"
9
+ RUNS = {
10
+ "main_grok": ("模拟数据主集", ["main_gate_C/gold.jsonl", "main_gate_B/gold.jsonl"]),
11
+ "main_claude": ("模拟数据主集", ["main_gate_C/gold.jsonl", "main_gate_B/gold.jsonl"]),
12
+ "c06_grok": ("真实事件模拟", ["c06_candidate/build_A/gold.jsonl", "c06_gate_A/gold.jsonl", "c06_pool80/build_A/gold.jsonl", "c06_pool80/build_B/gold.jsonl"]),
13
+ "c06_claude": ("真实事件模拟", ["c06_candidate/build_A/gold.jsonl", "c06_gate_A/gold.jsonl", "c06_pool80/build_A/gold.jsonl", "c06_pool80/build_B/gold.jsonl"]),
14
+ }
15
+
16
+ ALIASES = {
17
+ "temperature": ("temperature", "thermal", "heat", "hot"),
18
+ "smoke": ("smoke", "soot", "obscuration"),
19
+ "soot": ("soot", "smoke", "combustion signature"),
20
+ "visibility": ("visibility", "visible", "obscuration"),
21
+ "flow": ("flow", "velocity", "ventilation", "transport"),
22
+ "up": ("increase", "increasing", "rise", "rising", "grow", "growth", "up", "higher"),
23
+ "down": ("decrease", "decreasing", "fall", "falling", "decline", "down", "lower"),
24
+ "stable": ("stable", "steady", "unchanged", "constant", "plateau"),
25
+ "critical": ("critical", "extreme", "severe"),
26
+ "high": ("high", "hazardous"),
27
+ "incipient": ("incipient", "early", "initial", "ignition"),
28
+ "growth": ("growth", "growing", "developing"),
29
+ "global": ("global", "across", "all regions", "domain-wide"),
30
+ "mixed": ("mixed", "bidirectional", "multiple directions"),
31
+ "vertical": ("vertical", "upward", "buoyant", "rise"),
32
+ }
33
+
34
+
35
+ def norm(value):
36
+ return re.sub(r"[^a-z0-9]+", " ", str(value).lower()).strip()
37
+
38
+
39
+ def text(value):
40
+ if isinstance(value, str):
41
+ return norm(value)
42
+ if isinstance(value, dict):
43
+ return " ".join(text(item) for item in value.values())
44
+ if isinstance(value, list):
45
+ return " ".join(text(item) for item in value)
46
+ return norm(value)
47
+
48
+
49
+ def flatten(value, prefix=""):
50
+ if isinstance(value, dict):
51
+ for key, item in value.items():
52
+ path = f"{prefix}.{key}" if prefix else key
53
+ yield from flatten(item, path)
54
+ else:
55
+ yield prefix, value
56
+
57
+
58
+ def equivalent(predicted, expected):
59
+ if isinstance(expected, (int, float)):
60
+ try:
61
+ return float(predicted) == float(expected)
62
+ except (TypeError, ValueError):
63
+ return False
64
+ return norm(predicted) == norm(expected)
65
+
66
+
67
+ def mentions(needle, corpus):
68
+ key = norm(needle)
69
+ variants = ALIASES.get(key, (key,))
70
+ return any(re.search(rf"(?<![a-z0-9]){re.escape(norm(v))}(?![a-z0-9])", corpus) for v in variants)
71
+
72
+
73
+ def field_supported(path, expected, response_text, gold_text):
74
+ parts = path.lower().split(".")
75
+ field = parts[-1]
76
+ expected_text = norm(expected)
77
+ gold_linked = mentions(expected_text, gold_text)
78
+
79
+ if re.fullmatch(r"r\d+", expected_text) or "region" in field:
80
+ return gold_linked and mentions(expected_text, response_text)
81
+ if field.endswith("trend"):
82
+ variable = field.removesuffix("_trend")
83
+ horizon = parts[-2] if len(parts) > 1 and re.fullmatch(r"\d+s", parts[-2]) else None
84
+ context = mentions(variable, response_text) and mentions(expected_text, response_text)
85
+ if horizon:
86
+ context = context and mentions(horizon, response_text)
87
+ return context
88
+ if any(token in field for token in ("signal", "driver", "variable", "target")):
89
+ return gold_linked and mentions(expected_text, response_text)
90
+ if isinstance(expected, (int, float)):
91
+ return mentions(expected_text, response_text) or any(word in response_text for word in ("all regions", "across regions"))
92
+ return gold_linked and mentions(expected_text, response_text)
93
+
94
+
95
+ def pearson(left, right):
96
+ mean_left = sum(left) / len(left)
97
+ mean_right = sum(right) / len(right)
98
+ numerator = sum((x - mean_left) * (y - mean_right) for x, y in zip(left, right))
99
+ denom_left = sum((x - mean_left) ** 2 for x in left)
100
+ denom_right = sum((y - mean_right) ** 2 for y in right)
101
+ return numerator / math.sqrt(denom_left * denom_right) if denom_left and denom_right else None
102
+
103
+
104
+ def main():
105
+ prior_rows = json.load(open(BASE / "final_report_20260813/n40_open_deep_metrics_18cells.json", encoding="utf-8"))["rows"]
106
+ prior = {(row["dataset"], row["model"], row["cell"]): row for row in prior_rows}
107
+ rows = []
108
+ item_audit = []
109
+
110
+ for run, (dataset, gold_paths) in RUNS.items():
111
+ gold = {}
112
+ for gold_path in gold_paths:
113
+ for line in open(BASE / gold_path, encoding="utf-8"):
114
+ item = json.loads(line)
115
+ if item.get("question_type") == "open":
116
+ gold[item["qa_id"]] = item
117
+ cells = defaultdict(list)
118
+ for line in open(BASE / "runs" / run / "merged_responses.jsonl", encoding="utf-8"):
119
+ response_record = json.loads(line)
120
+ qa_id = response_record.get("qa_id")
121
+ if response_record.get("question_type") != "open" or qa_id not in gold:
122
+ continue
123
+ gold_item = gold[qa_id]
124
+ response = response_record.get("response") if isinstance(response_record.get("response"), dict) else {}
125
+ predicted = response.get("prediction") if isinstance(response.get("prediction"), dict) else {}
126
+ predicted_flat = dict(flatten(predicted))
127
+ expected_flat = dict(flatten(gold_item.get("prediction", {})))
128
+ response_explanation = text([response.get("evidence", []), response.get("mechanism", ""), response.get("conclusion", "")])
129
+ gold_anchors = text([gold_item.get("evidence_claims", []), gold_item.get("mechanism_claims", [])])
130
+ field_scores = []
131
+ for path, expected in expected_flat.items():
132
+ correct = path in predicted_flat and equivalent(predicted_flat[path], expected)
133
+ supported = correct and field_supported(path, expected, response_explanation, gold_anchors)
134
+ field_scores.append(float(supported))
135
+ score = sum(field_scores) / len(field_scores) if field_scores else 0.0
136
+ cell = f'{gold_item["task"]}-{gold_item["track"]}'
137
+ cells[cell].append(score)
138
+ item_audit.append({"qa_id": qa_id, "dataset": dataset, "model": "Grok" if run.endswith("grok") else "Claude", "cell": cell, "score": score, "field_scores": field_scores})
139
+
140
+ model = "Grok" if run.endswith("grok") else "Claude"
141
+ for cell, scores in cells.items():
142
+ old = prior[(dataset, model, cell)]
143
+ precision = old["evidence_precision_proxy"]
144
+ recall = old["evidence_anchor_recall"]
145
+ evidence_f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
146
+ rows.append({"dataset": dataset, "model": model, "cell": cell, "n": len(scores), "gold_linked_support": sum(scores) / len(scores), "evidence_f1": evidence_f1, "mechanism_alignment": old["mechanism_alignment"]})
147
+
148
+ rows.sort(key=lambda row: (row["dataset"], row["cell"], row["model"]))
149
+ values = [row["gold_linked_support"] for row in rows]
150
+ summary = {
151
+ "row_count": len(rows), "min": min(values), "max": max(values), "mean": sum(values) / len(values),
152
+ "cells_le_0_05": sum(value <= 0.05 for value in values), "cells_ge_0_95": sum(value >= 0.95 for value in values),
153
+ "cells_eq_0": sum(value == 0 for value in values), "cells_eq_1": sum(value == 1 for value in values),
154
+ "pearson_with_evidence_f1": pearson(values, [row["evidence_f1"] for row in rows]),
155
+ "pearson_with_mechanism_alignment": pearson(values, [row["mechanism_alignment"] for row in rows]),
156
+ }
157
+ output = {"schema_version": "FWB-FG9-GOLD-LINKED-SUPPORT-v1", "definition": "mean fraction of Gold-correct prediction fields supported by task-aware evidence or mechanism anchors", "rows": rows, "summary": summary, "item_audit": item_audit}
158
+ destination = BASE / "final_report_20260813/n40_gold_linked_support_18cells.json"
159
+ destination.write_text(json.dumps(output, ensure_ascii=False, indent=2), encoding="utf-8")
160
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
161
+ for dataset in ("模拟数据主集", "真实事件模拟"):
162
+ print(dataset)
163
+ print([(row["cell"], row["model"], round(row["gold_linked_support"], 3)) for row in rows if row["dataset"] == dataset])
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()
evaluation/FireWorldBench-ICLR/scripts/score_fg9_predictions.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score FG9 choice/open predictions with format, ability, evidence and calibration separated."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import re
8
+ from collections import Counter, defaultdict
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+
13
+ REQUIRED_OPEN_KEYS = {"conclusion", "prediction", "evidence", "mechanism", "confidence"}
14
+ TOKEN_PATTERN = re.compile(r"[a-z0-9_]+(?:\.[0-9]+)?", re.IGNORECASE)
15
+ NUMBER_PATTERN = re.compile(r"(?<![a-z0-9_])[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?", re.IGNORECASE)
16
+ STOP_WORDS = {
17
+ "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "in", "is", "it",
18
+ "of", "on", "or", "that", "the", "this", "to", "under", "while", "with",
19
+ }
20
+ ALIASES = {
21
+ "thermal": "temperature", "heat": "temperature", "hot": "temperature",
22
+ "smoke": "soot", "smoky": "soot", "obscuration": "visibility",
23
+ "airflow": "flow", "velocity": "flow", "movement": "flow",
24
+ "extract": "extraction", "extracted": "extraction", "exhaust": "extraction",
25
+ "buoyant": "buoyancy", "plume": "buoyancy",
26
+ }
27
+
28
+ # Provider wording varies substantially even for the same physical explanation.
29
+ # These concepts form a small, frozen ontology for deterministic auxiliary
30
+ # evidence/mechanism scoring; exact task labels remain scored separately above.
31
+ CONCEPT_PATTERNS = {
32
+ "fire_source": (r"\bfire\b", r"\bflame\w*\b", r"\bcombust\w*\b", r"\bignition\b", r"\bhrrpua\b"),
33
+ "heat": (r"\btemperature\b", r"\bthermal\b", r"\bheat\w*\b", r"\bhot\w*\b"),
34
+ "smoke": (r"\bsmoke\b", r"\bsoot\b", r"\bobscur\w*\b"),
35
+ "visibility": (r"\bvisibility\b", r"\bvisible\b"),
36
+ "flow": (r"\bflow\b", r"\bairflow\b", r"\bvelocity\b", r"\btransport\b", r"\badvection\b"),
37
+ "ventilation": (r"\bventilat\w*\b", r"\blongitudinal\s+flow\b"),
38
+ "extraction": (r"\bextract\w*\b", r"\bexhaust\w*\b"),
39
+ "buoyancy": (r"\bbuoyan\w*\b", r"\bconvect\w*\b", r"\bplume\b"),
40
+ "ceiling_jet": (r"\bceiling\s+jet\b",),
41
+ "backlayering": (r"\bbacklayer\w*\b", r"\bupstream\s+smoke\b"),
42
+ "sensor": (r"\bsensor\w*\b", r"\bmeasurement\s+(?:fault|conflict)\b"),
43
+ "forecast": (r"\bforecast\w*\b", r"\bpredict\w*\b", r"\bextrapolat\w*\b"),
44
+ "threshold": (r"\bthreshold\b", r"\bcross(?:es|ed|ing)?\b"),
45
+ "risk": (r"\brisk\b", r"\bhazard\w*\b"),
46
+ "growth": (r"\bgrowth\b", r"\bdeveloped\b", r"\bexpan\w*\b", r"\bincreas\w*\b", r"\brise\b"),
47
+ "decay": (r"\bdecay\b", r"\bdecreas\w*\b", r"\bdeclin\w*\b", r"\bdissipat\w*\b"),
48
+ "continuity": (r"\bcontinuit\w*\b", r"\bconsistent\b", r"\bcoupl\w*\b"),
49
+ "anomaly": (r"\banomal\w*\b", r"\binconsistent\b", r"\bviolation\b", r"\bconflict\b"),
50
+ }
51
+
52
+
53
+ def load_jsonl(path: Path) -> list[dict]:
54
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
55
+
56
+
57
+ def balanced_object(text: str) -> str | None:
58
+ start = text.find("{")
59
+ while start >= 0:
60
+ depth = 0
61
+ quoted = False
62
+ escaped = False
63
+ for index in range(start, len(text)):
64
+ char = text[index]
65
+ if quoted:
66
+ if escaped:
67
+ escaped = False
68
+ elif char == "\\":
69
+ escaped = True
70
+ elif char == '"':
71
+ quoted = False
72
+ continue
73
+ if char == '"':
74
+ quoted = True
75
+ elif char == "{":
76
+ depth += 1
77
+ elif char == "}":
78
+ depth -= 1
79
+ if depth == 0:
80
+ return text[start:index + 1]
81
+ start = text.find("{", start + 1)
82
+ return None
83
+
84
+
85
+ def response_value(row: dict) -> Any:
86
+ for key in ("response", "parsed", "output", "answer", "content", "text", "raw_response"):
87
+ if key in row:
88
+ return row[key]
89
+ return row
90
+
91
+
92
+ def parse_object(value: Any) -> tuple[dict | None, bool]:
93
+ if isinstance(value, dict):
94
+ return value, True
95
+ if isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict):
96
+ return value[0], False
97
+ if not isinstance(value, str):
98
+ return None, False
99
+ text = value.strip()
100
+ direct = text
101
+ if text.startswith("```"):
102
+ direct = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.IGNORECASE)
103
+ try:
104
+ parsed = json.loads(direct)
105
+ return (parsed, text == direct) if isinstance(parsed, dict) else (None, False)
106
+ except json.JSONDecodeError:
107
+ candidate = balanced_object(text)
108
+ if candidate:
109
+ try:
110
+ parsed = json.loads(candidate)
111
+ return (parsed, False) if isinstance(parsed, dict) else (None, False)
112
+ except json.JSONDecodeError:
113
+ pass
114
+ return None, False
115
+
116
+
117
+ def flatten(value: Any, prefix: str = "") -> dict[str, Any]:
118
+ if not isinstance(value, dict):
119
+ return {prefix: value}
120
+ output = {}
121
+ for key, item in value.items():
122
+ path = f"{prefix}.{key}" if prefix else str(key)
123
+ output.update(flatten(item, path))
124
+ return output
125
+
126
+
127
+ def normalize_choices(value: Any) -> list[str] | None:
128
+ if isinstance(value, dict):
129
+ if "choices" in value:
130
+ return normalize_choices(value["choices"])
131
+ for key in ("choice", "selected_option", "answer", "label", "prediction"):
132
+ if key in value:
133
+ result = normalize_choices(value[key])
134
+ if result is not None:
135
+ return result
136
+ return None
137
+ if isinstance(value, list):
138
+ labels = []
139
+ for item in value:
140
+ if not isinstance(item, str) or not re.fullmatch(r"[A-Z]", item.strip(), re.IGNORECASE):
141
+ return None
142
+ labels.append(item.strip().upper())
143
+ return sorted(labels) if len(labels) == len(set(labels)) else None
144
+ if not isinstance(value, str):
145
+ return None
146
+ match = re.fullmatch(r"\s*([A-Z])\s*", value, re.IGNORECASE)
147
+ return [match.group(1).upper()] if match else None
148
+
149
+
150
+ def normalize_choice(value: Any) -> str | None:
151
+ """Legacy single-choice adapter retained for older analysis scripts."""
152
+ choices = normalize_choices(value)
153
+ return choices[0] if choices and len(choices) == 1 else None
154
+
155
+
156
+ def normalize_open(value: Any) -> tuple[dict | None, dict | None, bool]:
157
+ parsed, strict_json = parse_object(value)
158
+ if parsed is None:
159
+ return None, None, False
160
+ report = parsed
161
+ if "report" in parsed and isinstance(parsed["report"], dict):
162
+ report = parsed["report"]
163
+ strict_json = False
164
+ prediction = report.get("prediction")
165
+ if not isinstance(prediction, dict):
166
+ for key in ("answer", "result", "fields"):
167
+ if isinstance(report.get(key), dict):
168
+ prediction = report[key]
169
+ break
170
+ format_valid = (
171
+ strict_json and REQUIRED_OPEN_KEYS.issubset(report) and isinstance(report.get("prediction"), dict)
172
+ and isinstance(report.get("evidence"), list) and isinstance(report.get("mechanism"), (str, list, dict))
173
+ and isinstance(report.get("confidence"), (int, float)) and 0 <= float(report["confidence"]) <= 1
174
+ )
175
+ return prediction if isinstance(prediction, dict) else None, report, format_valid
176
+
177
+
178
+ def tokens(value: Any) -> Counter[str]:
179
+ if isinstance(value, dict):
180
+ value = " ".join(str(item) for item in value.values())
181
+ elif isinstance(value, list):
182
+ value = " ".join(str(item) for item in value)
183
+ text = str(value).lower().replace("kg/m3", "kg m3").replace("m/s", "mps")
184
+ text = re.sub(r"_(?:p10|p50|p90|p95|mean)\b", " ", text)
185
+ text = text.replace("_", " ").replace("-", " ")
186
+ text = NUMBER_PATTERN.sub(lambda match: f" num{float(match.group()):.2g} ", text)
187
+ normalized = []
188
+ for token in TOKEN_PATTERN.findall(text):
189
+ if token in STOP_WORDS:
190
+ continue
191
+ normalized.append(ALIASES.get(token, token))
192
+ return Counter(normalized)
193
+
194
+
195
+ def token_f1(a: Any, b: Any) -> float:
196
+ left, right = tokens(a), tokens(b)
197
+ if not left and not right:
198
+ return 1.0
199
+ if not left or not right:
200
+ return 0.0
201
+ overlap = sum((left & right).values())
202
+ precision = overlap / sum(left.values())
203
+ recall = overlap / sum(right.values())
204
+ return 2 * precision * recall / (precision + recall) if precision + recall else 0.0
205
+
206
+
207
+ def claim_list(value: Any) -> list[str]:
208
+ if value is None:
209
+ return []
210
+ if isinstance(value, str):
211
+ return [value]
212
+ if isinstance(value, dict):
213
+ if "observation" in value:
214
+ prefix = str(value.get("region", ""))
215
+ return [f"{prefix} {value['observation']}".strip()]
216
+ for key in ("statement", "observation", "claim", "text"):
217
+ if key in value:
218
+ return [str(value[key])]
219
+ return [json.dumps(value, sort_keys=True)]
220
+ if isinstance(value, list):
221
+ output = []
222
+ for item in value:
223
+ output.extend(claim_list(item))
224
+ return output
225
+ return [str(value)]
226
+
227
+
228
+ def claim_metrics(predicted: Any, gold: Any, threshold: float = 0.30) -> tuple[float, float, float, float]:
229
+ pred_claims, gold_claims = claim_list(predicted), claim_list(gold)
230
+ if not pred_claims and not gold_claims:
231
+ return 1.0, 1.0, 1.0, 0.0
232
+ if not pred_claims:
233
+ return 0.0, 0.0, 0.0, 0.0
234
+ if not gold_claims:
235
+ return 0.0, 0.0, 0.0, 1.0
236
+ scores = [[token_f1(pred, target) for target in gold_claims] for pred in pred_claims]
237
+ matched_pred = sum(max(row) >= threshold for row in scores)
238
+ matched_gold = sum(max(scores[p][g] for p in range(len(pred_claims))) >= threshold
239
+ for g in range(len(gold_claims)))
240
+ precision = matched_pred / len(pred_claims)
241
+ recall = matched_gold / len(gold_claims)
242
+ f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
243
+ hallucination = 1.0 - precision
244
+ return precision, recall, f1, hallucination
245
+
246
+
247
+ def physical_concepts(value: Any) -> set[str]:
248
+ text = " ".join(claim_list(value)).lower().replace("_", " ")
249
+ return {
250
+ concept
251
+ for concept, patterns in CONCEPT_PATTERNS.items()
252
+ if any(re.search(pattern, text) for pattern in patterns)
253
+ }
254
+
255
+
256
+ def concept_metrics(predicted: Any, gold: Any) -> tuple[float, float, float, float]:
257
+ predicted_concepts = physical_concepts(predicted)
258
+ gold_concepts = physical_concepts(gold)
259
+ if not predicted_concepts and not gold_concepts:
260
+ return 1.0, 1.0, 1.0, 0.0
261
+ if not predicted_concepts:
262
+ return 0.0, 0.0, 0.0, 0.0
263
+ if not gold_concepts:
264
+ return 0.0, 0.0, 0.0, 1.0
265
+ overlap = predicted_concepts & gold_concepts
266
+ precision = len(overlap) / len(predicted_concepts)
267
+ recall = len(overlap) / len(gold_concepts)
268
+ f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
269
+ return precision, recall, f1, 1.0 - precision
270
+
271
+
272
+ def numeric_values(value: Any) -> list[float]:
273
+ return [float(match.group()) for claim in claim_list(value) for match in NUMBER_PATTERN.finditer(claim)]
274
+
275
+
276
+ def numeric_grounding_metrics(predicted: Any, gold: Any) -> tuple[float, float, float, float]:
277
+ pred_values, gold_values = numeric_values(predicted), numeric_values(gold)
278
+ if not pred_values and not gold_values:
279
+ return 1.0, 1.0, 1.0, 0.0
280
+ if not pred_values:
281
+ return 0.0, 0.0, 0.0, 0.0
282
+ if not gold_values:
283
+ return 0.0, 0.0, 0.0, 0.0
284
+ available = set(range(len(gold_values)))
285
+ matched = 0
286
+ for predicted_value in pred_values:
287
+ candidates = []
288
+ for index in available:
289
+ expected = gold_values[index]
290
+ tolerance = (max(0.02, 0.05 * abs(expected)) if abs(expected) >= 0.1 else
291
+ max(1e-7, 0.10 * abs(expected)))
292
+ error = abs(predicted_value - expected)
293
+ if error <= tolerance:
294
+ candidates.append((error, index))
295
+ if candidates:
296
+ _, index = min(candidates)
297
+ available.remove(index)
298
+ matched += 1
299
+ precision = matched / len(pred_values)
300
+ recall = matched / len(gold_values)
301
+ f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
302
+ # Coverage measures whether required numeric slots were attempted, not whether
303
+ # extra numbers were emitted. Correctness remains isolated in P/R/F1.
304
+ coverage = min(len(pred_values), len(gold_values)) / len(gold_values)
305
+ return precision, recall, f1, coverage
306
+
307
+
308
+ def macro_f1(pairs: list[tuple[Any, Any]]) -> float:
309
+ labels = sorted({str(gold) for gold, _ in pairs} | {str(pred) for _, pred in pairs})
310
+ if not labels:
311
+ return 0.0
312
+ scores = []
313
+ for label in labels:
314
+ tp = sum(str(gold) == label and str(pred) == label for gold, pred in pairs)
315
+ fp = sum(str(gold) != label and str(pred) == label for gold, pred in pairs)
316
+ fn = sum(str(gold) == label and str(pred) != label for gold, pred in pairs)
317
+ precision = tp / (tp + fp) if tp + fp else 0.0
318
+ recall = tp / (tp + fn) if tp + fn else 0.0
319
+ scores.append(2 * precision * recall / (precision + recall) if precision + recall else 0.0)
320
+ return sum(scores) / len(scores)
321
+
322
+
323
+ # --- Slot-MacroF1 primitives (per-slot exact-match F1, macro-averaged over slots) ---
324
+ def dice(pred: Any, gold: Any) -> float:
325
+ """Sørensen–Dice on option sets (choice component, unchanged from prior definition)."""
326
+ ps, gs = set(pred or []), set(gold)
327
+ if not ps and not gs:
328
+ return 1.0
329
+ if not ps or not gs:
330
+ return 0.0
331
+ return 2 * len(ps & gs) / (len(ps) + len(gs))
332
+
333
+
334
+ def slot_norm(v: Any) -> str:
335
+ return re.sub(r"[^a-z0-9]+", " ", str(v).lower()).strip()
336
+
337
+
338
+ def slot_f1(pairs: list[tuple[Any, Any]]) -> float:
339
+ """Per-slot exact-match F1 = 2TP/(2TP+FP+FN). pairs = list[(gold, pred_or_None)]."""
340
+ tp = fp = fn = 0
341
+ for e, p in pairs:
342
+ if p is None:
343
+ fn += 1
344
+ elif slot_norm(e) == slot_norm(p):
345
+ tp += 1
346
+ else:
347
+ fp += 1
348
+ denom = 2 * tp + fp + fn
349
+ return 2 * tp / denom if denom else 0.0
350
+
351
+
352
+ def slot_macro_f1(field_pairs: dict[str, list]) -> float:
353
+ """Macro-average per-slot exact-match F1 over fields. field_pairs = {field: [(gold,pred)]}."""
354
+ if not field_pairs:
355
+ return 0.0
356
+ vals = [slot_f1(ps) for ps in field_pairs.values()]
357
+ return sum(vals) / len(vals) if vals else 0.0
358
+
359
+
360
+ def combine(choice_macro: float, open_slot_macro: float, has_c: bool, has_o: bool) -> float:
361
+ if has_c and has_o:
362
+ return (choice_macro + open_slot_macro) / 2
363
+ if has_c:
364
+ return choice_macro
365
+ if has_o:
366
+ return open_slot_macro
367
+ return 0.0
368
+
369
+
370
+ def ece(rows: list[tuple[float, float]], bins: int = 10) -> float | None:
371
+ if not rows:
372
+ return None
373
+ total = len(rows)
374
+ value = 0.0
375
+ for index in range(bins):
376
+ low, high = index / bins, (index + 1) / bins
377
+ bucket = [(confidence, correct) for confidence, correct in rows
378
+ if low <= confidence < high or index == bins - 1 and confidence == 1.0]
379
+ if bucket:
380
+ value += len(bucket) / total * abs(
381
+ sum(confidence for confidence, _ in bucket) / len(bucket) -
382
+ sum(correct for _, correct in bucket) / len(bucket)
383
+ )
384
+ return value
385
+
386
+
387
+ def wilson_interval(successes: int, total: int, z: float = 1.959963984540054) -> tuple[float, float]:
388
+ """Return the two-sided 95% Wilson interval for a binomial proportion."""
389
+ if total <= 0:
390
+ return 0.0, 0.0
391
+ proportion = successes / total
392
+ denominator = 1.0 + z * z / total
393
+ centre = (proportion + z * z / (2.0 * total)) / denominator
394
+ margin = z * math.sqrt(
395
+ proportion * (1.0 - proportion) / total + z * z / (4.0 * total * total)
396
+ ) / denominator
397
+ return max(0.0, centre - margin), min(1.0, centre + margin)
398
+
399
+
400
+ def aggregate(scored: list[dict], key_fields: tuple[str, ...]) -> list[dict]:
401
+ groups: dict[tuple, list[dict]] = defaultdict(list)
402
+ for row in scored:
403
+ groups[tuple(row.get(key) for key in key_fields)].append(row)
404
+ reports = []
405
+ for key, rows in sorted(groups.items(), key=lambda item: tuple(str(value) for value in item[0])):
406
+ field_pairs: dict[str, list[tuple[Any, Any]]] = defaultdict(list)
407
+ for row in rows:
408
+ for field, pair in row["field_pairs"].items():
409
+ field_pairs[field].append(tuple(pair))
410
+ component = {
411
+ field: {
412
+ "accuracy": sum(gold == pred for gold, pred in pairs) / len(pairs),
413
+ "macro_f1": macro_f1(pairs),
414
+ "gold_label_counts": dict(sorted(Counter(str(gold) for gold, _ in pairs).items())),
415
+ "predicted_label_counts": dict(sorted(Counter(
416
+ "<missing>" if pred is None else str(pred) for _, pred in pairs
417
+ ).items())),
418
+ "confusion_counts": dict(sorted(Counter(
419
+ f"{gold} -> {'<missing>' if pred is None else pred}" for gold, pred in pairs
420
+ ).items())),
421
+ }
422
+ for field, pairs in sorted(field_pairs.items())
423
+ }
424
+ joint_successes = sum(row["joint_correct"] for row in rows)
425
+ joint_ci_low, joint_ci_high = wilson_interval(int(joint_successes), len(rows))
426
+ field_correct = sum(
427
+ expected == actual
428
+ for row in rows for expected, actual in row["field_pairs"].values()
429
+ )
430
+ field_total = sum(len(row["field_pairs"]) for row in rows)
431
+ field_micro_accuracy = field_correct / field_total if field_total else 0.0
432
+ nonlinear_partial_credit = sum(row["completion_ratio"] ** 3.5 for row in rows) / len(rows)
433
+ completion_micro_accuracy = sum(row["completion_ratio"] for row in rows) / len(rows)
434
+ partial_credit_by_exponent = {
435
+ str(exponent): sum(row["completion_ratio"] ** exponent for row in rows) / len(rows)
436
+ for exponent in (1.5, 2.0, 2.5, 3.0, 3.25, 3.5)
437
+ }
438
+ component_macro_f1 = (
439
+ sum(metrics["macro_f1"] for metrics in component.values()) / len(component)
440
+ if component else 0.0
441
+ )
442
+ calibration = [(row["confidence"], row["joint_correct"]) for row in rows if row["confidence"] is not None]
443
+ reports.append({
444
+ **dict(zip(key_fields, key)),
445
+ "count": len(rows),
446
+ "response_rate": sum(row["responded"] for row in rows) / len(rows),
447
+ "format_valid_rate": sum(row["format_valid"] for row in rows) / len(rows),
448
+ "joint_accuracy": joint_successes / len(rows),
449
+ "joint_accuracy_wilson_95": [joint_ci_low, joint_ci_high],
450
+ "field_correct": field_correct,
451
+ "field_total": field_total,
452
+ "field_micro_accuracy": field_micro_accuracy,
453
+ "completion_micro_accuracy": completion_micro_accuracy,
454
+ "nonlinear_partial_credit": nonlinear_partial_credit,
455
+ "nonlinear_partial_credit_exponent": 3.5,
456
+ "quadratic_partial_credit": partial_credit_by_exponent["2.0"],
457
+ "partial_credit_by_exponent": partial_credit_by_exponent,
458
+ "component_macro_f1": component_macro_f1,
459
+ "component_metrics": component,
460
+ "evidence_precision": sum(row["evidence_precision"] for row in rows) / len(rows),
461
+ "evidence_recall": sum(row["evidence_recall"] for row in rows) / len(rows),
462
+ "evidence_f1": sum(row["evidence_f1"] for row in rows) / len(rows),
463
+ "mechanism_f1": sum(row["mechanism_f1"] for row in rows) / len(rows),
464
+ "evidence_lexical_f1": sum(row["evidence_lexical_f1"] for row in rows) / len(rows),
465
+ "mechanism_lexical_f1": sum(row["mechanism_lexical_f1"] for row in rows) / len(rows),
466
+ "hallucination_rate": sum(row["hallucination_rate"] for row in rows) / len(rows),
467
+ "numeric_grounding_precision": sum(row["numeric_grounding_precision"] for row in rows) / len(rows),
468
+ "numeric_grounding_recall": sum(row["numeric_grounding_recall"] for row in rows) / len(rows),
469
+ "numeric_grounding_f1": sum(row["numeric_grounding_f1"] for row in rows) / len(rows),
470
+ "numeric_evidence_coverage": sum(row["numeric_evidence_coverage"] for row in rows) / len(rows),
471
+ "confidence_coverage": len(calibration) / len(rows),
472
+ "brier": (sum((confidence - correct) ** 2 for confidence, correct in calibration) / len(calibration)
473
+ if calibration else None),
474
+ "ece_10": ece(calibration),
475
+ })
476
+ return reports
477
+
478
+
479
+ def main() -> None:
480
+ parser = argparse.ArgumentParser()
481
+ parser.add_argument("--gold", type=Path, required=True)
482
+ parser.add_argument("--predictions", type=Path, nargs="+", required=True)
483
+ parser.add_argument("--output", type=Path, required=True)
484
+ args = parser.parse_args()
485
+ gold_rows = load_jsonl(args.gold)
486
+ prediction_rows = [row for path in args.predictions for row in load_jsonl(path)]
487
+ predictions = {}
488
+ for row in prediction_rows:
489
+ qa_id = row.get("qa_id")
490
+ if not qa_id:
491
+ continue
492
+ previous = predictions.get(qa_id)
493
+ if previous is None or (previous.get("status") != "ok" and row.get("status") == "ok"):
494
+ predictions[qa_id] = row
495
+ scored = []
496
+ for gold in gold_rows:
497
+ record = predictions.get(gold["qa_id"])
498
+ record_ok = record is not None and record.get("status") == "ok"
499
+ value = response_value(record) if record_ok else None
500
+ confidence = None
501
+ format_valid = False
502
+ if gold["question_type"] == "choice":
503
+ predicted_choices = normalize_choices(value)
504
+ parsed_choice, _ = parse_object(value)
505
+ if parsed_choice and isinstance(parsed_choice.get("confidence"), (int, float)):
506
+ raw_confidence = float(parsed_choice["confidence"])
507
+ if 0 <= raw_confidence <= 1:
508
+ confidence = raw_confidence
509
+ expected = gold.get("correct_options")
510
+ if expected is None:
511
+ expected = [gold["correct_option"]]
512
+ expected_choices = sorted(expected)
513
+ expected_set = set(expected_choices)
514
+ predicted_set = set(predicted_choices or [])
515
+ choice_union = expected_set | predicted_set
516
+ completion_ratio = (len(expected_set & predicted_set) / len(choice_union)
517
+ if choice_union else 0.0)
518
+ field_pairs = {"choice_exact_set": (
519
+ ",".join(expected_choices),
520
+ ",".join(predicted_choices) if predicted_choices is not None else None,
521
+ )}
522
+ joint_correct = float(predicted_choices == expected_choices)
523
+ format_valid = predicted_choices is not None
524
+ evidence_p = evidence_r = evidence_score = mechanism_score = hallucination = 0.0
525
+ evidence_lexical = mechanism_lexical = 0.0
526
+ numeric_p = numeric_r = numeric_score = numeric_coverage = 0.0
527
+ else:
528
+ predicted, report, format_valid = normalize_open(value)
529
+ gold_flat = flatten(gold["prediction"])
530
+ predicted_flat = flatten(predicted or {})
531
+ field_pairs = {field: (expected, predicted_flat.get(field)) for field, expected in gold_flat.items()}
532
+ joint_correct = float(bool(field_pairs) and all(expected == actual for expected, actual in field_pairs.values()))
533
+ completion_ratio = (sum(expected == actual for expected, actual in field_pairs.values()) /
534
+ len(field_pairs) if field_pairs else 0.0)
535
+ if report:
536
+ raw_confidence = report.get("confidence")
537
+ if isinstance(raw_confidence, (int, float)) and 0 <= float(raw_confidence) <= 1:
538
+ confidence = float(raw_confidence)
539
+ _, _, evidence_lexical, _ = claim_metrics(
540
+ report.get("evidence"), gold.get("evidence_claims", []))
541
+ _, _, mechanism_lexical, _ = claim_metrics(
542
+ report.get("mechanism"), gold.get("mechanism_claims", []))
543
+ evidence_p, evidence_r, evidence_score, evidence_h = concept_metrics(
544
+ report.get("evidence"), gold.get("evidence_claims", []))
545
+ _, _, mechanism_score, mechanism_h = concept_metrics(
546
+ report.get("mechanism"), gold.get("mechanism_claims", []))
547
+ hallucination = (evidence_h + mechanism_h) / 2
548
+ numeric_p, numeric_r, numeric_score, numeric_coverage = numeric_grounding_metrics(
549
+ report.get("evidence"), gold.get("evidence_claims", []))
550
+ else:
551
+ evidence_p = evidence_r = evidence_score = mechanism_score = 0.0
552
+ evidence_lexical = mechanism_lexical = 0.0
553
+ hallucination = 0.0
554
+ numeric_p = numeric_r = numeric_score = numeric_coverage = 0.0
555
+ provenance = gold.get("provenance", {})
556
+ scored.append({
557
+ "qa_id": gold["qa_id"], "task": gold["task"], "track": gold["track"],
558
+ "subtrack": gold["subtrack"], "question_type": gold["question_type"],
559
+ "state_family": provenance.get("state_family"), "archetype": provenance.get("archetype"),
560
+ "responded": record_ok, "format_valid": format_valid,
561
+ "joint_correct": joint_correct, "field_pairs": field_pairs,
562
+ "completion_ratio": completion_ratio,
563
+ "evidence_precision": evidence_p, "evidence_recall": evidence_r, "evidence_f1": evidence_score,
564
+ "mechanism_f1": mechanism_score, "hallucination_rate": hallucination,
565
+ "evidence_lexical_f1": evidence_lexical, "mechanism_lexical_f1": mechanism_lexical,
566
+ "numeric_grounding_precision": numeric_p, "numeric_grounding_recall": numeric_r,
567
+ "numeric_grounding_f1": numeric_score, "numeric_evidence_coverage": numeric_coverage,
568
+ "confidence": confidence,
569
+ })
570
+ report = {
571
+ "schema_version": "FWB-FG9-SCORE-v2-exact-set-full-open",
572
+ "gold_count": len(gold_rows), "prediction_record_count": len(prediction_rows),
573
+ "prediction_file_count": len(args.predictions),
574
+ "prediction_status_counts": dict(sorted(Counter(row.get("status", "missing") for row in prediction_rows).items())),
575
+ "matched_prediction_count": sum(row["responded"] for row in scored),
576
+ "overall": aggregate(scored, ("question_type",)),
577
+ "by_track_type": aggregate(scored, ("track", "question_type")),
578
+ "by_task_track_type": aggregate(scored, ("task", "track", "question_type")),
579
+ "by_subtrack_type": aggregate(scored, ("subtrack", "question_type")),
580
+ "by_state_type": aggregate(scored, ("state_family", "question_type")),
581
+ "by_archetype_type": aggregate(scored, ("archetype", "question_type")),
582
+ "notes": {
583
+ "core": "Joint and component label metrics include missing/malformed outputs as incorrect.",
584
+ "primary_metrics": "All question types use nonlinear_partial_credit = mean(completion_ratio^3.5). Open completion_ratio is correct_required_fields/requested_fields. Choice completion_ratio is Jaccard similarity between predicted and gold selected-option sets. Exact-set/JEM, linear completion, and component_macro_f1 remain mandatory audit metrics.",
585
+ "partial_credit": "The global exponent 3.5 is fixed for every item, dataset, cell, question type, and model. Choice Jaccard penalizes both omissions and extra selections without rewarding true-negative unselected options. The score is deterministic and contains no per-cell or model-specific tuning.",
586
+ "interval": "joint_accuracy_wilson_95 is the two-sided 95% Wilson interval for choice Accuracy or open JEM.",
587
+ "format": "format_valid_rate is reported separately and never replaces ability metrics.",
588
+ "evidence": "Evidence/mechanism F1 use a frozen physical-concept ontology; lexical F1 is also retained as a surface-form diagnostic.",
589
+ "numeric": "Numeric grounding separately checks cited values against gold physical observations.",
590
+ "judge": "LLM-judge scoring is optional and excluded from the primary leaderboard.",
591
+ },
592
+ }
593
+ args.output.parent.mkdir(parents=True, exist_ok=True)
594
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
595
+ print(json.dumps({"gold_count": report["gold_count"], "matched": report["matched_prediction_count"],
596
+ "overall": report["overall"]}, indent=2))
597
+
598
+
599
+ if __name__ == "__main__":
600
+ main()
evaluation/FireWorldBench-ICLR/scripts/score_six_metrics.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compute the six FireWorldBench leaderboard metrics without an LLM judge."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import importlib.util
7
+ import json
8
+ import re
9
+ from collections import defaultdict
10
+ from pathlib import Path
11
+
12
+
13
+ def load_jsonl(path: Path):
14
+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
15
+
16
+
17
+ def gold_linked_items(gold_rows, prediction_rows, support_scorer):
18
+ predictions = {}
19
+ for row in prediction_rows:
20
+ if row.get("qa_id") and (row["qa_id"] not in predictions or row.get("status") == "ok"):
21
+ predictions[row["qa_id"]] = row
22
+ output = []
23
+ for gold in gold_rows:
24
+ record = predictions.get(gold["qa_id"], {})
25
+ response = record.get("response") if record.get("status") == "ok" and isinstance(record.get("response"), dict) else {}
26
+ predicted = response.get("prediction") if isinstance(response.get("prediction"), dict) else {}
27
+ predicted_flat = dict(support_scorer.flatten(predicted))
28
+ expected_flat = dict(support_scorer.flatten(gold.get("prediction", {})))
29
+ explanation = support_scorer.text([response.get("evidence", []), response.get("mechanism", ""), response.get("conclusion", "")])
30
+ anchors = support_scorer.text([gold.get("evidence_claims", []), gold.get("mechanism_claims", [])])
31
+ scores = []
32
+ for path, expected in expected_flat.items():
33
+ correct = path in predicted_flat and support_scorer.equivalent(predicted_flat[path], expected)
34
+ scores.append(float(correct and support_scorer.field_supported(path, expected, explanation, anchors)))
35
+ output.append({"qa_id": gold["qa_id"], "task": gold["task"], "track": gold["track"],
36
+ "question_type": gold["question_type"],
37
+ "gold_linked_support": sum(scores) / len(scores) if scores else 0.0})
38
+ return output
39
+
40
+
41
+ BIN_MAP = {"none": "none", "early": "present", "middle": "present", "late": "present", "present": "present"}
42
+
43
+
44
+ def coarsen_l13(pred):
45
+ """L1-3 open: collapse first_violation_bin to {none, present}; lowercase violation_type."""
46
+ if not isinstance(pred, dict):
47
+ return pred
48
+ out = dict(pred)
49
+ if "first_violation_bin" in out:
50
+ out["first_violation_bin"] = BIN_MAP.get(str(out["first_violation_bin"]).lower(),
51
+ str(out["first_violation_bin"]).lower())
52
+ if "violation_type" in out:
53
+ out["violation_type"] = str(out["violation_type"]).lower()
54
+ return out
55
+
56
+
57
+ def layer_label(row, group_by):
58
+ """Return the cell label for a row under the requested grouping."""
59
+ if group_by == "physical":
60
+ return row.get("physical_axis") or row.get("task")
61
+ if group_by == "fire":
62
+ return row.get("fire_axis") or row.get("task")
63
+ return row.get("task")
64
+
65
+
66
+ def key(row, group_by="task"):
67
+ return (layer_label(row, group_by), row.get("track"), row.get("question_type"))
68
+
69
+
70
+ def main():
71
+ parser = argparse.ArgumentParser(description=__doc__)
72
+ parser.add_argument("--gold", type=Path, required=True)
73
+ parser.add_argument("--predictions", type=Path, nargs="+", required=True)
74
+ parser.add_argument("--output", type=Path, required=True)
75
+ parser.add_argument("--group-by", choices=("task", "physical", "fire"), default="physical",
76
+ help="group cells by the five-layer physical axis (physical -> P1-P5, 20 cells, default), "
77
+ "fire axis (fire -> T1-T3) or fine-grained task (9 tasks). "
78
+ "Requires gold rows carrying physical_axis / fire_axis labels.")
79
+ args = parser.parse_args()
80
+ package = Path(__file__).resolve().parent
81
+ spec = importlib.util.spec_from_file_location("fwb_base_scorer", package / "score_fg9_predictions.py")
82
+ scorer = importlib.util.module_from_spec(spec); spec.loader.exec_module(scorer)
83
+ support_spec = importlib.util.spec_from_file_location("fwb_support_scorer", package / "score_fg9_gold_linked_support.py")
84
+ support_scorer = importlib.util.module_from_spec(support_spec); support_spec.loader.exec_module(support_scorer)
85
+ deep_spec = importlib.util.spec_from_file_location("fwb_deep_scorer", package / "score_fg9_deep_metrics_by_cell.py")
86
+ deep_scorer = importlib.util.module_from_spec(deep_spec); deep_spec.loader.exec_module(deep_scorer)
87
+ gold_rows = load_jsonl(args.gold)
88
+ prediction_rows = [row for path in args.predictions for row in load_jsonl(path)]
89
+ prediction_map = {}
90
+ for row in prediction_rows:
91
+ if row.get("qa_id") and (row["qa_id"] not in prediction_map or row.get("status") == "ok"):
92
+ prediction_map[row["qa_id"]] = row
93
+ # Reuse the frozen public scorer by invoking its normalization/metric primitives.
94
+ scored = []
95
+ for gold in gold_rows:
96
+ record = prediction_map.get(gold["qa_id"]); ok = record is not None and record.get("status") == "ok"
97
+ value = scorer.response_value(record) if ok else None
98
+ confidence = None
99
+ if gold["question_type"] == "choice":
100
+ pred = scorer.normalize_choices(value); expected = sorted(gold.get("correct_options", [gold.get("correct_option")]))
101
+ union = set(pred or []) | set(expected); ratio = len(set(pred or []) & set(expected)) / len(union) if union else 0
102
+ pairs = {"choice_exact_set": (",".join(expected), ",".join(pred) if pred is not None else None)}
103
+ parsed, _ = scorer.parse_object(value)
104
+ if parsed and isinstance(parsed.get("confidence"), (int, float)): confidence = float(parsed["confidence"])
105
+ ef1 = mf1 = 0.0
106
+ cd = scorer.dice(pred, expected)
107
+ else:
108
+ pred, report, _ = scorer.normalize_open(value)
109
+ if gold.get("task") == "L1-3":
110
+ pred = coarsen_l13(pred)
111
+ gf, pf = scorer.flatten(gold["prediction"]), scorer.flatten(pred or {})
112
+ pairs = {field: (expected, pf.get(field)) for field, expected in gf.items()}; ratio = sum(a == b for a,b in pairs.values()) / len(pairs)
113
+ if report:
114
+ confidence = float(report["confidence"]) if isinstance(report.get("confidence"), (int,float)) else None
115
+ free=deep_scorer.text([report.get("conclusion",""),report.get("evidence",[]),report.get("mechanism","")]); ft=deep_scorer.toks(free)
116
+ anchors=[]
117
+ for claim in gold.get("evidence_claims") or []:
118
+ observation=(claim.get("observation") or "").lower()
119
+ variable=next((v for v in deep_scorer.VARS if v in observation),None)
120
+ anchors.append((str(claim.get("region","")).lower(),variable))
121
+ recall=sum(((region in free)+(variable in free if variable else 0))/(2 if variable else 1) for region,variable in anchors)/max(1,len(anchors))
122
+ claims=set(value.lower() for value in re.findall(r"\bR\d+\b",free,re.I))|(ft&deep_scorer.VARS)
123
+ anchored={value for anchor in anchors for value in anchor if value}
124
+ precision=len(claims&anchored)/len(claims) if claims else 0
125
+ ef1=2*precision*recall/(precision+recall) if precision+recall else 0
126
+ gold_tokens=deep_scorer.toks(" ".join(c.get("statement","") for c in gold.get("mechanism_claims") or []))-{"the","and","with","that","this","from","into","first"}
127
+ mechanism_tokens=deep_scorer.toks(deep_scorer.text(report.get("mechanism","")))
128
+ mf1=len(gold_tokens&mechanism_tokens)/len(gold_tokens) if gold_tokens else 0
129
+ else: ef1 = mf1 = 0.0
130
+ cd = None
131
+ scored.append({"task":gold["task"],"physical_axis":gold.get("physical_axis"),"fire_axis":gold.get("fire_axis"),
132
+ "track":gold["track"],"question_type":gold["question_type"],"pairs":pairs,"ratio":ratio,
133
+ "confidence":confidence,"correct":float(ratio==1),"evidence_f1":ef1,"mechanism_alignment":mf1,
134
+ "choice_dice":cd})
135
+ gls = {row["qa_id"]:row["gold_linked_support"] for row in gold_linked_items(gold_rows,prediction_rows,support_scorer)}
136
+ for row,gold in zip(scored,gold_rows): row["gold_linked_support"] = gls[gold["qa_id"]]
137
+ groups=defaultdict(list)
138
+ for row in scored: groups[key(row, args.group_by)].append(row)
139
+ def summarize(rows):
140
+ fp=defaultdict(list)
141
+ for row in rows:
142
+ for field,pair in row["pairs"].items(): fp[field].append(pair)
143
+ calibration=[(r["confidence"],r["correct"]) for r in rows if r["confidence"] is not None and 0<=r["confidence"]<=1]
144
+ open_rows=[r for r in rows if r["question_type"]=="open"]
145
+ choice_rows=[r for r in rows if r["question_type"]=="choice"]
146
+ open_fp=defaultdict(list)
147
+ for row in open_rows:
148
+ for field,pair in row["pairs"].items(): open_fp[field].append(pair)
149
+ c_dice=[r["choice_dice"] for r in choice_rows]
150
+ choice_macro=sum(c_dice)/len(c_dice) if c_dice else 0.0
151
+ open_slot_macro=scorer.slot_macro_f1(open_fp)
152
+ macro_f1=scorer.combine(choice_macro, open_slot_macro, bool(choice_rows), bool(open_rows))
153
+ return {"n":len(rows),"completion_accuracy":sum(r["ratio"] for r in rows)/len(rows),
154
+ "macro_f1":macro_f1,
155
+ "evidence_f1":sum(r["evidence_f1"] for r in open_rows)/len(open_rows) if open_rows else None,
156
+ "mechanism_alignment":sum(r["mechanism_alignment"] for r in open_rows)/len(open_rows) if open_rows else None,
157
+ "brier_score":sum((c-y)**2 for c,y in calibration)/len(calibration) if calibration else None,
158
+ "gold_linked_support":sum(r["gold_linked_support"] for r in open_rows)/len(open_rows) if open_rows else None}
159
+ if args.group_by == "task":
160
+ cells = [{"task": k[0], "track": k[1], "question_type": k[2], **summarize(v)} for k, v in sorted(groups.items())]
161
+ cells_key = "by_task_track_type"
162
+ else:
163
+ cells = [{"label": k[0], "track": k[1], "question_type": k[2], **summarize(v)} for k, v in sorted(groups.items())]
164
+ cells_key = "by_cell"
165
+ result={"schema_version":"FWB-FG9-SIX-METRICS-v2-ACC","metrics":["completion_accuracy","macro_f1","evidence_f1","mechanism_alignment","brier_score","gold_linked_support"],
166
+ "grouping": args.group_by,
167
+ "overall":summarize(scored),cells_key:cells,
168
+ "notes":{"direction":"Higher is better except Brier Score, where lower is better.","scope":"Completion Accuracy, Macro-F1 and Brier apply to choice and open. Evidence-F1, Mechanism Alignment and Gold-linked Support apply to open responses only.","completion_accuracy":"For choice, mean Jaccard similarity between predicted and Gold option sets. For open, mean fraction of required fields predicted correctly.","judge":"All six metrics are deterministic; no model judge is used."}}
169
+ args.output.parent.mkdir(parents=True,exist_ok=True); args.output.write_text(json.dumps(result,ensure_ascii=False,indent=2)+"\n",encoding="utf-8")
170
+ print(json.dumps(result["overall"],ensure_ascii=False,indent=2))
171
+
172
+ if __name__ == "__main__": main()
evaluation/FireWorldBench-ICLR/setup.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # Unless required by applicable law or agreed to in writing, software
6
+ # distributed under the License is distributed on an "AS IS" BASIS,
7
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8
+ # See the License for the specific language governing permissions and
9
+ # limitations under the License.
10
+
11
+ from setuptools import setup
12
+
13
+ setup(
14
+ name="fireworldbench",
15
+ version="0.1.0",
16
+ description="FireWorldBench: a multimodal benchmark for fire-physics world understanding",
17
+ long_description=open("README.md", encoding="utf8").read(),
18
+ long_description_content_type="text/markdown",
19
+ classifiers=[
20
+ "Intended Audience :: Science/Research",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: Apache Software License",
24
+ "Operating System :: OS Independent",
25
+ ],
26
+ python_requires=">=3.8",
27
+ install_requires=["requests>=2.31"],
28
+ )
main_synthetic/assets/{events/FWBFR-546B1539D42C5585/smoke3d/birdseye/volume_birdseye_t060.png → final_optimized/FWBFG9-00646A8DF42ADA88C2/soot_density_t30.png} RENAMED
File without changes
main_synthetic/assets/final_optimized/FWBFG9-05E56EC571CF510027/soot_density_t10.png ADDED

Git LFS Details

  • SHA256: 9c4058f9d7de4594ea8302bbade31c9d1da15a546af0dad5ed29c6baecb49f6d
  • Pointer size: 131 Bytes
  • Size of remote file: 142 kB
main_synthetic/assets/final_optimized/FWBFG9-05E56EC571CF510027/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: 79919da900c3a83931fc3bc34a4f73506e723b9d1787fc74ce28a385385a85d1
  • Pointer size: 131 Bytes
  • Size of remote file: 106 kB
main_synthetic/assets/final_optimized/FWBFG9-0EF2817BEC74364FEB/temperature_t60.png ADDED

Git LFS Details

  • SHA256: 41a564e3ceabadba34575a22313a6680f3e683c9173688349c781bb832b59863
  • Pointer size: 131 Bytes
  • Size of remote file: 131 kB
main_synthetic/assets/final_optimized/FWBFG9-11D1296B6CB31957A8/temperature_t60.png ADDED

Git LFS Details

  • SHA256: a5d1e14737fb016ec04099c0a8e09215ca8f168c0f75c6dfd57b01731bebc3ba
  • Pointer size: 131 Bytes
  • Size of remote file: 108 kB
main_synthetic/assets/final_optimized/FWBFG9-17F3B1D1D364EA3150/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: c5c1cbe0c8e919adb0cad36350d4d7e15bdb17aad50cc70aca4ed6c1739b8a15
  • Pointer size: 131 Bytes
  • Size of remote file: 135 kB
main_synthetic/assets/final_optimized/FWBFG9-260BA18DDE41A73818/temperature_t60.png ADDED

Git LFS Details

  • SHA256: 7103a8aeb41e318e4f93843bbde6a394121a90ff409fc0f4761f31d2529a7605
  • Pointer size: 131 Bytes
  • Size of remote file: 131 kB
main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t010.png → final_optimized/FWBFG9-2877A6954E7C9CF5C3/soot_density_t30.png} RENAMED
File without changes
main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t030.png → final_optimized/FWBFG9-2877A6954E7C9CF5C3/soot_density_t60.png} RENAMED
File without changes
main_synthetic/assets/final_optimized/FWBFG9-357CF5649A3B863AB4/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: a224ff20637fbb0e5340a13265825dcc63049595bad1612c210ec8dec77d95be
  • Pointer size: 131 Bytes
  • Size of remote file: 209 kB
main_synthetic/assets/{i50/FWBFR-0F21B5E03A63EEC3/temperature/temperature_t060.png → final_optimized/FWBFG9-375A6BB14314EB280B/soot_density_t10.png} RENAMED
File without changes
main_synthetic/assets/final_optimized/FWBFG9-375A6BB14314EB280B/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: 2b1e44254716aa0f702f18db022ef9aa5807f07ec99bd9ccce945e00f1613e97
  • Pointer size: 131 Bytes
  • Size of remote file: 110 kB
main_synthetic/assets/final_optimized/FWBFG9-3CCFD86F74E3A9D08E/soot_density_t60.png ADDED

Git LFS Details

  • SHA256: ff309f9ff9b77dc1ea359088cd8fcd739cd38edd8a0c0e00d6e8f512791a861a
  • Pointer size: 131 Bytes
  • Size of remote file: 113 kB
main_synthetic/assets/final_optimized/FWBFG9-3F4B407538BE87D948/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: d0dbde917ecbf1e0e238af5897cc733e9f391a7964b66ffdac363a4b63a177a2
  • Pointer size: 131 Bytes
  • Size of remote file: 223 kB
main_synthetic/assets/final_optimized/FWBFG9-3F4B407538BE87D948/soot_density_t60.png ADDED

Git LFS Details

  • SHA256: cca27c9767a0ae2fb18e481165389e4a2dd31297170ca4badd0d222694339b0e
  • Pointer size: 131 Bytes
  • Size of remote file: 172 kB
main_synthetic/assets/final_optimized/FWBFG9-451C773FBA9C30D53D/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: b26f35eba0a05b8f8ca4d0bc31a90f43a3b22e927b72dcbb64bdc4194fe4a9e7
  • Pointer size: 131 Bytes
  • Size of remote file: 116 kB
main_synthetic/assets/final_optimized/FWBFG9-4643D810275BF3A05C/soot_density_t60.png ADDED

Git LFS Details

  • SHA256: 0c2824d27a0517bdc3f626707e5969eb180414f4710eb4a7975a1dd45fcfdeb3
  • Pointer size: 131 Bytes
  • Size of remote file: 104 kB
main_synthetic/assets/final_optimized/FWBFG9-4AEBACEF01C0DC6826/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: d832e01aebbd831c8c029a12e55674b31e0dc5b3c2910b561de507bd4505a3cb
  • Pointer size: 131 Bytes
  • Size of remote file: 194 kB
main_synthetic/assets/final_optimized/FWBFG9-4AEBACEF01C0DC6826/soot_density_t60.png ADDED

Git LFS Details

  • SHA256: 15ba87cc1eff830185cb444073e2dc57c9aeb60f55ef76090ae5255ba2dac0b5
  • Pointer size: 131 Bytes
  • Size of remote file: 180 kB
main_synthetic/assets/final_optimized/FWBFG9-4EBBF51A2588AEACD3/temperature_t60.png ADDED

Git LFS Details

  • SHA256: e11c3c2e96c63c8b4d55cb083aa5e2486d0af63a0f430921812d93dc520e42a8
  • Pointer size: 130 Bytes
  • Size of remote file: 89 kB
main_synthetic/assets/final_optimized/FWBFG9-54BD966E1831DFD38C/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: 48e698e8bc553076b584a297865ea9f0d56b84f4fdcb5ceb2ef77a7dab3a6948
  • Pointer size: 131 Bytes
  • Size of remote file: 152 kB
main_synthetic/assets/final_optimized/FWBFG9-56757B303A98C6E550/soot_density_t30.png ADDED

Git LFS Details

  • SHA256: a4fed5e31907390f1ef52bc5df2ef221dcec7a609e3a452c87d429d893475135
  • Pointer size: 131 Bytes
  • Size of remote file: 156 kB
main_synthetic/assets/final_optimized/FWBFG9-56757B303A98C6E550/soot_density_t60.png ADDED

Git LFS Details

  • SHA256: 6045986d52acfc3d99ae7c2fb91b5205ce85f2f68f3538e3b345eab0717a4fea
  • Pointer size: 131 Bytes
  • Size of remote file: 153 kB