Eurus132 commited on
Commit
e5dc06b
·
verified ·
1 Parent(s): eb95d13

Simplify layout and add bilingual ExtFoamBench introduction

Browse files

Highlight ExtFoamBench tasks, geometry assets and evaluation metrics. Bundle optional tools and consolidate documentation. Scientific data and scoring implementation remain unchanged.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. GUIDE.md +71 -0
  2. LICENSE.md +12 -12
  3. README.md +29 -98
  4. README_zh.md +60 -0
  5. SHA256SUMS +10 -73
  6. VERSION +1 -1
  7. benchmarks/__init__.py +0 -1
  8. benchmarks/evaluation/README.md +0 -12
  9. benchmarks/evaluation/__init__.py +0 -31
  10. benchmarks/evaluation/__main__.py +0 -10
  11. benchmarks/evaluation/adapters/__init__.py +0 -22
  12. benchmarks/evaluation/adapters/chatcfd.py +0 -85
  13. benchmarks/evaluation/adapters/coding_agent.py +0 -48
  14. benchmarks/evaluation/adapters/common.py +0 -71
  15. benchmarks/evaluation/adapters/easyfoam.py +0 -108
  16. benchmarks/evaluation/adapters/foamagent.py +0 -57
  17. benchmarks/evaluation/aggregate.py +0 -100
  18. benchmarks/evaluation/basic_advanced.py +0 -807
  19. benchmarks/evaluation/cli.py +0 -79
  20. benchmarks/evaluation/comparison.py +0 -750
  21. benchmarks/evaluation/evidence_contract.py +0 -119
  22. benchmarks/evaluation/execution.py +0 -62
  23. benchmarks/evaluation/extbench.py +0 -1572
  24. benchmarks/evaluation/field_candidate.py +0 -23
  25. benchmarks/evaluation/field_extractor.py +0 -421
  26. benchmarks/evaluation/foam.py +0 -84
  27. benchmarks/evaluation/foam_arrays.py +0 -129
  28. benchmarks/evaluation/foam_field.py +0 -155
  29. benchmarks/evaluation/foam_io.py +0 -29
  30. benchmarks/evaluation/frozen_recovery.py +0 -713
  31. benchmarks/evaluation/health.py +0 -69
  32. benchmarks/evaluation/io.py +0 -39
  33. benchmarks/evaluation/measurement_specs.py +0 -45
  34. benchmarks/evaluation/mesh.py +0 -54
  35. benchmarks/evaluation/models.py +0 -86
  36. benchmarks/evaluation/numerical.py +0 -253
  37. benchmarks/evaluation/pipeline.py +0 -166
  38. benchmarks/evaluation/preparation.py +0 -172
  39. benchmarks/evaluation/profiles.py +0 -74
  40. benchmarks/evaluation/profiles/advanced.json +0 -19
  41. benchmarks/evaluation/profiles/basic.json +0 -19
  42. benchmarks/evaluation/profiles/extended.json +0 -19
  43. benchmarks/evaluation/qoi.py +0 -79
  44. benchmarks/evaluation/qoi_glue.py +0 -493
  45. benchmarks/evaluation/qoi_reference.py +0 -566
  46. benchmarks/evaluation/reference.py +0 -44
  47. benchmarks/evaluation/reporting.py +0 -89
  48. benchmarks/evaluation/retained_fields.py +0 -304
  49. benchmarks/evaluation/schema.py +0 -21
  50. benchmarks/evaluation/stability.py +0 -48
GUIDE.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Usage guide / 使用指南
2
+
3
+ [English overview](README.md) · [中文介绍](README_zh.md)
4
+
5
+ ## Files and task identity / 文件与任务标识
6
+
7
+ `data/extended.jsonl` is the 100-task ExtFoamBench catalog. Each row has `task_id`, `track`, `case_id`, `family`, `task_origin`, `usr_requirement`, and `external_asset_ids`. Use `(track, case_id)` to join task records to the `cases` mappings in reference-QoI and numerical-statistics JSON files. Basic/Advanced catalogs follow the same format and retain upstream attribution.
8
+
9
+ `data/extended.jsonl` 是 100 条 Ext 原创任务的索引,包含上述字段。使用 `(track, case_id)` 与参考 QoI、数值统计中的 `cases` 条目对应;Basic/Advanced 采用相同格式,并注明上游来源。
10
+
11
+ Reference input JSONs contain OpenFOAM file text, such as `0/U`, `system/controlDict` and `Allrun`; some Extended tasks have `reference_subcases`. Geometry declarations resolve through `benchmarks/assets/manifest.json`. Keep reference inputs and answers outside the solving agent's accessible workspace.
12
+
13
+ 参考输入 JSON 保存 OpenFOAM 文件内容,部分 Ext 任务还包含多个参考分支。几何声明通过资产清单关联文件。参考输入与答案应置于求解智能体无法读取的位置。
14
+
15
+ ## Optional evaluator / 可选评估器
16
+
17
+ The scorer, schemas and scripts are bundled in `tools/evaluation-tools.zip`. Extract it **into the downloaded repository root**, preserving its paths. Use Python 3.11/3.12 and a dedicated evaluator environment; current HF `datasets` dependencies may require a different NumPy version.
18
+
19
+ 评估器、格式定义和脚本集中在工具包中。请将其**解压到下载的仓库根目录**,保留相对路径。使用 Python 3.11/3.12 和独立评估环境,避免与最新 HF 数据加载依赖的 NumPy 版本冲突。
20
+
21
+ ```bash
22
+ python -m zipfile -e tools/evaluation-tools.zip .
23
+ python -m pip install -r requirements.txt
24
+ python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json
25
+ python examples/inspect_task.py --track extended --case-id nozzleCDV/1
26
+ ```
27
+
28
+ These commands inspect data without running a model or CFD solver. The inspection output includes evaluator-side information; it is not an agent prompt.
29
+
30
+ 上述命令只检查数据,不调用模型或 CFD 求解器。任务查看命令包含评价侧信息,不应直接作为智能体提示词。
31
+
32
+ To export one reference input without solving it / 导出一个参考算例输入:
33
+
34
+ ```bash
35
+ python benchmarks/scripts/materialize_benchmark.py --benchmark benchmarks/FoamBench_extended_openfoam13_fixed.json --case-id nozzleCDV/1 --output-root outputs/reference-input
36
+ ```
37
+
38
+ To evaluate an existing compatible run, replace `/path/to/run` with your retained artifacts / 评价已有运行结果时,将路径换成实际结果目录:
39
+
40
+ ```bash
41
+ python -m benchmarks.evaluation evaluate --profile benchmarks/evaluation/profiles/extended.json --adapter easyfoam --run-root /path/to/run --output outputs/evaluation
42
+ ```
43
+
44
+ Other adapters: `foamagent`, `chatcfd`, `coding-agent`. Their required layouts are defined in the extracted `benchmarks/evaluation/adapters/`. Full-profile evaluation counts missing tasks as failures; a single-task run does not reproduce a full-benchmark score.
45
+
46
+ 其他适配器支持上述三种布局,具体输入结构见解压后的目录。完整配置会将未运行任务计为失败,单任务运行不代表完整基准成绩。
47
+
48
+ ## Metric fields and protocol / 指标字段与协议
49
+
50
+ | Metric / 指标 | Field under `overall` / 汇总字段 |
51
+ | --- | --- |
52
+ | ECR | `execution_pass_rate` |
53
+ | Numerical acceptance / 数值接受率 | `numerical_pass_rate_all_tasks` |
54
+ | QoI acceptance / 物理接受率 | `physics_grounded_qoi_pass_rate_all_tasks` |
55
+ | TAR | `end_to_end_pass_rate` |
56
+
57
+ Rates use all assigned tasks and range from 0 to 1. Execution gates Numerical/QoI acceptance; all mandatory criteria must pass. Conditional rates and partial-quality scores are supplementary. The Extended rules retain their declared `provisional` tolerance status. In the supplied Basic/Advanced scorer, physical ranges/signatures are mandatory, while profiles/history/shock locations are reference-agreement diagnostics; check manuscript-to-version alignment before claiming identical historical scores. Spatial coverage counts profile-field combinations; early-convergence markers can satisfy the stop condition.
58
+
59
+ 上述比例均以全部指定任务为分母,范围为 0–1。数值和物理接受以执行通过为前提,所有必需准则均需通过;条件通过率和部分质量分数属于辅助信息。Ext 保留原有 `provisional` 容差状态。当前 Basic/Advanced 实现将物理范围/特征作为必需准则,曲线、历史与激波位置作为参考一致性诊断;如需复现历史论文分数,应核对具体版本。空间覆盖按曲线与场的组合统计,执行终止条件允许提前收敛标记。
60
+
61
+ Actual simulations require OpenFOAM **Foundation 13**. Offline extraction uses retained data, but some missing measurement fields or topology-changing geometries require native `foamPostProcess`. `--prepare` writes derived fields; `--check-mesh` enables a fresh mesh audit. Use copies of valuable run artifacts when preparing measurements.
62
+
63
+ 真实仿真需要 OpenFOAM **Foundation 13**。离线提取通常读取留存数据,但部分测量场或拓扑变化几何需要原生后处理工具。`--prepare` 会写入派生场,`--check-mesh` 可启动网格检查;处理重要运行结果时建议使用副本。
64
+
65
+ ## Coverage, provenance and versions / 覆盖、来源与版本
66
+
67
+ - All 226 tasks have reference-QoI entries; 215 have nonempty numerical statistics. Missing: `nozzleCDV/4` and all ten `riemann2D` tasks. See [coverage](metadata/coverage.json). / 226 个任务均有参考 QoI 条目;215 个有非空数值统计,11 个缺失条目已明确记录。
68
+ - References are simulation-derived. Raw solution fields/logs, historical agent trajectories/checkpoints, and raw repeatability/negative-control/sensitivity experiment archives are not included. / 参考数据由仿真生成;本包未包含完整原始场、日志、历史智能体轨迹/检查点和重复验证、负对照、敏感性实验原始归档。
69
+ - Ext task design, evaluation resources and offline reference data are EasyFoam contributions. Basic/Advanced task definitions come from [FoamBench](https://github.com/NLR-Theseus/cfdllmbench). CFD source attribution is detailed in the paper's Appendix A; the asset manifest records OpenFOAM tutorial sources and checksums. / Ext 任务设计、评价资源和离线参考数据属于 EasyFoam 贡献;Basic/Advanced 任务来自 FoamBench,CFD 来源见论文附录 A,几何来源见资产清单。
70
+ - [Source manifest](metadata/source_manifest.json) identifies unchanged source files, including those inside the optional ZIP. [Validation](metadata/validation.json) records packaging checks. Run `python scripts/verify_release.py` to verify this release without extracting the tools. / 来源清单包含工具包内部文件的哈希;验证报告记录检查结果,无需解压工具即可运行完整性检查。
71
+ - **1.1.0** changes documentation and packaging only. **1.0.0** remains available with the original unpacked tool layout. Freeze dataset and evaluator versions together when reporting results. / 1.1.0 仅调整文档与打包;1.0.0 保留原有展开工具目录。报告实验时应同时固定数据和评估器版本。
LICENSE.md CHANGED
@@ -1,12 +1,12 @@
1
- # Component licenses and attribution
2
-
3
- This collection contains original and adapted material. The Hub uses `license: other` with this file as its license entry point because no single license label describes every component.
4
-
5
- | Component | Retained terms / notice |
6
- | --- | --- |
7
- | EasyFoam project code and original project material | Existing project Apache-2.0 license in `LICENSE`, subject to third-party exceptions |
8
- | Inherited FoamBench Basic/Advanced task content | Upstream BSD-3-Clause notice in `LICENSES/FoamBench-BSD-3-Clause.txt`; retain applicable OpenFOAM/other embedded notices |
9
- | OpenFOAM tutorial-derived case content and geometry | Existing GPL-3.0-or-later notices and `LICENSES/GPL-3.txt`; see `benchmarks/assets/README.md` and `manifest.json` |
10
- | Generated task catalogs | Projections of the corresponding task records; preserve their source attribution and applicable terms |
11
-
12
- The packaging does not relicense upstream content or override embedded notices. Scientific authorship of the evaluation/reference data and original ExtFoamBench task design is distinguished from upstream ownership in `docs/PROVENANCE.md`. No new CC-BY, CC0 or other blanket grant is introduced by this release.
 
1
+ # Component licenses and attribution
2
+
3
+ This collection contains original and adapted material. The Hub uses `license: other` with this file as its license entry point because no single license label describes every component.
4
+
5
+ | Component | Retained terms / notice |
6
+ | --- | --- |
7
+ | EasyFoam project code and original project material | Existing project Apache-2.0 license in `LICENSE`, subject to third-party exceptions |
8
+ | Inherited FoamBench Basic/Advanced task content | Upstream BSD-3-Clause notice in `LICENSES/FoamBench-BSD-3-Clause.txt`; retain applicable OpenFOAM/other embedded notices |
9
+ | OpenFOAM tutorial-derived case content and geometry | Existing GPL-3.0-or-later notices and `LICENSES/GPL-3.txt`; see `benchmarks/assets/README.md` and `manifest.json` |
10
+ | Generated task catalogs | Projections of the corresponding task records; preserve their source attribution and applicable terms |
11
+
12
+ The packaging does not relicense upstream content or override embedded notices. Scientific authorship of the evaluation/reference data and original ExtFoamBench task design is distinguished from upstream ownership in `GUIDE.md`. No new CC-BY, CC0 or other blanket grant is introduced by this release.
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- pretty_name: ExtFoamBench — CFD Tasks, Evaluation Protocols and Offline Reference Data
3
  language:
4
  - en
5
  license: other
@@ -41,130 +41,61 @@ configs:
41
 
42
  # ExtFoamBench
43
 
44
- **100 new CFD tasks, task-specific QoI acceptance rules, and offline reference data for evaluating OpenFOAM agents.**
45
 
46
- This release accompanies [EasyFoam: Skill-Oriented OpenFOAM Agents with Evidence-Driven Evolution](https://openreview.net/forum?id=GhQ5YmhU8B). It brings together three research contributions: the **ExtFoamBench task dataset**, the **execution / numerical / physical acceptance evaluation framework**, and **offline reference simulations summarized as QoIs and numerical diagnostics**.
47
 
48
- The EasyFoam Skill library is available separately on [GitHub](https://github.com/CAS-CLab/EasyFoam). Installing that library does not require downloading this dataset. This dataset includes an offline evaluator; using it does not require installing the EasyFoam agent or providing a model API key.
49
 
50
- ## Contributions and attribution
51
 
52
- | Component | Task count | Task origin | Contribution in this release |
53
- | --- | ---: | --- | --- |
54
- | **ExtFoamBench / Extended** | **100** | New task suite developed by the EasyFoam authors, using attributed CFD source cases and geometry | New tasks, task-specific evaluation rules, and offline reference data |
55
- | FoamBench Basic | 110 | Existing [FoamBench / CFDLLMBench](https://github.com/NLR-Theseus/cfdllmbench), adapted for OpenFOAM Foundation 13 | Evaluation rules and offline reference data developed/generated by the EasyFoam authors |
56
- | FoamBench Advanced | 16 | Existing FoamBench / CFDLLMBench, adapted for OpenFOAM Foundation 13 | Evaluation rules and offline reference data developed/generated by the EasyFoam authors |
57
 
58
- **The 126 Basic/Advanced tasks are not claimed as an original EasyFoam dataset.** They are included for compatibility with the evaluation suite. The EasyFoam authors' evaluation and offline-reference contributions cover all **226** tasks. Existing geometry, OpenFOAM tutorials, and upstream benchmark materials retain their provenance and licenses.
59
 
60
- The default Hub configuration, `extended`, shows only the 100 ExtFoamBench tasks. `basic` and `advanced` expose inherited tasks separately. `all` combines the 226 evaluation tasks. The `test` split name means benchmark evaluation tasks; it does **not** describe the historical held-out split used in the EasyFoam skill-evolution experiments.
61
 
62
- ## ExtFoamBench coverage
63
 
64
- Each of the ten families contains ten tasks: a baseline and nine variants.
65
 
66
- | Family | Physical setting |
67
- | --- | --- |
68
- | `yPlusVerification` | Near-wall resolution and wall-law verification |
69
- | `risingBubble` | Buoyancy-driven two-phase bubble motion |
70
- | `supersonicCrossJet` | Supersonic cross-flow / jet interaction |
71
- | `nozzleCDV` | Compressible converging-diverging nozzle flow |
72
- | `MRF_stirredReactor` | Rotating stirred-reactor flow |
73
- | `ERCOFTA_pump` | Rotating-pump pressure and flow response |
74
- | `compressibleBubbleCollapse` | Compressible bubble-collapse dynamics |
75
- | `aerofoilNACA0012` | Airfoil aerodynamic response |
76
- | `drivaerFastback` | Vehicle external aerodynamics |
77
- | `riemann2D` | Two-dimensional compressible Riemann flow |
78
 
79
- Variants cover operating conditions and boundary conditions, geometry and mesh, physics and closure models, solver/numerical settings, and study/workflow requirements. Some tasks require multiple runs, comparisons, parallel execution, or restart workflows.
80
 
81
- ## What is downloaded?
82
 
83
- | Location | Contents |
84
- | --- | --- |
85
- | `data/*.jsonl` | Hub-readable task catalog: identifiers, original requirements, origin, and permitted geometry identifiers |
86
- | `benchmarks/FoamBench_*_fixed*.json` | Reference case input dictionaries, including OpenFOAM files and any reference subcases |
87
- | `benchmarks/FoamBench_*_reference_qois.json` | Offline reference QoIs, principal metrics, and acceptance tolerances for each track |
88
- | `benchmarks/FoamBench_extended_*measurement_specs.json` | Per-task measurement definitions for ExtFoamBench |
89
- | `benchmarks/FoamBench_extended_*qoi_design.json` | Family/branch QoI design and principal-versus-diagnostic roles |
90
- | `benchmarks/FoamBench_extended_*evidence_contract.v1.json` | Evidence format and discovery contract |
91
- | `benchmarks/reference_statistics/` | Parsed reference residual, Courant, continuity, and related numerical diagnostics |
92
- | `benchmarks/assets/` | Seven geometry assets, original source locations, and SHA-256 checksums |
93
- | `benchmarks/evaluation/`, `schemas/` | Offline evaluation implementation and validation schemas |
94
- | `benchmarks/scripts/` | Reference materialization, extraction, comparison, and asset checking utilities |
95
- | `metadata/` | Version, family coverage, missing-data inventory, and source checksums |
96
- | `docs/` | Data format, evaluation, provenance, and release notes |
97
-
98
- Reference data are **simulation-derived computational references**, with the assumptions and limits of their configurations. Raw solution fields, raw reference logs, historical agent rollouts, and paper-result archives are not included in this release. No historical train/validation/test split is inferred or invented.
99
-
100
- ## Quick start: inspect a task locally
101
-
102
- From the downloaded repository root, using Python 3.11 or 3.12:
103
-
104
- ```bash
105
- python examples/inspect_task.py --track extended --case-id nozzleCDV/1
106
- python scripts/verify_release.py
107
- ```
108
-
109
- Both commands use the Python standard library and do not run a model or a CFD solver. The inspection command shows the task plus the associated measurement and reference-metric summary. Its output is intended for a human or evaluator, not as an agent prompt.
110
-
111
- For the Hub task catalog, install `datasets` in a separate environment from the pinned evaluator dependencies, and use:
112
 
113
  ```python
114
  from datasets import load_dataset
115
 
116
- tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test")
117
  print(len(tasks)) # 100
118
  print(tasks[0]["usr_requirement"])
119
  ```
120
 
121
- The task catalog excludes reference input files and reference values. Load/download the full repository if you need the evaluator and reference data; `load_dataset` loads only the selected task table. Pin the repository revision when reporting experiments.
122
-
123
- ## Quick start: validate the evaluator inputs
124
-
125
- ```bash
126
- python -m pip install -r requirements.txt
127
- python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json
128
- python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/basic.json
129
- python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/advanced.json
130
- python benchmarks/scripts/validate_benchmark_assets.py --benchmark benchmarks/FoamBench_extended_openfoam13_fixed.json --manifest benchmarks/assets/manifest.json
131
- ```
132
-
133
- These checks require no OpenFOAM installation. Materialize one **reference input case** without solving it:
134
 
135
  ```bash
136
- python benchmarks/scripts/materialize_benchmark.py --benchmark benchmarks/FoamBench_basic_openfoam13_fixed_final.json --case-id Cavity/1 --output-root outputs/reference-input
137
  ```
138
 
139
- Actual CFD simulation requires **OpenFOAM Foundation 13** and the appropriate system tools. This release does not launch an agent. The offline evaluator consumes existing run artifacts; some derived measurements require native OpenFOAM tools. See [Evaluation](docs/EVALUATION.md) before enabling preparation or mesh auditing.
140
-
141
- ## Evaluation: execution, numerics, and physics
142
-
143
- The framework measures whether a task completes (**E**), satisfies applicable numerical checks (**N**), and satisfies every mandatory task-specific physical/QoI criterion (**Q**). It reports execution completion rate (**ECR**) and joint task acceptance rate (**TAR**):
144
-
145
- ```text
146
- ECR = count(E passes) / number of assigned tasks
147
- TAR = count(E and N and Q all pass) / number of assigned tasks
148
- ```
149
-
150
- A high ECR alone does not establish physically acceptable task completion. Measurements can be scalars, spatial profiles, time histories, events, or branch-dependent responses. The supplied contracts fix extraction semantics, tolerances, missing-evidence behavior, and aggregation. Optional diagnostic scores and continuous quality values are not substitutes for mandatory acceptance checks or TAR.
151
-
152
- See [Evaluation](docs/EVALUATION.md) for the implementation fields, [Data format](docs/DATA_FORMAT.md) for file relationships, and [release notes](docs/RELEASE_NOTES.md) for current protocol boundaries.
153
-
154
- ## Reference visibility and intended use
155
-
156
- This is a public research dataset and evaluation resource. Give a solving agent only the selected task requirements, allowed assets, and explicitly task-visible measurement instructions. Keep reference inputs, reference values, and evaluator files outside its accessible workspace. A working-directory setting alone is not read-access isolation.
157
-
158
- The benchmark supports comparative research under its declared contracts. Passing it is not a general certification of physical validity or engineering suitability. Researchers should report software/data revisions, model and runtime settings, task membership, and any changed acceptance rules.
159
 
160
- ## Data completeness and versioning
161
 
162
- All 226 tasks have reference-QoI case entries. Parsed numerical reference statistics are nonempty for **215 of 226** tasks. They are unavailable for `nozzleCDV/4` and all ten `riemann2D` tasks in the Extended track; missing statistics are recorded explicitly in [coverage.json](metadata/coverage.json), not filled with synthetic values. Case-entry presence is not a claim that every optional diagnostic or conditional QoI is available.
163
 
164
- Release `1.0.0` packages the supplied data and scorer without changing their numerical contents. Embedded schema versions and the Extended contract's `provisional` tolerance status are retained. This package is not a certification that all current defaults reproduce every historical table in the manuscript. Changes to tasks, reference values, extraction, or scoring require a new release. See [release notes](docs/RELEASE_NOTES.md).
165
 
166
- ## Attribution and licenses
167
 
168
- Use of ExtFoamBench tasks or the EasyFoam evaluation/reference resources should cite the [EasyFoam paper](https://openreview.net/forum?id=GhQ5YmhU8B). Use of Basic/Advanced should also credit the [upstream FoamBench work](https://github.com/NLR-Theseus/cfdllmbench). Dataset originality and reuse permissions are described separately in [Provenance](docs/PROVENANCE.md) and [component licenses](LICENSE.md).
169
 
170
- This is a mixed-origin collection. The repository does not apply a new blanket license that overrides upstream terms. Apache-2.0 project terms, the FoamBench BSD-3-Clause notice, and OpenFOAM GPL notices are retained in `LICENSE` and `LICENSES/`.
 
1
  ---
2
+ pretty_name: ExtFoamBench — CFD Tasks, Geometry Assets and Evaluation Metrics
3
  language:
4
  - en
5
  license: other
 
41
 
42
  # ExtFoamBench
43
 
44
+ **English** | [中文介绍](README_zh.md)
45
 
46
+ **100 CFD tasks · 7 geometry assets · task-specific physical evaluation**
47
 
48
+ ExtFoamBench is a benchmark for evaluating OpenFOAM agents, introduced in [EasyFoam](https://openreview.net/forum?id=GhQ5YmhU8B). This repository focuses on **the ExtFoamBench dataset, the geometry assets needed by its tasks, and the evaluation metrics and acceptance criteria**.
49
 
50
+ ## Core resources
51
 
52
+ | Resource | What it provides | Files |
53
+ | --- | --- | --- |
54
+ | **ExtFoamBench dataset** | 100 tasks across 10 families, covering operating conditions, mesh/geometry, physics, numerical settings and multi-run workflows | [Task table](data/extended.jsonl) · [Reference case inputs](benchmarks/FoamBench_extended_openfoam13_fixed.json) |
55
+ | **Geometry assets** | 7 ready-to-use geometry files for stirred-reactor, airfoil and vehicle cases, with source attribution and checksums | [Assets](benchmarks/assets/) · [Manifest](benchmarks/assets/manifest.json) |
56
+ | **Evaluation metrics and criteria** | Execution, numerical and physical acceptance; per-task QoI definitions, measurement rules, reference comparisons and tolerances | [Measurement specs](benchmarks/FoamBench_extended_openfoam13_measurement_specs.json) · [QoI design](benchmarks/FoamBench_extended_openfoam13_qoi_design.json) · [Reference values and tolerances](benchmarks/FoamBench_extended_openfoam13_reference_qois.json) |
57
 
58
+ Each family has a baseline and nine variants: `yPlusVerification`, `risingBubble`, `supersonicCrossJet`, `nozzleCDV`, `MRF_stirredReactor`, `ERCOFTA_pump`, `compressibleBubbleCollapse`, `aerofoilNACA0012`, `drivaerFastback`, and `riemann2D`.
59
 
60
+ The tasks are developed by the EasyFoam authors. Geometry assets are redistributed from attributed OpenFOAM 13 sources; their original notices are retained.
61
 
62
+ ## Evaluation
63
 
64
+ A task is assessed along three dimensions: **E** (execution completes), **N** (applicable numerical checks pass), and **Q** (all mandatory physical/QoI criteria pass).
65
 
66
+ - **ECR** = tasks passing E / all assigned tasks.
67
+ - **TAR** = tasks passing E, N and Q together / all assigned tasks.
 
 
 
 
 
 
 
 
 
 
68
 
69
+ QoI rules specify what to measure, spatial/time support, comparison methods and acceptance tolerances. Missing outputs remain in the denominator. Diagnostic or continuous scores do not override failed mandatory criteria.
70
 
71
+ ## Use the dataset
72
 
73
+ Install `datasets`, then load the default Extended track:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  ```python
76
  from datasets import load_dataset
77
 
78
+ tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test", revision="v1.1.0")
79
  print(len(tasks)) # 100
80
  print(tasks[0]["usr_requirement"])
81
  ```
82
 
83
+ To download geometry, criteria and reference data as well:
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  ```bash
86
+ hf download Eurus132/ExtFoamBench --repo-type dataset --revision v1.1.0 --local-dir ExtFoamBench
87
  ```
88
 
89
+ The task table contains requirements and metadata. Reference case inputs and reference answers are for evaluation; keep them outside the solving agent's accessible workspace. The `test` label denotes benchmark tasks, not the historical skill-evolution held-out split.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ ## Supporting resources
92
 
93
+ For broader comparison, the repository also includes **FoamBench Basic (110)** and **Advanced (16)** from [upstream FoamBench](https://github.com/NLR-Theseus/cfdllmbench). These are inherited tasks; the EasyFoam authors contribute their **evaluation criteria and offline reference data**. Select `basic`, `advanced`, or `all` (226 tasks) to browse them.
94
 
95
+ Offline QoI references and numerical summaries support evaluation across all three tracks. The [optional evaluation tools](tools/evaluation-tools.zip) bundle the scorer, scripts and schemas; extract them only when needed. The [guide](GUIDE.md) covers usage, data coverage and protocol details. The [EasyFoam Skill library](https://github.com/CAS-CLab/EasyFoam) is distributed separately.
96
 
97
+ ## Citation and licenses
98
 
99
+ Cite [EasyFoam](https://openreview.net/forum?id=GhQ5YmhU8B) when using ExtFoamBench or its evaluation/reference resources, and credit [FoamBench](https://github.com/NLR-Theseus/cfdllmbench) when using Basic/Advanced. See [component licenses](LICENSE.md) for project and third-party terms.
100
 
101
+ Version **1.1.0** simplifies the presentation and adds this optional-tool layout. Scientific data, acceptance criteria and scoring code are unchanged from **1.0.0**, which remains available.
README_zh.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ExtFoamBench
2
+
3
+ [English](README.md) | **中文介绍**
4
+
5
+ **100 个 CFD 任务 · 7 个几何资产 · 面向任务物理响应的评价体系**
6
+
7
+ ExtFoamBench 是 [EasyFoam 论文](https://openreview.net/forum?id=GhQ5YmhU8B)提出的 OpenFOAM 智能体评测基准。本仓库重点提供三部分:**ExtFoamBench 数据集、任务所需的几何资产,以及评价指标与接受准则**。
8
+
9
+ ## 核心内容
10
+
11
+ | 资源 | 内容 | 文件入口 |
12
+ | --- | --- | --- |
13
+ | **ExtFoamBench 数据集** | 10 个任务家族、100 个任务,覆盖工况、几何与网格、物理模型、数值设置和多次运行工作流 | [任务列表](data/extended.jsonl) · [参考算例输入](benchmarks/FoamBench_extended_openfoam13_fixed.json) |
14
+ | **几何资产** | 适用于搅拌反应器、翼型和车辆算例的 7 个几何文件,附来源与校验值 | [几何目录](benchmarks/assets/) · [资产清单](benchmarks/assets/manifest.json) |
15
+ | **评价指标与准则** | 执行、数值和物理三个维度的评价,以及逐任务 QoI 定义、测量方式、参考比较与容差 | [测量规范](benchmarks/FoamBench_extended_openfoam13_measurement_specs.json) · [QoI 设计](benchmarks/FoamBench_extended_openfoam13_qoi_design.json) · [参考值与容差](benchmarks/FoamBench_extended_openfoam13_reference_qois.json) |
16
+
17
+ 每个家族包含 1 个基准任务和 9 个变体:`yPlusVerification`、`risingBubble`、`supersonicCrossJet`、`nozzleCDV`、`MRF_stirredReactor`、`ERCOFTA_pump`、`compressibleBubbleCollapse`、`aerofoilNACA0012`、`drivaerFastback` 和 `riemann2D`。
18
+
19
+ 任务由 EasyFoam 作者设计。几何资产来自已注明出处的 OpenFOAM 13 资源,保留原有归属与许可说明。
20
+
21
+ ## 评价方式
22
+
23
+ 每个任务从三个维度评价:**E:执行完成;N:满足适用的数值条件;Q:所有必需的物理量/QoI 准则通过。**
24
+
25
+ - **ECR(执行完成率)** = E 通过的任务数 / 全部指定任务数。
26
+ - **TAR(任务接受率)** = E、N、Q 同时通过的任务数 / 全部指定任务数。
27
+
28
+ QoI 准则规定测什么、在哪里和什么时间测、如何比较,以及允许多大误差。缺失输出仍计入任务总数;诊断分数或连续质量分数不能覆盖必需准则的失败。
29
+
30
+ ## 使用数据集
31
+
32
+ 安装 `datasets` 后,读取默认的 Extended 任务:
33
+
34
+ ```python
35
+ from datasets import load_dataset
36
+
37
+ tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test", revision="v1.1.0")
38
+ print(len(tasks)) # 100
39
+ print(tasks[0]["usr_requirement"])
40
+ ```
41
+
42
+ 同时下载几何资产、评价准则和参考数据:
43
+
44
+ ```bash
45
+ hf download Eurus132/ExtFoamBench --repo-type dataset --revision v1.1.0 --local-dir ExtFoamBench
46
+ ```
47
+
48
+ 任务表包含需求和元数据。参考算例输入和参考答案用于评价,应放在求解智能体无法读取的位置。这里的 `test` 表示基准评测任务,并非论文中技能演化实验的历史留出划分。
49
+
50
+ ## 配套资源
51
+
52
+ 为方便更广泛的比较,本仓库附带来自[上游 FoamBench](https://github.com/NLR-Theseus/cfdllmbench) 的 **Basic(110 个)**和 **Advanced(16 个)**任务。它们不是 EasyFoam 的原创任务;EasyFoam 作者为其提供了**评价准则和离线参考数据**。可选择 `basic`、`advanced` 或 `all`(226 个任务)浏览。
53
+
54
+ 三组任务的离线 QoI 参考值和数值统计用于支持评价。[可选评价工具包](tools/evaluation-tools.zip)集中提供评估器、脚本和格式定义,需要时再解压。[使用指南](GUIDE.md)说明工具运行方法、数据覆盖情况和评价协议细节。[EasyFoam Skill 库](https://github.com/CAS-CLab/EasyFoam)独立发布。
55
+
56
+ ## 引用与许可
57
+
58
+ 使用 ExtFoamBench 或其评价/参考资源时,请引用 [EasyFoam](https://openreview.net/forum?id=GhQ5YmhU8B);使用 Basic/Advanced 时,同时注明 [FoamBench](https://github.com/NLR-Theseus/cfdllmbench) 的贡献。项目与第三方资源的许可见[组件许可证说明](LICENSE.md)。
59
+
60
+ **1.1.0** 版本精简了页面与文件组织,并增加中英文介绍。科学数据、接受准则和评分代码与 **1.0.0** 一致,旧版仍可下载。
SHA256SUMS CHANGED
@@ -1,5 +1,4 @@
1
  fec9848fa0a1a2a2d7f78eebc2cac8239fe830c918d5776a684ed129beb203d9 .gitignore
2
- b5375698c34737e22fabdf9cea774287609ce6edc3fa8c73791c3749e89c3bca benchmarks/__init__.py
3
  0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f benchmarks/assets/manifest.json
4
  0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz
5
  f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz
@@ -9,49 +8,6 @@ f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/ass
9
  d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117 benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj
10
  d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj
11
  b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540 benchmarks/assets/README.md
12
- 6488b16a905c9e6ae7d33f06bd55fbf276c917df54f53984f4f4ba3504f1710d benchmarks/evaluation/__init__.py
13
- b965c21513f41de952a6f983700e961845746fd1b3df1c56ab1e7a612ca8be8f benchmarks/evaluation/__main__.py
14
- dc4d21e3f45bd036f5a0d23ef2e9bf4406f4e34a76437472e3b9bbb25ff5bd40 benchmarks/evaluation/adapters/__init__.py
15
- b8933e85b63abc1c792fdad5ddd76dedb2e0344e38ce6d2e8991ee760e7419ce benchmarks/evaluation/adapters/chatcfd.py
16
- cdf7354b586bc67898bc2f3b44292aacd7fc9d7a58f0544efa9c603ac69a8f11 benchmarks/evaluation/adapters/coding_agent.py
17
- 260f1efc5943ef598fa02b3dae130101961fc0c2ce22080abec2b4836d850d63 benchmarks/evaluation/adapters/common.py
18
- 5ffd5d35e2431ae568b3e78b647aa85d091d01c124bcdacedcb6e68d4474339b benchmarks/evaluation/adapters/easyfoam.py
19
- a33bcc116b3043c2b70a1342d0d3c71c30eac42f1ea286ca08b543f0e6496c40 benchmarks/evaluation/adapters/foamagent.py
20
- 513e63ba562da617ef6f665c452bec8c2d308ca1e716629ac6ca360494724849 benchmarks/evaluation/aggregate.py
21
- 1f8db418394f143b9ecb780eec4118ebde99885130cc30552f64735c5ea93307 benchmarks/evaluation/basic_advanced.py
22
- 9d4a6bc429e0ef9a751384be2d777101f7f2d91dfee7edbdc6e3e0d771154ccd benchmarks/evaluation/cli.py
23
- eb44b8d8020e5f9c22f19880884ade107afd395246b0d9ad8f78b9a6a4d30280 benchmarks/evaluation/comparison.py
24
- 272bc7e44456c330fd7ac97685279538f8b0715d8aae3deb88366314fea1efc9 benchmarks/evaluation/evidence_contract.py
25
- cd2e1ff40d7dcb830b4230d86e143652d1d93a1b007019e3583384486a242604 benchmarks/evaluation/execution.py
26
- 78cd982892e8ede31ee7e951cec87c7c595813a975bf4b111ea0d980b37633b5 benchmarks/evaluation/extbench.py
27
- 51d8bb69224ed37ae0de073700c5f9cfd403095f53fa16d633a3eb777e1a0b13 benchmarks/evaluation/field_candidate.py
28
- 95900ed3c04bc04846e2dd2dd6ae4f98c2fb0aba4b85978199c20b1a444f4c0e benchmarks/evaluation/field_extractor.py
29
- 3c6a38077eecae484f264cd46478b21687b21ca33f543f4f041d954bdfa98205 benchmarks/evaluation/foam.py
30
- 80bd6344a529cc574693053b97b14cccb209c40a099b01a942f8654ddf24c614 benchmarks/evaluation/foam_arrays.py
31
- ce3a16fb9e29587eaabd816bdfda832bcdc83e3744ac233e1365b3350146ddf9 benchmarks/evaluation/foam_field.py
32
- a043e6a9022c30aea8fa94b8f753f1608804c526644a1f851c23453b7482727a benchmarks/evaluation/foam_io.py
33
- 55bd6f2c61c4e3cef677e4cf428433ae9e3fb8b778efc10bb281e814fc2c5d05 benchmarks/evaluation/frozen_recovery.py
34
- 1cf606f832b4410908faaddeb439d0ca768cf134f4832f87f901c113a17d25da benchmarks/evaluation/health.py
35
- 83c7166635578af9b5ed7eaeac96c06df7b65ab0936dc39a5310e5c42a6003e4 benchmarks/evaluation/io.py
36
- eb16a2dbd37f6ddb112adb6a92f5b3c1b8aa6295592d8f5430d7d3a24f0ff334 benchmarks/evaluation/measurement_specs.py
37
- 7f35b96268d62aca315d70f2c14a6bdda602bb51b70666fb1fa7667bc88a0cbf benchmarks/evaluation/mesh.py
38
- 75cdb75a677e47c786769d541e019085eb84a3de73b0539647143d869115d8ef benchmarks/evaluation/models.py
39
- f87a0946dc0d29c656e362d56e3aa0cc68c495d6daecf5d17f429a916e6468ff benchmarks/evaluation/numerical.py
40
- 4921843f568f4ff06d4f02d270da87a8833d34dac2a448aae1a090caa68d2206 benchmarks/evaluation/pipeline.py
41
- 95d54ca4f2dea32c9223cc092db6ac1e93fd045ab3a47a965c10f035b6211bd3 benchmarks/evaluation/preparation.py
42
- 5e8791bf4840c8ea18d1f5c70ca922b100e7694a07e75f2c7fb47a9b834137a2 benchmarks/evaluation/profiles/advanced.json
43
- a9976b3f6d2125a9ada142614052eb7d4cbc263ac8c1781f7b3fd4f0e567e2e4 benchmarks/evaluation/profiles/basic.json
44
- 8bbbc58e77b09da38eef2565e95b8d69c88b1db21ac696e9991b887e2394af85 benchmarks/evaluation/profiles/extended.json
45
- 5cf9b70b1ec3ae040d2e3b478e61d5c4e1bf838106621e3d3f7c1827670841a5 benchmarks/evaluation/profiles.py
46
- 305eba7114c1ae50521c05aa12ad95c9db35304af33665ea5e655bfd8f17c51b benchmarks/evaluation/qoi.py
47
- af47ba704a5edcd8490261a7ddba07fe9204473ae4d19d3b09a7e4f7fb9f548f benchmarks/evaluation/qoi_glue.py
48
- 99a6af4a1f422bbb4f808602b744b2fa3660b4a7740e39ab24f3f4fcad9bda6b benchmarks/evaluation/qoi_reference.py
49
- e0b13a6223ffa692f1297ba76b6817db4156bb3c3c3d2abfa96afc095d41511f benchmarks/evaluation/README.md
50
- 627725f472e89d9b97ff8cedf23d2ac92097a53f27f23d648f7be0bf943d33b1 benchmarks/evaluation/reference.py
51
- 159655e9dadb4367a59a7ea1a804856c5280b3bc025c2892f06fd0535e265bae benchmarks/evaluation/reporting.py
52
- 0c54e9671b9f7353cbc28ecf9798d678db4bfacaa5f7c184bf4e45ebef9ec4a7 benchmarks/evaluation/retained_fields.py
53
- 477332e61a0f668ff51db9817ec874706051d37c2dedf65b5ca43b73435c9583 benchmarks/evaluation/schema.py
54
- b9ba1b4c4583e9b393c699d47bab71a82aed159519408062b631147bd70d25a5 benchmarks/evaluation/stability.py
55
  74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027 benchmarks/FoamBench_advanced_openfoam13_fixed_final.json
56
  31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63 benchmarks/FoamBench_advanced_openfoam13_reference_qois.json
57
  50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523 benchmarks/FoamBench_basic_openfoam13_fixed_final.json
@@ -64,39 +20,20 @@ fb1db5034a1d2688ad360c6b0810bab68c33d4c6dc1dc5bec29095e93b077393 benchmarks/Foa
64
  6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b benchmarks/reference_statistics/advanced.json
65
  3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72 benchmarks/reference_statistics/basic.json
66
  637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9 benchmarks/reference_statistics/extended.json
67
- 5c1f78137dc1c7032363bb0ebf96cf01f19c9f2ffb48abd7fef39cb8b54a9f82 benchmarks/scripts/__init__.py
68
- 113840a36b914722ff422505b1ed128daf023ee20bf287ab8ebfcd1af938a786 benchmarks/scripts/build_extbench_reference.py
69
- 827836c6f2363f0104917b6573dc86935ffc58fd3b9dcdf0ca83cd5ce874f753 benchmarks/scripts/compare_foambench_qois.py
70
- 845727247e81e82d75abb0e05b62d1bd15f9a7d8512533b749b8a20e1631f6a5 benchmarks/scripts/extract_extbench_qois.py
71
- 1110f0962468820146307099c463c1be8a25cbc5c3729fd7abc116d7fe06d27a benchmarks/scripts/extract_foambench_candidate_qois.py
72
- cf3c18a0329ac576fc05e35ba2f70f95f0c1d6668a86fe6a65d8402de41a1abe benchmarks/scripts/extract_foambench_qois.py
73
- 265ac1ec1fcc347c82e9351a86305d6f7bafaf3bd8ff69075904ebaf285ed2bc benchmarks/scripts/materialize_benchmark.py
74
- fc1268f130f4b0800b5a75346198e97896bd5e74b07ea3face5d0e4afa0d6d2c benchmarks/scripts/recover_extbench_qoi.py
75
- ca2f885342099b4a06f425d971bee5edc24b199b596000e9997f8940b23770b4 benchmarks/scripts/validate_benchmark_assets.py
76
  488b6a139660cbcafd3de131c1e7e3c6758e71f609003e69cbfa1f9991afe95a data/advanced.jsonl
77
  50a62e6ab16faa998dd1c284db6ecb4e8ac78ee226c8be4e0fb6cce741e7581f data/basic.jsonl
78
  edfd82f84456540c89844eae84143dc4897a93599b1b28f278a945de5826981e data/extended.jsonl
79
- 07019bf3f590423b1b0804e6a8ac1dacf97677cb23a4842c4e5a0e601c155974 docs/DATA_FORMAT.md
80
- f0c1d691c071253fa66517e68349d9c2ee6c6d73f963a967c10173180693342b docs/EVALUATION.md
81
- 4f1353233c7d1d86da7f49d51a64f584805c435f8b052c37b37d30c84927530d docs/PROVENANCE.md
82
- a3690d9a63846f36f58bd8e79e1ab974a4d46673a16943166e8ad0fd9b91faf1 docs/RELEASE_NOTES.md
83
- c05b1930bed5658497b9ac9de230127c23a8541b274adfd270c995943773f4d5 examples/inspect_task.py
84
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
85
- 1c8f0e5ad4fe2f145137ef723f54d62e8891a2b1b3467c90bc33c4c6680c907f LICENSE.md
86
  7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22 LICENSES/FoamBench-BSD-3-Clause.txt
87
  8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903 LICENSES/GPL-3.txt
88
  770397d605802346385b7c69ab27b919c1b734d653c6ed64b255349e5ffeaef2 metadata/coverage.json
89
- a82a5872d4c62c7a0159ee23c684273e0eb61f4cd252f0db735e15e00364f95a metadata/families.json
90
- ffc93609ac4a7d0f858696da211e1ec214409df51b8223d6833fd318b0d19f86 metadata/release.json
91
- 74105bd146098de3bbe19c995eed3b3e5c63cad8b9480d08db34333292fec1d5 metadata/source_manifest.json
92
- 9b912f908b65a553835273e3cfe3745b5d63f5d148ec1b719412db2471dbd0d7 metadata/validation.json
93
- ba391bbb79dd26d51519409f44987afff3757513aa7bf9519b053795c2f156d8 README.md
94
- df4bd25666834a74821035deda2154cd2922e3e0d2d00db0bd02f99ba4ad8caf requirements.txt
95
- d49505bf35dffc763df91b13c8b5885e78b607af56d7aceba01e427c3fa19a6b schemas/benchmark_evaluation.schema.json
96
- 32a7f0865e9c851848fc775f9bde1125bd03749b4130d34fe95d5ffc62a700c0 schemas/benchmark_profile.schema.json
97
- 88fb894b919323c0457f1cb4bf934f72320d644299185127c164579343606425 schemas/foambench_qoi_candidate.schema.json
98
- 9204923e5b93e333459ccfc43394137deaee1bf19d6f01beaf8ada664806d7e8 schemas/foambench_qoi_comparison.schema.json
99
- 2ef632eb4ed82ad78213de6ee4b18aa36558916a106cb258505493c95285ac68 schemas/foambench_qoi_reference.schema.json
100
- 839a77fa504b7f13b2b6803c0ca2448df83418779cee2a2a5a5acdc18cd8760c schemas/qoi_recovery_plan.schema.json
101
- 73da798dd8c3ff74733a2a08a8d914d9e85c6d3184196dd0f2f8d0a45789a45a scripts/verify_release.py
102
- 59854984853104df5c353e2f681a15fc7924742f9a2e468c29af248dce45ce03 VERSION
 
1
  fec9848fa0a1a2a2d7f78eebc2cac8239fe830c918d5776a684ed129beb203d9 .gitignore
 
2
  0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f benchmarks/assets/manifest.json
3
  0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz
4
  f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz
 
8
  d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117 benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj
9
  d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj
10
  b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540 benchmarks/assets/README.md
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027 benchmarks/FoamBench_advanced_openfoam13_fixed_final.json
12
  31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63 benchmarks/FoamBench_advanced_openfoam13_reference_qois.json
13
  50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523 benchmarks/FoamBench_basic_openfoam13_fixed_final.json
 
20
  6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b benchmarks/reference_statistics/advanced.json
21
  3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72 benchmarks/reference_statistics/basic.json
22
  637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9 benchmarks/reference_statistics/extended.json
 
 
 
 
 
 
 
 
 
23
  488b6a139660cbcafd3de131c1e7e3c6758e71f609003e69cbfa1f9991afe95a data/advanced.jsonl
24
  50a62e6ab16faa998dd1c284db6ecb4e8ac78ee226c8be4e0fb6cce741e7581f data/basic.jsonl
25
  edfd82f84456540c89844eae84143dc4897a93599b1b28f278a945de5826981e data/extended.jsonl
26
+ dfeed01d712c4915d2c2f0eccb60575de454eab740c97642ce9ed9d628346d50 GUIDE.md
 
 
 
 
27
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
28
+ e3ef265ef148001bef8936ecef4074605705b28d47c5be54f73e44893f2f25f1 LICENSE.md
29
  7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22 LICENSES/FoamBench-BSD-3-Clause.txt
30
  8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903 LICENSES/GPL-3.txt
31
  770397d605802346385b7c69ab27b919c1b734d653c6ed64b255349e5ffeaef2 metadata/coverage.json
32
+ 678ee25dd7207becec717dda6f981ed42dc240575452e5f18db0fd4df93ba4f3 metadata/release.json
33
+ 801975a7617517d8286bc8d91fa6e6041ad3e09433edcb1f9249750530e05902 metadata/source_manifest.json
34
+ a308986a00db26567dc02fc6c4651667bf742bfc2f1997a8ee700f8f2faa918a metadata/validation.json
35
+ fd31e2cca58d84ca3581c3fa8f3e2ee5f24edddf71adff196f7bc3785d3fef19 README.md
36
+ 483b2e6058e6145e9dc4d62cadb650e7187d45d8a4c37e0f1a70dc7fd24d05a5 README_zh.md
37
+ 15d37d4b5c2293675fb977568f43a34e2eed8951a4e245407771cf9e09a4fdf5 scripts/verify_release.py
38
+ 6bf6fd0963a10c4a42e7de6529b4e75ca144e81716fa000cde8ea26d5c45a021 tools/evaluation-tools.zip
39
+ 6ca2e3356014241331fb2b399428fca23c558e3f3d428edcf4f56eb0fe907069 VERSION
 
 
 
 
 
 
VERSION CHANGED
@@ -1 +1 @@
1
- 1.0.0
 
1
+ 1.1.0
benchmarks/__init__.py DELETED
@@ -1 +0,0 @@
1
- """FoamBench assets and evaluation utilities."""
 
 
benchmarks/evaluation/README.md DELETED
@@ -1,12 +0,0 @@
1
- # Standalone EasyFoam benchmark evaluator
2
-
3
- This directory contains the supplied evaluation implementation for Basic, Advanced and Extended tracks. See [Evaluation](../../docs/EVALUATION.md) for metric definitions, commands, dependencies, native-tool behavior and protocol boundaries, and the [dataset card](../../README.md) for contribution attribution.
4
-
5
- From the repository root:
6
-
7
- ```bash
8
- python -m pip install -r requirements.txt
9
- python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json
10
- ```
11
-
12
- Agent campaign launchers and skill-evolution runtime code are distributed separately from this dataset. No model API key is needed to inspect the dataset or evaluate retained artifacts.
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/__init__.py DELETED
@@ -1,31 +0,0 @@
1
- """Dataset-independent FoamBench evaluation framework."""
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from .aggregate import aggregate_results
7
- from .models import BenchmarkProfile, CaseArtifact
8
-
9
-
10
- def evaluate_campaign(
11
- profile: BenchmarkProfile,
12
- *,
13
- adapter_name: str,
14
- run_root: Path,
15
- output_dir: Path | None = None,
16
- check_mesh: bool = False,
17
- mesh_timeout: float = 120.0,
18
- ) -> dict[str, Any]:
19
- """Evaluate a campaign without importing the full pipeline at package import time."""
20
- from .pipeline import evaluate_campaign as run_evaluation
21
-
22
- return run_evaluation(
23
- profile,
24
- adapter_name=adapter_name,
25
- run_root=run_root,
26
- output_dir=output_dir,
27
- check_mesh=check_mesh,
28
- mesh_timeout=mesh_timeout,
29
- )
30
-
31
- __all__ = ["BenchmarkProfile", "CaseArtifact", "aggregate_results", "evaluate_campaign"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/__main__.py DELETED
@@ -1,10 +0,0 @@
1
- import json
2
- import sys
3
-
4
- from .cli import main
5
-
6
- try:
7
- raise SystemExit(main())
8
- except (OSError, ValueError, RuntimeError, json.JSONDecodeError) as exc:
9
- print(f"foambench-evaluate: error: {exc}", file=sys.stderr)
10
- raise SystemExit(2)
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/__init__.py DELETED
@@ -1,22 +0,0 @@
1
- from .easyfoam import EasyFoamAdapter
2
- from .foamagent import FoamAgentAdapter
3
- from .chatcfd import ChatCFDAdapter
4
- from .coding_agent import CodingAgentAdapter
5
-
6
- ADAPTERS = {
7
- "easyfoam": EasyFoamAdapter,
8
- "foamagent": FoamAgentAdapter,
9
- "chatcfd": ChatCFDAdapter,
10
- "coding-agent": CodingAgentAdapter,
11
- }
12
-
13
-
14
- def create_adapter(name: str, *args, **kwargs):
15
- try:
16
- adapter = ADAPTERS[name]
17
- except KeyError as exc:
18
- raise ValueError(f"unknown evaluation adapter: {name}") from exc
19
- return adapter(*args, **kwargs)
20
-
21
-
22
- __all__ = ["EasyFoamAdapter", "FoamAgentAdapter", "ChatCFDAdapter", "create_adapter"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/chatcfd.py DELETED
@@ -1,85 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from ..io import read_object
6
- from ..models import BenchmarkProfile, CaseArtifact
7
- from .common import duration, token_usage
8
-
9
-
10
- class ChatCFDAdapter:
11
- """Normalize ChatCFD rollouts for the shared FoamBench scorer.
12
-
13
- ChatCFD writes a case_run.log and keeps its model accounting in either a
14
- rollout manifest or qa_logs.jsonl. The adapter deliberately does not
15
- infer case identity from generated files: a manifest is the reproducible
16
- source of truth for benchmark membership.
17
- """
18
-
19
- def __init__(self, run_root: Path, profile: BenchmarkProfile):
20
- self.run_root = run_root.resolve(strict=True)
21
- self.profile = profile
22
-
23
- def discover(self) -> dict[str, CaseArtifact]:
24
- artifacts: dict[str, CaseArtifact] = {}
25
- for manifest_path in sorted(self.run_root.rglob("rollout_manifest.json")):
26
- manifest = read_object(manifest_path)
27
- case_id = manifest.get("case_id")
28
- if not isinstance(case_id, str) or case_id in artifacts:
29
- continue
30
- rollout = manifest_path.parent
31
- case_ref = manifest.get("case_path", "case")
32
- case_dir = Path(case_ref)
33
- if not case_dir.is_absolute():
34
- case_dir = rollout / case_dir
35
- case_dir = case_dir.resolve()
36
- family, variant = self.profile.identity(case_id)
37
- logs = [p.resolve() for p in case_dir.glob("log.*") if p.is_file()]
38
- logs.extend(p.resolve() for p in (case_dir / "case_run.log", case_dir / "Allrun.out", case_dir / "Allrun.err") if p.is_file())
39
- normalized = dict(manifest)
40
- normalized["duration_seconds"] = duration(manifest)
41
- normalized["token_usage"] = token_usage(manifest)
42
- if manifest.get("resource_measurement") == "request-journal-v1":
43
- # Shared CSV reporting uses input/output names. Preserve the
44
- # raw journal totals and completeness flags alongside aliases.
45
- usage = normalized["token_usage"]
46
- usage["input_tokens"] = usage["prompt_tokens"]
47
- usage["output_tokens"] = usage["response_tokens"]
48
- # Task selection and generation/repair have separate logs.
49
- qa_logs = {p.resolve() for p in (rollout / "qa_logs.jsonl", case_dir / "qa_logs.jsonl") if p.is_file()}
50
- if not normalized["token_usage"] and qa_logs:
51
- totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0}
52
- for path in sorted(qa_logs):
53
- for key, value in self._qa_usage(path).items():
54
- totals[key] += value
55
- normalized["token_usage"] = totals
56
- artifacts[case_id] = CaseArtifact(
57
- case_id=case_id,
58
- dataset=self.profile.dataset,
59
- family=str(manifest.get("family") or family),
60
- variant=str(manifest.get("variant") or variant),
61
- replicate=int(manifest.get("replicate", 1)),
62
- rollout_dir=rollout,
63
- # Like Foam-Agent, ChatCFD supplies generic solver evidence,
64
- # not an EasyFoam workflow workspace with formal run records.
65
- workspace_dir=None,
66
- case_dir=case_dir if case_dir.is_dir() else None,
67
- manifest=normalized,
68
- solver_logs=tuple(sorted(set(logs))),
69
- )
70
- return artifacts
71
-
72
- @staticmethod
73
- def _qa_usage(path: Path) -> dict[str, int]:
74
- import json
75
- totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0}
76
- for line in path.read_text(encoding="utf-8").splitlines():
77
- try:
78
- row = json.loads(line)
79
- except json.JSONDecodeError:
80
- continue
81
- totals["calls"] += 1
82
- totals["prompt_tokens"] += int(row.get("prompt_tokens", 0) or 0)
83
- totals["response_tokens"] += int(row.get("response_tokens", 0) or 0)
84
- totals["reasoning_tokens"] += int(row.get("reasoning_tokens", 0) or 0)
85
- return totals
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/coding_agent.py DELETED
@@ -1,48 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from ..io import read_object
6
- from ..models import BenchmarkProfile, CaseArtifact
7
-
8
-
9
- class CodingAgentAdapter:
10
- """Use externally recorded output discovery; impose no agent-side file contract."""
11
-
12
- def __init__(self, run_root: Path, profile: BenchmarkProfile):
13
- self.run_root = run_root.resolve(strict=True)
14
- self.profile = profile
15
-
16
- def discover(self) -> dict[str, CaseArtifact]:
17
- result = {}
18
- for path in sorted(self.run_root.glob("*/*/replicate_001/rollout_manifest.json")):
19
- manifest = read_object(path)
20
- if manifest.get("experiment_kind") != "requirement_only_coding_agent.v1":
21
- raise ValueError(f"Unexpected experiment manifest: {path}")
22
- case_id = manifest["case_id"]
23
- if case_id in result:
24
- raise ValueError(f"Duplicate case: {case_id}")
25
- rollout = path.parent
26
- workspace = rollout / "workspace"
27
- ref = manifest.get("output_discovery", {}).get("case_ref")
28
- case_dir = None
29
- if isinstance(ref, str):
30
- candidate = (workspace / ref).resolve()
31
- if not candidate.is_relative_to(workspace.resolve()):
32
- raise ValueError(f"Case escapes workspace: {ref}")
33
- case_dir = candidate
34
- logs = []
35
- for ref in manifest.get("solver_log_refs", []):
36
- candidate = (rollout / ref).resolve()
37
- if not candidate.is_relative_to(rollout.resolve()):
38
- raise ValueError(f"Log escapes rollout: {ref}")
39
- if candidate.is_file():
40
- logs.append(candidate)
41
- family, variant = self.profile.identity(case_id)
42
- result[case_id] = CaseArtifact(
43
- case_id=case_id, dataset=self.profile.dataset, family=family, variant=variant,
44
- replicate=1, rollout_dir=rollout, workspace_dir=workspace, case_dir=case_dir,
45
- manifest={**manifest, "agent_mode": "coding-only", "domain_assets_enabled": False},
46
- solver_logs=tuple(logs),
47
- )
48
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/common.py DELETED
@@ -1,71 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from ..io import read_object
7
-
8
-
9
- def formal_records(workspace: Path) -> tuple[Path, ...]:
10
- paths: list[Path] = []
11
- workflow_path = workspace / "workflow.json"
12
- if workflow_path.is_file():
13
- workflow = read_object(workflow_path)
14
- refs = workflow.get("artifacts", {}).get("run_records", [])
15
- for ref in refs if isinstance(refs, list) else []:
16
- if isinstance(ref, str):
17
- paths.append(workspace / ref)
18
- paths.extend(workspace.glob("runs/formal-*/run_record.json"))
19
- unique = {path.resolve() for path in paths if path.is_file()}
20
- return tuple(sorted(unique))
21
-
22
-
23
- def successful_formal_records(paths: tuple[Path, ...]) -> tuple[Path, ...]:
24
- successful = []
25
- for path in paths:
26
- record = read_object(path)
27
- if record.get("mode") == "formal" and record.get("terminal_status") == "succeeded":
28
- successful.append(path)
29
- return tuple(successful)
30
-
31
-
32
- def logs_from_records(workspace: Path, records: tuple[Path, ...]) -> tuple[Path, ...]:
33
- logs: list[Path] = []
34
- for path in records:
35
- record = read_object(path)
36
- for command in record.get("commands", []) if isinstance(record.get("commands"), list) else []:
37
- if not isinstance(command, dict):
38
- continue
39
- for key in ("stdout_ref", "stderr_ref"):
40
- ref = command.get(key)
41
- if isinstance(ref, str):
42
- candidate = workspace / ref
43
- if candidate.is_file():
44
- logs.append(candidate.resolve())
45
- return tuple(dict.fromkeys(logs))
46
-
47
-
48
- def token_usage(manifest: dict[str, Any]) -> dict[str, Any]:
49
- usage = manifest.get("token_usage")
50
- if isinstance(usage, dict):
51
- return dict(usage)
52
- attempts = manifest.get("attempts")
53
- if isinstance(attempts, list) and attempts and isinstance(attempts[-1], dict):
54
- usage = attempts[-1].get("token_usage")
55
- return dict(usage) if isinstance(usage, dict) else {}
56
-
57
-
58
- def duration(manifest: dict[str, Any]) -> float | None:
59
- value = manifest.get("duration_seconds")
60
- if isinstance(value, (int, float)):
61
- return float(value)
62
- process = manifest.get("process")
63
- if isinstance(process, dict) and isinstance(process.get("duration_seconds"), (int, float)):
64
- return float(process["duration_seconds"])
65
- attempts = manifest.get("attempts")
66
- values = [
67
- float(item["duration_seconds"])
68
- for item in attempts if isinstance(attempts, list) and isinstance(item, dict)
69
- and isinstance(item.get("duration_seconds"), (int, float))
70
- ] if isinstance(attempts, list) else []
71
- return sum(values) if values else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/easyfoam.py DELETED
@@ -1,108 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from ..foam import FATAL_RE, final_log_time, normal_end
6
- from ..foam_io import read_text
7
- from ..io import read_object
8
- from ..models import BenchmarkProfile, CaseArtifact
9
- from .common import duration, formal_records, logs_from_records, successful_formal_records, token_usage
10
-
11
-
12
- class EasyFoamAdapter:
13
- """Normalize supported EasyFoam rollout layouts."""
14
-
15
- def __init__(self, run_root: Path, profile: BenchmarkProfile):
16
- self.run_root = run_root.resolve(strict=True)
17
- self.profile = profile
18
-
19
- def discover(self) -> dict[str, CaseArtifact]:
20
- artifacts: dict[str, CaseArtifact] = {}
21
- legacy = sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json"))
22
- current = sorted(self.run_root.rglob("run_manifest.json")) if not legacy else []
23
- for path in [*legacy, *current]:
24
- manifest = read_object(path)
25
- case_id = manifest.get("case_id")
26
- if not isinstance(case_id, str) or case_id in artifacts:
27
- continue
28
- rollout = path.parent
29
- workspace = self._workspace(rollout, manifest)
30
- family, variant = self.profile.identity(case_id)
31
- coding_only = manifest.get("agent_mode") == "coding-only" or manifest.get("domain_assets_enabled") is False
32
- case_dir = workspace / "case" if workspace else None
33
- if coding_only and case_dir and case_dir.is_dir():
34
- # Coding-only rollouts intentionally do not retain EasyFoam
35
- # formal records. Avoid scanning their large workspaces for
36
- # workflow/run-record artifacts before using generic logs.
37
- records = ()
38
- generic_logs = [item for item in case_dir.glob("log.*") if item.is_file()]
39
- generic_logs.extend(
40
- item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file()
41
- )
42
- logs = _successful_generic_logs(generic_logs)
43
- else:
44
- records = formal_records(workspace) if workspace and workspace.is_dir() else ()
45
- logs = logs_from_records(workspace, successful_formal_records(records)) if workspace else ()
46
- normalized = dict(manifest)
47
- normalized["duration_seconds"] = duration(manifest)
48
- normalized["token_usage"] = token_usage(manifest)
49
- artifacts[case_id] = CaseArtifact(
50
- case_id=case_id,
51
- dataset=self.profile.dataset,
52
- family=str(manifest.get("family") or family),
53
- variant=str(manifest.get("variant") or variant),
54
- replicate=int(manifest.get("replicate", 1)),
55
- rollout_dir=rollout,
56
- workspace_dir=workspace,
57
- case_dir=case_dir,
58
- manifest=normalized,
59
- formal_run_records=records,
60
- solver_logs=logs,
61
- workflow_path=workspace / "workflow.json" if workspace else None,
62
- evidence_summary_path=workspace / "evidence_summary.json" if workspace else None,
63
- )
64
- return artifacts
65
-
66
- def _workspace(self, rollout: Path, manifest: dict) -> Path | None:
67
- direct = rollout / "workspace"
68
- if direct.is_dir():
69
- return direct.resolve()
70
- ref = manifest.get("workspace_ref")
71
- if isinstance(ref, str):
72
- candidate = Path(ref)
73
- if not candidate.is_absolute():
74
- candidate = self.run_root / candidate
75
- return candidate.resolve()
76
- return None
77
-
78
-
79
- def _successful_generic_logs(paths: list[Path]) -> tuple[Path, ...]:
80
- """Select final successful solver evidence without failed repair/postprocess logs."""
81
- canonical_paths = tuple(sorted({item.resolve() for item in paths if item.name == "log.foamRun"}))
82
- if canonical_paths:
83
- # log.foamRun is the runner's canonical solver log. Do not read
84
- # multi-hundred-MB repair logs during artifact discovery; execution
85
- # and numerical gates perform the substantive log checks later.
86
- return canonical_paths
87
- if paths:
88
- # Avoid eagerly loading every repair/post-processing log merely to
89
- # choose evidence. Prefer the newest generic log; gate parsing will
90
- # validate its contents when it is actually evaluated.
91
- existing = [item.resolve() for item in paths if item.is_file()]
92
- if existing:
93
- return (max(existing, key=lambda item: item.stat().st_mtime),)
94
- evidence = []
95
- for path in sorted({item.resolve() for item in paths}):
96
- text = read_text(path)
97
- if FATAL_RE.search(text):
98
- continue
99
- evidence.append((path, text, final_log_time(text)))
100
- canonical = [item for item in evidence if item[0].name == "log.foamRun"]
101
- if canonical:
102
- return tuple(item[0] for item in canonical)
103
- timed = [item for item in evidence if item[2] is not None]
104
- if timed:
105
- latest = max(float(item[2]) for item in timed if item[2] is not None)
106
- return tuple(item[0] for item in timed if item[2] == latest)
107
- ended = [item for item in evidence if normal_end(item[1])]
108
- return tuple(item[0] for item in (ended or evidence))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/adapters/foamagent.py DELETED
@@ -1,57 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from ..io import read_object
6
- from ..models import BenchmarkProfile, CaseArtifact
7
- from .common import duration, token_usage
8
-
9
-
10
- class FoamAgentAdapter:
11
- def __init__(self, run_root: Path, profile: BenchmarkProfile):
12
- self.run_root = run_root.resolve(strict=True)
13
- self.profile = profile
14
-
15
- def discover(self) -> dict[str, CaseArtifact]:
16
- artifacts: dict[str, CaseArtifact] = {}
17
- for path in sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json")):
18
- manifest = read_object(path)
19
- case_id = manifest.get("case_id")
20
- if not isinstance(case_id, str) or case_id in artifacts:
21
- continue
22
- rollout = path.parent
23
- case_dir = rollout / "case"
24
- family, variant = self.profile.identity(case_id)
25
- logs = [item for item in case_dir.glob("log.*") if item.is_file()]
26
- logs.extend(item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file())
27
- process = manifest.get("process") if isinstance(manifest.get("process"), dict) else {}
28
- attempts = manifest.get("attempts") if isinstance(manifest.get("attempts"), list) else []
29
- last_attempt = attempts[-1] if attempts and isinstance(attempts[-1], dict) else {}
30
- normalized = dict(manifest)
31
- normalized["return_code"] = process.get(
32
- "return_code", last_attempt.get("return_code", manifest.get("return_code"))
33
- )
34
- normalized["timed_out"] = bool(process.get(
35
- "timed_out", last_attempt.get("timed_out", manifest.get("timed_out", False))
36
- ))
37
- normalized["duration_seconds"] = duration(manifest)
38
- normalized["token_usage"] = token_usage(manifest)
39
- for metrics_path in (rollout / "llm_metrics.json", rollout / "attempt_001.llm_metrics.json"):
40
- if metrics_path.is_file():
41
- normalized["token_usage"] = token_usage({"token_usage": read_object(metrics_path)})
42
- break
43
- if isinstance(manifest.get("execution"), dict):
44
- normalized["source_execution"] = manifest["execution"]
45
- artifacts[case_id] = CaseArtifact(
46
- case_id=case_id,
47
- dataset=self.profile.dataset,
48
- family=str(manifest.get("family") or family),
49
- variant=str(manifest.get("variant") or variant),
50
- replicate=int(manifest.get("replicate", 1)),
51
- rollout_dir=rollout,
52
- workspace_dir=None,
53
- case_dir=case_dir,
54
- manifest=normalized,
55
- solver_logs=tuple(sorted({item.resolve() for item in logs})),
56
- )
57
- return artifacts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/aggregate.py DELETED
@@ -1,100 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import statistics
4
- from collections import Counter
5
- from typing import Any
6
-
7
-
8
- def _rate(count: int, denominator: int) -> float | None:
9
- return count / denominator if denominator else None
10
-
11
-
12
- def aggregate_results(rows: list[dict[str, Any]]) -> dict[str, Any]:
13
- total = len(rows)
14
- execution = sum(bool(row.get("scores", {}).get("execution_pass")) for row in rows)
15
- numerical = sum(bool(row.get("scores", {}).get("numerical_pass")) for row in rows)
16
- qoi = sum(
17
- bool(
18
- row.get("scores", {}).get(
19
- "physics_grounded_qoi_pass",
20
- row.get("scores", {}).get("qoi_pass"),
21
- )
22
- )
23
- for row in rows
24
- )
25
- end_to_end = sum(bool(row.get("scores", {}).get("end_to_end_pass")) for row in rows)
26
- ratios = [float(row.get("qoi", {}).get("effective_pass_ratio", 0.0)) for row in rows]
27
- coverage = [
28
- float(comparison["qoi_coverage_fraction"])
29
- for row in rows
30
- for comparison in [row.get("qoi", {}).get("comparison")]
31
- if isinstance(comparison, dict) and isinstance(comparison.get("qoi_coverage_fraction"), (int, float))
32
- ]
33
- failures = Counter(
34
- failure
35
- for row in rows
36
- for failure in row.get("failure_categories", [])
37
- )
38
- return {
39
- "task_count": total,
40
- "execution_pass_count": execution,
41
- "execution_pass_rate": _rate(execution, total),
42
- "numerical_pass_count": numerical,
43
- "numerical_pass_rate_all_tasks": _rate(numerical, total),
44
- "numerical_pass_rate_execution_pass": _rate(numerical, execution),
45
- "physics_grounded_qoi_pass_count": qoi,
46
- "physics_grounded_qoi_pass_rate_all_tasks": _rate(qoi, total),
47
- "physics_grounded_qoi_pass_rate_execution_pass": _rate(qoi, execution),
48
- "end_to_end_pass_count": end_to_end,
49
- "end_to_end_pass_rate": _rate(end_to_end, total),
50
- "mean_qoi_pass_ratio_all_tasks": statistics.fmean(ratios) if ratios else None,
51
- "mean_qoi_coverage_evaluated": statistics.fmean(coverage) if coverage else None,
52
- "failure_taxonomy": dict(sorted(failures.items())),
53
- }
54
-
55
-
56
- def aggregate_evolution(groups: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
57
- """Paired repeated-split reporting. Duplicate tasks remain group-qualified."""
58
- metrics = ("execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass")
59
-
60
- def summarize(rows):
61
- for row in rows:
62
- for side in ("initial", "evolved"):
63
- scores = row.get("reporting_scores", {}).get(side)
64
- if not isinstance(scores, dict) or any(type(scores.get(key)) is not bool for key in metrics):
65
- raise ValueError("independent reporting scores are missing; reward is not a pass metric")
66
- if scores["end_to_end_pass"] != all(scores[key] for key in metrics[:3]):
67
- raise ValueError("TAR is inconsistent with the three task-level checks")
68
- return {metric: {
69
- side: {"count": sum(row["reporting_scores"][side][metric] for row in rows),
70
- "rate": statistics.fmean(row["reporting_scores"][side][metric] for row in rows)}
71
- for side in ("initial", "evolved")
72
- } | {
73
- "gain": statistics.fmean(int(row["reporting_scores"]["evolved"][metric]) - int(row["reporting_scores"]["initial"][metric]) for row in rows),
74
- "failed_to_passed": sum(not row["reporting_scores"]["initial"][metric] and row["reporting_scores"]["evolved"][metric] for row in rows),
75
- "passed_to_failed": sum(row["reporting_scores"]["initial"][metric] and not row["reporting_scores"]["evolved"][metric] for row in rows),
76
- } for metric in metrics}
77
-
78
- per_group = {}
79
- all_rows = []
80
- for group_id, rows in groups.items():
81
- keys = {(row["dataset"], row["case_id"]) for row in rows}
82
- if not rows or len(keys) != len(rows):
83
- raise ValueError(f"empty or duplicate test tasks in group {group_id}")
84
- per_group[group_id] = {"task_count": len(rows), "metrics": summarize(rows)}
85
- all_rows.extend(dict(row, group_id=group_id) for row in rows)
86
- families = {family: summarize([row for row in all_rows if row["family"] == family])
87
- for family in sorted({row["family"] for row in all_rows})}
88
- means = {metric: {side: {
89
- "mean": statistics.fmean(group["metrics"][metric][side]["rate"] for group in per_group.values()),
90
- "min": min(group["metrics"][metric][side]["rate"] for group in per_group.values()),
91
- "max": max(group["metrics"][metric][side]["rate"] for group in per_group.values()),
92
- } for side in ("initial", "evolved")} for metric in metrics}
93
- return {"groups": per_group, "group_rates": means, "families": families,
94
- "family_equal_weight_rates": {metric: {side: statistics.fmean(family[metric][side]["rate"] for family in families.values())
95
- for side in ("initial", "evolved")} for metric in metrics},
96
- "test_records_per_condition": len(all_rows),
97
- "unique_task_count": len({(row["dataset"], row["case_id"]) for row in all_rows}),
98
- "test_frequency": dict(Counter(f"{row['dataset']}::{row['case_id']}" for row in all_rows)),
99
- "interpretation": "Descriptive repeated splits; overlapping tasks and groups are not independent samples.",
100
- "cases": all_rows}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/basic_advanced.py DELETED
@@ -1,807 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Structured QoIs shared by FoamBench Basic and Advanced references/candidates."""
3
- from __future__ import annotations
4
-
5
- import argparse
6
- import json
7
- import math
8
- import re
9
- import subprocess
10
- from pathlib import Path
11
- from typing import Any, Callable
12
-
13
- from .foam_arrays import FoamArrayError, foam_path, read_scalar_field, read_vector_field
14
- from .foam_io import magnitude, read_text
15
- from .io import utc_now, write_json
16
- from .schema import validate
17
-
18
-
19
- ADVANCED_TEMPLATE = {
20
- "Cavity_LES": "Cavity", "Cavity_SA": "Cavity", "Cavity_geometry_1": "Cavity",
21
- "Cylinder_LES": "Cylinder", "Cylinder_SA": "Cylinder",
22
- "Diamond_Obstacle_KOMEGASST": "Obstacle", "Diamond_Obstacle_SA": "Obstacle",
23
- "Double_Square_SA": "Obstacle", "Rectangular_Obstacle_KOMEGASST": "Obstacle",
24
- "Rectangular_Obstacle_SA": "Obstacle", "counterFlowFlame2D_KE": "counterFlowFlame2D",
25
- "counterFlowFlame2D_SA": "counterFlowFlame2D", "nozzleFlow2D_SA": "Nozzle",
26
- "obliqueShock_KE": "Shock", "obliqueShock_LES": "Shock", "wedge_SA": "Shock",
27
- }
28
-
29
- GROUPS = {
30
- "BernardCells": "thermal_state", "Cavity": "cavity_response", "Cylinder": "wake_response",
31
- "counterFlowFlame2D": "flame_response", "damBreakWithObstacle": "free_surface_response",
32
- "forwardStep": "shock_response", "obliqueShock": "shock_response", "wedge": "shock_response",
33
- "Shock": "shock_response", "pitzDaily": "separation_response", "Obstacle": "obstacle_response",
34
- "shallowWaterWithSquareBump": "surface_response", "squareBend": "bend_response",
35
- "Nozzle": "nozzle_response",
36
- }
37
-
38
- PHYSICS_METRICS = {
39
- "BernardCells": ("temperature_min", "temperature_max", "convection_mean_speed"),
40
- "Cavity": ("response_speed_max", "reverse_flow_min_u"),
41
- "Cylinder": ("wake_deficit_final",),
42
- "counterFlowFlame2D": ("species_sum_max_error", "reaction_temperature_span"),
43
- "damBreakWithObstacle": ("water_volume_relative_drift", "front_net_advance"),
44
- "forwardStep": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
45
- "obliqueShock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
46
- "wedge": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
47
- "Shock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
48
- "pitzDaily": ("reverse_flow_volume_fraction", "streamwise_pressure_change_magnitude"),
49
- "Obstacle": ("streamwise_pressure_change_magnitude",),
50
- "shallowWaterWithSquareBump": ("mid_bump_height_relative_change",),
51
- "squareBend": ("streamwise_pressure_change_magnitude",),
52
- "Nozzle": ("flow_speed_max",),
53
- }
54
-
55
- # Each family already extracts one spatial response profile. Making that
56
- # profile mandatory adds field-structure discrimination without introducing
57
- # another observable or extractor. Scalar envelopes remain the
58
- # reference-independent admissibility check; profiles are the deliberately
59
- # stricter, reference-anchored response-shape check.
60
- PRINCIPAL_RESPONSE_PROFILES = {
61
- "BernardCells": ("thermal_vertical_profile",),
62
- "Cavity": ("centerline_velocity_profiles",),
63
- "Cylinder": ("wake_velocity_profiles",),
64
- "counterFlowFlame2D": ("reaction_zone_profile",),
65
- "damBreakWithObstacle": ("free_surface_profile",),
66
- "forwardStep": ("pressure_mach_profiles",),
67
- "obliqueShock": ("pressure_mach_profiles",),
68
- "wedge": ("pressure_mach_profiles",),
69
- "Shock": ("pressure_mach_profiles",),
70
- "pitzDaily": ("separation_profiles",),
71
- "Obstacle": ("separation_profiles",),
72
- "shallowWaterWithSquareBump": ("surface_profile",),
73
- "squareBend": ("bend_axial_profile",),
74
- "Nozzle": ("nozzle_axial_profile",),
75
- }
76
-
77
-
78
- def principal_metrics(template: str) -> tuple[str, ...]:
79
- return PHYSICS_METRICS[template] + PRINCIPAL_RESPONSE_PROFILES[template]
80
-
81
-
82
- def numeric_times(case: Path) -> list[tuple[float, Path]]:
83
- result = []
84
- for child in case.iterdir():
85
- if child.is_dir():
86
- try:
87
- result.append((float(child.name), child))
88
- except ValueError:
89
- pass
90
- return sorted(result)
91
-
92
-
93
- def align(values: list[Any], count: int) -> list[Any]:
94
- if len(values) == count:
95
- return values
96
- if len(values) == 1 and count:
97
- return values * count
98
- return []
99
-
100
-
101
- def scalars(directory: Path, name: str, count: int) -> list[float]:
102
- path = foam_path(directory, name)
103
- if path is None:
104
- return []
105
- try:
106
- return align(read_scalar_field(path), count)
107
- except (FoamArrayError, OSError, ValueError):
108
- return []
109
-
110
-
111
- def vectors(directory: Path, name: str, count: int) -> list[tuple[float, float, float]]:
112
- path = foam_path(directory, name)
113
- if path is None:
114
- return []
115
- try:
116
- return align(read_vector_field(path), count)
117
- except (FoamArrayError, OSError, ValueError):
118
- match = re.search(
119
- r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)",
120
- read_text(path),
121
- )
122
- return [(float(match[1]), float(match[2]), float(match[3]))] * count if match else []
123
-
124
-
125
- def geometry(case: Path) -> tuple[list[tuple[float, float, float]], list[float], float, Path]:
126
- times = numeric_times(case)
127
- for time, directory in reversed(times):
128
- c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
129
- if c_path and v_path:
130
- centres = read_vector_field(c_path)
131
- volumes = align(read_scalar_field(v_path), len(centres))
132
- if centres and volumes:
133
- return centres, volumes, time, directory
134
- # C and Vc are measurement products, not required solver outputs. The
135
- # independent evaluator also runs without prepare_campaign(), so recover
136
- # the same geometric quantities directly from a retained static polyMesh.
137
- # This uses no reference values and never writes into the frozen case.
138
- if not times:
139
- raise ValueError(f"no retained time directories for measurement: {case}")
140
- from .retained_fields import derive_cell_geometry
141
- try:
142
- volumes, centres, _ = derive_cell_geometry(case)
143
- except (ValueError, OSError) as exc:
144
- raise ValueError(f"missing C/Vc and retained mesh geometry unavailable: {case}: {exc}") from exc
145
- time, directory = times[-1]
146
- count = raw_field_count(directory)
147
- if count is not None and count != len(centres):
148
- raise ValueError(f"retained field/mesh cell count mismatch: {case}")
149
- return centres, volumes, time, directory
150
-
151
-
152
- def raw_field_count(directory: Path) -> int | None:
153
- for name, reader in (("alpha.water", read_scalar_field), ("h", read_scalar_field),
154
- ("T", read_scalar_field), ("p", read_scalar_field), ("U", read_vector_field)):
155
- path = foam_path(directory, name)
156
- if path is None:
157
- continue
158
- try:
159
- count = len(reader(path))
160
- except (FoamArrayError, OSError, ValueError):
161
- continue
162
- if count > 1:
163
- return count
164
- return None
165
-
166
-
167
- def geometry_for_time(
168
- case: Path, directory: Path, fallback_centres: list[tuple[float, float, float]], fallback_volumes: list[float],
169
- ) -> tuple[list[tuple[float, float, float]], list[float]]:
170
- expected = raw_field_count(directory)
171
- if expected in {None, len(fallback_centres)}:
172
- return fallback_centres, fallback_volumes
173
- c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
174
- if not c_path or not v_path:
175
- for function in ("writeCellCentres", "writeCellVolumes"):
176
- completed = subprocess.run(
177
- ["foamPostProcess", "-case", str(case), "-func", function, "-time", directory.name],
178
- stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=False,
179
- )
180
- if completed.returncode != 0:
181
- raise ValueError(f"{case}: {function} failed at time {directory.name}")
182
- c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
183
- if not c_path or not v_path:
184
- raise ValueError(f"{case}: no time-local C/Vc at {directory.name}")
185
- centres = read_vector_field(c_path)
186
- volumes = align(read_scalar_field(v_path), len(centres))
187
- if len(centres) != expected or not volumes:
188
- raise ValueError(f"{case}: time-local geometry mismatch at {directory.name}")
189
- return centres, volumes
190
-
191
-
192
- def bounds(centres: list[tuple[float, float, float]]) -> tuple[list[float], list[float]]:
193
- return ([min(p[i] for p in centres) for i in range(3)], [max(p[i] for p in centres) for i in range(3)])
194
-
195
-
196
- def primary_axis(spans: list[float]) -> int:
197
- """Choose x/y/z deterministically when extents differ only by roundoff."""
198
- largest = max(spans)
199
- return next(i for i, span in enumerate(spans) if math.isclose(span, largest, rel_tol=1e-12, abs_tol=0.0))
200
-
201
-
202
- def weighted(values: list[float], volumes: list[float]) -> float:
203
- denominator = sum(volumes)
204
- return sum(value * volume for value, volume in zip(values, volumes)) / denominator
205
-
206
-
207
- def bins(
208
- centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
209
- fields: dict[str, list[float]], *, count: int = 41,
210
- selector: Callable[[tuple[float, float, float]], bool] | None = None,
211
- ) -> list[list[float]]:
212
- low, high = bounds(centres)
213
- span = high[axis] - low[axis]
214
- groups: list[list[int]] = [[] for _ in range(count)]
215
- for index, point in enumerate(centres):
216
- if selector is not None and not selector(point):
217
- continue
218
- slot = min(count - 1, max(0, int((point[axis] - low[axis]) / max(span, 1e-30) * count)))
219
- groups[slot].append(index)
220
- rows = []
221
- for indices in groups:
222
- if not indices:
223
- continue
224
- weights = [volumes[i] for i in indices]
225
- row = [weighted([centres[i][axis] for i in indices], weights)]
226
- for values in fields.values():
227
- row.append(weighted([values[i] for i in indices], weights))
228
- rows.append(row)
229
- return rows
230
-
231
-
232
- def profile(profile_id: str, coordinate: str, rows: list[list[float]], fields: list[str]) -> dict[str, Any]:
233
- return {"profile_id": profile_id, "columns": [coordinate, *fields], "rows": rows}
234
-
235
-
236
- def named_profiles(items: list[dict[str, Any]]) -> dict[str, Any]:
237
- return {"kind": "named_profiles", "profiles": items}
238
-
239
-
240
- def history(points: list[dict[str, float]]) -> dict[str, Any]:
241
- return {"kind": "time_history", "points": points}
242
-
243
-
244
- def velocity_fields(directory: Path, count: int) -> tuple[list[tuple[float, float, float]], dict[str, list[float]]]:
245
- velocity = vectors(directory, "U", count)
246
- if not velocity:
247
- return [], {}
248
- return velocity, {
249
- "u": [v[0] for v in velocity], "v": [v[1] for v in velocity],
250
- "speed": magnitude(velocity),
251
- }
252
-
253
-
254
- def thermo(case: Path) -> tuple[float, float]:
255
- text = read_text(case / "constant" / "physicalProperties")
256
- mw = re.search(r"(?m)^\s*molWeight\s+([-+0-9.eE]+)\s*;", text)
257
- cp = re.search(r"(?m)^\s*Cp\s+([-+0-9.eE]+)\s*;", text)
258
- if not mw or not cp:
259
- return 1.4, 287.0
260
- gas = 8314.46261815324 / float(mw[1])
261
- heat = float(cp[1])
262
- return (heat / (heat - gas) if heat > gas else 1.4), gas
263
-
264
-
265
- def state_fields(case: Path, directory: Path, count: int) -> dict[str, list[float]]:
266
- _, fields = velocity_fields(directory, count)
267
- for name in (
268
- "p", "p_rgh", "rho", "T", "CH4", "O2", "CO2", "H2O", "N2", "Qdot",
269
- "alpha.water", "alpha.fuel", "h",
270
- ):
271
- values = scalars(directory, name, count)
272
- if values:
273
- fields[name] = values
274
- if fields.get("T") and fields.get("speed"):
275
- gamma, gas = thermo(case)
276
- fields["Mach"] = [u / math.sqrt(gamma * gas * t) if t > 0 else 0.0 for u, t in zip(fields["speed"], fields["T"])]
277
- hu = vectors(directory, "hU", count)
278
- if hu and fields.get("h"):
279
- fields["Froude"] = [
280
- q / h / math.sqrt(9.81 * h) if h > 1e-12 else 0.0
281
- for q, h in zip(magnitude(hu), fields["h"])
282
- ]
283
- return fields
284
-
285
-
286
- def line_profile(
287
- profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float],
288
- axis: int, fixed_axis: int, fraction: float, fields: dict[str, list[float]], names: list[str],
289
- ) -> dict[str, Any]:
290
- low, high = bounds(centres)
291
- target = low[fixed_axis] + fraction * (high[fixed_axis] - low[fixed_axis])
292
- target = min((point[fixed_axis] for point in centres), key=lambda value: abs(value - target))
293
- bandwidth = max((high[fixed_axis] - low[fixed_axis]) / 41.0, 1e-12)
294
- selected = lambda point: abs(point[fixed_axis] - target) <= bandwidth
295
- usable = {name: fields[name] for name in names if name in fields}
296
- return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable, selector=selected), list(usable))
297
-
298
-
299
- def section_profile(
300
- profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
301
- fields: dict[str, list[float]], names: list[str],
302
- ) -> dict[str, Any]:
303
- usable = {name: fields[name] for name in names if name in fields}
304
- return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable), list(usable))
305
-
306
-
307
- def histories(
308
- case: Path, centres: list[tuple[float, float, float]], volumes: list[float],
309
- measure: Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None],
310
- ) -> dict[str, Any]:
311
- points = []
312
- for time, directory in numeric_times(case):
313
- local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes)
314
- fields = state_fields(case, directory, len(local_centres))
315
- value = measure(fields, local_centres, local_volumes)
316
- if value is not None and math.isfinite(value):
317
- points.append({"time": time, "value": float(value)})
318
- return history(points)
319
-
320
-
321
- def shock_events(value: dict[str, Any]) -> dict[str, Any]:
322
- events = []
323
- for item in value.get("profiles", []):
324
- columns, rows = item["columns"], item["rows"]
325
- if "p" not in columns or len(rows) < 2:
326
- continue
327
- p_index = columns.index("p")
328
- candidates = []
329
- coordinate_min, coordinate_max = rows[0][0], rows[-1][0]
330
- interior_low = coordinate_min + 0.05 * (coordinate_max - coordinate_min)
331
- interior_high = coordinate_max - 0.05 * (coordinate_max - coordinate_min)
332
- for left, right in zip(rows, rows[1:]):
333
- dx = right[0] - left[0]
334
- coordinate = 0.5 * (right[0] + left[0])
335
- if dx > 0 and interior_low < coordinate < interior_high:
336
- candidates.append((abs(right[p_index] - left[p_index]) / dx, coordinate, dx))
337
- if candidates:
338
- _, coordinate, cell = max(candidates)
339
- events.append({"profile_id": item["profile_id"], "field": "p", "coordinate": coordinate, "local_cell_size": cell})
340
- return {"kind": "profile_feature_locations", "events": events}
341
-
342
-
343
- def relative_drift(values: list[float]) -> float | None:
344
- finite_values = [float(value) for value in values if math.isfinite(value)]
345
- if len(finite_values) < 2:
346
- return None
347
- scale = max(abs(finite_values[0]), sum(abs(value) for value in finite_values) / len(finite_values), 1e-12)
348
- return (max(finite_values) - min(finite_values)) / scale
349
-
350
-
351
- def pressure_change(
352
- pressure: list[float], centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
353
- ) -> float | None:
354
- if not pressure:
355
- return None
356
- cut = max(1, len(pressure) // 10)
357
- ordered = sorted(zip(centres, pressure, volumes), key=lambda item: item[0][axis])
358
- first, last = ordered[:cut], ordered[-cut:]
359
- return weighted([p for _, p, _ in first], [w for _, _, w in first]) - weighted(
360
- [p for _, p, _ in last], [w for _, _, w in last]
361
- )
362
-
363
-
364
- def inventory_series(case: Path, field_name: str) -> list[float]:
365
- centres, volumes, _, _ = geometry(case)
366
- values = []
367
- for _, directory in numeric_times(case):
368
- local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes)
369
- field = scalars(directory, field_name, len(local_centres))
370
- if field:
371
- values.append(sum(value * volume for value, volume in zip(field, local_volumes)))
372
- return values
373
-
374
-
375
- def shock_pressure_jump_ratio(profiles: dict[str, Any]) -> float | None:
376
- ratios = []
377
- for item in profiles.get("profiles", []):
378
- columns, rows = item.get("columns", []), item.get("rows", [])
379
- if "p" not in columns:
380
- continue
381
- index = columns.index("p")
382
- for left, right in zip(rows, rows[1:]):
383
- low, high = sorted((float(left[index]), float(right[index])))
384
- if low > 0:
385
- ratios.append(high / low)
386
- return max(ratios) if ratios else None
387
-
388
-
389
- def family_qois(case: Path, template: str) -> dict[str, Any]:
390
- centres, volumes, _, latest = geometry(case)
391
- low, high = bounds(centres)
392
- spans = [high[i] - low[i] for i in range(3)]
393
- primary = primary_axis(spans)
394
- secondary = 1 if primary == 0 else 0
395
- fields = state_fields(case, latest, len(centres))
396
- if fields.get("p"):
397
- pressure_mean = weighted(fields["p"], volumes)
398
- fields["p_gauge"] = [value - pressure_mean for value in fields["p"]]
399
- qois: dict[str, Any] = {}
400
-
401
- def downstream_min_u(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
402
- values = [u for point, u in zip(c, f.get("u", [])) if point[primary] >= low[primary] + 0.5 * spans[primary]]
403
- return min(values) if values else None
404
-
405
- def middle_section_mean(name: str, fraction: float = 0.5) -> Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None]:
406
- def measure(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
407
- values = f.get(name, [])
408
- if not values:
409
- return None
410
- local_low, local_high = bounds(c)
411
- target = local_low[primary] + fraction * (local_high[primary] - local_low[primary])
412
- target = min((point[primary] for point in c), key=lambda value: abs(value - target))
413
- width = max((local_high[primary] - local_low[primary]) / 41.0, 1e-12)
414
- selected = [(value, volume) for point, value, volume in zip(c, values, v) if abs(point[primary] - target) <= width]
415
- return weighted([item[0] for item in selected], [item[1] for item in selected]) if selected else None
416
- return measure
417
-
418
- def wake_deficit(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
419
- streamwise = f.get("u", [])
420
- if not streamwise:
421
- return None
422
- local_low, local_high = bounds(c)
423
- span = local_high[primary] - local_low[primary]
424
- width = max(span / 41.0, 1e-12)
425
- section_values = []
426
- for fraction in (0.10, 0.65):
427
- target = local_low[primary] + fraction * span
428
- target = min((point[primary] for point in c), key=lambda value: abs(value - target))
429
- selected = [(u, volume) for point, u, volume in zip(c, streamwise, v)
430
- if abs(point[primary] - target) <= width]
431
- if not selected:
432
- return None
433
- section_values.append(weighted([item[0] for item in selected], [item[1] for item in selected]))
434
- upstream, wake = section_values
435
- return (upstream - wake) / max(abs(upstream), 1e-12)
436
-
437
- if template == "BernardCells":
438
- qois["thermal_vertical_profile"] = named_profiles([
439
- line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["T", "u", "v", "speed"])
440
- ])
441
- qois["circulation_strength_history"] = histories(case, centres, volumes, lambda f, c, v: weighted(f["speed"], v) if f.get("speed") else None)
442
- if fields.get("T"):
443
- qois["temperature_min"] = min(fields["T"])
444
- qois["temperature_max"] = max(fields["T"])
445
- if fields.get("speed"):
446
- qois["convection_mean_speed"] = weighted(fields["speed"], volumes)
447
- elif template == "Cavity":
448
- qois["centerline_velocity_profiles"] = named_profiles([
449
- line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["u", "v", "speed"]),
450
- line_profile("horizontal_centerline", centres, volumes, 0, 1, 0.5, fields, ["u", "v", "speed"]),
451
- ])
452
- qois["kinetic_energy_history"] = histories(case, centres, volumes, lambda f, c, w: 0.5 * weighted([v*v for v in f["speed"]], w) if f.get("speed") else None)
453
- if fields.get("speed"):
454
- qois["response_speed_max"] = max(fields["speed"])
455
- if fields.get("u"):
456
- qois["reverse_flow_min_u"] = min(fields["u"])
457
- elif template == "Cylinder":
458
- qois["wake_velocity_profiles"] = named_profiles([
459
- line_profile(f"wake_x_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"])
460
- for fraction in (0.65, 0.80)
461
- ])
462
- qois["wake_deficit_history"] = histories(case, centres, volumes, wake_deficit)
463
- points = qois["wake_deficit_history"].get("points", [])
464
- if points:
465
- qois["wake_deficit_final"] = float(points[-1]["value"])
466
- elif template == "counterFlowFlame2D":
467
- names = ["T", "CO2"] + (["Qdot"] if fields.get("Qdot") else [])
468
- qois["reaction_zone_profile"] = named_profiles([section_profile("reaction_axis", centres, volumes, primary, fields, names)])
469
- if fields.get("Qdot"):
470
- qois["heat_release_history"] = histories(case, centres, volumes, lambda f, c, w: sum(v*vol for v, vol in zip(f["Qdot"], w)) if f.get("Qdot") else None)
471
- else:
472
- qois["peak_temperature_history"] = histories(case, centres, volumes, lambda f, c, v: max(f["T"]) if f.get("T") else None)
473
- species = [fields[name] for name in ("CH4", "O2", "CO2", "H2O", "N2") if fields.get(name)]
474
- if len(species) == 5:
475
- qois["species_sum_max_error"] = max(abs(sum(values) - 1.0) for values in zip(*species))
476
- if fields.get("T"):
477
- qois["reaction_temperature_span"] = max(fields["T"]) - min(fields["T"])
478
- elif template == "damBreakWithObstacle":
479
- qois["front_position_history"] = histories(case, centres, volumes, lambda f, c, v: max((p[0] for p, a in zip(c, f.get("alpha.water", [])) if a >= 0.5), default=None))
480
- alpha = fields.get("alpha.water", [])
481
- rows = []
482
- for slot in bins(centres, volumes, 0, {"alpha": alpha}):
483
- x = slot[0]
484
- width = spans[0] / 41
485
- wet_y = [p[1] for p, a in zip(centres, alpha) if abs(p[0] - x) <= width and a >= 0.5]
486
- if wet_y:
487
- rows.append([x, max(wet_y)])
488
- qois["free_surface_profile"] = named_profiles([profile("alpha_0.5_surface", "x", rows, ["surface_y"])])
489
- drift = relative_drift(inventory_series(case, "alpha.water"))
490
- if drift is not None:
491
- qois["water_volume_relative_drift"] = drift
492
- front_points = qois["front_position_history"].get("points", [])
493
- if len(front_points) >= 2:
494
- qois["front_net_advance"] = float(front_points[-1]["value"]) - float(front_points[0]["value"])
495
- elif template in {"forwardStep", "obliqueShock", "wedge", "Shock"}:
496
- profiles = named_profiles([
497
- line_profile(f"streamline_{fraction:.2f}", centres, volumes, primary, secondary, fraction, fields, ["p", "Mach", "u", "speed"])
498
- for fraction in (0.25, 0.50, 0.75)
499
- ])
500
- qois["pressure_mach_profiles"] = profiles
501
- qois["shock_feature_locations"] = shock_events(profiles)
502
- if fields.get("Mach"):
503
- qois["supersonic_volume_fraction"] = sum(
504
- volume for mach, volume in zip(fields["Mach"], volumes) if mach > 1.0
505
- ) / sum(volumes)
506
- jump = shock_pressure_jump_ratio(profiles)
507
- if jump is not None:
508
- qois["shock_pressure_jump_ratio"] = jump
509
- elif template in {"pitzDaily", "Obstacle"}:
510
- qois["separation_profiles"] = named_profiles([
511
- section_profile("streamwise_sections", centres, volumes, primary, fields, ["u", "v", "speed", "p_gauge"]),
512
- *[line_profile(f"wake_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"]) for fraction in (0.65, 0.80)],
513
- ])
514
- qois["recirculation_strength_history"] = histories(case, centres, volumes, downstream_min_u)
515
- downstream = [
516
- (u, volume) for point, u, volume in zip(centres, fields.get("u", []), volumes)
517
- if point[primary] >= low[primary] + 0.5 * spans[primary]
518
- ]
519
- if downstream:
520
- qois["reverse_flow_volume_fraction"] = sum(
521
- volume for u, volume in downstream if u < 0.0
522
- ) / sum(volume for _, volume in downstream)
523
- change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary)
524
- if change is not None:
525
- qois["streamwise_pressure_change_magnitude"] = abs(change)
526
- elif template == "shallowWaterWithSquareBump":
527
- qois["surface_profile"] = named_profiles([section_profile("bump_axis", centres, volumes, primary, fields, ["h", "Froude"])])
528
- qois["mid_bump_height_history"] = histories(case, centres, volumes, middle_section_mean("h"))
529
- height_points = qois["mid_bump_height_history"].get("points", [])
530
- if len(height_points) >= 2:
531
- first, last = float(height_points[0]["value"]), float(height_points[-1]["value"])
532
- qois["mid_bump_height_relative_change"] = abs(last - first) / max(abs(first), 1e-12)
533
- elif template in {"squareBend", "Nozzle"}:
534
- prefix = "bend" if template == "squareBend" else "nozzle"
535
- qois[f"{prefix}_axial_profile"] = named_profiles([section_profile("axial_sections", centres, volumes, primary, fields, ["p", "p_rgh", "Mach", "u", "speed"])])
536
- def pressure_drop(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
537
- return pressure_change(f.get("p") or f.get("p_rgh") or [], c, v, primary)
538
- qois["pressure_drop_history"] = histories(case, centres, volumes, pressure_drop)
539
- if template == "squareBend":
540
- change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary)
541
- if change is not None:
542
- qois["streamwise_pressure_change_magnitude"] = abs(change)
543
- else:
544
- drift = relative_drift(inventory_series(case, "alpha.fuel"))
545
- if drift is not None:
546
- qois["transported_phase_inventory_relative_drift"] = drift
547
- if fields.get("speed"):
548
- qois["flow_speed_max"] = max(fields["speed"])
549
- else:
550
- raise ValueError(f"no structured QoI family for {template}")
551
- return qois
552
-
553
-
554
- def structured_errors(name: str, value: Any) -> list[str]:
555
- if isinstance(value, (int, float)) and not isinstance(value, bool):
556
- return [] if math.isfinite(float(value)) else [f"{name}: non-finite scalar"]
557
- if not isinstance(value, dict):
558
- return [f"{name}: not structured"]
559
- if value.get("kind") == "time_history":
560
- return [] if len(value.get("points", [])) >= 2 else [f"{name}: fewer than two history points"]
561
- if value.get("kind") == "named_profiles":
562
- profiles = value.get("profiles", [])
563
- return [] if profiles and all(len(p.get("rows", [])) >= 2 and len(p.get("columns", [])) >= 2 for p in profiles) else [f"{name}: incomplete profiles"]
564
- if value.get("kind") == "profile_feature_locations":
565
- return [] if value.get("events") else [f"{name}: no feature events"]
566
- return [f"{name}: unsupported kind"]
567
-
568
-
569
- def extract(
570
- case: Path,
571
- case_id: str,
572
- requested_metrics: list[str] | None = None,
573
- *,
574
- required_metrics: list[str] | None = None,
575
- log_paths: list[Path] | None = None,
576
- ) -> dict[str, Any]:
577
- family = case_id.split("/", 1)[0]
578
- template = ADVANCED_TEMPLATE.get(case_id, family)
579
- values = family_qois(case, template)
580
- requested = requested_metrics or sorted(values)
581
- required = required_metrics or requested
582
- selected = {name: values[name] for name in requested if name in values}
583
- missing = sorted(set(required) - set(selected))
584
- errors = [
585
- error for name, value in selected.items() if name in required
586
- for error in structured_errors(name, value)
587
- ]
588
- _, _, latest_time, _ = geometry(case)
589
- complete = not missing and not errors
590
- return {
591
- "schema_version": "foambench.qoi.candidate", "case_id": case_id, "family": template,
592
- "latest_time": latest_time, "status": "complete" if complete else "incomplete",
593
- "principal_qoi_group": GROUPS[template],
594
- "principal_metrics": sorted(name for name in required if name in selected),
595
- "required_metrics": required, "missing_metrics": missing, "qois": selected,
596
- "health": {"status": "pass" if complete else "fail", "checks": {
597
- "principal_qoi_complete": not missing, "structured_qoi_valid": not errors,
598
- "measurement_geometry_available": True, "no_proxy_fallback": True,
599
- }, "validation_errors": errors},
600
- }
601
-
602
-
603
- FIELD_NORMALIZATION_FLOORS = {
604
- "p": 1.0, "p_gauge": 1.0, "p_rgh": 1.0, "T": 0.1, "CO2": 1e-6, "Qdot": 1e-3,
605
- "u": 1e-5, "v": 1e-5, "speed": 1e-5, "Mach": 1e-4,
606
- "h": 1e-6, "Froude": 1e-4, "surface_y": 1e-6,
607
- }
608
- HISTORY_NORMALIZATION_FLOORS = {
609
- "circulation_strength_history": 1e-6, "kinetic_energy_history": 1e-8,
610
- "wake_deficit_history": 1e-4, "recirculation_strength_history": 1e-5,
611
- "heat_release_history": 1e-3, "peak_temperature_history": 0.1,
612
- "front_position_history": 1e-5, "mid_bump_height_history": 1e-6,
613
- "pressure_drop_history": 1.0,
614
- }
615
-
616
-
617
- def tolerance(name: str, value: dict[str, Any], group: str) -> dict[str, Any]:
618
- kind = value.get("kind")
619
- if kind == "time_history":
620
- return {"kind": kind, "normalized_rmse_max": 0.06 if group == "shock_response" else 0.08,
621
- "normalized_linf_max": 0.15 if group == "shock_response" else 0.20,
622
- "minimum_time_coverage": 1.0,
623
- "normalization_floor": HISTORY_NORMALIZATION_FLOORS.get(name, 1e-8), "provisional": True}
624
- if kind == "named_profiles":
625
- columns = {column for item in value.get("profiles", []) for column in item.get("columns", [])[1:]}
626
- return {"kind": kind, "normalized_l1_max": 0.05 if group == "shock_response" else 0.08,
627
- "normalized_linf_max": 0.15 if group == "shock_response" else 0.20,
628
- "normalization_floors": {column: FIELD_NORMALIZATION_FLOORS.get(column, 1e-8) for column in sorted(columns)},
629
- "criterion_role": "principal_response_shape",
630
- "reference_independent": False,
631
- "threshold_source": "reference_anchored_spatial_response_shape",
632
- "provisional": True}
633
- if kind == "profile_feature_locations":
634
- return {"kind": kind, "maximum_cell_offset": 2.0, "physical_floor": 1e-10, "provisional": True}
635
- raise ValueError(f"unsupported structured tolerance for {kind}")
636
-
637
-
638
- def uniform_scalars(path: Path) -> list[float]:
639
- return [
640
- float(match)
641
- for match in re.findall(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", read_text(path))
642
- ]
643
-
644
-
645
- def uniform_vector_magnitudes(path: Path) -> list[float]:
646
- return [
647
- math.sqrt(sum(float(component) ** 2 for component in match))
648
- for match in re.findall(
649
- r"\bvalue\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)\s*;",
650
- read_text(path),
651
- )
652
- ]
653
-
654
-
655
- def physical_tolerance(template: str, name: str, case: Path) -> dict[str, Any]:
656
- common: dict[str, Any] = {
657
- "kind": "physics_range",
658
- "criterion_role": "principal_physics",
659
- "reference_independent": True,
660
- }
661
- if template == "BernardCells" and name in {"temperature_min", "temperature_max"}:
662
- imposed = uniform_scalars(case / "0" / "T")
663
- if len(imposed) < 2:
664
- raise ValueError(f"{case}: cannot determine imposed temperature envelope")
665
- low, high = min(imposed), max(imposed)
666
- margin = max(1e-6, 0.02 * max(high - low, 1e-6))
667
- bounds = (low - margin, high + margin)
668
- return {**common, "low": bounds[0], "high": bounds[1],
669
- "threshold_source": "imposed_temperature_boundary_envelope", "provisional": False}
670
- if template == "BernardCells" and name == "convection_mean_speed":
671
- return {**common, "low": 1e-12, "high": 1e6,
672
- "threshold_source": "nontrivial_buoyant_response", "provisional": True}
673
- if template == "Cavity":
674
- imposed = uniform_vector_magnitudes(case / "0" / "U")
675
- lid_speed = max(imposed, default=0.0)
676
- if lid_speed <= 0:
677
- raise ValueError(f"{case}: cannot determine moving-wall speed")
678
- if name == "response_speed_max":
679
- return {**common, "low": 0.10 * lid_speed, "high": 1.0 * lid_speed,
680
- "threshold_source": "lid_speed_response_envelope_tightened", "provisional": True}
681
- if name == "reverse_flow_min_u":
682
- return {**common, "low": -1.0 * lid_speed, "high": -0.05 * lid_speed,
683
- "threshold_source": "main_vortex_reverse_flow_envelope_tightened", "provisional": True}
684
- if template == "shallowWaterWithSquareBump" and name == "mid_bump_height_relative_change":
685
- initial_depths = uniform_scalars(case / "0" / "h")
686
- initial_depth = sum(initial_depths) / len(initial_depths) if initial_depths else 0.0
687
- # The shallow-water family changes regime with its prompt-specified
688
- # initial depth. A single non-zero floor would accept a numerically
689
- # stagnant response for the deeper cases.
690
- low = 2e-4 if initial_depth <= 0.012 else 0.1
691
- return {**common, "low": low, "high": 1.0,
692
- "threshold_source": "initial_depth_conditioned_bump_response", "provisional": True}
693
- fixed = {
694
- # These are first-stage family envelopes: they reject merely non-zero
695
- # signatures while retaining the checked-in reference regimes. They
696
- # are intentionally absolute and reference-independent; later runs can
697
- # replace them with law-based relations or repeatability envelopes.
698
- ("Cylinder", "wake_deficit_final"): (0.03, 0.15, "bounded_dimensionless_wake_deficit"),
699
- ("counterFlowFlame2D", "species_sum_max_error"): (0.0, 5e-5, "species_mass_fraction_closure_tightened"),
700
- ("counterFlowFlame2D", "reaction_temperature_span"): (500.0, 3000.0, "bounded_thermal_reaction_zone"),
701
- ("damBreakWithObstacle", "water_volume_relative_drift"): (0.0, 5e-3, "closed_phase_volume_conservation_tightened"),
702
- ("damBreakWithObstacle", "front_net_advance"): (0.03, 0.25, "bounded_downstream_free_surface_advance"),
703
- ("forwardStep", "supersonic_volume_fraction"): (0.40, 1.0, "supersonic_regime_coverage_tightened"),
704
- ("obliqueShock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
705
- ("wedge", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
706
- ("Shock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
707
- ("forwardStep", "shock_pressure_jump_ratio"): (1.50, 20.0, "bounded_compressive_pressure_feature"),
708
- ("obliqueShock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"),
709
- ("wedge", "shock_pressure_jump_ratio"): (2.00, 6.50, "bounded_compressive_pressure_feature"),
710
- ("Shock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"),
711
- ("pitzDaily", "reverse_flow_volume_fraction"): (1e-3, 0.08, "bounded_separated_reverse_flow_signature"),
712
- ("pitzDaily", "streamwise_pressure_change_magnitude"): (8.0, 140.0, "bounded_streamwise_pressure_response"),
713
- ("Obstacle", "streamwise_pressure_change_magnitude"): (0.005, 10.0, "bounded_obstacle_pressure_response"),
714
- ("squareBend", "streamwise_pressure_change_magnitude"): (3e4, 1.2e5, "bounded_bend_pressure_response"),
715
- ("Nozzle", "flow_speed_max"): (100.0, 1000.0, "bounded_nozzle_flow_response"),
716
- }
717
- if (template, name) not in fixed:
718
- raise ValueError(f"no physics tolerance for {template}/{name}")
719
- low, high, source = fixed[(template, name)]
720
- exact_sources = {"species_mass_fraction_closure", "closed_phase_volume_conservation"}
721
- return {**common, "low": low, "high": high, "threshold_source": source,
722
- "provisional": source not in exact_sources}
723
-
724
-
725
- def diagnostic_scalar_tolerance(value: float) -> dict[str, Any]:
726
- scale = max(abs(float(value)), 1e-12)
727
- return {
728
- "low": float(value) - 0.2 * scale,
729
- "high": float(value) + 0.2 * scale,
730
- "kind": "diagnostic_scalar_reference",
731
- "provisional": True,
732
- "threshold_source": "reference_diagnostic_relative_band",
733
- }
734
-
735
-
736
- def build_references(run_root: Path) -> tuple[dict[str, Any], dict[str, Any]]:
737
- documents: dict[str, dict[str, Any]] = {}
738
- for track in ("basic", "advanced"):
739
- records = {}
740
- for wrapper in sorted((run_root / "materialized" / track).iterdir()):
741
- case = wrapper / "case"
742
- if not case.is_dir():
743
- continue
744
- case_id = wrapper.name.replace("__", "/", 1) if track == "basic" else wrapper.name
745
- candidate = extract(case, case_id)
746
- if candidate["status"] != "complete":
747
- raise ValueError(f"{case_id}: {candidate['health'].get('validation_errors') or candidate['missing_metrics']}")
748
- group, qois = candidate["principal_qoi_group"], candidate["qois"]
749
- principal = list(principal_metrics(candidate["family"]))
750
- missing_principal = sorted(set(principal) - set(qois))
751
- if missing_principal:
752
- raise ValueError(f"{case_id}: missing physics metrics {missing_principal}")
753
- roles = {name: "principal" if name in principal else "diagnostic" for name in qois}
754
- tolerances = {
755
- name: tolerance(name, value, group)
756
- if isinstance(value, dict) and name in principal else (
757
- physical_tolerance(candidate["family"], name, case)
758
- if name in principal else (
759
- diagnostic_scalar_tolerance(value)
760
- if isinstance(value, (int, float)) and not isinstance(value, bool)
761
- else tolerance(name, value, group)
762
- )
763
- )
764
- for name, value in qois.items()
765
- }
766
- records[case_id] = {
767
- "track": track, "family": candidate["family"], "source_case_id": case_id,
768
- "latest_time": candidate["latest_time"], "principal_qoi_group": group,
769
- "principal_metrics": sorted(principal), "qois": qois,
770
- "metric_roles": roles, "tolerances": tolerances,
771
- "health": candidate["health"], "extraction": {
772
- "producer": "benchmarks/evaluation/basic_advanced.py",
773
- "geometry": "field-derived physics metrics plus physical-coordinate reference diagnostics",
774
- "reference_run": str(run_root),
775
- },
776
- }
777
- documents[track] = {
778
- "schema_version": "foambench.reference_qois.v2", "generated_at": utc_now(),
779
- "openfoam_version": "Foundation v13", "producer": "benchmarks/evaluation/basic_advanced.py",
780
- "design": "guide/foambench_basic_advanced_qoi_design.md",
781
- "tolerance_policy": "physics_grounded_scalar_and_response_shape_joint_gate.v2",
782
- "summary": {"tracks": [track], "case_count": len(records), "health_pass_count": len(records), "health_fail_count": 0},
783
- "notes": ["Principal scalar QoIs are reference-independent family physics criteria extracted from retained fields.",
784
- "One existing spatial response profile per family is also principal and must jointly pass its reference-anchored shape tolerance.",
785
- "Other histories, profiles, and feature locations remain diagnostic and do not decide Physics-grounded pass.",
786
- "Provisional physical-signature and response-shape limits require future valid-alternative calibration."],
787
- "cases": records,
788
- }
789
- validate(documents[track], "foambench_qoi_reference.schema.json")
790
- return documents["basic"], documents["advanced"]
791
-
792
-
793
- def main() -> int:
794
- parser = argparse.ArgumentParser(description=__doc__)
795
- parser.add_argument("--run-root", required=True, type=Path)
796
- parser.add_argument("--basic-output", required=True, type=Path)
797
- parser.add_argument("--advanced-output", required=True, type=Path)
798
- args = parser.parse_args()
799
- basic, advanced = build_references(args.run_root.resolve(strict=True))
800
- write_json(args.basic_output, basic)
801
- write_json(args.advanced_output, advanced)
802
- print(json.dumps({"basic": len(basic["cases"]), "advanced": len(advanced["cases"])}, indent=2))
803
- return 0
804
-
805
-
806
- if __name__ == "__main__":
807
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/cli.py DELETED
@@ -1,79 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import argparse
4
- import json
5
- import sys
6
- from pathlib import Path
7
-
8
- from .io import read_object
9
- from .models import BenchmarkProfile
10
- from .pipeline import evaluate_campaign
11
- from .preparation import prepare_campaign
12
- from .profiles import load_assets
13
- from .reporting import summary_table
14
- from .schema import validate
15
-
16
-
17
- def build_parser() -> argparse.ArgumentParser:
18
- parser = argparse.ArgumentParser(description="Evaluate FoamBench rollouts with a dataset-independent scorer.")
19
- subparsers = parser.add_subparsers(dest="command", required=True)
20
- validate = subparsers.add_parser("validate-profile", help="validate benchmark profile assets")
21
- validate.add_argument("--profile", type=Path, required=True)
22
- evaluate = subparsers.add_parser("evaluate", help="evaluate one rollout campaign")
23
- evaluate.add_argument("--profile", type=Path, required=True)
24
- evaluate.add_argument("--adapter", choices=("easyfoam", "foamagent", "chatcfd", "coding-agent"), required=True)
25
- evaluate.add_argument("--run-root", type=Path, required=True)
26
- evaluate.add_argument("--output", type=Path, required=True)
27
- evaluate.add_argument(
28
- "--prepare", action="store_true",
29
- help="generate measurement-only C, Vc, and vorticity fields before evaluation",
30
- )
31
- evaluate.add_argument("--prepare-jobs", type=int, default=1)
32
- evaluate.add_argument(
33
- "--check-mesh", action="store_true",
34
- help="run read-only checkMesh when no retained mesh log is available",
35
- )
36
- evaluate.add_argument("--mesh-timeout", type=float, default=120.0)
37
- return parser
38
-
39
-
40
- def main(argv: list[str] | None = None) -> int:
41
- args = build_parser().parse_args(argv)
42
- validate(read_object(args.profile), "benchmark_profile.schema.json")
43
- profile = BenchmarkProfile.load(args.profile)
44
- if args.command == "validate-profile":
45
- benchmark, references = load_assets(profile)
46
- print(json.dumps({
47
- "profile_id": profile.profile_id,
48
- "dataset": profile.dataset,
49
- "benchmark_case_count": len(benchmark),
50
- "reference_case_count": len(references),
51
- "status": "pass",
52
- }, indent=2, sort_keys=True))
53
- return 0
54
- if args.prepare:
55
- prepare_campaign(
56
- profile,
57
- adapter_name=args.adapter,
58
- run_root=args.run_root,
59
- output_root=args.output.resolve() / "preparation",
60
- jobs=args.prepare_jobs,
61
- )
62
- report = evaluate_campaign(
63
- profile,
64
- adapter_name=args.adapter,
65
- run_root=args.run_root,
66
- output_dir=args.output,
67
- check_mesh=args.check_mesh,
68
- mesh_timeout=args.mesh_timeout,
69
- )
70
- print(summary_table(report["overall"]))
71
- return 0
72
-
73
-
74
- if __name__ == "__main__":
75
- try:
76
- raise SystemExit(main())
77
- except (OSError, ValueError, RuntimeError) as exc:
78
- print(f"foambench-evaluate: error: {exc}", file=sys.stderr)
79
- raise SystemExit(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/comparison.py DELETED
@@ -1,750 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Compare candidate FoamBench QoIs with checked-in reference contracts.
3
-
4
- Coverage and numerical agreement are reported separately. Related field
5
- statistics are scored as equal-weight QoI groups; ranges and runtime metrics
6
- remain available as diagnostics but do not determine the group score. A
7
- missing QoI means that the benchmark cannot assess that part of the result; it
8
- is not relabelled as an out-of-tolerance value.
9
- """
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import json
14
- import math
15
- import re
16
- import sys
17
- from datetime import datetime, timezone
18
- from pathlib import Path
19
- from typing import Any
20
-
21
-
22
- def finite(value: Any) -> float | None:
23
- if isinstance(value, bool) or not isinstance(value, (int, float)):
24
- return None
25
- result = float(value)
26
- return result if math.isfinite(result) else None
27
-
28
-
29
- def scalar_observation(value: Any) -> float | None:
30
- direct = finite(value)
31
- if direct is not None:
32
- return direct
33
- if isinstance(value, dict) and value.get("kind") in {"scalar_ratio", "window_regression"}:
34
- return finite(value.get("value"))
35
- return None
36
-
37
-
38
- def interpolate(points: list[dict[str, Any]], time: float) -> float | None:
39
- rows = [(finite(item.get("time")), finite(item.get("value"))) for item in points if isinstance(item, dict)]
40
- rows = sorted((t, v) for t, v in rows if t is not None and v is not None)
41
- if not rows or time < rows[0][0] or time > rows[-1][0]:
42
- return None
43
- for index, (left_t, left_v) in enumerate(rows):
44
- if abs(time - left_t) <= 1e-12 * max(1.0, abs(time)):
45
- return left_v
46
- if index + 1 < len(rows) and left_t < time < rows[index + 1][0]:
47
- right_t, right_v = rows[index + 1]
48
- weight = (time - left_t) / (right_t - left_t)
49
- return left_v + weight * (right_v - left_v)
50
- return None
51
-
52
-
53
- def compare_history(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
54
- reference_points = reference.get("points", [])
55
- candidate_points = candidate.get("points", [])
56
- pairs = []
57
- for point in reference_points if isinstance(reference_points, list) else []:
58
- time, reference_value = finite(point.get("time")), finite(point.get("value")) if isinstance(point, dict) else (None, None)
59
- if time is None or reference_value is None:
60
- continue
61
- candidate_value = interpolate(candidate_points if isinstance(candidate_points, list) else [], time)
62
- if candidate_value is not None:
63
- pairs.append((reference_value, candidate_value))
64
- required_coverage = finite(tolerance.get("minimum_time_coverage")) or 1.0
65
- coverage = len(pairs) / len(reference_points) if reference_points else 0.0
66
- if not pairs:
67
- return {"status": "missing", "coverage_fraction": coverage}
68
- floor = finite(tolerance.get("normalization_floor")) or 1e-12
69
- norm = max(math.sqrt(sum(ref * ref for ref, _ in pairs) / len(pairs)), floor)
70
- errors = [cand - ref for ref, cand in pairs]
71
- nrmse = math.sqrt(sum(error * error for error in errors) / len(errors)) / norm
72
- nlinf = max(abs(error) for error in errors) / norm
73
- rmse_limit = finite(tolerance.get("normalized_rmse_max"))
74
- linf_limit = finite(tolerance.get("normalized_linf_max"))
75
- valid = rmse_limit is not None and linf_limit is not None
76
- passed = valid and coverage >= required_coverage and nrmse <= rmse_limit and nlinf <= linf_limit
77
- return {"status": "within_tolerance" if passed else "invalid_contract" if not valid else "out_of_tolerance",
78
- "coverage_fraction": coverage, "aligned_point_count": len(pairs),
79
- "normalized_rmse": nrmse, "normalized_linf": nlinf,
80
- "normalized_rmse_max": rmse_limit, "normalized_linf_max": linf_limit}
81
-
82
-
83
- def profile_key(profile: dict[str, Any]) -> str:
84
- """Normalize centerline aliases by the coordinate direction they sample."""
85
- name = Path(str(profile.get("profile_id", ""))).name.lower()
86
- stem = Path(name).stem
87
- if stem in {"centreline_y0", "centerline_y0", "centerliney", "horizontal", "horizontalcenterline", "horizontalcentreline"}:
88
- return "horizontal.xy"
89
- if stem in {"centreline_x0", "centerline_x0", "centerlinex", "vertical", "verticalcenterline", "verticalcentreline"}:
90
- return "vertical.xy"
91
- return name
92
-
93
-
94
- def compare_profiles(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
95
- references = {profile_key(item): item for item in reference.get("profiles", []) if isinstance(item, dict)}
96
- candidates = {profile_key(item): item for item in candidate.get("profiles", []) if isinstance(item, dict)}
97
- l1_limit, linf_limit = finite(tolerance.get("normalized_l1_max")), finite(tolerance.get("normalized_linf_max"))
98
- if l1_limit is None or linf_limit is None:
99
- return {"status": "invalid_contract"}
100
- fields: list[dict[str, Any]] = []
101
- expected_fields = sum(max(0, len(item.get("columns", [])) - 1) for item in references.values())
102
- for key, ref_profile in references.items():
103
- cand_profile = candidates.get(key)
104
- if cand_profile is None:
105
- continue
106
- ref_columns, cand_columns = ref_profile.get("columns", []), cand_profile.get("columns", [])
107
- ref_rows, cand_rows = ref_profile.get("rows", []), cand_profile.get("rows", [])
108
- if len(ref_columns) < 2 or ref_columns[0] not in cand_columns:
109
- continue
110
- cand_x = cand_columns.index(ref_columns[0])
111
- for field in ref_columns[1:]:
112
- if field not in cand_columns:
113
- continue
114
- ref_i, cand_i = ref_columns.index(field), cand_columns.index(field)
115
- cand_points = [{"time": row[cand_x], "value": row[cand_i]} for row in cand_rows]
116
- pairs = [(row[ref_i], interpolate(cand_points, row[0])) for row in ref_rows]
117
- pairs = [(ref, cand) for ref, cand in pairs if finite(ref) is not None and cand is not None]
118
- if not pairs:
119
- continue
120
- declared_floors = tolerance.get("normalization_floors", {})
121
- field_floor = finite(declared_floors.get(field)) if isinstance(declared_floors, dict) else None
122
- norm = max(sum(abs(ref) for ref, _ in pairs) / len(pairs), field_floor or finite(tolerance.get("normalization_floor")) or 1e-12)
123
- errors = [abs(cand - ref) for ref, cand in pairs]
124
- fields.append({"profile": key, "field": field, "normalized_l1": sum(errors) / len(errors) / norm,
125
- "normalized_linf": max(errors) / norm})
126
- coverage = len(fields) / expected_fields if expected_fields else 0.0
127
- passed = bool(fields) and coverage == 1.0 and all(item["normalized_l1"] <= l1_limit and item["normalized_linf"] <= linf_limit for item in fields)
128
- return {"status": "within_tolerance" if passed else "missing" if not fields else "out_of_tolerance",
129
- "coverage_fraction": coverage, "observed_field_count": len(fields),
130
- "expected_field_count": expected_fields, "fields": fields,
131
- "normalized_l1_max": l1_limit, "normalized_linf_max": linf_limit}
132
-
133
-
134
- def compare_events(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
135
- def groups(value: dict[str, Any]) -> dict[tuple[str, str], list[dict[str, Any]]]:
136
- result: dict[tuple[str, str], list[dict[str, Any]]] = {}
137
- for event in value.get("events", []):
138
- if isinstance(event, dict):
139
- result.setdefault((profile_key({"profile_id": event.get("profile_id", "")}), str(event.get("field"))), []).append(event)
140
- return result
141
- refs, cands = groups(reference), groups(candidate)
142
- cell_limit = finite(tolerance.get("maximum_cell_offset"))
143
- if cell_limit is None:
144
- return {"status": "invalid_contract"}
145
- offsets = []
146
- for key, ref_events in refs.items():
147
- cand_events = cands.get(key, [])
148
- available = list(cand_events)
149
- for event in ref_events:
150
- coordinate = finite(event.get("coordinate"))
151
- if coordinate is None or not available:
152
- continue
153
- match = min(
154
- available,
155
- key=lambda item: abs(value - coordinate) if (value := finite(item.get("coordinate"))) is not None else math.inf,
156
- )
157
- available.remove(match)
158
- matched_coordinate = finite(match.get("coordinate"))
159
- if matched_coordinate is None:
160
- continue
161
- cell = max(finite(event.get("local_cell_size")) or 0.0, finite(match.get("local_cell_size")) or 0.0,
162
- finite(tolerance.get("physical_floor")) or 1e-12)
163
- offsets.append(abs(matched_coordinate - coordinate) / cell)
164
- expected = sum(len(items) for items in refs.values())
165
- coverage = len(offsets) / expected if expected else 0.0
166
- passed = expected > 0 and coverage == 1.0 and max(offsets, default=math.inf) <= cell_limit
167
- return {"status": "within_tolerance" if passed else "missing" if not offsets else "out_of_tolerance",
168
- "coverage_fraction": coverage, "maximum_cell_offset": max(offsets, default=None), "allowed_cell_offset": cell_limit}
169
-
170
-
171
- def compare_structured(reference: dict[str, Any], candidate: Any, tolerance: dict[str, Any]) -> dict[str, Any]:
172
- if not isinstance(candidate, dict) or candidate.get("kind") != reference.get("kind"):
173
- return {"status": "missing"}
174
- kind = reference.get("kind")
175
- if kind == "time_history":
176
- return compare_history(reference, candidate, tolerance)
177
- if kind == "branched_time_histories":
178
- ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {})
179
- results = {name: compare_history(value, cand_branches.get(name, {}), tolerance)
180
- for name, value in ref_branches.items()}
181
- passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values())
182
- return {"status": "within_tolerance" if passed else "out_of_tolerance", "branches": results,
183
- "coverage_fraction": sum(item.get("coverage_fraction", 0.0) for item in results.values()) / len(results) if results else 0.0}
184
- if kind == "named_profiles":
185
- return compare_profiles(reference, candidate, tolerance)
186
- if kind == "profile_feature_locations":
187
- return compare_events(reference, candidate, tolerance)
188
- if kind == "component_trajectory":
189
- refs = {str(item.get("component_id")): item for item in reference.get("series", [])}
190
- cands = {str(item.get("component_id")): item for item in candidate.get("series", [])}
191
- results = {key: compare_history({"points": item.get("points", [])}, {"points": cands.get(key, {}).get("points", [])}, tolerance)
192
- for key, item in refs.items()}
193
- passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values())
194
- return {"status": "within_tolerance" if passed else "out_of_tolerance", "components": results}
195
- if kind == "component_scalars":
196
- refs = {str(item.get("component_id")): finite(item.get("value")) for item in reference.get("components", [])}
197
- cands = {str(item.get("component_id")): finite(item.get("value")) for item in candidate.get("components", [])}
198
- relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
199
- if relative is None:
200
- return {"status": "invalid_contract"}
201
- errors = {key: abs(cands[key] - ref) / max(abs(ref), floor) for key, ref in refs.items() if ref is not None and cands.get(key) is not None}
202
- physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
203
- observed = [value for value in cands.values() if value is not None]
204
- physically_valid = all(
205
- (physical_low is None or value >= physical_low)
206
- and (physical_high is None or value <= physical_high)
207
- for value in observed
208
- )
209
- passed = len(errors) == len(refs) and physically_valid and all(error <= relative for error in errors.values())
210
- return {"status": "within_tolerance" if passed else "missing" if not errors else "out_of_tolerance",
211
- "relative_errors": errors, "physical_bounds_pass": physically_valid,
212
- "physical_low": physical_low, "physical_high": physical_high}
213
- if kind == "branch_scalars":
214
- ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {})
215
- relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
216
- if relative is None:
217
- return {"status": "invalid_contract"}
218
- errors: dict[str, Any] = {}
219
- for branch, ref_metrics in ref_branches.items():
220
- cand_metrics = cand_branches.get(branch, {})
221
- errors[branch] = {
222
- name: abs(float(cand_metrics[name]) - float(ref)) / max(abs(float(ref)), floor)
223
- for name, ref in ref_metrics.items()
224
- if name in cand_metrics and finite(ref) is not None and finite(cand_metrics[name]) is not None
225
- }
226
- complete = set(errors) == set(ref_branches) and all(set(errors[b]) == set(ref_branches[b]) for b in ref_branches)
227
- physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
228
- observed = [value for branch in cand_branches.values() if isinstance(branch, dict) for value in branch.values()
229
- if finite(value) is not None]
230
- physically_valid = all(
231
- (physical_low is None or float(value) >= physical_low)
232
- and (physical_high is None or float(value) <= physical_high)
233
- for value in observed
234
- )
235
- passed = complete and physically_valid and all(error <= relative for branch in errors.values() for error in branch.values())
236
- return {"status": "within_tolerance" if passed else "missing" if not complete else "out_of_tolerance",
237
- "relative_errors": errors, "relative_max": relative,
238
- "physical_bounds_pass": physically_valid, "physical_low": physical_low,
239
- "physical_high": physical_high}
240
- scalar_ref, scalar_cand = scalar_observation(reference), scalar_observation(candidate)
241
- if scalar_ref is not None and scalar_cand is not None:
242
- relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
243
- if relative is None:
244
- return {"status": "invalid_contract"}
245
- error = abs(scalar_cand - scalar_ref) / max(abs(scalar_ref), floor)
246
- physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
247
- physically_valid = (
248
- (physical_low is None or scalar_cand >= physical_low)
249
- and (physical_high is None or scalar_cand <= physical_high)
250
- )
251
- passed = error <= relative and physically_valid
252
- return {"status": "within_tolerance" if passed else "out_of_tolerance",
253
- "relative_error": error, "relative_max": relative, "physical_bounds_pass": physically_valid,
254
- "physical_low": physical_low, "physical_high": physical_high}
255
- return {"status": "invalid_contract", "reason": f"unsupported structured kind {kind!r}"}
256
-
257
-
258
- def comparison_quality(result: dict[str, Any]) -> float:
259
- """Map comparison distance to [0, 1] without changing strict status."""
260
- status = result.get("status")
261
- if status == "within_tolerance":
262
- return 1.0
263
- if status in {"missing", "invalid_contract"}:
264
- return 0.0
265
- distances: list[float] = []
266
- for key in ("relative_error", "normalized_rmse", "normalized_l1", "maximum_cell_offset"):
267
- value = finite(result.get(key))
268
- limit = finite(result.get({
269
- "relative_error": "relative_max",
270
- "normalized_rmse": "normalized_rmse_max",
271
- "normalized_l1": "normalized_l1_max",
272
- "maximum_cell_offset": "allowed_cell_offset",
273
- }[key]))
274
- if value is not None and limit is not None and limit > 0:
275
- distances.append(value / limit)
276
- for value in result.get("fields", []) if isinstance(result.get("fields"), list) else []:
277
- if isinstance(value, dict):
278
- q = comparison_quality({
279
- "status": "within_tolerance" if value.get("normalized_l1", math.inf) <= (result.get("normalized_l1_max") or 0.0) else "out_of_tolerance",
280
- "normalized_l1": value.get("normalized_l1"),
281
- "normalized_l1_max": result.get("normalized_l1_max"),
282
- })
283
- distances.append(1.0 - q)
284
- for value in result.get("branches", {}).values() if isinstance(result.get("branches"), dict) else []:
285
- if isinstance(value, dict):
286
- distances.append(1.0 - comparison_quality(value))
287
- ratio = sum(distances) / len(distances) if distances else 1.0
288
- return max(0.0, min(1.0, 1.0 / (1.0 + ratio)))
289
-
290
-
291
- def load_cases(path: Path) -> dict[str, Any]:
292
- data = json.loads(path.read_text(encoding="utf-8"))
293
- cases = data.get("cases") if isinstance(data, dict) else None
294
- if not isinstance(cases, dict):
295
- raise ValueError(f"JSON has no cases object: {path}")
296
- return cases
297
-
298
-
299
- def write_json(path: Path, value: Any) -> None:
300
- path.parent.mkdir(parents=True, exist_ok=True)
301
- temporary = path.with_name(path.name + ".tmp")
302
- temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
303
- temporary.replace(path)
304
-
305
-
306
- STAT_SUFFIX_RE = re.compile(r"_(?:min|max|mean|range)$")
307
- SCORING_POLICY = "grouped_qois"
308
- EXPLICIT_SCORING_POLICY = "explicit_principal_qoi_group"
309
-
310
-
311
- def case_scoring_policy(reference: dict[str, Any]) -> str:
312
- return EXPLICIT_SCORING_POLICY if isinstance(reference.get("metric_roles"), dict) else SCORING_POLICY
313
-
314
-
315
- def metric_role(name: str, explicit_roles: dict[str, Any] | None = None) -> str:
316
- """Classify metrics without changing the extracted raw values.
317
-
318
- Residual and Courant values remain useful diagnostics, while ``range`` is
319
- a deterministic derivative of min/max. All other legacy measurements are
320
- scored, but related statistics are aggregated as one QoI group below.
321
- """
322
- explicit = explicit_roles.get(name) if explicit_roles else None
323
- if explicit in {"principal", "scored"}:
324
- return "scored"
325
- if explicit in {"diagnostic", "redundant"}:
326
- return explicit
327
- if "residual" in name or "courant" in name:
328
- return "diagnostic"
329
- if name.endswith("_range"):
330
- return "redundant"
331
- return "scored"
332
-
333
-
334
- def metric_group(name: str, principal_group: str | None = None,
335
- explicit_roles: dict[str, Any] | None = None) -> str:
336
- if principal_group and explicit_roles and explicit_roles.get(name) in {"principal", "scored"}:
337
- return principal_group
338
- if name in {"center_u", "center_v", "center_w", "center_speed"}:
339
- return "center_velocity"
340
- return STAT_SUFFIX_RE.sub("", name)
341
-
342
-
343
- def comparison_outcome(*, missing: list[str], out_of_tolerance: list[str],
344
- invalid_contract: list[str], accepted: bool) -> str:
345
- if invalid_contract:
346
- return "invalid_contract"
347
- if accepted:
348
- return "pass"
349
- if missing and out_of_tolerance:
350
- return "incomplete_and_out_of_tolerance"
351
- if missing:
352
- return "incomplete"
353
- return "out_of_tolerance"
354
-
355
-
356
- def rollout_status(comparison: dict[str, Any]) -> str:
357
- """Map a QoI result to a rollout status after execution has passed."""
358
- return {
359
- "pass": "scientifically_validated",
360
- "incomplete": "execution_passed_qoi_incomplete",
361
- "out_of_tolerance": "execution_passed_qoi_out_of_tolerance",
362
- "incomplete_and_out_of_tolerance": "execution_passed_qoi_incomplete_and_out_of_tolerance",
363
- "invalid_contract": "execution_passed_qoi_evaluation_error",
364
- "error": "execution_passed_qoi_evaluation_error",
365
- }.get(str(comparison.get("status")), "execution_passed_qoi_evaluation_error")
366
-
367
-
368
- def compare_case(reference: dict[str, Any], candidate: dict[str, Any], required_fraction: float) -> dict[str, Any]:
369
- references = reference.get("qois") if isinstance(reference.get("qois"), dict) else {}
370
- tolerances = reference.get("tolerances") if isinstance(reference.get("tolerances"), dict) else {}
371
- candidates = candidate.get("qois") if isinstance(candidate.get("qois"), dict) else {}
372
- explicit_roles = reference.get("metric_roles") if isinstance(reference.get("metric_roles"), dict) else None
373
- principal_group = reference.get("principal_qoi_group") if isinstance(reference.get("principal_qoi_group"), str) else None
374
- role_for = lambda name: metric_role(name, explicit_roles)
375
- metrics: dict[str, Any] = {}
376
- passed = 0
377
- out_of_tolerance: list[str] = []
378
- missing: list[str] = []
379
- invalid_contract: list[str] = []
380
- diagnostic_out_of_tolerance: list[str] = []
381
- diagnostic_missing: list[str] = []
382
- redundant_metric_count = 0
383
- groups: dict[str, dict[str, Any]] = {}
384
- for name, reference_value in sorted(references.items()):
385
- role = role_for(name)
386
- group = metric_group(name, principal_group, explicit_roles)
387
- if role == "redundant":
388
- redundant_metric_count += 1
389
- value = finite(candidates.get(name))
390
- metrics[name] = {
391
- "status": "available" if value is not None else "missing",
392
- "role": role,
393
- "group": group,
394
- "reference_value": reference_value,
395
- "candidate_value": value,
396
- }
397
- continue
398
- group_record = groups.setdefault(group, {
399
- "role": "scored" if role == "scored" else role,
400
- "metrics": [],
401
- "passed_metric_count": 0,
402
- "observed_metric_count": 0,
403
- "invalid_metric_count": 0,
404
- "quality_sum": 0.0,
405
- "coverage_fraction": 1.0,
406
- })
407
- group_record["metrics"].append(name)
408
- tolerance = tolerances.get(name) if isinstance(tolerances.get(name), dict) else {}
409
- if isinstance(reference_value, dict):
410
- result = compare_structured(reference_value, candidates.get(name), tolerance)
411
- result["quality"] = comparison_quality(result)
412
- status = result.get("status")
413
- is_missing = status == "missing"
414
- is_invalid = status == "invalid_contract"
415
- is_pass = status == "within_tolerance"
416
- structured_coverage = finite(result.get("coverage_fraction"))
417
- if structured_coverage is not None:
418
- group_record["coverage_fraction"] = min(
419
- group_record["coverage_fraction"], structured_coverage
420
- )
421
- elif is_missing:
422
- group_record["coverage_fraction"] = 0.0
423
- if is_missing:
424
- missing.append(name)
425
- if role == "diagnostic":
426
- diagnostic_missing.append(name)
427
- elif is_invalid and role == "scored":
428
- invalid_contract.append(name)
429
- group_record["invalid_metric_count"] += 1
430
- else:
431
- group_record["observed_metric_count"] += int(role == "scored")
432
- if role == "scored":
433
- passed += int(is_pass)
434
- group_record["passed_metric_count"] += int(is_pass)
435
- group_record["quality_sum"] += float(result["quality"])
436
- if not is_pass:
437
- out_of_tolerance.append(name)
438
- elif role == "diagnostic" and not is_pass:
439
- diagnostic_out_of_tolerance.append(name)
440
- metrics[name] = {"role": role, "group": group, "reference_value": reference_value,
441
- "candidate_value": candidates.get(name), **result}
442
- continue
443
- value = finite(candidates.get(name))
444
- low, high = finite(tolerance.get("low")), finite(tolerance.get("high"))
445
- if value is None:
446
- missing.append(name)
447
- group_record["coverage_fraction"] = 0.0
448
- if role == "diagnostic":
449
- diagnostic_missing.append(name)
450
- metrics[name] = {
451
- "status": "missing",
452
- "role": role,
453
- "group": group,
454
- "reference_value": reference_value,
455
- "quality": 0.0,
456
- }
457
- continue
458
- if low is None or high is None:
459
- group_record["coverage_fraction"] = 0.0
460
- if role == "scored":
461
- invalid_contract.append(name)
462
- group_record["invalid_metric_count"] += 1
463
- metrics[name] = {
464
- "status": "invalid_contract" if role == "scored" else "available_without_tolerance",
465
- "role": role,
466
- "group": group,
467
- "reference_value": reference_value,
468
- "candidate_value": value,
469
- "quality": 0.0,
470
- }
471
- continue
472
- physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
473
- physical_pass = (
474
- (physical_low is None or value >= physical_low)
475
- and (physical_high is None or value <= physical_high)
476
- )
477
- is_pass = low <= value <= high and physical_pass
478
- tolerance_span = max(high - low, 1e-12)
479
- distance = 0.0 if is_pass else min(abs(value - min(max(value, low), high)) / tolerance_span, 1.0)
480
- quality = 1.0 if is_pass else max(0.0, 1.0 - distance)
481
- if role == "scored":
482
- passed += int(is_pass)
483
- group_record["observed_metric_count"] += 1
484
- group_record["passed_metric_count"] += int(is_pass)
485
- group_record["quality_sum"] += quality
486
- if not is_pass:
487
- out_of_tolerance.append(name)
488
- elif role == "diagnostic" and not is_pass:
489
- diagnostic_out_of_tolerance.append(name)
490
- metrics[name] = {
491
- "status": "within_tolerance" if is_pass else "out_of_tolerance",
492
- "role": role,
493
- "group": group,
494
- "reference_value": reference_value,
495
- "candidate_value": value,
496
- "low": low,
497
- "high": high,
498
- "absolute_error": abs(value - float(reference_value)),
499
- "criterion_role": tolerance.get("criterion_role"),
500
- "threshold_source": tolerance.get("threshold_source"),
501
- "reference_independent": tolerance.get("reference_independent", False),
502
- "provisional": tolerance.get("provisional"),
503
- "physical_bounds_pass": physical_pass,
504
- "physical_low": physical_low,
505
- "physical_high": physical_high,
506
- "physical_threshold_source": tolerance.get("physical_threshold_source"),
507
- "quality": quality,
508
- }
509
- scored_groups = {
510
- name: record for name, record in groups.items() if record["role"] == "scored"
511
- }
512
- scored_metrics = [name for name in references if role_for(name) == "scored"]
513
- scored_missing = [name for name in missing if role_for(name) == "scored"]
514
- scored_count = len(scored_metrics)
515
- extracted_count = sum(record["observed_metric_count"] for record in scored_groups.values())
516
- evaluated_count = extracted_count
517
- coverage = extracted_count / scored_count if scored_count else 0.0
518
- metric_value_pass_fraction = passed / evaluated_count if evaluated_count else None
519
- metric_joint_pass_fraction = passed / scored_count if scored_count else 0.0
520
- group_scores: dict[str, dict[str, Any]] = {}
521
- for group_name, record in sorted(scored_groups.items()):
522
- member_count = len(record["metrics"])
523
- group_score = record["quality_sum"] / member_count if member_count else 0.0
524
- group_coverage = (
525
- min(record["observed_metric_count"] / member_count, record["coverage_fraction"])
526
- if member_count else 0.0
527
- )
528
- group_scores[group_name] = {
529
- "score": group_score,
530
- "coverage_fraction": group_coverage,
531
- "metric_count": member_count,
532
- "observed_metric_count": record["observed_metric_count"],
533
- "passed_metric_count": record["passed_metric_count"],
534
- "metrics": record["metrics"],
535
- }
536
- qoi_pass_ratio = (
537
- sum(item["score"] for item in group_scores.values()) / len(group_scores)
538
- if group_scores else 0.0
539
- )
540
- qoi_coverage_fraction = (
541
- sum(item["coverage_fraction"] for item in group_scores.values()) / len(group_scores)
542
- if group_scores else 0.0
543
- )
544
- # Continuous quality is intentionally separate from the strict scientific
545
- # acceptance bit. It exposes partial QoI agreement to Evolution without
546
- # weakening the all-groups physics-grounded contract.
547
- qoi_quality = qoi_pass_ratio * qoi_coverage_fraction
548
- physics_grounded_accepted = bool(
549
- scored_groups
550
- and not scored_missing
551
- and not invalid_contract
552
- and not out_of_tolerance
553
- and passed == scored_count
554
- and all(
555
- item["coverage_fraction"] == 1.0
556
- for item in group_scores.values()
557
- )
558
- )
559
- threshold_pass = bool(
560
- scored_groups
561
- and qoi_coverage_fraction == 1.0
562
- and qoi_pass_ratio >= required_fraction
563
- )
564
- outcome = comparison_outcome(
565
- missing=scored_missing,
566
- out_of_tolerance=out_of_tolerance,
567
- invalid_contract=invalid_contract,
568
- accepted=physics_grounded_accepted,
569
- )
570
- diagnostic_names = [name for name in references if role_for(name) == "diagnostic"]
571
- diagnostic_observed = [
572
- name for name in diagnostic_names
573
- if metrics.get(name, {}).get("status") not in {None, "missing", "invalid_contract"}
574
- ]
575
- diagnostic_passed = [
576
- name for name in diagnostic_names if metrics.get(name, {}).get("status") == "within_tolerance"
577
- ]
578
- return {
579
- "schema_version": "foambench.qoi.case_comparison.v3",
580
- "scoring_policy": case_scoring_policy(reference),
581
- "status": outcome,
582
- "coverage_status": "complete" if scored_count and not scored_missing else "incomplete",
583
- "value_status": (
584
- "not_assessed" if not scored_count
585
- else "within_tolerance" if metric_value_pass_fraction is not None and metric_value_pass_fraction >= required_fraction
586
- else "out_of_tolerance"
587
- ),
588
- "required_metric_count": scored_count,
589
- "extracted_metric_count": extracted_count,
590
- "evaluated_metric_count": evaluated_count,
591
- "passed_metric_count": passed,
592
- "coverage_fraction": coverage,
593
- "value_pass_fraction": metric_value_pass_fraction,
594
- "joint_pass_fraction": metric_joint_pass_fraction,
595
- "qoi_pass_ratio": qoi_pass_ratio,
596
- "qoi_quality": qoi_quality,
597
- "qoi_coverage_fraction": qoi_coverage_fraction,
598
- "group_count": len(group_scores),
599
- "group_scores": group_scores,
600
- "physics_grounded_qoi_pass": physics_grounded_accepted,
601
- "threshold_pass": threshold_pass,
602
- "diagnostic_metric_count": sum(len(record["metrics"]) for record in groups.values() if record["role"] == "diagnostic"),
603
- "diagnostic_observed_metric_count": len(diagnostic_observed),
604
- "diagnostic_passed_metric_count": len(diagnostic_passed),
605
- "diagnostic_reference_coverage_fraction": (
606
- len(diagnostic_observed) / len(diagnostic_names) if diagnostic_names else None
607
- ),
608
- "diagnostic_reference_pass_fraction": (
609
- len(diagnostic_passed) / len(diagnostic_observed) if diagnostic_observed else None
610
- ),
611
- "redundant_metric_count": redundant_metric_count,
612
- # Raw metric fractions remain available above; the canonical case-level
613
- # quality score is qoi_pass_ratio.
614
- "pass_fraction": metric_joint_pass_fraction,
615
- "required_fraction": required_fraction,
616
- "missing_metrics": missing,
617
- "scored_missing_metrics": scored_missing,
618
- "diagnostic_missing_metrics": diagnostic_missing,
619
- "out_of_tolerance_metrics": out_of_tolerance,
620
- "diagnostic_out_of_tolerance_metrics": diagnostic_out_of_tolerance,
621
- "invalid_contract_metrics": invalid_contract,
622
- "metrics": metrics,
623
- }
624
-
625
-
626
- def main() -> int:
627
- parser = argparse.ArgumentParser(description=__doc__)
628
- parser.add_argument("--reference-qois", required=True, type=Path)
629
- parser.add_argument("--candidate-qois", required=True, type=Path)
630
- parser.add_argument("--case-id", action="append")
631
- parser.add_argument(
632
- "--required-fraction",
633
- type=float,
634
- default=1.0,
635
- help="Optional observed-value/QoI-ratio threshold; physics_grounded_qoi_pass always requires every scored group.",
636
- )
637
- parser.add_argument("--output", type=Path)
638
- parser.add_argument("--json", action="store_true")
639
- args = parser.parse_args()
640
- if not 0 < args.required_fraction <= 1:
641
- parser.error("--required-fraction must be in (0, 1]")
642
-
643
- references = load_cases(args.reference_qois.resolve(strict=True))
644
- candidates = load_cases(args.candidate_qois.resolve(strict=True))
645
- selected = args.case_id or sorted(references)
646
- unknown = sorted(set(selected) - set(references))
647
- if unknown:
648
- raise ValueError("unknown reference case IDs: " + ", ".join(unknown))
649
-
650
- results: dict[str, Any] = {}
651
- missing_cases: list[str] = []
652
- for case_id in selected:
653
- candidate = candidates.get(case_id)
654
- if not isinstance(candidate, dict):
655
- missing_cases.append(case_id)
656
- missing_metrics = sorted(references[case_id].get("qois", {}))
657
- results[case_id] = {
658
- "scoring_policy": case_scoring_policy(references[case_id]),
659
- "status": "missing_candidate_case",
660
- "coverage_status": "incomplete",
661
- "value_status": "not_assessed",
662
- "required_metric_count": len(missing_metrics),
663
- "extracted_metric_count": 0,
664
- "evaluated_metric_count": 0,
665
- "passed_metric_count": 0,
666
- "coverage_fraction": 0.0,
667
- "value_pass_fraction": None,
668
- "joint_pass_fraction": 0.0,
669
- "qoi_pass_ratio": 0.0,
670
- "qoi_coverage_fraction": 0.0,
671
- "group_count": 0,
672
- "pass_fraction": 0.0,
673
- "missing_metrics": missing_metrics,
674
- "out_of_tolerance_metrics": [],
675
- "invalid_contract_metrics": [],
676
- }
677
- else:
678
- results[case_id] = compare_case(references[case_id], candidate, args.required_fraction)
679
-
680
- family_rows: dict[str, list[dict[str, Any]]] = {}
681
- for case_id, result in results.items():
682
- if "pass_fraction" in result:
683
- reference_family = references.get(case_id, {}).get("family")
684
- family = reference_family if isinstance(reference_family, str) and reference_family else case_id.split("/", 1)[0]
685
- family_rows.setdefault(family, []).append(result)
686
- def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
687
- assessed = [row["value_pass_fraction"] for row in rows if row.get("value_pass_fraction") is not None]
688
- qoi_ratios = [row["qoi_pass_ratio"] for row in rows if row.get("qoi_pass_ratio") is not None]
689
- return {
690
- "case_count": len(rows),
691
- "passed_case_count": sum(row["status"] == "pass" for row in rows),
692
- "incomplete_case_count": sum(bool(row.get("missing_metrics")) for row in rows),
693
- "out_of_tolerance_case_count": sum(bool(row.get("out_of_tolerance_metrics")) for row in rows),
694
- "macro_coverage_fraction": sum(row["coverage_fraction"] for row in rows) / len(rows),
695
- "macro_value_pass_fraction": sum(assessed) / len(assessed) if assessed else None,
696
- "macro_joint_pass_fraction": sum(row["joint_pass_fraction"] for row in rows) / len(rows),
697
- "macro_qoi_pass_ratio": sum(qoi_ratios) / len(qoi_ratios) if qoi_ratios else 0.0,
698
- "macro_qoi_coverage_fraction": sum(row.get("qoi_coverage_fraction", 0.0) for row in rows) / len(rows),
699
- }
700
-
701
- families = {family: summarize(rows) for family, rows in sorted(family_rows.items())}
702
- passed_cases = sum(result.get("status") == "pass" for result in results.values())
703
- aggregate = summarize(list(results.values())) if results else {
704
- "incomplete_case_count": 0,
705
- "out_of_tolerance_case_count": 0,
706
- "macro_coverage_fraction": 0.0,
707
- "macro_value_pass_fraction": None,
708
- "macro_joint_pass_fraction": 0.0,
709
- "macro_qoi_pass_ratio": 0.0,
710
- "macro_qoi_coverage_fraction": 0.0,
711
- }
712
- policies = {result.get("scoring_policy", SCORING_POLICY) for result in results.values()}
713
- report = {
714
- "schema_version": "foambench.qoi.comparison.v3",
715
- "scoring_policy": policies.pop() if len(policies) == 1 else "mixed",
716
- "generated_at": datetime.now(timezone.utc).isoformat(),
717
- "status": "pass" if passed_cases == len(selected) and not missing_cases else "fail",
718
- "case_count": len(selected),
719
- "passed_case_count": passed_cases,
720
- "case_pass_fraction": passed_cases / len(selected) if selected else 0.0,
721
- "incomplete_case_count": aggregate["incomplete_case_count"],
722
- "out_of_tolerance_case_count": aggregate["out_of_tolerance_case_count"],
723
- "macro_coverage_fraction": aggregate["macro_coverage_fraction"],
724
- "macro_value_pass_fraction": aggregate["macro_value_pass_fraction"],
725
- "macro_joint_pass_fraction": aggregate["macro_joint_pass_fraction"],
726
- "macro_qoi_pass_ratio": aggregate["macro_qoi_pass_ratio"],
727
- "macro_qoi_coverage_fraction": aggregate["macro_qoi_coverage_fraction"],
728
- "missing_cases": missing_cases,
729
- "families": families,
730
- "cases": results,
731
- }
732
- if args.output:
733
- write_json(args.output.resolve(), report)
734
- if args.json or not args.output:
735
- print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
736
- else:
737
- print(
738
- f"comparison: {args.output.resolve()} "
739
- f"(physics_grounded={passed_cases}/{len(selected)}, "
740
- f"qoi_pass_ratio={report['macro_qoi_pass_ratio']:.4f})"
741
- )
742
- return 0 if report["status"] == "pass" else 1
743
-
744
-
745
- if __name__ == "__main__":
746
- try:
747
- raise SystemExit(main())
748
- except (OSError, ValueError, json.JSONDecodeError) as exc:
749
- print(f"compare_foambench_qois.py: error: {exc}", file=sys.stderr)
750
- raise SystemExit(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/evidence_contract.py DELETED
@@ -1,119 +0,0 @@
1
- """Canonical evidence discovery for the Extended FoamBench contract.
2
-
3
- The resolver deliberately separates *where/how an agent writes a file* from
4
- the physical quantity represented by its contents. Callers still validate
5
- headers, units, time semantics, and dimensions before using a file as QoI
6
- evidence; this module only provides deterministic semantic routing.
7
- """
8
- from __future__ import annotations
9
-
10
- import re
11
- import json
12
- from pathlib import Path
13
- from typing import Any
14
-
15
-
16
- CANONICAL_ALIASES: dict[str, tuple[str, ...]] = {
17
- "force_coefficients": ("forcecoeffs", "forcecoefficients", "forcecoefficient", "aerodynamicloads", "aeroloads", "loads"),
18
- "patch_flux": ("patchflowrate", "patchflow", "massflow", "massflux", "rhophi", "fluxhistory"),
19
- "patch_pressure": ("patchaverage", "patchintegrate", "pressurerise", "pressuredifference", "patchpressure"),
20
- "wall_law_profile": ("spaldingcomparison", "uplusyplus", "walllawprofile", "velocityprofile", "wallprofile"),
21
- "centerline_profile": ("centerline", "centreline", "horizontal", "vertical", "px0", "py0", "rhox0", "rhoy0"),
22
- "bubble_geometry": ("bubblegeometry", "bubblemetrics", "interfacegeometry"),
23
- }
24
-
25
- CONTRACT_VERSION = "foambench.evidence.contract.v1"
26
- CONTRACT_FILE = Path(__file__).resolve().parents[1] / "FoamBench_extended_openfoam13_evidence_contract.v1.json"
27
-
28
- # A manifest may use the QoI name instead of the routing kind. This mapping
29
- # keeps that interface stable while allowing metric extractors to retain their
30
- # own physical validation rules.
31
- METRIC_KINDS = {
32
- "Cd": "force_coefficients", "Cl": "force_coefficients", "Cm": "force_coefficients",
33
- "Cd_mean": "force_coefficients", "Cd_rms": "force_coefficients",
34
- "Cl_mean": "force_coefficients", "Cl_rms": "force_coefficients",
35
- "first_cell_yplus": "wall_law_profile", "spalding_log_rmse": "wall_law_profile",
36
- "centerline_profiles": "centerline_profile", "event_locations": "centerline_profile",
37
- "mass_flow_rate": "patch_flux", "volumetric_flow_rate": "patch_flux",
38
- "pressure_rise": "patch_pressure", "pressure_rise_history": "patch_pressure",
39
- }
40
-
41
-
42
- def compact_name(value: str) -> str:
43
- return re.sub(r"[^a-z0-9]", "", value.lower())
44
-
45
-
46
- def evidence_roots(case: Path) -> tuple[Path, ...]:
47
- parent = case.parent
48
- roots = (
49
- case / "postProcessing", case / "postprocessing", case / "results", case / "outputs",
50
- parent / "postProcessing", parent / "postprocessing", parent / "results", parent / "outputs",
51
- parent / "evidence", parent / "reports",
52
- )
53
- return tuple(dict.fromkeys(root for root in roots if root.is_dir()))
54
-
55
-
56
- def _manifest_paths(case: Path) -> tuple[Path, ...]:
57
- """Locate the optional agent-emitted manifest without trusting its paths."""
58
- return tuple(dict.fromkeys((case / "evidence/qoi_manifest.v1.json", case.parent / "evidence/qoi_manifest.v1.json")))
59
-
60
-
61
- def declared_evidence(case: Path, kind: str) -> list[Path]:
62
- """Return manifest-declared files for *kind* after path containment checks."""
63
- paths: list[Path] = []
64
- accepted_metrics = {kind, *[metric for metric, mapped in METRIC_KINDS.items() if mapped == kind]}
65
- for manifest_path in _manifest_paths(case):
66
- try:
67
- payload = json.loads(manifest_path.read_text(encoding="utf-8"))
68
- except (OSError, ValueError, TypeError):
69
- continue
70
- entries = payload.get("entries", []) if isinstance(payload, dict) else []
71
- if not isinstance(entries, list):
72
- continue
73
- for entry in entries:
74
- if not isinstance(entry, dict) or entry.get("metric") not in accepted_metrics and entry.get("kind") != kind:
75
- continue
76
- raw = entry.get("path")
77
- if not isinstance(raw, str) or not raw:
78
- continue
79
- candidate = (manifest_path.parent.parent / raw).resolve()
80
- allowed = tuple(root.resolve() for root in evidence_roots(case))
81
- if candidate.is_file() and any(candidate == root or root in candidate.parents for root in allowed):
82
- paths.append(candidate)
83
- return sorted(set(paths))
84
-
85
-
86
- def resolve_evidence(case: Path, kind: str, *, suffixes: tuple[str, ...] = ()) -> list[Path]:
87
- """Return files whose path semantically addresses canonical evidence kind.
88
-
89
- This function never parses or promotes a file. The metric-specific
90
- extractor remains responsible for schema/header/unit validation.
91
- """
92
- aliases = CANONICAL_ALIASES.get(kind, (kind,))
93
- paths: set[Path] = set(declared_evidence(case, kind))
94
- for root in evidence_roots(case):
95
- for path in root.rglob("*"):
96
- if not path.is_file():
97
- continue
98
- if suffixes and path.suffix.lower() not in suffixes:
99
- continue
100
- compact = compact_name(str(path))
101
- if any(compact_name(alias) in compact for alias in aliases):
102
- paths.add(path)
103
- return sorted(paths)
104
-
105
-
106
- def canonical_evidence_manifest() -> dict[str, object]:
107
- """Machine-readable resolver contract for reports and future agents."""
108
- fallback = {
109
- "schema_version": CONTRACT_VERSION,
110
- "normalization": "lowercase_ascii_alphanumeric_path_matching",
111
- "kinds": {key: list(value) for key, value in CANONICAL_ALIASES.items()},
112
- "content_validation": "required_by_metric_extractor",
113
- "proxy_policy": "semantic routing never authorizes a proxy metric",
114
- }
115
- try:
116
- payload = json.loads(CONTRACT_FILE.read_text(encoding="utf-8"))
117
- except (OSError, ValueError, TypeError):
118
- return fallback
119
- return payload if isinstance(payload, dict) else fallback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/execution.py DELETED
@@ -1,62 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Any
4
-
5
- from .adapters.common import successful_formal_records
6
- from .foam import FATAL_RE, converged_early, final_log_time, latest_time_dir, normal_end, read_logs
7
- from .models import CaseArtifact
8
-
9
-
10
- def evaluate_execution(artifact: CaseArtifact, expected_time: float | None) -> dict[str, Any]:
11
- case_dir = artifact.case_dir
12
- latest, _ = latest_time_dir(case_dir)
13
- logs = artifact.solver_logs
14
- text = read_logs(logs)
15
- log_time = final_log_time(text)
16
- successful = successful_formal_records(artifact.formal_run_records)
17
- requires_formal_record = (
18
- artifact.workspace_dir is not None
19
- and artifact.manifest.get("agent_mode") != "coding-only"
20
- and artifact.manifest.get("domain_assets_enabled") is not False
21
- )
22
- manifest_status = str(artifact.manifest.get("status", ""))
23
- timed_out = bool(artifact.manifest.get("timed_out")) or manifest_status == "timed_out"
24
- process_ok = artifact.manifest.get("return_code") in {None, 0}
25
- observed_time = max(value for value in (latest, log_time) if value is not None) if any(
26
- value is not None for value in (latest, log_time)
27
- ) else None
28
- reached = observed_time is not None and (
29
- expected_time is None
30
- or observed_time >= expected_time - max(1e-12, abs(expected_time) * 1e-9)
31
- or converged_early(text)
32
- )
33
- checks = {
34
- "case_directory_exists": bool(case_dir and case_dir.is_dir()),
35
- "control_dict_exists": bool(case_dir and (case_dir / "system" / "controlDict").is_file()),
36
- "agent_not_timed_out": not timed_out,
37
- "agent_process_succeeded": process_ok,
38
- "formal_run_succeeded": bool(successful) if requires_formal_record else True,
39
- "solver_log_exists": bool(logs),
40
- "no_fatal_log_marker": FATAL_RE.search(text) is None,
41
- "latest_time_exists": latest is not None,
42
- "stop_condition_reached": reached,
43
- }
44
- # Some retained run records omit the literal OpenFOAM "End" line from the
45
- # selected stdout ref. Keep it as evidence rather than a hard requirement.
46
- evidence = {
47
- "normal_end_marker": normal_end(text),
48
- "converged_early_marker": converged_early(text),
49
- "formal_run_records": [str(path) for path in successful],
50
- "solver_logs": [str(path) for path in logs],
51
- }
52
- failed = [name for name, passed in checks.items() if not passed]
53
- return {
54
- "schema_version": "foambench.execution.v2",
55
- "status": "pass" if not failed else "fail",
56
- "expected_latest_time": expected_time,
57
- "candidate_latest_time": latest,
58
- "candidate_final_log_time": log_time,
59
- "checks": checks,
60
- "failed_checks": failed,
61
- "evidence": evidence,
62
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/extbench.py DELETED
@@ -1,1572 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Extract and audit Extended FoamBench QoIs without fallback proxies."""
3
- from __future__ import annotations
4
-
5
- import argparse
6
- import csv
7
- import json
8
- import math
9
- import re
10
- import statistics
11
- from pathlib import Path
12
- from typing import Any
13
-
14
- from .evidence_contract import canonical_evidence_manifest, evidence_roots, resolve_evidence
15
- from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_field, read_vector_list
16
- from .io import utc_now, write_json
17
- from .retained_fields import derive_cell_geometry, pump_measurements, static_mesh
18
- from .measurement_specs import load_measurement_spec
19
-
20
- ROOT = Path(__file__).resolve().parents[2]
21
- DEFAULT_DESIGN = ROOT / "benchmarks/FoamBench_extended_openfoam13_qoi_design.json"
22
- NUMERIC = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")
23
-
24
-
25
- def named_numeric_rows(path: Path) -> tuple[list[str], list[list[float]]]:
26
- """Read a whitespace/CSV table using the last compatible header."""
27
- headers: list[list[str]] = []
28
- rows: list[list[float]] = []
29
- try:
30
- for line in path.read_text(errors="ignore").splitlines():
31
- stripped = line.strip()
32
- if not stripped:
33
- continue
34
- if stripped.startswith("#"):
35
- names = stripped[1:].strip().replace(",", " ").split()
36
- if names:
37
- headers.append(names)
38
- continue
39
- parts = stripped.replace("(", " ").replace(")", " ").replace(",", " ").split()
40
- if parts and all(NUMERIC.match(value) for value in parts):
41
- rows.append([float(value) for value in parts])
42
- elif (not rows and ("," in stripped or "\t" in stripped)
43
- and any(re.search(r"[A-Za-z_]", value) and not NUMERIC.fullmatch(value) for value in parts)):
44
- names = [item.strip() for item in stripped.split(",")] if "," in stripped else stripped.split("\t")
45
- if names:
46
- headers.append(names)
47
- except OSError:
48
- return [], []
49
- if not rows:
50
- return [], []
51
- width = len(rows[0])
52
- header = next((names for names in reversed(headers) if len(names) == width), [])
53
- return header, [row for row in rows if len(row) == width]
54
-
55
-
56
- def matching_files(case: Path, needles: tuple[str, ...], suffixes: tuple[str, ...] = ()) -> list[Path]:
57
- """Find explicit post-processing evidence in the case or its workspace."""
58
- parent = case.parent
59
- roots = [case / "postProcessing", case / "results", parent / "postProcessing", parent / "postprocessing", parent / "results"]
60
- paths: list[Path] = []
61
- for root in roots:
62
- if not root.is_dir():
63
- continue
64
- paths.extend(path for path in root.rglob("*") if path.is_file()
65
- and (not suffixes or path.suffix.lower() in suffixes)
66
- and any(needle.lower() in str(path).lower() for needle in needles))
67
- return sorted(set(paths))
68
-
69
-
70
- def evidence_path(case: Path, path: Path) -> str:
71
- """Serialize evidence paths for both native case and sibling workspace outputs."""
72
- try:
73
- return str(path.relative_to(case))
74
- except ValueError:
75
- return "../" + str(path.relative_to(case.parent))
76
-
77
-
78
- def design_case_contract(case_id: str, design: dict[str, Any]) -> tuple[str | None, list[str]]:
79
- """Return the branch and principal metrics for one family/variant."""
80
- if "/" not in case_id:
81
- raise ValueError(f"case id must be family/variant: {case_id}")
82
- family_name, variant = case_id.split("/", 1)
83
- family = next((item for item in design.get("families", []) if item.get("family") == family_name), None)
84
- if family is None:
85
- raise ValueError(f"design has no family for {case_id}")
86
- return required_metrics(family, variant)
87
-
88
-
89
- def design_case_conditionals(case_id: str, design: dict[str, Any]) -> list[str]:
90
- if "/" not in case_id:
91
- raise ValueError(f"case id must be family/variant: {case_id}")
92
- family_name, variant = case_id.split("/", 1)
93
- family = next((item for item in design.get("families", []) if item.get("family") == family_name), None)
94
- if family is None:
95
- raise ValueError(f"design has no family for {case_id}")
96
- for branch in family.get("branches", []):
97
- if variant in branch.get("cases", []):
98
- return [item["name"] for item in branch.get("conditional_qois", [])]
99
- return []
100
-
101
-
102
- def extract_contract_case(case: Path, case_id: str, design: dict[str, Any] | None = None) -> dict[str, Any]:
103
- """Extract one candidate using only the design contract."""
104
- selected_design = design or json.loads(DEFAULT_DESIGN.read_text(encoding="utf-8"))
105
- branch_id, metrics = design_case_contract(case_id, selected_design)
106
- measurement_spec = load_measurement_spec(case_id)
107
- if measurement_spec is not None:
108
- declared = [item.get("metric") for item in measurement_spec.get("principal_measurements", [])]
109
- if declared != metrics:
110
- raise ValueError(f"measurement contract drift for {case_id}: {declared!r} != {metrics!r}")
111
- conditionals = design_case_conditionals(case_id, selected_design)
112
- result = extract_case(
113
- case, case_id.split("/", 1)[0], case_id.split("/", 1)[1], metrics,
114
- conditional_metrics=conditionals,
115
- )
116
- result["branch_id"] = branch_id
117
- result["conditional_metrics"] = conditionals
118
- result["contract_version"] = selected_design.get("schema_version")
119
- if measurement_spec is not None:
120
- result["measurement_contract"] = measurement_spec
121
- return result
122
-
123
-
124
- def locate_case(run_root: Path, family: str, variant: str) -> Path | None:
125
- candidates = (
126
- run_root / f"{family}__{variant}" / "full_run_case",
127
- run_root / f"{family}__{variant}" / "case",
128
- run_root / family / variant / "full_run_case",
129
- run_root / family / variant / "case",
130
- run_root / family / variant,
131
- )
132
- return next((path for path in candidates if path.is_dir()), None)
133
-
134
-
135
- def required_metrics(family: dict[str, Any], variant: str) -> tuple[str | None, list[str]]:
136
- for branch in family.get("branches", []):
137
- if variant in branch.get("cases", []):
138
- metrics = [item["name"] for item in branch.get("principal_qois", [])]
139
- return branch.get("id"), metrics
140
- return None, []
141
-
142
-
143
- def final_fraction(values: list[float], fraction: float = 0.2, minimum: int = 5) -> list[float]:
144
- if not values:
145
- return []
146
- count = min(len(values), max(minimum, math.ceil(len(values) * fraction)))
147
- return values[-count:]
148
-
149
-
150
- def force_coefficients(case: Path) -> tuple[dict[str, list[float]], list[str]]:
151
- files = matching_files(case, ("forcecoeffs.dat",), (".dat", ".csv", ".raw"))
152
- files.extend(resolve_evidence(case, "force_coefficients", suffixes=(".dat", ".csv", ".raw")))
153
- # Content-addressed fallback: a different agent may call this table
154
- # loads.csv or aero_coefficients.dat. The header is the physical contract.
155
- candidates = [path for root in evidence_roots(case) for path in root.rglob("*")
156
- if path.is_file() and path.suffix.lower() in {".dat", ".csv", ".raw"}]
157
- for path in candidates:
158
- if path in files:
159
- continue
160
- header, _ = named_numeric_rows(path)
161
- if "Time" in header and any(name in header for name in ("Cd", "Cl", "Cm")):
162
- files.append(path)
163
- files = sorted(set(files))
164
- columns: dict[str, list[float]] = {}
165
- evidence: list[str] = []
166
- for path in files:
167
- header, rows = named_numeric_rows(path)
168
- if not header or "Time" not in header:
169
- continue
170
- for name in ("Cd", "Cl", "Cm"):
171
- if name not in header:
172
- continue
173
- index = header.index(name)
174
- columns.setdefault(name, []).extend(
175
- row[index] for row in rows if math.isfinite(row[index])
176
- )
177
- evidence.append(evidence_path(case, path))
178
- return columns, evidence
179
-
180
-
181
- def extract_force_metric(case: Path, metric: str) -> tuple[float | None, list[str], str]:
182
- columns, evidence = force_coefficients(case)
183
- base = metric.removesuffix("_mean").removesuffix("_rms")
184
- values = final_fraction(columns.get(base, []))
185
- if not values:
186
- return None, [], "header_addressed_force_coefficients.v1"
187
- if metric.endswith("_rms"):
188
- mean = statistics.fmean(values)
189
- value = math.sqrt(statistics.fmean((item - mean) ** 2 for item in values))
190
- else:
191
- value = statistics.fmean(values)
192
- return value, evidence, "header_addressed_force_coefficients.v1"
193
-
194
-
195
- def spalding_metrics_from_files(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]:
196
- log_errors: list[float] = []
197
- first_yplus: list[float] = []
198
- evidence: list[str] = []
199
- for path in files:
200
- header, rows = named_numeric_rows(path)
201
- normalized = {
202
- re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): index
203
- for index, name in enumerate(header)
204
- }
205
- y_index = next(
206
- (normalized[name] for name in ("yplus", "firstcellyplus", "yplusmin", "firstcellyplusmin") if name in normalized),
207
- None,
208
- )
209
- predicted_index = next(
210
- (normalized[name] for name in ("spaldingyplus", "yplusspaldingup", "yplusspaldinguplus", "yplusspalding") if name in normalized),
211
- None,
212
- )
213
- if y_index is None:
214
- continue
215
- # Zero is a valid observed wall resolution. Missing evidence is an
216
- # absent row, not a non-positive value.
217
- y_values = [row[y_index] for row in rows if len(row) > y_index and math.isfinite(row[y_index]) and row[y_index] >= 0]
218
- if y_values:
219
- first_yplus.append(min(y_values))
220
- if predicted_index is None:
221
- # A first-cell summary is valid endpoint evidence, but it cannot
222
- # be relabelled as a profile residual.
223
- evidence.append(evidence_path(relative_to, path))
224
- continue
225
- valid = [
226
- (row[y_index], row[predicted_index]) for row in rows
227
- if len(row) > max(y_index, predicted_index)
228
- and math.isfinite(row[y_index]) and math.isfinite(row[predicted_index])
229
- and row[y_index] >= 0 and row[predicted_index] >= 0
230
- ]
231
- if not valid:
232
- continue
233
- log_errors.extend(
234
- math.log1p(yplus) - math.log1p(predicted)
235
- for yplus, predicted in valid
236
- )
237
- evidence.append(evidence_path(relative_to, path))
238
- result: dict[str, float] = {}
239
- if log_errors:
240
- result["spalding_log_rmse"] = math.sqrt(statistics.fmean(value * value for value in log_errors))
241
- if first_yplus:
242
- result["first_cell_yplus"] = statistics.fmean(first_yplus)
243
- return result, evidence
244
-
245
-
246
- def standard_yplus_metrics(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]:
247
- """Read OpenFOAM's standard ``yPlus.dat`` patch summary.
248
-
249
- The standard table has the schema ``Time patch min max average``. It is
250
- therefore intentionally parsed separately from ``named_numeric_rows``,
251
- which rejects the non-numeric patch column. A zero average remains a
252
- valid observation.
253
- """
254
- rows: list[tuple[float, str, float, float, float]] = []
255
- evidence: list[str] = []
256
- for path in files:
257
- if path.name.lower() != "yplus.dat":
258
- continue
259
- try:
260
- for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
261
- parts = line.split()
262
- if len(parts) < 5 or parts[0].startswith("#"):
263
- continue
264
- try:
265
- time = float(parts[0])
266
- minimum, maximum, average = float(parts[2]), float(parts[3]), float(parts[4])
267
- except ValueError:
268
- continue
269
- if all(math.isfinite(value) for value in (time, minimum, maximum, average)):
270
- rows.append((time, parts[1], minimum, maximum, average))
271
- except OSError:
272
- continue
273
- if rows:
274
- evidence.append(evidence_path(relative_to, path))
275
- if not rows:
276
- return {}, []
277
- final_time = max(row[0] for row in rows)
278
- final_rows = [row for row in rows if abs(row[0] - final_time) <= 1e-12 * max(1.0, abs(final_time))]
279
- # Symmetric wall patches are one declared response; average their final
280
- # values while retaining the source file as auditable evidence.
281
- return {"first_cell_yplus": statistics.fmean(row[4] for row in final_rows)}, sorted(set(evidence))
282
-
283
-
284
- def spalding_metrics(case: Path) -> tuple[dict[str, float], list[str]]:
285
- files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv"))
286
- # OpenFOAM's standard yPlus function object writes ``yPlus.dat`` with a
287
- # non-numeric patch-name column (``Time patch min max average``). It is
288
- # intentionally handled by ``standard_yplus_metrics`` below, so discover
289
- # it by basename instead of sending it through ``named_numeric_rows``.
290
- for root in evidence_roots(case):
291
- files.extend(
292
- path for path in root.rglob("*")
293
- if path.is_file() and path.name.lower() == "yplus.dat"
294
- )
295
- # The rollout measurement writer emits an explicit wall table instead of
296
- # a Spalding profile. yPlus_min is valid endpoint evidence; it is not
297
- # treated as a profile residual.
298
- files.extend(matching_files(case, ("yplus_wall.csv",), (".csv",)))
299
- # Accept semantically equivalent wall tables even when the file name is
300
- # agent-specific, provided the table contains a y+ column.
301
- for root in evidence_roots(case):
302
- for path in root.rglob("*"):
303
- if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}:
304
- continue
305
- header, _ = named_numeric_rows(path)
306
- normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")) for name in header}
307
- if "yplus" in normalized or "firstcellyplus" in normalized:
308
- files.append(path)
309
- files = sorted(set(files))
310
- standard_values, standard_evidence = standard_yplus_metrics(files, case)
311
- wall_files = [path for path in files if path.name.lower() == "yplus_wall.csv"]
312
- wall_values: list[float] = []
313
- wall_evidence: list[str] = []
314
- for path in wall_files:
315
- try:
316
- with path.open(newline="", encoding="utf-8", errors="ignore") as handle:
317
- for row in csv.DictReader(handle):
318
- raw = row.get("yPlus_min") or row.get("yplus_min") or row.get("first_cell_yplus")
319
- if raw is not None:
320
- value = float(raw)
321
- if math.isfinite(value) and value >= 0:
322
- wall_values.append(value)
323
- if wall_values:
324
- wall_evidence.append(evidence_path(case, path))
325
- except (OSError, ValueError):
326
- continue
327
- # Branch-labelled evidence is handled separately for the multi-Re case.
328
- files = [path for path in files if "branches" not in tuple(evidence_path(case, path).split("/"))]
329
- values, evidence = spalding_metrics_from_files([path for path in files if path not in wall_files], case)
330
- if "first_cell_yplus" not in values:
331
- # CSV profile variants use a header with a literal ``y+`` token or a
332
- # yplus column and do not necessarily contain a yPlus_min summary.
333
- for path in files:
334
- if path in wall_files:
335
- continue
336
- header, rows = named_numeric_rows(path)
337
- normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): i for i, name in enumerate(header)}
338
- index = next((normalized[name] for name in ("yplus", "firstcellyplus") if name in normalized), None)
339
- if index is not None:
340
- vals = [row[index] for row in rows if len(row) > index and math.isfinite(row[index]) and row[index] >= 0]
341
- if vals:
342
- values["first_cell_yplus"] = vals[0]
343
- evidence.append(evidence_path(case, path))
344
- break
345
- if wall_values:
346
- # The final row is the retained endpoint; using the mean would mix
347
- # initialization transients with the declared final wall resolution.
348
- values["first_cell_yplus"] = wall_values[-1]
349
- evidence.extend(wall_evidence)
350
- if "first_cell_yplus" not in values and standard_values:
351
- values.update(standard_values)
352
- evidence.extend(standard_evidence)
353
- return values, sorted(set(evidence))
354
-
355
-
356
- def branchwise_spalding_metrics(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
357
- branches: dict[str, Any] = {}
358
- evidence: list[str] = []
359
- files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv"))
360
- by_branch: dict[str, list[Path]] = {}
361
- for path in files:
362
- match = re.search(r"Re_tau_(180|395|590)", str(path))
363
- if match:
364
- by_branch.setdefault(f"Re_tau_{match.group(1)}", []).append(path)
365
- for branch, branch_files in sorted(by_branch.items()):
366
- values, refs = spalding_metrics_from_files(sorted(branch_files), case)
367
- if {"spalding_log_rmse", "first_cell_yplus"} <= set(values):
368
- branches[branch] = values
369
- evidence.extend(refs)
370
- expected = {"Re_tau_180", "Re_tau_395", "Re_tau_590"}
371
- if set(branches) != expected:
372
- return None, sorted(set(evidence))
373
- return {"kind": "branch_scalars", "branches": branches}, sorted(set(evidence))
374
-
375
-
376
- def stirrer_power_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
377
- files = matching_files(case, ("surfaceFieldValue.dat",), (".dat",))
378
- points: list[dict[str, float]] = []
379
- evidence: list[str] = []
380
- for path in files:
381
- header, rows = named_numeric_rows(path)
382
- fields = [name for name in header if name != "Time" and "stressUSf" in name]
383
- if "Time" not in header or not fields:
384
- continue
385
- time_index, power_index = header.index("Time"), header.index(fields[0])
386
- points.extend({"time": row[time_index], "value": row[power_index]} for row in rows if math.isfinite(row[power_index]))
387
- evidence.append(evidence_path(case, path))
388
- if not points:
389
- return None, []
390
- points.sort(key=lambda item: item["time"])
391
- return {"kind": "time_history", "quantity": "surface_integrated_stressUSf_power", "points": points}, evidence
392
-
393
-
394
- def named_sample_profiles(case: Path, names: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]:
395
- profiles: list[dict[str, Any]] = []
396
- evidence: list[str] = []
397
- roots = [case, *evidence_roots(case)]
398
- candidates: list[Path] = []
399
- for root in roots:
400
- candidates.extend(item for item in root.rglob("*") if item.is_file() and (
401
- item.name in names or (item.suffix.lower() == ".csv" and item.parent.name.lower() == "profiles")
402
- ))
403
- for path in sorted(set(candidates)):
404
- header, rows = named_numeric_rows(path)
405
- if len(header) < 2 or not rows or not profile_has_physical_columns(header):
406
- continue
407
- profiles.append({
408
- "profile_id": evidence_path(case, path),
409
- "columns": header,
410
- "rows": rows,
411
- })
412
- evidence.append(evidence_path(case, path))
413
- if not profiles:
414
- return None, []
415
- return {"kind": "named_profiles", "profiles": profiles}, evidence
416
-
417
-
418
- def result_profile_tables(case: Path, tokens: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]:
419
- """Read explicit profile tables from workspace/results when named output
420
- files use a family-specific filename instead of horizontal.xy/vertical.xy.
421
- """
422
- profiles: list[dict[str, Any]] = []
423
- evidence: list[str] = []
424
- roots = list(evidence_roots(case))
425
- resolved = resolve_evidence(case, "centerline_profile", suffixes=(".csv", ".dat", ".raw", ".xy"))
426
- for root in roots:
427
- if not root.is_dir():
428
- continue
429
- for path in sorted(root.rglob("*")):
430
- if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}:
431
- continue
432
- if path not in resolved and not any(token.lower() in path.name.lower() for token in tokens):
433
- continue
434
- header, rows = named_numeric_rows(path)
435
- if len(header) < 2 or not rows or not profile_has_physical_columns(header):
436
- continue
437
- profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows})
438
- evidence.append(evidence_path(case, path))
439
- if not profiles:
440
- return None, []
441
- return {"kind": "named_profiles", "profiles": profiles}, sorted(set(evidence))
442
-
443
-
444
- def profile_has_physical_columns(header: list[str]) -> bool:
445
- """Require a coordinate and at least one sampled physical field."""
446
- normalized = [re.sub(r"[^a-z0-9]", "", name.lower()) for name in header]
447
- has_coordinate = any(name in {"x", "y", "z", "coordinate", "position", "arc"} or name.startswith(("x", "y", "z")) for name in normalized)
448
- has_field = any(
449
- name in {"p", "rho", "u", "ux", "uy", "uz"}
450
- or name.startswith(("px", "py", "pz", "rhox", "rhoy", "rhoz"))
451
- for name in normalized
452
- )
453
- return has_coordinate and has_field
454
-
455
-
456
- def named_profiles_containing(case: Path, tokens: tuple[str, ...], required_columns: tuple[str, ...] = ()) -> tuple[dict[str, Any] | None, list[str]]:
457
- """Read explicitly named sample tables; never infer a physical metric from field extrema."""
458
- profiles: list[dict[str, Any]] = []
459
- evidence: list[str] = []
460
- for root in (case, *evidence_roots(case)):
461
- for path in sorted(item for item in root.rglob("*") if item.is_file() and path_like_sample(item, tokens)):
462
- header, rows = named_numeric_rows(path)
463
- if len(header) < 2 or not rows or any(column not in header for column in required_columns):
464
- continue
465
- profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows})
466
- evidence.append(evidence_path(case, path))
467
- return ({"kind": "named_profiles", "profiles": profiles}, evidence) if profiles else (None, [])
468
-
469
-
470
- def path_like_sample(path: Path, tokens: tuple[str, ...]) -> bool:
471
- name = path.name.lower()
472
- return path.suffix.lower() in {".xy", ".raw", ".dat", ".csv"} and any(token.lower() in name for token in tokens)
473
-
474
-
475
- def field_dimensions(case: Path, field: str) -> str | None:
476
- for path in sorted(case.rglob(field), reverse=True):
477
- if not path.is_file() or not path.parent.name.replace(".", "", 1).isdigit():
478
- continue
479
- header = path.read_bytes()[:4096].decode("ascii", errors="ignore")
480
- match = re.search(r"dimensions\s*\[([^]]+)\]", header)
481
- if match:
482
- return " ".join(match.group(1).split())
483
- return None
484
-
485
-
486
- def evidence_branch(case: Path, path: Path) -> str:
487
- try:
488
- parts = path.relative_to(case).parts
489
- except ValueError:
490
- parts = path.relative_to(case.parent).parts
491
- try:
492
- index = parts.index("postProcessing")
493
- except ValueError:
494
- return "root"
495
- return "/".join(parts[:index]) or "root"
496
-
497
-
498
- def explicit_mass_flow_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
499
- branch_points: dict[str, list[dict[str, float]]] = {}
500
- evidence: list[str] = []
501
- candidates = matching_files(case, ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi"), (".dat", ".raw", ".csv"))
502
- # Some benchmark variants materialize several nested operating-point cases;
503
- # accept their postProcessing evidence without flattening those branches.
504
- if not candidates:
505
- candidates = sorted(path for path in case.rglob("*") if path.is_file()
506
- and path.suffix.lower() in {".dat", ".raw", ".csv"}
507
- and any(token.lower() in str(path).lower()
508
- for token in ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi")))
509
- for path in candidates:
510
- patch_match = re.search(r"patch=([^)/]+)", str(path))
511
- if patch_match is not None and patch_match.group(1).lower() not in {"inlet", "inlet1", "main", "mainstream"}:
512
- # The principal pump/nozzle response is the declared inlet flow;
513
- # do not concatenate inlet and outlet fluxes into one history.
514
- continue
515
- header, rows = named_numeric_rows(path)
516
- mass_columns = [column for column in header if any(token in column.lower() for token in ("rhophi", "massflow", "massflux", "sum(phi)"))]
517
- if "Time" not in header or not mass_columns:
518
- continue
519
- t_index, value_index = header.index("Time"), header.index(mass_columns[0])
520
- branch = evidence_branch(case, path)
521
- branch_points.setdefault(branch, []).extend(
522
- {"time": row[t_index], "value": row[value_index]}
523
- for row in rows if math.isfinite(row[value_index])
524
- )
525
- evidence.append(evidence_path(case, path))
526
- if not branch_points:
527
- return None, []
528
- dimensions = field_dimensions(case, "phi")
529
- quantity = {
530
- "1 0 -1 0 0 0 0": "explicit_mass_flow",
531
- "0 3 -1 0 0 0 0": "explicit_volumetric_flow",
532
- }.get(dimensions, "explicit_flux_unknown_dimensions")
533
- branches = {
534
- branch: {"kind": "time_history", "quantity": quantity,
535
- "points": sorted(points, key=lambda item: item["time"])}
536
- for branch, points in sorted(branch_points.items())
537
- }
538
- if set(branches) == {"root"}:
539
- result = branches["root"]
540
- else:
541
- result = {"kind": "branched_time_histories", "quantity": quantity, "branches": branches}
542
- result["field_dimensions"] = dimensions
543
- return result, sorted(set(evidence))
544
-
545
-
546
- def explicit_patch_pressure(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
547
- histories: dict[str, list[dict[str, float]]] = {}
548
- evidence: list[str] = []
549
- for path in matching_files(case, ("patchAverage", "patchIntegrate", "pressureRise", "pressure_rise"), (".dat", ".raw", ".csv")):
550
- header, rows = named_numeric_rows(path)
551
- pressure_columns = [column for column in header if column != "Time" and any(token in column.lower() for token in ("p", "pressure"))]
552
- match = re.search(r"patch=([^)/]+)", str(path))
553
- if "Time" not in header or not pressure_columns or not match:
554
- continue
555
- patch_name = match.group(1)
556
- t_index, value_index = header.index("Time"), header.index(pressure_columns[0])
557
- histories.setdefault(patch_name, []).extend({"time": row[t_index], "value": row[value_index]} for row in rows if math.isfinite(row[value_index]))
558
- evidence.append(evidence_path(case, path))
559
- inlet_name = next((name for name in histories if "inlet" in name.lower()), None)
560
- outlet_name = next((name for name in histories if "outlet" in name.lower()), None)
561
- if inlet_name is None or outlet_name is None:
562
- return None, []
563
- inlet = {round(point["time"], 12): point["value"] for point in histories[inlet_name]}
564
- outlet = {round(point["time"], 12): point["value"] for point in histories[outlet_name]}
565
- points = [
566
- {"time": time, "value": outlet[time] - inlet[time]}
567
- for time in sorted(set(inlet) & set(outlet))
568
- ]
569
- if not points:
570
- return None, []
571
- return {
572
- "kind": "time_history",
573
- "quantity": "pressure_rise",
574
- "definition": "outlet_minus_inlet_patch_average",
575
- "source_patches": {"inlet": inlet_name, "outlet": outlet_name},
576
- "points": points,
577
- }, sorted(set(evidence))
578
-
579
-
580
- def crossjet_inlet_mass_flux_ratio(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
581
- fluxes: dict[str, list[tuple[float, float]]] = {}
582
- evidence: list[str] = []
583
- for path in resolve_evidence(case, "patch_flux", suffixes=(".dat", ".raw", ".csv")):
584
- match = re.search(r"patch=([^)/]+)", str(path))
585
- if match is None:
586
- match = re.search(r"(?m)^\s*#\s*Selection\s*:\s*patch\(([^)]+)\)", path.read_text(errors="ignore"))
587
- if match is None:
588
- continue
589
- patch = match.group(1).lower()
590
- canonical = (
591
- "inlet1" if patch in {"inlet1", "inlet", "main", "mainstream", "maininlet", "mainflowinlet"}
592
- else "inlet2" if patch in {"inlet2", "jet", "injection", "jetinlet"}
593
- else None
594
- )
595
- if canonical is None:
596
- continue
597
- header, rows = named_numeric_rows(path)
598
- columns = [column for column in header if column != "Time" and "sum(phi)" in column]
599
- if "Time" not in header or not columns:
600
- continue
601
- ti, vi = header.index("Time"), header.index(columns[0])
602
- fluxes.setdefault(canonical, []).extend((row[ti], row[vi]) for row in rows)
603
- evidence.append(evidence_path(case, path))
604
- if not all(fluxes.get(patch) for patch in ("inlet1", "inlet2")):
605
- return None, []
606
- main = sorted(fluxes["inlet1"])[-1]
607
- jet = sorted(fluxes["inlet2"])[-1]
608
- if main[1] == 0:
609
- return None, []
610
- return {
611
- "kind": "scalar_ratio",
612
- "quantity": "jet_to_mainstream_mass_flux_ratio",
613
- "value": abs(jet[1] / main[1]),
614
- "mainstream_flux": main[1],
615
- "jet_flux": jet[1],
616
- "time": min(main[0], jet[0]),
617
- "patch_aliases": {"mainstream": "inlet1", "jet": "inlet2"},
618
- }, sorted(set(evidence))
619
-
620
-
621
- def phase_volume_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
622
- points: list[dict[str, float]] = []
623
- evidence: list[str] = []
624
- for time, directory in numeric_time_dirs(case):
625
- alpha_path = foam_path(directory, "alpha.water")
626
- volume_path = foam_path(directory, "Vc")
627
- if alpha_path is None or volume_path is None:
628
- continue
629
- try:
630
- alpha = read_scalar_field(alpha_path)
631
- volumes = read_scalar_field(volume_path)
632
- except (OSError, ValueError, RuntimeError):
633
- continue
634
- if len(alpha) != len(volumes) or not volumes:
635
- continue
636
- total = sum(volumes)
637
- if total <= 0:
638
- continue
639
- points.append({"time": time, "value": sum(a * v for a, v in zip(alpha, volumes)) / total})
640
- evidence.extend((evidence_path(case, alpha_path), evidence_path(case, volume_path)))
641
- if not points:
642
- return None, []
643
- return {"kind": "time_history", "quantity": "volume_weighted_alpha_water", "points": points}, sorted(set(evidence))
644
-
645
-
646
- def volume_average_speed_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
647
- points: list[dict[str, float]] = []
648
- evidence: list[str] = []
649
- for time, directory in numeric_time_dirs(case):
650
- velocity_path = foam_path(directory, "U")
651
- volume_path = foam_path(directory, "Vc")
652
- if velocity_path is None or volume_path is None:
653
- continue
654
- try:
655
- velocity = read_vector_field(velocity_path)
656
- volumes = read_scalar_field(volume_path)
657
- except (OSError, ValueError, RuntimeError):
658
- continue
659
- if len(velocity) != len(volumes) or not volumes:
660
- continue
661
- total = sum(volumes)
662
- if total <= 0:
663
- continue
664
- value = sum(math.sqrt(u * u + v * v + w * w) * volume
665
- for (u, v, w), volume in zip(velocity, volumes)) / total
666
- if not math.isfinite(value):
667
- continue
668
- points.append({"time": time, "value": value})
669
- evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path)))
670
- if not points:
671
- return None, []
672
- return {"kind": "time_history", "quantity": "volume_average_speed", "points": points}, sorted(set(evidence))
673
-
674
-
675
- def volume_speed_rms_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
676
- points: list[dict[str, float]] = []
677
- evidence: list[str] = []
678
- for time, directory in numeric_time_dirs(case):
679
- velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc")
680
- if velocity_path is None or volume_path is None:
681
- continue
682
- try:
683
- velocity, volumes = read_vector_field(velocity_path), read_scalar_field(volume_path)
684
- except (OSError, ValueError, RuntimeError):
685
- continue
686
- if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0:
687
- continue
688
- speeds = [math.sqrt(u * u + v * v + w * w) for u, v, w in velocity]
689
- total = sum(volumes)
690
- mean = sum(speed * volume for speed, volume in zip(speeds, volumes)) / total
691
- rms = math.sqrt(sum((speed - mean) ** 2 * volume for speed, volume in zip(speeds, volumes)) / total)
692
- if math.isfinite(rms):
693
- points.append({"time": time, "value": rms})
694
- evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path)))
695
- if not points:
696
- return None, []
697
- return {"kind": "time_history", "quantity": "volume_speed_spatial_rms", "points": points}, sorted(set(evidence))
698
-
699
-
700
- def volume_average_speed_final(case: Path) -> tuple[float | None, list[str]]:
701
- """Extract a final-state mixing response from retained U and cell volumes."""
702
- for _, directory in reversed(numeric_time_dirs(case)):
703
- velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc")
704
- if velocity_path is None:
705
- continue
706
- try:
707
- # Retained agent fields can contain a uniform internal U while Vc
708
- # still has one volume per cell. Decode the concrete array first
709
- # so the uniform vector is expanded using an observed cell count.
710
- if volume_path is not None:
711
- volumes = read_scalar_field(volume_path)
712
- geometry_evidence = [volume_path]
713
- else:
714
- from .retained_fields import derive_cell_geometry
715
- volumes, _, geometry_evidence = derive_cell_geometry(case)
716
- try:
717
- velocity = read_vector_field(velocity_path)
718
- except (ValueError, RuntimeError):
719
- velocity = read_vector_field_allow_uniform(velocity_path, len(volumes))
720
- if volume_path is not None and len(volumes) == 1 and len(velocity) > 1:
721
- volumes = volumes * len(velocity)
722
- except (OSError, ValueError, RuntimeError):
723
- continue
724
- if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0:
725
- continue
726
- total = sum(volumes)
727
- value = sum(math.sqrt(u * u + v * v + w * w) * volume
728
- for (u, v, w), volume in zip(velocity, volumes)) / total
729
- if math.isfinite(value):
730
- return value, [evidence_path(case, path) for path in [velocity_path, *geometry_evidence]]
731
- return None, []
732
-
733
-
734
- def read_vector_field_allow_uniform(path: Path, count: int) -> list[tuple[float, float, float]]:
735
- try:
736
- return read_vector_field(path)
737
- except (ValueError, RuntimeError):
738
- text = path.read_text(encoding="ascii", errors="ignore")
739
- match = re.search(r"internalField\s+uniform\s+\(([^)]+)\)", text)
740
- if match is None:
741
- raise
742
- values = [float(item) for item in match.group(1).split()]
743
- if len(values) != 3:
744
- raise ValueError(f"invalid uniform vector field: {path}")
745
- return [(values[0], values[1], values[2])] * count
746
-
747
-
748
- def read_scalar_field_allow_uniform(path: Path, count: int) -> list[float]:
749
- """Read a scalar field while preserving the semantics of a uniform field."""
750
- try:
751
- values = read_scalar_field(path)
752
- except (ValueError, RuntimeError):
753
- text = path.read_text(encoding="ascii", errors="ignore")
754
- match = re.search(r"internalField\s+uniform\s+([^;]+);", text)
755
- if match is None:
756
- raise
757
- return [float(match.group(1).strip())] * count
758
- if len(values) == 1 and count > 1:
759
- # OpenFOAM permits a uniform field to be serialized as one value.
760
- return values * count
761
- return values
762
-
763
-
764
- def crossjet_interior_pressure_span(case: Path) -> tuple[float | None, list[str]]:
765
- """Return the pressure response in the declared internal CrossJet window.
766
-
767
- The span is deliberately computed from the retained pressure field rather
768
- than from ``grad(p)``. This remains extractable for references that store
769
- ``p`` as a uniform field and avoids treating a missing/zero post-processing
770
- gradient as a shock observable.
771
- """
772
- for _, directory in reversed(numeric_time_dirs(case)):
773
- centre_path, pressure_path = foam_path(directory, "C"), foam_path(directory, "p")
774
- if pressure_path is None:
775
- continue
776
- try:
777
- if centre_path is not None:
778
- centres = read_vector_field(centre_path)
779
- geometry_evidence = [centre_path]
780
- else:
781
- from .retained_fields import derive_cell_geometry
782
- _, centres, geometry_evidence = derive_cell_geometry(case)
783
- pressure = read_scalar_field_allow_uniform(pressure_path, len(centres))
784
- except (OSError, ValueError, RuntimeError):
785
- continue
786
- if len(pressure) != len(centres):
787
- continue
788
- values = [value for (x, y, _), value in zip(centres, pressure)
789
- if -1.0 <= x <= 1.0 and 0.1 <= y <= 0.95]
790
- if values:
791
- return max(values) - min(values), [evidence_path(case, path) for path in [*geometry_evidence, pressure_path]]
792
- return None, []
793
-
794
-
795
- def crossjet_interior_pressure_gradient_max(case: Path) -> tuple[float | None, list[str]]:
796
- """Return the maximum interior pressure span."""
797
- return crossjet_interior_pressure_span(case)
798
-
799
-
800
- def profile_event_locations(profiles: dict[str, Any]) -> dict[str, Any] | None:
801
- events: list[dict[str, Any]] = []
802
- for profile in profiles.get("profiles", []):
803
- columns = profile.get("columns", [])
804
- rows = profile.get("rows", [])
805
- if len(columns) < 2 or len(rows) < 5:
806
- continue
807
- coordinate_index = 0
808
- for field in ("p", "rho"):
809
- field_index = next((index for index, name in enumerate(columns)
810
- if name.lower() == field or name.lower().startswith(field + "_")), None)
811
- if field_index is None:
812
- continue
813
- gradients: list[tuple[int, float, float]] = []
814
- for index in range(len(rows) - 1):
815
- spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index])
816
- if spacing <= 0:
817
- continue
818
- gradient = abs(rows[index + 1][field_index] - rows[index][field_index]) / spacing
819
- coordinate = (rows[index + 1][coordinate_index] + rows[index][coordinate_index]) / 2
820
- gradients.append((index, coordinate, gradient))
821
- if not gradients:
822
- continue
823
- peak = max(value for _, _, value in gradients)
824
- threshold = 0.05 * peak
825
- candidates = [
826
- item for position, item in enumerate(gradients)
827
- if item[2] >= threshold
828
- and (position == 0 or item[2] >= gradients[position - 1][2])
829
- and (position == len(gradients) - 1 or item[2] > gradients[position + 1][2])
830
- ]
831
- selected: list[tuple[int, float, float]] = []
832
- for candidate in sorted(candidates, key=lambda item: item[2], reverse=True):
833
- if all(abs(candidate[0] - item[0]) >= 4 for item in selected):
834
- selected.append(candidate)
835
- if len(selected) == 12:
836
- break
837
- for index, coordinate, magnitude in sorted(selected, key=lambda item: item[1]):
838
- local_spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index])
839
- events.append({
840
- "profile_id": profile["profile_id"],
841
- "field": field,
842
- "coordinate": coordinate,
843
- "gradient_magnitude": magnitude,
844
- "local_cell_size": local_spacing,
845
- })
846
- if not events:
847
- return None
848
- return {
849
- "kind": "profile_feature_locations",
850
- "detector": "local_abs_gradient_peaks.v1",
851
- "relative_prominence": 0.05,
852
- "minimum_separation_samples": 4,
853
- "maximum_features_per_field_profile": 12,
854
- "events": events,
855
- }
856
-
857
-
858
- def final_riemann_profiles(profiles: dict[str, Any]) -> dict[str, Any]:
859
- """Select each centerline's latest saved time and use its physical axis.
860
-
861
- OpenFOAM raw sets may prefix x/y/z with arc distance. Preserve the sampled
862
- values, but put x (horizontal) or y (vertical) first for event detection.
863
- """
864
- from .comparison import profile_key
865
- selected: dict[str, tuple[float, dict[str, Any]]] = {}
866
- for profile in profiles.get("profiles", []):
867
- key = profile_key(profile)
868
- axis = {"horizontal.xy": "x", "vertical.xy": "y"}.get(key)
869
- columns = profile.get("columns", [])
870
- if axis is None or axis not in columns:
871
- continue
872
- try:
873
- time = float(Path(profile["profile_id"]).parent.name)
874
- except ValueError:
875
- time = -math.inf
876
- if key in selected and time < selected[key][0]:
877
- continue
878
- order = [columns.index(axis)] + [i for i, name in enumerate(columns) if name != axis]
879
- normalized = {**profile, "columns": [columns[i] for i in order],
880
- "rows": [[row[i] for i in order] for row in profile["rows"]]}
881
- selected[key] = (time, normalized)
882
- return {"kind": "named_profiles", "profiles": [item[1] for item in selected.values()]}
883
-
884
-
885
- def numeric_time_dirs(case: Path) -> list[tuple[float, Path]]:
886
- result: list[tuple[float, Path]] = []
887
- for path in case.iterdir():
888
- if not path.is_dir():
889
- continue
890
- try:
891
- result.append((float(path.name), path))
892
- except ValueError:
893
- pass
894
- return sorted(result)
895
-
896
-
897
- def mesh_dir(case: Path, time_dir: Path) -> Path:
898
- local = time_dir / "polyMesh"
899
- return local if local.is_dir() else case / "constant/polyMesh"
900
-
901
-
902
- def connected_components(active: set[int], owner: list[int], neighbour: list[int]) -> list[list[int]]:
903
- adjacency: dict[int, list[int]] = {cell: [] for cell in active}
904
- for left, right in zip(owner, neighbour):
905
- if left in active and right in active:
906
- adjacency[left].append(right)
907
- adjacency[right].append(left)
908
- components: list[list[int]] = []
909
- unseen = set(active)
910
- while unseen:
911
- seed = unseen.pop()
912
- stack = [seed]
913
- component = [seed]
914
- while stack:
915
- for cell in adjacency[stack.pop()]:
916
- if cell in unseen:
917
- unseen.remove(cell)
918
- stack.append(cell)
919
- component.append(cell)
920
- components.append(component)
921
- return components
922
-
923
-
924
- def component_geometry(
925
- cells: list[int], gas: list[float], volumes: list[float], centres: list[tuple[float, float, float]], volume_factor: float
926
- ) -> dict[str, float]:
927
- weights = [max(0.0, min(1.0, gas[cell])) * volumes[cell] for cell in cells]
928
- volume = sum(weights)
929
- if volume <= 0:
930
- return {}
931
- centroid = [sum(weight * centres[cell][axis] for weight, cell in zip(weights, cells)) / volume for axis in range(3)]
932
- xx = sum(weight * (centres[cell][0] - centroid[0]) ** 2 for weight, cell in zip(weights, cells)) / volume
933
- yy = sum(weight * (centres[cell][1] - centroid[1]) ** 2 for weight, cell in zip(weights, cells)) / volume
934
- xy = sum(weight * (centres[cell][0] - centroid[0]) * (centres[cell][1] - centroid[1]) for weight, cell in zip(weights, cells)) / volume
935
- root = math.sqrt(max(0.0, (xx - yy) ** 2 + 4 * xy * xy))
936
- major = max(0.0, (xx + yy + root) / 2)
937
- minor = max(0.0, (xx + yy - root) / 2)
938
- aspect = math.sqrt(major / minor) if minor > 0 else None
939
- return {
940
- "volume": volume,
941
- "centroid_x": centroid[0],
942
- "centroid_y": centroid[1],
943
- "centroid_z": centroid[2],
944
- "aspect_ratio": aspect,
945
- "equivalent_radius_3d": (3 * volume * volume_factor / (4 * math.pi)) ** (1 / 3),
946
- }
947
-
948
-
949
- def axisymmetric_volume_factor(case: Path) -> float:
950
- boundary = case / "constant/polyMesh/boundary"
951
- if not boundary.is_file() or "wedge" not in boundary.read_text(encoding="utf-8", errors="ignore"):
952
- return 1.0
953
- points_path = foam_path(case / "constant/polyMesh", "points")
954
- if points_path is None:
955
- return 1.0
956
- angles = [math.atan2(y, x) for x, y, _ in read_vector_list(points_path) if x > 0]
957
- if not angles:
958
- return 1.0
959
- wedge_angle = max(angles) - min(angles)
960
- return 2 * math.pi / wedge_angle if wedge_angle > 0 else 1.0
961
-
962
-
963
- def bubble_history(case: Path) -> tuple[list[dict[str, Any]], list[str], list[str]]:
964
- history: list[dict[str, Any]] = []
965
- evidence: list[str] = []
966
- errors: list[str] = []
967
- dynamic = not static_mesh(case)
968
- volume_factor = axisymmetric_volume_factor(case)
969
- cached_geometry: tuple[list[float], list[tuple[float, float, float]]] | None = None
970
- cached_topology: tuple[list[int], list[int]] | None = None
971
- time_dirs = numeric_time_dirs(case)
972
- if not dynamic:
973
- for _, directory in reversed(time_dirs):
974
- volume_path = foam_path(directory, "Vc")
975
- centre_path = foam_path(directory, "C")
976
- if volume_path and centre_path:
977
- cached_geometry = (read_scalar_field(volume_path), read_vector_field(centre_path))
978
- break
979
- topology_dir = case / "constant/polyMesh"
980
- owner_path = foam_path(topology_dir, "owner")
981
- neighbour_path = foam_path(topology_dir, "neighbour")
982
- if owner_path and neighbour_path:
983
- cached_topology = (read_label_list(owner_path), read_label_list(neighbour_path))
984
- if cached_geometry is None:
985
- try:
986
- volumes, centres, mesh_paths = derive_cell_geometry(case)
987
- cached_geometry = (volumes, centres)
988
- evidence.extend(evidence_path(case, path) for path in mesh_paths)
989
- boundary_path = foam_path(topology_dir, "boundary")
990
- if boundary_path:
991
- evidence.append(evidence_path(case, boundary_path))
992
- except (OSError, ValueError, RuntimeError) as exc:
993
- errors.append(f"retained mesh geometry: {exc}")
994
- previous_tracks: dict[int, tuple[float, float, float]] = {}
995
- next_track = 1
996
- for time, directory in time_dirs:
997
- alpha_path = foam_path(directory, "alpha.water")
998
- if alpha_path is None:
999
- continue
1000
- volume_path = foam_path(directory, "Vc")
1001
- centre_path = foam_path(directory, "C")
1002
- try:
1003
- if cached_geometry is not None and not dynamic:
1004
- geometry = cached_geometry
1005
- elif volume_path and centre_path:
1006
- geometry = (read_scalar_field(volume_path), read_vector_field(centre_path))
1007
- if not dynamic:
1008
- cached_geometry = geometry
1009
- else:
1010
- errors.append(f"{directory.name}: missing C/Vc measurement fields")
1011
- continue
1012
- topology_dir = mesh_dir(case, directory)
1013
- owner_path = foam_path(topology_dir, "owner")
1014
- neighbour_path = foam_path(topology_dir, "neighbour")
1015
- if (owner_path is None or neighbour_path is None) and dynamic:
1016
- # Dynamic solvers may not retain a polyMesh in every output
1017
- # directory. Reuse the immutable mesh topology only when it
1018
- # is present and the field length remains compatible.
1019
- owner_path = foam_path(case / "constant/polyMesh", "owner")
1020
- neighbour_path = foam_path(case / "constant/polyMesh", "neighbour")
1021
- if cached_topology is not None and not dynamic:
1022
- topology = cached_topology
1023
- elif owner_path and neighbour_path:
1024
- topology = (read_label_list(owner_path), read_label_list(neighbour_path))
1025
- if not dynamic:
1026
- cached_topology = topology
1027
- else:
1028
- errors.append(f"{directory.name}: missing owner/neighbour topology")
1029
- continue
1030
- volumes, centres = geometry
1031
- alpha = read_scalar_field_allow_uniform(alpha_path, len(volumes))
1032
- if not (len(alpha) == len(volumes) == len(centres)):
1033
- errors.append(f"{directory.name}: alpha/C/Vc length mismatch")
1034
- continue
1035
- gas = [1.0 - value for value in alpha]
1036
- active = {index for index, value in enumerate(gas) if value >= 0.5}
1037
- components = connected_components(active, *topology)
1038
- geometries = [component_geometry(item, gas, volumes, centres, volume_factor) for item in components]
1039
- geometries = sorted((item for item in geometries if item), key=lambda item: item["volume"], reverse=True)
1040
- if geometries:
1041
- cutoff = geometries[0]["volume"] * 1e-4
1042
- geometries = [item for item in geometries if item["volume"] >= cutoff]
1043
- available = set(previous_tracks)
1044
- for item in geometries:
1045
- point = (item["centroid_x"], item["centroid_y"], item["centroid_z"])
1046
- if available:
1047
- track = min(available, key=lambda key: sum((a - b) ** 2 for a, b in zip(point, previous_tracks[key])))
1048
- available.remove(track)
1049
- else:
1050
- track = next_track
1051
- next_track += 1
1052
- item["track_id"] = track
1053
- previous_tracks = {
1054
- item["track_id"]: (item["centroid_x"], item["centroid_y"], item["centroid_z"])
1055
- for item in geometries
1056
- }
1057
- history.append({"time": time, "components": geometries})
1058
- evidence.extend(evidence_path(case, path) for path in (alpha_path, volume_path, centre_path) if path)
1059
- except (OSError, ValueError, RuntimeError) as exc:
1060
- errors.append(f"{directory.name}: {exc}")
1061
- # A dynamic case may intentionally retain geometry/topology only at the
1062
- # endpoint. Earlier missing derived fields make the optional trajectory
1063
- # incomplete, but must not invalidate endpoint principal QoIs when the
1064
- # final saved state was successfully measured.
1065
- if history and history[-1].get("time") == (time_dirs[-1][0] if time_dirs else None):
1066
- errors = []
1067
- return history, sorted(set(evidence)), errors
1068
-
1069
-
1070
- def component_trajectory(history: list[dict[str, Any]], field: str, all_components: bool = False) -> dict[str, Any] | None:
1071
- rows = [item for item in history if item["components"]]
1072
- if not rows:
1073
- return None
1074
- tracks = sorted({component["track_id"] for item in rows for component in item["components"]}) if all_components else [rows[0]["components"][0]["track_id"]]
1075
- series = []
1076
- for track in tracks:
1077
- points = []
1078
- omitted_invalid = 0
1079
- for item in rows:
1080
- component = next((part for part in item["components"] if part["track_id"] == track), None)
1081
- if component is not None:
1082
- value = component[field]
1083
- if value is None:
1084
- omitted_invalid += 1
1085
- continue
1086
- points.append({"time": item["time"], "value": value})
1087
- series.append({
1088
- "component_id": track,
1089
- "points": points,
1090
- "omitted_invalid_sample_count": omitted_invalid,
1091
- "quality_note": "degenerate_component_geometry_samples_omitted" if omitted_invalid else None,
1092
- })
1093
- return {"kind": "component_trajectory", "component_identity": "nearest_centroid_continuation", "series": series}
1094
-
1095
-
1096
- def collapse_events(radius: dict[str, Any]) -> dict[str, Any]:
1097
- events = []
1098
- for series in radius["series"]:
1099
- points = series["points"]
1100
- index = next((i for i in range(1, len(points) - 1) if points[i]["value"] <= points[i - 1]["value"] and points[i]["value"] < points[i + 1]["value"]), None)
1101
- censored = index is None
1102
- if points:
1103
- index = min(range(len(points)), key=lambda i: points[i]["value"]) if index is None else index
1104
- events.append({"component_id": series["component_id"], "time": points[index]["time"], "radius": points[index]["value"], "censored_at_time_boundary": censored})
1105
- status = "complete" if events and all(not event["censored_at_time_boundary"] for event in events) else "censored"
1106
- return {"kind": "component_events", "status": status, "detector": "first_strict_rebound_minimum_else_global_minimum", "events": events}
1107
-
1108
-
1109
- def rise_velocity(centroid: dict[str, Any]) -> dict[str, Any] | None:
1110
- points = centroid["series"][0]["points"]
1111
- if len(points) < 3:
1112
- return None
1113
- end = points[-1]["time"]
1114
- selected = [point for point in points if 0.3 * end <= point["time"] <= 0.7 * end]
1115
- if len(selected) < 2:
1116
- return None
1117
- times = [point["time"] for point in selected]
1118
- values = [point["value"] for point in selected]
1119
- mt, my = statistics.fmean(times), statistics.fmean(values)
1120
- denominator = sum((time - mt) ** 2 for time in times)
1121
- if denominator == 0:
1122
- return None
1123
- slope = sum((time - mt) * (value - my) for time, value in zip(times, values)) / denominator
1124
- return {"kind": "window_regression", "value": slope, "window": [times[0], times[-1]], "normalized_window": [0.3, 0.7], "sample_count": len(times)}
1125
-
1126
-
1127
- def bubble_metrics(case: Path, family: str) -> tuple[dict[str, Any], list[str], list[str]]:
1128
- history, evidence, errors = bubble_history(case)
1129
- if family == "risingBubble":
1130
- centroid = component_trajectory(history, "centroid_y")
1131
- aspect = component_trajectory(history, "aspect_ratio")
1132
- values: dict[str, Any] = {}
1133
- if centroid:
1134
- values["bubble_centroid_y_history"] = centroid
1135
- values["bubble_centroid_y_final"] = final_component_scalar(centroid, "bubble_centroid_y_final")
1136
- velocity = rise_velocity(centroid)
1137
- if velocity:
1138
- values["rise_velocity"] = velocity
1139
- if aspect:
1140
- values["shape_aspect_ratio_history"] = aspect
1141
- values["shape_aspect_ratio_final"] = final_component_scalar(aspect, "shape_aspect_ratio_final")
1142
- radius = component_trajectory(history, "equivalent_radius_3d")
1143
- if radius:
1144
- values["equivalent_radius_final"] = final_component_scalar(radius, "equivalent_radius_final")
1145
- return values, evidence, errors
1146
- radius = component_trajectory(history, "equivalent_radius_3d", all_components=True)
1147
- if not radius:
1148
- return {}, evidence, errors
1149
- event = collapse_events(radius)
1150
- values = {
1151
- "equivalent_radius_history": radius,
1152
- "equivalent_radius_final": final_component_scalar(radius, "equivalent_radius_final", all_components=True),
1153
- "final_component_count": len(radius.get("series", [])),
1154
- "collapse_time_censored_diagnostic": event,
1155
- }
1156
- minima = []
1157
- for series in radius.get("series", []):
1158
- observed = [point for point in series.get("points", [])
1159
- if isinstance(point.get("value"), (int, float)) and math.isfinite(point["value"])]
1160
- if observed:
1161
- point = min(observed, key=lambda item: item["value"])
1162
- minima.append({"component_id": series.get("component_id"), "time": point["time"], "value": point["value"]})
1163
- if minima:
1164
- values["minimum_observed_equivalent_radius"] = {
1165
- "kind": "component_scalars", "quantity": "minimum_observed_equivalent_radius", "components": minima
1166
- }
1167
- if event["status"] == "complete":
1168
- values["collapse_time"] = event
1169
- return values, evidence, errors
1170
-
1171
-
1172
- def final_component_scalar(
1173
- trajectory: dict[str, Any], quantity: str, *, all_components: bool = False
1174
- ) -> dict[str, Any]:
1175
- """Return the last valid connected-component observation.
1176
-
1177
- The full trajectory remains available as a diagnostic, while this endpoint
1178
- response can be recovered when only the final field was retained.
1179
- """
1180
- series = trajectory.get("series", []) if isinstance(trajectory, dict) else []
1181
- components = []
1182
- selected = series if all_components else series[:1]
1183
- for item in selected:
1184
- points = [point for point in item.get("points", [])
1185
- if isinstance(point, dict) and isinstance(point.get("value"), (int, float))
1186
- and math.isfinite(float(point["value"]))]
1187
- if points:
1188
- point = points[-1]
1189
- components.append({"component_id": item.get("component_id"), "time": point["time"], "value": point["value"]})
1190
- return {"kind": "component_scalars", "quantity": quantity, "components": components}
1191
-
1192
-
1193
- def structured_qoi_errors(name: str, value: Any) -> list[str]:
1194
- errors: list[str] = []
1195
- if isinstance(value, (int, float)):
1196
- return [] if not isinstance(value, bool) and math.isfinite(float(value)) else [f"{name}: non-finite scalar"]
1197
- if not isinstance(value, dict):
1198
- return [f"{name}: unsupported QoI value"]
1199
- kind = value.get("kind")
1200
- if kind in {"time_history", "window_regression", "scalar_ratio"}:
1201
- if kind == "time_history":
1202
- points = value.get("points")
1203
- if not isinstance(points, list) or not points:
1204
- return [f"{name}: empty time history"]
1205
- for point in points:
1206
- if not isinstance(point, dict) or not all(
1207
- isinstance(point.get(key), (int, float)) and math.isfinite(float(point[key]))
1208
- for key in ("time", "value")
1209
- ):
1210
- errors.append(f"{name}: invalid time-history point")
1211
- break
1212
- elif not isinstance(value.get("value"), (int, float)) or not math.isfinite(float(value["value"])):
1213
- errors.append(f"{name}: invalid scalar object")
1214
- elif kind == "branched_time_histories":
1215
- branches = value.get("branches")
1216
- if not isinstance(branches, dict) or not branches:
1217
- errors.append(f"{name}: no branches")
1218
- else:
1219
- for branch, history in branches.items():
1220
- errors.extend(structured_qoi_errors(f"{name}/{branch}", history))
1221
- elif kind == "branch_scalars":
1222
- branches = value.get("branches")
1223
- if not isinstance(branches, dict) or not branches:
1224
- errors.append(f"{name}: no scalar branches")
1225
- else:
1226
- for branch, metrics in branches.items():
1227
- if not isinstance(metrics, dict) or not metrics or any(
1228
- not isinstance(item, (int, float)) or isinstance(item, bool) or not math.isfinite(float(item))
1229
- for item in metrics.values()
1230
- ):
1231
- errors.append(f"{name}/{branch}: invalid branch scalar")
1232
- elif kind == "component_scalars":
1233
- components = value.get("components")
1234
- if not isinstance(components, list) or not components:
1235
- errors.append(f"{name}: no component scalars")
1236
- elif any(not isinstance(item.get("value"), (int, float)) or not math.isfinite(float(item["value"]))
1237
- for item in components if isinstance(item, dict)):
1238
- errors.append(f"{name}: invalid component scalar")
1239
- elif kind == "component_trajectory":
1240
- series = value.get("series")
1241
- if not isinstance(series, list) or not series:
1242
- errors.append(f"{name}: no component trajectories")
1243
- else:
1244
- for item in series:
1245
- points = item.get("points", []) if isinstance(item, dict) else []
1246
- valid = [point for point in points if isinstance(point, dict)
1247
- and isinstance(point.get("value"), (int, float))
1248
- and math.isfinite(float(point["value"]))]
1249
- if len(valid) < 2:
1250
- errors.append(f"{name}: component has fewer than two valid points")
1251
- elif kind == "named_profiles":
1252
- profiles = value.get("profiles")
1253
- if not isinstance(profiles, list) or not profiles:
1254
- errors.append(f"{name}: no named profiles")
1255
- elif any(not profile.get("rows") or len(profile.get("columns", [])) < 2 for profile in profiles):
1256
- errors.append(f"{name}: empty or unlabelled profile")
1257
- elif kind in {"profile_events", "profile_feature_locations"}:
1258
- if not isinstance(value.get("events"), list):
1259
- errors.append(f"{name}: invalid event collection")
1260
- else:
1261
- errors.append(f"{name}: unknown structured kind {kind!r}")
1262
- return errors
1263
-
1264
-
1265
- def extract_case(
1266
- case: Path,
1267
- family: str,
1268
- variant: str,
1269
- metrics: list[str],
1270
- *,
1271
- conditional_metrics: list[str] | None = None,
1272
- ) -> dict[str, Any]:
1273
- values: dict[str, Any] = {}
1274
- evidence: dict[str, list[str]] = {}
1275
- methods: dict[str, str] = {}
1276
- spalding, spalding_evidence = spalding_metrics(case) if family == "yPlusVerification" else ({}, [])
1277
- branchwise_spalding, branchwise_spalding_evidence = branchwise_spalding_metrics(case) if family == "yPlusVerification" else (None, [])
1278
- bubbles, bubble_evidence, bubble_errors = bubble_metrics(case, family) if family in {"risingBubble", "compressibleBubbleCollapse"} else ({}, [], [])
1279
- stirrer_power, stirrer_evidence = stirrer_power_history(case) if family == "MRF_stirredReactor" else (None, [])
1280
- riemann_profiles, riemann_evidence = named_sample_profiles(case, ("horizontal.xy", "vertical.xy")) if family == "riemann2D" else (None, [])
1281
- if family == "riemann2D" and riemann_profiles is None:
1282
- riemann_profiles, riemann_evidence = result_profile_tables(case, ("centreline", "centerline", "p_x", "p_y", "rho_x", "rho_y"))
1283
- if riemann_profiles is not None:
1284
- riemann_profiles = final_riemann_profiles(riemann_profiles)
1285
- riemann_events = profile_event_locations(riemann_profiles) if riemann_profiles is not None else None
1286
- nozzle_profiles, nozzle_evidence = named_profiles_containing(case, ("centerline",), ("p",)) if family == "nozzleCDV" else (None, [])
1287
- crossjet_profiles, crossjet_evidence = named_profiles_containing(case, ("trajectory", "centerline", "section"), ()) if family == "supersonicCrossJet" else (None, [])
1288
- mass_flow, mass_flow_evidence = explicit_mass_flow_history(case) if family in {"ERCOFTA_pump", "nozzleCDV"} else (None, [])
1289
- patch_pressure, patch_pressure_evidence = explicit_patch_pressure(case) if family == "ERCOFTA_pump" else (None, [])
1290
- retained_values, retained_evidence, retained_errors = {}, {}, []
1291
- if family == "ERCOFTA_pump":
1292
- retained_values, retained_evidence, retained_errors = pump_measurements(case)
1293
- crossjet_flux_ratio, crossjet_flux_evidence = crossjet_inlet_mass_flux_ratio(case) if family == "supersonicCrossJet" else (None, [])
1294
- phase_volume, phase_volume_evidence = phase_volume_history(case) if family == "MRF_stirredReactor" else (None, [])
1295
- average_speed, average_speed_evidence = volume_average_speed_history(case) if family == "MRF_stirredReactor" else (None, [])
1296
- speed_rms, speed_rms_evidence = volume_speed_rms_history(case) if family == "MRF_stirredReactor" else (None, [])
1297
- speed_final, speed_final_evidence = volume_average_speed_final(case) if family == "MRF_stirredReactor" else (None, [])
1298
- pressure_span, pressure_span_evidence = crossjet_interior_pressure_span(case) if family == "supersonicCrossJet" else (None, [])
1299
- conditional_metrics = conditional_metrics or []
1300
- requested_metrics = list(dict.fromkeys([*metrics, *conditional_metrics]))
1301
- for metric in requested_metrics:
1302
- if metric in {"Cd", "Cl", "Cm", "Cd_mean", "Cd_rms", "Cl_mean", "Cl_rms"}:
1303
- value, refs, method = extract_force_metric(case, metric)
1304
- elif metric in spalding:
1305
- value, refs, method = spalding[metric], spalding_evidence, "spalding_named_profile_or_endpoint.v1"
1306
- elif metric == "branchwise_wall_law_metrics" and branchwise_spalding is not None:
1307
- value, refs, method = branchwise_spalding, branchwise_spalding_evidence, "branchwise_spalding_metrics.v1"
1308
- elif metric in bubbles:
1309
- value, refs, method = bubbles[metric], bubble_evidence, "connected_gas_component_history.v1"
1310
- elif metric == "stirrer_power_history" and stirrer_power is not None:
1311
- value, refs, method = stirrer_power, stirrer_evidence, "named_stirrer_power_history.v1"
1312
- elif metric == "phase_volume_fraction_history" and phase_volume is not None:
1313
- value, refs, method = phase_volume, phase_volume_evidence, "volume_weighted_phase_fraction.v1"
1314
- elif metric == "volume_average_speed_history" and average_speed is not None:
1315
- value, refs, method = average_speed, average_speed_evidence, "volume_weighted_speed.v1"
1316
- elif metric == "volume_speed_rms_history" and speed_rms is not None:
1317
- value, refs, method = speed_rms, speed_rms_evidence, "volume_weighted_speed_rms.v1"
1318
- elif metric == "volume_average_speed_final" and speed_final is not None:
1319
- value, refs, method = speed_final, speed_final_evidence, "volume_weighted_final_speed.v1"
1320
- elif metric == "centerline_profiles" and riemann_profiles is not None:
1321
- value, refs, method = riemann_profiles, riemann_evidence, "named_centerline_profiles.v1"
1322
- elif metric == "event_locations" and riemann_events is not None:
1323
- value, refs, method = riemann_events, riemann_evidence, "local_abs_gradient_peaks.v1"
1324
- elif metric == "centerline_pressure_profile" and nozzle_profiles is not None:
1325
- value, refs, method = nozzle_profiles, nozzle_evidence, "named_centerline_pressure_profile.v1"
1326
- elif metric in retained_values:
1327
- # The retained-field measurement is the canonical path. Agent
1328
- # emitted tables remain useful evidence, but a one-point table or
1329
- # a table with a different time grid must not mask a complete
1330
- # history available in the original fields.
1331
- value, refs, method = retained_values[metric], retained_evidence[metric], "retained_boundary_field_measurement.v1"
1332
- elif metric == "mass_flow_rate" and mass_flow is not None:
1333
- value, refs, method = mass_flow, mass_flow_evidence, "explicit_mass_flux_history.v1"
1334
- elif metric == "volumetric_flow_rate" and mass_flow is not None:
1335
- value, refs, method = mass_flow, mass_flow_evidence, "explicit_volumetric_flux_history.v1"
1336
- elif metric == "pressure_rise" and patch_pressure is not None:
1337
- value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1"
1338
- elif metric == "pressure_rise_history" and patch_pressure is not None:
1339
- value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1"
1340
- elif metric == "jet_centerline_trajectory" and crossjet_profiles is not None:
1341
- value, refs, method = crossjet_profiles, crossjet_evidence, "declared_jet_trajectory_profile.v1"
1342
- elif metric == "jet_to_mainstream_mass_flux_ratio" and crossjet_flux_ratio is not None:
1343
- value, refs, method = crossjet_flux_ratio, crossjet_flux_evidence, "named_inlet_mass_flux_ratio.v1"
1344
- elif metric == "interior_pressure_span" and pressure_span is not None:
1345
- value, refs, method = pressure_span, pressure_span_evidence, "internal_pressure_span_from_p_field.v1"
1346
- else:
1347
- value, refs, method = None, [], "not_implemented_without_declared_v3_evidence"
1348
- if value is not None and (not isinstance(value, float) or math.isfinite(value)):
1349
- values[metric] = value
1350
- evidence[metric] = refs
1351
- methods[metric] = method
1352
- extraction_errors = list(bubble_errors)
1353
- if "stirrer_power_history" in metrics and stirrer_power is None:
1354
- extraction_errors.append("stirrer_power_history: no named stirrer power evidence")
1355
- missing = sorted(set(metrics) - set(values))
1356
- principal_values = {name: values[name] for name in metrics if name in values}
1357
- conditional_values = {name: values[name] for name in conditional_metrics if name in values}
1358
- validation_errors = [
1359
- error for name, value in principal_values.items()
1360
- for error in structured_qoi_errors(name, value)
1361
- ]
1362
- diagnostic_qois = {name: value for name, value in bubbles.items() if name not in metrics}
1363
- if family == "yPlusVerification":
1364
- for name, value in spalding.items():
1365
- if name not in metrics:
1366
- diagnostic_qois[name] = value
1367
- if branchwise_spalding is not None and "branchwise_wall_law_metrics" not in metrics:
1368
- diagnostic_qois["branchwise_wall_law_metrics"] = branchwise_spalding
1369
- if stirrer_power is not None and "stirrer_power_history" not in metrics:
1370
- diagnostic_qois["stirrer_power_history"] = stirrer_power
1371
- if phase_volume is not None and "phase_volume_fraction_history" not in metrics:
1372
- diagnostic_qois["phase_volume_fraction_history"] = phase_volume
1373
- if nozzle_profiles is not None and "centerline_pressure_profile" not in metrics:
1374
- diagnostic_qois["centerline_pressure_profile"] = nozzle_profiles
1375
- if crossjet_profiles is not None and "jet_centerline_trajectory" not in metrics:
1376
- diagnostic_qois["jet_centerline_trajectory"] = crossjet_profiles
1377
- complete = not missing and not validation_errors and not extraction_errors
1378
- resolver = {
1379
- metric: {
1380
- "status": "selected" if metric in evidence else "unresolved",
1381
- "selected_evidence": sorted(set(evidence.get(metric, []))),
1382
- "method": methods.get(metric),
1383
- "physical_validation": "metric_extractor_contract.v1",
1384
- }
1385
- for metric in requested_metrics
1386
- }
1387
- return {
1388
- "schema_version": "foambench.qoi.candidate",
1389
- "case_id": f"{family}/{variant}",
1390
- "family": family,
1391
- "required_metrics": metrics,
1392
- "missing_metrics": missing,
1393
- "qois": principal_values,
1394
- "conditional_qois": conditional_values,
1395
- "conditional_status": {
1396
- name: "available" if name in conditional_values else "not_assessed_missing_evidence"
1397
- for name in conditional_metrics
1398
- },
1399
- "diagnostic_qois": diagnostic_qois,
1400
- "evidence": evidence,
1401
- "metric_methods": methods,
1402
- "evidence_contract": canonical_evidence_manifest(),
1403
- "resolver_report": resolver,
1404
- "extraction_errors": extraction_errors,
1405
- "retained_field_diagnostics": retained_errors,
1406
- "status": "complete" if complete else "incomplete",
1407
- "health": {
1408
- "status": "pass" if complete else "incomplete",
1409
- "checks": {
1410
- "principal_qoi_complete": not missing,
1411
- "structured_qoi_valid": not validation_errors,
1412
- "principal_extraction_error_free": not extraction_errors,
1413
- "no_proxy_fallback": True,
1414
- },
1415
- "validation_errors": [*validation_errors, *extraction_errors],
1416
- },
1417
- }
1418
-
1419
-
1420
- def metric_anomalies(cases: dict[str, dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
1421
- grouped: dict[tuple[str, str, str], list[tuple[str, float]]] = {}
1422
- anomalies: list[dict[str, Any]] = []
1423
- review: list[dict[str, Any]] = []
1424
- for case_id, record in cases.items():
1425
- for metric, value in record.get("qois", {}).items():
1426
- if isinstance(value, (int, float)):
1427
- grouped.setdefault((record["family"], str(record.get("branch_id")), metric), []).append((case_id, float(value)))
1428
- elif isinstance(value, dict) and value.get("kind") == "component_trajectory":
1429
- expected_components = 2 if case_id == "compressibleBubbleCollapse/10" else 1
1430
- if len(value.get("series", [])) != expected_components:
1431
- review.append({
1432
- "type": "unexpected_component_count",
1433
- "case_id": case_id,
1434
- "family": record["family"],
1435
- "metric": metric,
1436
- "expected": expected_components,
1437
- "observed": len(value.get("series", [])),
1438
- "interpretation": "review physical breakup versus threshold or mesh-induced disconnection",
1439
- })
1440
- for series in value.get("series", []):
1441
- for point in series.get("points", []):
1442
- sample = point.get("value")
1443
- if not isinstance(sample, (int, float)) or not math.isfinite(sample):
1444
- anomalies.append({
1445
- "type": "invalid_trajectory_point",
1446
- "case_id": case_id,
1447
- "family": record["family"],
1448
- "branch_id": record.get("branch_id"),
1449
- "metric": metric,
1450
- "component_id": series.get("component_id"),
1451
- "time": point.get("time"),
1452
- "value": sample,
1453
- "quality_flag": point.get("quality_flag"),
1454
- })
1455
- for (family, branch, metric), rows in sorted(grouped.items()):
1456
- values = [value for _, value in rows]
1457
- if any(not math.isfinite(value) for value in values):
1458
- anomalies.append({"type": "nonfinite", "family": family, "branch_id": branch, "metric": metric})
1459
- continue
1460
- if values and all(value == 0 for value in values):
1461
- anomalies.append({"type": "all_zero", "family": family, "branch_id": branch, "metric": metric, "case_count": len(values)})
1462
- if len(values) >= 2 and max(values) == min(values):
1463
- anomalies.append({"type": "constant_metric", "family": family, "branch_id": branch, "metric": metric, "value": values[0]})
1464
- nonzero = [abs(value) for value in values if value != 0]
1465
- if len(nonzero) >= 2 and max(nonzero) / min(nonzero) > 1e6:
1466
- review.append({"type": "dynamic_range_gt_1e6", "family": family, "branch_id": branch, "metric": metric, "minimum_abs": min(nonzero), "maximum_abs": max(nonzero), "interpretation": "review against declared variant relation; not automatically invalid"})
1467
- if len(values) >= 5:
1468
- median = statistics.median(values)
1469
- deviations = [abs(value - median) for value in values]
1470
- mad = statistics.median(deviations)
1471
- if mad > 0:
1472
- for case_id, value in rows:
1473
- score = abs(value - median) / mad
1474
- if score > 8:
1475
- review.append({"type": "robust_outlier", "family": family, "branch_id": branch, "metric": metric, "case_id": case_id, "value": value, "median": median, "mad_score": score, "interpretation": "review against declared variant relation; not automatically invalid"})
1476
- elif any(value != median for value in values):
1477
- for case_id, value in rows:
1478
- if value != median:
1479
- review.append({"type": "robust_outlier", "family": family, "branch_id": branch, "metric": metric, "case_id": case_id, "value": value, "median": median, "mad_score": None, "interpretation": "review against declared variant relation; not automatically invalid"})
1480
- return anomalies, review
1481
-
1482
-
1483
- def extract_campaign(run_roots: Path | list[Path], design: dict[str, Any]) -> dict[str, Any]:
1484
- roots = [run_roots] if isinstance(run_roots, Path) else list(run_roots)
1485
- cases: dict[str, dict[str, Any]] = {}
1486
- missing_case_dirs: list[str] = []
1487
- for family in design.get("families", []):
1488
- family_name = family["family"]
1489
- variants = sorted({variant for branch in family.get("branches", []) for variant in branch.get("cases", [])}, key=int)
1490
- for variant in variants:
1491
- branch, metrics = required_metrics(family, variant)
1492
- conditionals = [
1493
- item["name"] for item in next(
1494
- item for item in family.get("branches", []) if variant in item.get("cases", [])
1495
- ).get("conditional_qois", [])
1496
- ]
1497
- case_id = f"{family_name}/{variant}"
1498
- case_dir = None
1499
- for root in roots:
1500
- case_dir = locate_case(root, family_name, variant)
1501
- if case_dir is not None:
1502
- break
1503
- if case_dir is None:
1504
- missing_case_dirs.append(case_id)
1505
- continue
1506
- record = extract_case(
1507
- case_dir, family_name, variant, metrics, conditional_metrics=conditionals
1508
- )
1509
- record["branch_id"] = branch
1510
- record["case_dir"] = str(case_dir)
1511
- cases[case_id] = record
1512
- complete = sum(record["status"] == "complete" for record in cases.values())
1513
- anomalies, review = metric_anomalies(cases)
1514
- design_findings = [
1515
- {
1516
- "type": "reference_configuration_mismatch",
1517
- "case_id": "compressibleBubbleCollapse/2",
1518
- "severity": "resolved_by_contract_scope",
1519
- "finding": "The materialized reference contains a single 50 um sphere. The QoI branch is restricted to that observed single-bubble response and makes no unsupported radius-scaling claim.",
1520
- "evidence": "compressibleBubbleCollapse__2/full_run_case/system/setFieldsDict",
1521
- "action": "Retain the materialized_single_bubble_response branch unless separate radius subcases are generated.",
1522
- },
1523
- {
1524
- "type": "axisymmetric_geometry_mismatch",
1525
- "case_id": "compressibleBubbleCollapse/10",
1526
- "severity": "resolved_by_contract_scope",
1527
- "finding": "The off-axis gas region in the 5 degree wedge is evaluated under an explicit axisymmetric connected-region convention, not described as an ordinary second 3D sphere.",
1528
- "evidence": "compressibleBubbleCollapse__10/full_run_case/system/setFieldsDict and constant/polyMesh/boundary",
1529
- "action": "Retain the axisymmetric_ring_interaction branch unless a genuinely 3D two-bubble case is materialized.",
1530
- },
1531
- {
1532
- "type": "reference_coverage_gap",
1533
- "severity": "blocking",
1534
- "finding": "The 90-case main materialized run has no riemann2D directories. A separate riemann2d_parallel run exists, but it has not yet been merged into the unified reference audit and its diagnostics are not yet mapped to the profile/event contract.",
1535
- "evidence": "anonymous-reference/extended/riemann2D",
1536
- "action": "validate and import the ten separate Riemann runs into the unified current audit; do not synthesize profiles",
1537
- },
1538
- ]
1539
- if any(root.name == "materialized" and root.parent.name.startswith("riemann2d_parallel") for root in roots):
1540
- design_findings[-1]["severity"] = "resolved_for_current_audit"
1541
- design_findings[-1]["finding"] = "The separate ten-case Riemann run is included in this audit; profile and feature evidence is now extracted, while reference uncertainty remains a comparison-layer concern."
1542
- return {
1543
- "schema_version": "foambench.qoi_extraction_audit.v1",
1544
- "generated_at": utc_now(),
1545
- "run_roots": [str(root) for root in roots],
1546
- "case_count": len(cases),
1547
- "complete_case_count": complete,
1548
- "coverage_fraction": complete / len(cases) if cases else 0.0,
1549
- "missing_case_dirs": missing_case_dirs,
1550
- "structural_anomalies": anomalies,
1551
- "review_candidates": review,
1552
- "design_findings": design_findings,
1553
- "cases": cases,
1554
- }
1555
-
1556
-
1557
- def main() -> int:
1558
- parser = argparse.ArgumentParser(description=__doc__)
1559
- parser.add_argument("--run-root", type=Path, action="append", required=True, help="reference run root; repeat to merge independent materialized campaigns")
1560
- parser.add_argument("--design", type=Path, default=DEFAULT_DESIGN)
1561
- parser.add_argument("--output", type=Path, required=True)
1562
- args = parser.parse_args()
1563
- design = json.loads(args.design.read_text(encoding="utf-8"))
1564
- roots = [root.resolve(strict=True) for root in args.run_root]
1565
- report = extract_campaign(roots, design)
1566
- write_json(args.output.resolve(), report)
1567
- print(json.dumps({key: report[key] for key in ("case_count", "complete_case_count", "coverage_fraction", "missing_case_dirs", "structural_anomalies", "review_candidates")}, indent=2))
1568
- return 0
1569
-
1570
-
1571
- if __name__ == "__main__":
1572
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/field_candidate.py DELETED
@@ -1,23 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from .basic_advanced import extract
7
-
8
-
9
- def extract_field_candidate(
10
- case_dir: Path,
11
- case_id: str,
12
- requested_metrics: list[str],
13
- *,
14
- required_metrics: list[str] | None = None,
15
- log_paths: list[Path] | None = None,
16
- ) -> dict[str, Any]:
17
- return extract(
18
- case_dir,
19
- case_id,
20
- requested_metrics,
21
- required_metrics=required_metrics,
22
- log_paths=log_paths,
23
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/field_extractor.py DELETED
@@ -1,421 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Extract the numeric signatures used by the FoamBench v13 QoI contracts.
3
-
4
- The definitions in this module intentionally preserve the extractor that
5
- produced the checked-in reference JSON files. Candidate runs must use this
6
- same implementation so reference and candidate values have identical field,
7
- ordering, and proxy definitions.
8
- """
9
- from __future__ import annotations
10
-
11
- import argparse
12
- import json
13
- import math
14
- import re
15
- import sys
16
- from datetime import datetime, timezone
17
- from pathlib import Path
18
- from typing import Any
19
-
20
- ROOT = Path(__file__).resolve().parents[2]
21
- if str(ROOT) not in sys.path:
22
- sys.path.insert(0, str(ROOT))
23
-
24
- from benchmarks.evaluation.foam_io import field_path, magnitude, read_text
25
-
26
-
27
- NUMBER_RE = re.compile(r"[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?")
28
- VECTOR_RE = re.compile(r"\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)")
29
- RESIDUAL_RE = re.compile(
30
- r"Solving for (?P<field>[^,]+), Initial residual = (?P<initial>[-+0-9.eE]+), "
31
- r"Final residual = (?P<final>[-+0-9.eE]+), No Iterations (?P<iterations>\d+)"
32
- )
33
- COURANT_RE = re.compile(r"Courant Number mean:\s*(?P<mean>[-+0-9.eE]+)\s+max:\s*(?P<max>[-+0-9.eE]+)")
34
- FATAL_RE = re.compile(
35
- r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))",
36
- re.I,
37
- )
38
-
39
- FAMILY_PROBLEM_TYPES = {
40
- "BernardCells": "buoyant_thermal_convection",
41
- "Cavity": "lid_driven_cavity",
42
- "Cylinder": "cylinder_wake",
43
- "counterFlowFlame2D": "counterflow_flame",
44
- "damBreakWithObstacle": "free_surface_vof",
45
- "forwardStep": "compressible_shock",
46
- "obliqueShock": "compressible_shock",
47
- "pitzDaily": "separated_internal_flow",
48
- "shallowWaterWithSquareBump": "shallow_water_bump",
49
- "squareBend": "compressible_bend",
50
- "wedge": "compressible_shock",
51
- }
52
- FAMILY_ALIASES = {name.lower(): name for name in FAMILY_PROBLEM_TYPES}
53
-
54
-
55
- class ExtractionError(RuntimeError):
56
- """Raised when a field exists but cannot be interpreted safely."""
57
-
58
-
59
- def utc_now() -> str:
60
- return datetime.now(timezone.utc).isoformat()
61
-
62
-
63
- def write_json(path: Path, data: Any) -> None:
64
- path.parent.mkdir(parents=True, exist_ok=True)
65
- temporary = path.with_name(path.name + ".tmp")
66
- temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
67
- temporary.replace(path)
68
-
69
-
70
- def strip_comments(text: str) -> str:
71
- return re.sub(r"//.*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S))
72
-
73
-
74
- def foam_entry(text: str, key: str) -> str | None:
75
- match = re.search(rf"^\s*{re.escape(key)}\s+([^;\s]+)\s*;", strip_comments(text), re.M)
76
- return match.group(1) if match else None
77
-
78
-
79
- def latest_time_dir(case_dir: Path) -> tuple[float | None, Path | None]:
80
- choices: list[tuple[float, Path]] = []
81
- if not case_dir.is_dir():
82
- return None, None
83
- for child in case_dir.iterdir():
84
- if not child.is_dir():
85
- continue
86
- try:
87
- choices.append((float(child.name), child))
88
- except ValueError:
89
- continue
90
- return max(choices, key=lambda item: item[0]) if choices else (None, None)
91
-
92
-
93
- def clean_internal_field_text(text: str) -> str:
94
- marker = text.find("internalField")
95
- if marker < 0:
96
- return ""
97
- text = text[marker:]
98
- boundary = text.find("boundaryField")
99
- return text[:boundary] if boundary >= 0 else text
100
-
101
-
102
- def ensure_ascii_field(path: Path, text: str) -> None:
103
- header = text[: min(len(text), 4096)]
104
- if re.search(r"\bformat\s+binary\s*;", header):
105
- raise ExtractionError(
106
- f"binary OpenFOAM field is not supported directly: {path}; "
107
- "convert the latest time to ASCII with foamFormatConvert before evaluation"
108
- )
109
-
110
-
111
- def parse_scalar_field(path: Path) -> list[float]:
112
- raw = read_text(path)
113
- ensure_ascii_field(path, raw)
114
- text = clean_internal_field_text(raw)
115
- if not text:
116
- return []
117
- uniform = re.search(r"internalField\s+uniform\s+([-+0-9.eE]+)", text)
118
- if uniform:
119
- return [float(uniform.group(1))]
120
- start, end = text.find("("), text.rfind(")")
121
- body = text[start + 1 : end] if start >= 0 and end > start else text
122
- return [float(token) for token in NUMBER_RE.findall(body)]
123
-
124
-
125
- def parse_vector_field(path: Path) -> list[tuple[float, float, float]]:
126
- raw = read_text(path)
127
- ensure_ascii_field(path, raw)
128
- text = clean_internal_field_text(raw)
129
- if not text:
130
- return []
131
- uniform = re.search(
132
- r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)", text
133
- )
134
- if uniform:
135
- return [(float(uniform.group(1)), float(uniform.group(2)), float(uniform.group(3)))]
136
- return [(float(m.group(1)), float(m.group(2)), float(m.group(3))) for m in VECTOR_RE.finditer(text)]
137
-
138
-
139
- def scalar(latest: Path | None, name: str) -> list[float]:
140
- path = field_path(latest, name)
141
- return parse_scalar_field(path) if path else []
142
-
143
-
144
- def vector(latest: Path | None, name: str) -> list[tuple[float, float, float]]:
145
- path = field_path(latest, name)
146
- return parse_vector_field(path) if path else []
147
-
148
-
149
- def finite_values(values: list[float]) -> list[float]:
150
- return [value for value in values if math.isfinite(value)]
151
-
152
-
153
- def stats(values: list[float]) -> dict[str, float]:
154
- values = finite_values(values)
155
- if not values:
156
- return {}
157
- low, high = min(values), max(values)
158
- return {"min": low, "max": high, "mean": sum(values) / len(values), "range": high - low}
159
-
160
-
161
- def add_stats(qois: dict[str, float], prefix: str, values: list[float]) -> None:
162
- qois.update({f"{prefix}_{suffix}": value for suffix, value in stats(values).items()})
163
-
164
-
165
- def add_common_field_qois(qois: dict[str, float], latest: Path | None) -> None:
166
- velocities = vector(latest, "U")
167
- if velocities:
168
- add_stats(qois, "velocity_magnitude", magnitude(velocities))
169
- x, y, z = velocities[len(velocities) // 2]
170
- qois.update({"center_u": x, "center_v": y, "center_w": z, "center_speed": math.sqrt(x*x + y*y + z*z)})
171
- for name in ("p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", "nuTilda"):
172
- values = scalar(latest, name)
173
- if values:
174
- add_stats(qois, name.replace(".", "_"), values)
175
- vorticity = vector(latest, "vorticity")
176
- if vorticity:
177
- add_stats(qois, "vorticity_magnitude", magnitude(vorticity))
178
-
179
-
180
- def add_compressible_qois(qois: dict[str, float], latest: Path | None) -> None:
181
- temperatures = scalar(latest, "T")
182
- speeds = magnitude(vector(latest, "U"))
183
- if temperatures and speeds:
184
- mach = [
185
- speed / math.sqrt(1.4 * 0.7143 * temperature)
186
- for speed, temperature in zip(speeds, temperatures)
187
- if temperature > 0
188
- ]
189
- add_stats(qois, "mach", mach)
190
- pressures = scalar(latest, "p")
191
- if pressures:
192
- summary = stats(pressures)
193
- mean, low, high = summary.get("mean"), summary.get("min"), summary.get("max")
194
- if mean is not None and low is not None and high is not None and abs(mean) > 1e-12:
195
- qois["pressure_ratio_max_over_mean"] = high / mean
196
- qois["pressure_ratio_max_over_min"] = high / max(abs(low), 1e-12)
197
- if len(pressures) > 1:
198
- qois["shock_strength_proxy_max_dp_index"] = max(abs(b - a) for a, b in zip(pressures, pressures[1:]))
199
-
200
-
201
- def add_flame_qois(qois: dict[str, float], latest: Path | None) -> None:
202
- qdot = scalar(latest, "Qdot")
203
- if qdot:
204
- add_stats(qois, "Qdot", qdot)
205
- qois["integrated_Qdot_proxy"] = sum(finite_values(qdot))
206
- for species in ("CH4", "O2", "CO2", "H2O", "N2", "Ydefault"):
207
- values = scalar(latest, species)
208
- if values:
209
- add_stats(qois, species, values)
210
-
211
-
212
- def add_vof_qois(qois: dict[str, float], latest: Path | None) -> None:
213
- alpha = scalar(latest, "alpha.water")
214
- if not alpha:
215
- return
216
- clipped = [min(1.0, max(0.0, value)) for value in alpha if math.isfinite(value)]
217
- add_stats(qois, "alpha_water", clipped)
218
- if clipped:
219
- qois["alpha_water_volume_proxy"] = sum(clipped)
220
- qois["alpha_water_wet_fraction"] = sum(value > 0.5 for value in clipped) / len(clipped)
221
- last_wet = max((index for index, value in enumerate(clipped) if value > 0.5), default=0)
222
- qois["alpha_water_front_index_fraction"] = last_wet / max(len(clipped) - 1, 1)
223
-
224
-
225
- def add_shallow_water_qois(qois: dict[str, float], latest: Path | None) -> None:
226
- heights, total_heights, fluxes = scalar(latest, "h"), scalar(latest, "hTotal"), vector(latest, "hU")
227
- if heights:
228
- add_stats(qois, "h", heights)
229
- if total_heights:
230
- add_stats(qois, "hTotal", total_heights)
231
- velocities: list[float] = []
232
- froude: list[float] = []
233
- for height, flux in zip(heights, fluxes):
234
- if abs(height) <= 1e-12:
235
- continue
236
- speed = math.sqrt(sum(component * component for component in flux)) / abs(height)
237
- velocities.append(speed)
238
- if height > 0:
239
- froude.append(speed / math.sqrt(9.81 * height))
240
- add_stats(qois, "shallow_velocity", velocities)
241
- add_stats(qois, "froude", froude)
242
-
243
-
244
- def infer_family(case_id: str) -> str:
245
- first = case_id.split("/", 1)[0]
246
- return FAMILY_ALIASES.get(first.lower(), first)
247
-
248
-
249
- def infer_problem_type(family: str, latest: Path | None) -> str:
250
- if family in FAMILY_PROBLEM_TYPES:
251
- return FAMILY_PROBLEM_TYPES[family]
252
- names = {path.name.removesuffix(".gz") for path in latest.iterdir() if path.is_file()} if latest else set()
253
- if "alpha.water" in names:
254
- return "free_surface_vof"
255
- if {"h", "hU"} & names:
256
- return "shallow_water_bump"
257
- if "Qdot" in names or {"CH4", "O2"} & names:
258
- return "counterflow_flame"
259
- if {"p", "T", "U"} <= names:
260
- return "compressible_flow"
261
- return "generic_cfd"
262
-
263
-
264
- def parse_log_metrics(case_dir: Path, log_paths: list[Path] | None = None) -> tuple[dict[str, float], list[str]]:
265
- """Extract residual/Courant metrics from case logs and optional run logs.
266
-
267
- FoamAgent writes solver output into ``case/log.*``. EasyFoam keeps the
268
- same output under ``workspace/runs/formal-*/`` and records the paths in
269
- ``run_record.json``. ``log_paths`` lets an offline evaluator consume that
270
- evidence without copying or modifying the generated case.
271
- """
272
- candidates = sorted(
273
- {path for pattern in ("log.foamRun*", "log.*") for path in case_dir.glob(pattern) if path.is_file()},
274
- key=lambda path: (path.name != "log.foamRun", path.name),
275
- )
276
- if log_paths:
277
- candidates.extend(path for path in log_paths if path.is_file() and path not in candidates)
278
- texts = [(path, read_text(path)) for path in candidates]
279
- residuals: list[float] = []
280
- courants: list[float] = []
281
- fatal_logs: list[str] = []
282
- for path, text in texts:
283
- if FATAL_RE.search(text):
284
- fatal_logs.append(path.name)
285
- residuals.extend(float(match.group("final")) for match in RESIDUAL_RE.finditer(text))
286
- courants.extend(float(match.group("max")) for match in COURANT_RE.finditer(text))
287
- qois: dict[str, float] = {}
288
- if residuals:
289
- qois.update({"max_final_residual": max(residuals), "last_final_residual": residuals[-1]})
290
- if courants:
291
- qois.update({"max_courant": max(courants), "last_courant": courants[-1]})
292
- return qois, fatal_logs
293
-
294
-
295
- def required_metrics(reference_path: Path | None, case_id: str) -> tuple[list[str] | None, dict[str, Any] | None]:
296
- if reference_path is None:
297
- return None, None
298
- data = json.loads(reference_path.read_text(encoding="utf-8"))
299
- cases = data.get("cases") if isinstance(data, dict) else None
300
- if not isinstance(cases, dict) or not isinstance(cases.get(case_id), dict):
301
- raise ValueError(f"case {case_id!r} is absent from reference contract {reference_path}")
302
- record = cases[case_id]
303
- qois = record.get("qois")
304
- if not isinstance(qois, dict):
305
- raise ValueError(f"case {case_id!r} has no qois object in {reference_path}")
306
- return sorted(qois), record
307
-
308
-
309
- def extract_case_qois(
310
- case_dir: Path,
311
- case_id: str,
312
- reference_path: Path | None = None,
313
- log_paths: list[Path] | None = None,
314
- ) -> dict[str, Any]:
315
- case_dir = case_dir.resolve(strict=True)
316
- latest_time, latest = latest_time_dir(case_dir)
317
- family = infer_family(case_id)
318
- problem_type = infer_problem_type(family, latest)
319
- required, reference = required_metrics(reference_path, case_id)
320
- if reference and isinstance(reference.get("problem_type"), str):
321
- problem_type = reference["problem_type"]
322
-
323
- qois, fatal_logs = parse_log_metrics(case_dir, log_paths=log_paths)
324
- add_common_field_qois(qois, latest)
325
- if problem_type in {"compressible_shock", "compressible_flow", "compressible_bend"}:
326
- add_compressible_qois(qois, latest)
327
- if problem_type == "counterflow_flame":
328
- add_flame_qois(qois, latest)
329
- if problem_type == "free_surface_vof":
330
- add_vof_qois(qois, latest)
331
- if problem_type == "shallow_water_bump":
332
- add_shallow_water_qois(qois, latest)
333
- qois = {name: value for name, value in sorted(qois.items()) if math.isfinite(float(value))}
334
- missing = sorted(set(required or []) - set(qois))
335
- unexpected = sorted(set(qois) - set(required or [])) if required is not None else []
336
- control = read_text(case_dir / "system" / "controlDict")
337
- return {
338
- "schema_version": "foambench.qoi.candidate.v1",
339
- "generated_at": utc_now(),
340
- "producer": "benchmarks/evaluation/qoi_reference.py",
341
- "case_id": case_id,
342
- "family": family,
343
- "problem_type": problem_type,
344
- "application": foam_entry(control, "application"),
345
- "solver": foam_entry(control, "solver"),
346
- "latest_time": latest_time,
347
- "qois": qois,
348
- "coverage": {
349
- "required_count": len(required) if required is not None else None,
350
- "extracted_required_count": len(required) - len(missing) if required is not None else None,
351
- "fraction": (len(required) - len(missing)) / len(required) if required else None,
352
- "missing_metrics": missing,
353
- "unexpected_metrics": unexpected,
354
- },
355
- "fatal_logs": fatal_logs,
356
- "status": "complete" if latest and not missing and not fatal_logs else "incomplete",
357
- }
358
-
359
-
360
- def find_case_dirs(root: Path) -> list[Path]:
361
- return sorted({control.parents[1] for control in root.rglob("system/controlDict")})
362
-
363
-
364
- def infer_case_id(case_dir: Path, root: Path) -> str:
365
- relative = case_dir.resolve().relative_to(root.resolve())
366
- parts = list(relative.parts)
367
- if parts and parts[-1] in {"case", "workspace"}:
368
- parts.pop()
369
- if len(parts) >= 2 and parts[-1].startswith("replicate_"):
370
- parts.pop()
371
- return "/".join(parts[-2:]) if len(parts) >= 2 else (parts[0] if parts else case_dir.name)
372
-
373
-
374
- def main() -> int:
375
- parser = argparse.ArgumentParser(description=__doc__)
376
- parser.add_argument("--case", type=Path, action="append", default=[])
377
- parser.add_argument("--case-id", action="append", default=[])
378
- parser.add_argument("--root", type=Path)
379
- parser.add_argument("--reference-qois", type=Path)
380
- parser.add_argument("--output", type=Path)
381
- parser.add_argument("--require-complete", action="store_true")
382
- parser.add_argument("--json", action="store_true")
383
- args = parser.parse_args()
384
-
385
- explicit_cases = [path.resolve(strict=True) for path in args.case]
386
- if args.case_id and len(args.case_id) != len(explicit_cases):
387
- parser.error("--case-id count must match --case count")
388
- selected = [(path, args.case_id[index]) for index, path in enumerate(explicit_cases)]
389
- if args.root:
390
- root = args.root.resolve(strict=True)
391
- selected.extend((path, infer_case_id(path, root)) for path in find_case_dirs(root) if path not in explicit_cases)
392
- if not selected:
393
- parser.error("provide --case or --root")
394
-
395
- records: dict[str, Any] = {}
396
- for case_dir, case_id in selected:
397
- records[case_id] = extract_case_qois(case_dir, case_id, args.reference_qois)
398
- incomplete = sorted(case_id for case_id, record in records.items() if record["status"] != "complete")
399
- report = {
400
- "schema_version": "foambench.qoi.candidates.v1",
401
- "generated_at": utc_now(),
402
- "case_count": len(records),
403
- "complete_count": len(records) - len(incomplete),
404
- "incomplete_cases": incomplete,
405
- "cases": records,
406
- }
407
- if args.output:
408
- write_json(args.output.resolve(), report)
409
- if args.json or not args.output:
410
- print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
411
- else:
412
- print(f"qoi_report: {args.output.resolve()} ({report['complete_count']}/{len(records)} complete)")
413
- return 1 if args.require_complete and incomplete else 0
414
-
415
-
416
- if __name__ == "__main__":
417
- try:
418
- raise SystemExit(main())
419
- except (OSError, ValueError, ExtractionError, json.JSONDecodeError) as exc:
420
- print(f"extract_foambench_qois.py: error: {exc}", file=sys.stderr)
421
- raise SystemExit(2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/foam.py DELETED
@@ -1,84 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- from pathlib import Path
5
-
6
- from .foam_io import read_text
7
-
8
- NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
9
- TIME_RE = re.compile(rf"(?m)^\s*Time\s*=\s*({NUMBER})\s*s?\s*$")
10
- FATAL_RE = re.compile(
11
- r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))",
12
- re.I,
13
- )
14
- NONFINITE_RE = re.compile(r"(?<![A-Za-z])[-+]?(?:nan|inf(?:inity)?)(?![A-Za-z])", re.I)
15
-
16
-
17
- def final_time_dirs(case_dir: Path | None) -> tuple[float | None, list[Path], str]:
18
- if case_dir is None or not case_dir.is_dir():
19
- return None, [], "missing"
20
- values: list[tuple[float, Path]] = []
21
- for path in case_dir.iterdir():
22
- if not path.is_dir():
23
- continue
24
- try:
25
- value = float(path.name)
26
- except ValueError:
27
- continue
28
- if value > 0:
29
- values.append((value, path))
30
- if values:
31
- latest = max(value for value, _ in values)
32
- return latest, [path for value, path in values if value == latest], "reconstructed"
33
- processors = sorted(
34
- (path for path in case_dir.iterdir() if path.is_dir() and re.fullmatch(r"processor\d+", path.name)),
35
- key=lambda path: int(path.name[9:]),
36
- )
37
- processor_times = []
38
- for processor in processors:
39
- found = []
40
- for path in processor.iterdir():
41
- if not path.is_dir():
42
- continue
43
- try:
44
- value = float(path.name)
45
- except ValueError:
46
- continue
47
- if value > 0:
48
- found.append((value, path))
49
- processor_times.append(sorted(found))
50
- if processors and all(processor_times):
51
- common = set(value for value, _ in processor_times[0])
52
- for values in processor_times[1:]:
53
- common.intersection_update(value for value, _ in values)
54
- if not common:
55
- return None, [], "missing"
56
- latest = max(common)
57
- selected = [
58
- next(path for value, path in values if value == latest)
59
- for values in processor_times
60
- ]
61
- return latest, selected, "decomposed"
62
- return None, [], "missing"
63
-
64
-
65
- def latest_time_dir(case_dir: Path | None) -> tuple[float | None, Path | None]:
66
- latest, directories, _ = final_time_dirs(case_dir)
67
- return latest, directories[0] if directories else None
68
-
69
-
70
- def read_logs(paths: tuple[Path, ...] | list[Path]) -> str:
71
- return "\n".join(read_text(path) for path in paths if path.is_file())
72
-
73
-
74
- def normal_end(log_text: str) -> bool:
75
- return re.search(r"(?m)^\s*End\s*$", log_text) is not None
76
-
77
-
78
- def converged_early(log_text: str) -> bool:
79
- return re.search(r"solution converged|convergence criterion satisfied", log_text, re.I) is not None
80
-
81
-
82
- def final_log_time(log_text: str) -> float | None:
83
- values = [float(match.group(1)) for match in TIME_RE.finditer(log_text)]
84
- return values[-1] if values else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/foam_arrays.py DELETED
@@ -1,129 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Read complete OpenFOAM primitive arrays for v3 scientific QoIs."""
3
- from __future__ import annotations
4
-
5
- import gzip
6
- import re
7
- import struct
8
- from pathlib import Path
9
- from typing import Literal
10
-
11
-
12
- NUMBER = rb"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?"
13
-
14
-
15
- class FoamArrayError(RuntimeError):
16
- """Raised when a primitive array cannot be decoded unambiguously."""
17
-
18
-
19
- def _bytes(path: Path) -> bytes:
20
- return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
21
-
22
-
23
- def _header(data: bytes) -> bytes:
24
- end = data.find(b"// * * *")
25
- return data[: end if end >= 0 else min(len(data), 4096)]
26
-
27
-
28
- def _format(data: bytes) -> Literal["ascii", "binary"]:
29
- match = re.search(rb"\bformat\s+(ascii|binary)\s*;", _header(data))
30
- if not match:
31
- raise FoamArrayError("OpenFOAM header has no format entry")
32
- return match.group(1).decode("ascii") # type: ignore[return-value]
33
-
34
-
35
- def _arch(data: bytes) -> tuple[str, int, int]:
36
- match = re.search(rb'\barch\s+"([^\"]+)"\s*;', _header(data))
37
- arch = match.group(1).decode("ascii") if match else "LSB;label=32;scalar=64"
38
- endian = ">" if arch.startswith("MSB") else "<"
39
- label = int(re.search(r"label=(32|64)", arch).group(1)) if "label=" in arch else 32
40
- scalar = int(re.search(r"scalar=(32|64)", arch).group(1)) if "scalar=" in arch else 64
41
- return endian, label, scalar
42
-
43
-
44
- def _list_payload(data: bytes, marker: bytes | None = None) -> tuple[int, bytes]:
45
- if marker is None:
46
- header_end = data.find(b"// * * *")
47
- search = data[header_end if header_end >= 0 else 0 :]
48
- match = re.search(rb"\b(\d+)\s*\(", search)
49
- offset = (header_end if header_end >= 0 else 0) + (match.end() if match else 0)
50
- else:
51
- match = re.search(marker + rb"\s+(\d+)\s*\(", data)
52
- offset = match.end() if match else 0
53
- if not match:
54
- raise FoamArrayError("OpenFOAM nonuniform list header was not found")
55
- while offset < len(data) and data[offset : offset + 1] in (b"\n", b"\r"):
56
- offset += 1
57
- return int(match.group(1)), data[offset:]
58
-
59
-
60
- def _ascii_body(payload: bytes) -> bytes:
61
- end = payload.rfind(b")")
62
- return payload[:end] if end >= 0 else payload
63
-
64
-
65
- def read_scalar_field(path: Path) -> list[float]:
66
- data = _bytes(path)
67
- uniform = re.search(rb"internalField\s+uniform\s+(" + NUMBER + rb")", data)
68
- if uniform:
69
- return [float(uniform.group(1))]
70
- count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List<scalar>")
71
- if _format(data) == "ascii":
72
- values = [float(token) for token in re.findall(NUMBER, _ascii_body(payload))[:count]]
73
- else:
74
- endian, _, scalar_bits = _arch(data)
75
- code = "f" if scalar_bits == 32 else "d"
76
- size = scalar_bits // 8
77
- values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size]))
78
- if len(values) != count:
79
- raise FoamArrayError(f"{path}: declared {count} scalars but decoded {len(values)}")
80
- return values
81
-
82
-
83
- def read_vector_field(path: Path) -> list[tuple[float, float, float]]:
84
- data = _bytes(path)
85
- count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List<vector>")
86
- return _decode_vectors(path, data, count, payload)
87
-
88
-
89
- def read_vector_list(path: Path) -> list[tuple[float, float, float]]:
90
- data = _bytes(path)
91
- count, payload = _list_payload(data)
92
- return _decode_vectors(path, data, count, payload)
93
-
94
-
95
- def _decode_vectors(path: Path, data: bytes, count: int, payload: bytes) -> list[tuple[float, float, float]]:
96
- if _format(data) == "ascii":
97
- rows = re.findall(rb"\(\s*(" + NUMBER + rb")\s+(" + NUMBER + rb")\s+(" + NUMBER + rb")\s*\)", _ascii_body(payload))
98
- values = [(float(x), float(y), float(z)) for x, y, z in rows[:count]]
99
- else:
100
- endian, _, scalar_bits = _arch(data)
101
- code = "f" if scalar_bits == 32 else "d"
102
- size = scalar_bits // 8
103
- flat = struct.unpack(f"{endian}{count * 3}{code}", payload[: count * 3 * size])
104
- values = list(zip(flat[0::3], flat[1::3], flat[2::3]))
105
- if len(values) != count:
106
- raise FoamArrayError(f"{path}: declared {count} vectors but decoded {len(values)}")
107
- return values
108
-
109
-
110
- def read_label_list(path: Path) -> list[int]:
111
- data = _bytes(path)
112
- count, payload = _list_payload(data)
113
- if _format(data) == "ascii":
114
- values = [int(token) for token in re.findall(rb"[-+]?\d+", _ascii_body(payload))[:count]]
115
- else:
116
- endian, label_bits, _ = _arch(data)
117
- code = "i" if label_bits == 32 else "q"
118
- size = label_bits // 8
119
- values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size]))
120
- if len(values) != count:
121
- raise FoamArrayError(f"{path}: declared {count} labels but decoded {len(values)}")
122
- return values
123
-
124
-
125
- def foam_path(directory: Path, name: str) -> Path | None:
126
- for candidate in (directory / name, directory / f"{name}.gz"):
127
- if candidate.is_file():
128
- return candidate
129
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/foam_field.py DELETED
@@ -1,155 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import gzip
4
- import math
5
- import mmap
6
- import re
7
- import struct
8
- from pathlib import Path
9
- from typing import Any, Iterable
10
-
11
- NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
12
- NONFINITE_RE = re.compile(r"(?<![A-Za-z])[-+]?(?:nan|inf(?:inity)?)(?![A-Za-z])", re.I)
13
- FIELD_CLASS_RE = re.compile(
14
- r"\bclass\s+(?P<class>(?:vol|surface|point)(?:Scalar|Vector|SphericalTensor|SymmTensor|Tensor)Field)\s*;"
15
- )
16
- FORMAT_RE = re.compile(r"\bformat\s+(?P<format>ascii|binary)\s*;")
17
- OBJECT_RE = re.compile(r"\bobject\s+(?P<object>[^;\s]+)\s*;")
18
- LIST_RE = re.compile(
19
- rb"nonuniform\s+(?:List<)?(?P<type>scalar|vector|sphericalTensor|symmTensor|tensor|label)>?"
20
- rb"\s+(?P<count>\d+)\s*\("
21
- )
22
- COMPONENTS = {"scalar": 1, "vector": 3, "sphericalTensor": 1, "symmTensor": 6, "tensor": 9, "label": 1}
23
-
24
-
25
- def _stats(values: Iterable[float]) -> dict[str, Any]:
26
- low, high, count, nonfinite = math.inf, -math.inf, 0, 0
27
- for value in values:
28
- count += 1
29
- if math.isfinite(value):
30
- low, high = min(low, value), max(high, value)
31
- else:
32
- nonfinite += 1
33
- return {
34
- "count": count,
35
- "finite": nonfinite == 0,
36
- "nonfinite_count": nonfinite,
37
- "min": None if low == math.inf else low,
38
- "max": None if high == -math.inf else high,
39
- }
40
-
41
-
42
- def _binary_list_stats(
43
- data: bytes | mmap.mmap,
44
- match: re.Match[bytes],
45
- width: int,
46
- byte_order: str,
47
- ) -> dict[str, Any]:
48
- kind = match.group("type").decode("ascii")
49
- count = int(match.group("count"))
50
- item_count = count * COMPONENTS[kind]
51
- start, end = match.end(), match.end() + item_count * width
52
- if end > len(data) or not bytes(data[end : min(len(data), end + 16)]).lstrip().startswith(b")"):
53
- raise ValueError("binary field list does not match its declaration")
54
- unpacked = struct.iter_unpack(byte_order + ("d" if width == 8 else "f"), memoryview(data)[start:end])
55
- result = _stats(item[0] for item in unpacked)
56
- result.update({"value_type": kind, "element_count": count, "components": COMPONENTS[kind]})
57
- return result
58
-
59
-
60
- def _binary_internal_data(
61
- data: bytes | mmap.mmap,
62
- header: str,
63
- ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
64
- width_match = re.search(r"scalar=(32|64)", header)
65
- preferred = int(width_match.group(1)) // 8 if width_match else 8
66
- byte_order = ">" if "MSB" in header else "<"
67
- records = []
68
- for match in LIST_RE.finditer(data):
69
- for width in (preferred, 4 if preferred == 8 else 8):
70
- try:
71
- record = _binary_list_stats(data, match, width, byte_order)
72
- record["offset"] = match.start()
73
- records.append(record)
74
- break
75
- except ValueError:
76
- continue
77
- internal_marker, boundary_marker = data.find(b"internalField"), data.find(b"boundaryField")
78
- internal = next(
79
- (record for record in records if record["offset"] > internal_marker and (boundary_marker < 0 or record["offset"] < boundary_marker)),
80
- None,
81
- )
82
- if internal is None and internal_marker >= 0:
83
- stop = boundary_marker if boundary_marker > internal_marker else min(len(data), internal_marker + 1024)
84
- section = bytes(data[internal_marker:stop]).decode("ascii", errors="ignore")
85
- uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section)
86
- if uniform:
87
- internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1)))
88
- return records, internal
89
-
90
-
91
- def _binary_internal(path: Path, header: str) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
92
- if path.suffix == ".gz":
93
- with gzip.open(path, "rb") as stream:
94
- return _binary_internal_data(stream.read(), header)
95
- with path.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data:
96
- return _binary_internal_data(data, header)
97
-
98
-
99
- def _ascii_internal(raw: bytes) -> tuple[list[dict[str, Any]], dict[str, Any] | None, bool]:
100
- text = raw.decode("utf-8", errors="replace")
101
- marker = text.find("internalField")
102
- boundary = text.find("boundaryField", marker + 1) if marker >= 0 else -1
103
- section = text[marker : boundary if boundary >= 0 else len(text)] if marker >= 0 else ""
104
- uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section)
105
- if uniform:
106
- internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1)))
107
- return [internal], internal, NONFINITE_RE.search(section) is not None
108
- listed = re.search(
109
- rf"internalField\s+nonuniform\s+(?:List<)?(?P<type>scalar|vector|sphericalTensor|symmTensor|tensor)>?"
110
- rf"\s+(?P<count>\d+)\s*\((?P<body>.*?)\)\s*;",
111
- section,
112
- re.S,
113
- )
114
- if not listed:
115
- return [], None, NONFINITE_RE.search(section) is not None
116
- values = [float(token) for token in re.findall(NUMBER, listed.group("body"))]
117
- internal = _stats(values)
118
- kind, count = listed.group("type"), int(listed.group("count"))
119
- internal["count_matches_declaration"] = len(values) == count * COMPONENTS[kind]
120
- return [internal], internal, NONFINITE_RE.search(section) is not None
121
-
122
-
123
- def scan_field(path: Path, base: Path | None = None) -> dict[str, Any]:
124
- base = base or path.parent
125
- try:
126
- if path.suffix == ".gz":
127
- with gzip.open(path, "rb") as stream:
128
- header_bytes = stream.read(4096)
129
- else:
130
- header_bytes = path.read_bytes()[:4096]
131
- header = header_bytes.decode("ascii", errors="ignore")
132
- field_class, field_format = FIELD_CLASS_RE.search(header), FORMAT_RE.search(header)
133
- if not field_class or not field_format:
134
- return {"status": "skip", "reason": "not_a_supported_field", "parse_ok": False}
135
- if field_format.group("format") == "binary":
136
- records, internal = _binary_internal(path, header)
137
- nonfinite = any(not record["finite"] for record in records)
138
- else:
139
- raw = gzip.open(path, "rb").read() if path.suffix == ".gz" else path.read_bytes()
140
- records, internal, marker = _ascii_internal(raw)
141
- nonfinite = marker or any(not record["finite"] for record in records)
142
- parse_ok = internal is not None and all(record.get("count_matches_declaration", True) for record in records)
143
- object_match = OBJECT_RE.search(header)
144
- return {
145
- "path": str(path.relative_to(base)) if path.is_relative_to(base) else str(path),
146
- "status": "pass" if parse_ok and not nonfinite else "fail",
147
- "class": field_class.group("class"),
148
- "format": field_format.group("format"),
149
- "field": object_match.group("object") if object_match else path.name.removesuffix(".gz"),
150
- "internal": internal,
151
- "finite": not nonfinite,
152
- "parse_ok": parse_ok,
153
- }
154
- except (OSError, ValueError, struct.error) as exc:
155
- return {"status": "fail", "finite": False, "parse_ok": False, "error": str(exc)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/foam_io.py DELETED
@@ -1,29 +0,0 @@
1
- """Small shared OpenFOAM file helpers used by evaluators and CLI extractors."""
2
- from __future__ import annotations
3
-
4
- import gzip
5
- import math
6
- from pathlib import Path
7
-
8
-
9
- def read_text(path: Path) -> str:
10
- try:
11
- if path.suffix == ".gz":
12
- with gzip.open(path, "rt", encoding="utf-8", errors="ignore") as stream:
13
- return stream.read()
14
- return path.read_text(encoding="utf-8", errors="replace")
15
- except OSError:
16
- return ""
17
-
18
-
19
- def field_path(time_dir: Path | None, name: str) -> Path | None:
20
- if time_dir is None:
21
- return None
22
- for candidate in (time_dir / name, time_dir / f"{name}.gz"):
23
- if candidate.is_file():
24
- return candidate
25
- return None
26
-
27
-
28
- def magnitude(values: list[tuple[float, float, float]]) -> list[float]:
29
- return [math.sqrt(x * x + y * y + z * z) for x, y, z in values]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/frozen_recovery.py DELETED
@@ -1,713 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Deterministic QoI recovery for already-finished Extended FoamBench runs.
3
-
4
- This module deliberately has no solver or OpenFOAM command dependency. It
5
- reads only the retained case files named by an existing campaign artifact and
6
- returns a new candidate document in memory. The command-line driver writes
7
- the audit products to a separate directory; neither the frozen run nor its
8
- original QoI document is modified.
9
- """
10
- from __future__ import annotations
11
-
12
- import copy
13
- import gzip
14
- import hashlib
15
- import json
16
- import math
17
- import re
18
- from dataclasses import dataclass, field
19
- from pathlib import Path
20
- from typing import Any, Iterable
21
-
22
- from .comparison import compare_case
23
- from .extbench import (
24
- extract_contract_case,
25
- evidence_path,
26
- field_dimensions,
27
- numeric_time_dirs,
28
- profile_event_locations,
29
- read_scalar_field_allow_uniform,
30
- read_vector_field_allow_uniform,
31
- structured_qoi_errors,
32
- )
33
- from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_list
34
-
35
-
36
- RECOVERY_VERSION = "foambench.frozen_qoi_recovery.v1"
37
-
38
-
39
- @dataclass
40
- class RecoveryEvidence:
41
- """Values and audit information produced by one recovery branch."""
42
-
43
- values: dict[str, Any] = field(default_factory=dict)
44
- evidence: dict[str, list[str]] = field(default_factory=dict)
45
- methods: dict[str, str] = field(default_factory=dict)
46
- source_times: list[float] = field(default_factory=list)
47
- preflight: dict[str, Any] = field(default_factory=dict)
48
- reasons: list[str] = field(default_factory=list)
49
-
50
-
51
- def sha256_file(path: Path) -> str:
52
- digest = hashlib.sha256()
53
- with path.open("rb") as stream:
54
- for block in iter(lambda: stream.read(1024 * 1024), b""):
55
- digest.update(block)
56
- return digest.hexdigest()
57
-
58
-
59
- def _raw_bytes(path: Path) -> bytes:
60
- return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
61
-
62
-
63
- def _text(path: Path) -> str:
64
- return _raw_bytes(path).decode("utf-8", errors="ignore")
65
-
66
-
67
- def _named_block(text: str, name: str, start: int = 0) -> str | None:
68
- match = re.search(r"(?m)^\s*" + re.escape(name) + r"\s*\{", text[start:])
69
- if match is None:
70
- return None
71
- left = start + match.end()
72
- depth, index = 1, left
73
- while index < len(text) and depth:
74
- char = text[index]
75
- if char == "{":
76
- depth += 1
77
- elif char == "}":
78
- depth -= 1
79
- index += 1
80
- return text[left : index - 1] if depth == 0 else None
81
-
82
-
83
- def _boundary_block(case: Path, patch: str) -> str | None:
84
- path = foam_path(case / "constant/polyMesh", "boundary")
85
- if path is None:
86
- return None
87
- text = _text(path)
88
- anchor = text.find("object boundary")
89
- return _named_block(text, patch, max(anchor, 0))
90
-
91
-
92
- def _boundary_specs(case: Path) -> dict[str, dict[str, Any]]:
93
- path = foam_path(case / "constant/polyMesh", "boundary")
94
- if path is None:
95
- return {}
96
- text = _text(path)
97
- anchor = max(text.find("object boundary"), 0)
98
- result: dict[str, dict[str, Any]] = {}
99
- names = re.finditer(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\{", text[anchor:])
100
- for match in names:
101
- name = match.group(1)
102
- block = _named_block(text, name, anchor + match.start())
103
- if block is None:
104
- continue
105
- start_match = re.search(r"\bstartFace\s+([0-9]+)\s*;", block)
106
- count_match = re.search(r"\bnFaces\s+([0-9]+)\s*;", block)
107
- if start_match and count_match:
108
- result[name] = {
109
- "start_face": int(start_match.group(1)),
110
- "n_faces": int(count_match.group(1)),
111
- "type": (re.search(r"\btype\s+([^;\s]+)\s*;", block) or [None, ""])[1],
112
- }
113
- return result
114
-
115
-
116
- def _face_list(case: Path) -> list[list[int]]:
117
- path = foam_path(case / "constant/polyMesh", "faces")
118
- if path is None:
119
- return []
120
- text = _text(path)
121
- marker = re.search(r"\bobject\s+faces\s*;.*?\n\s*[0-9]+\s*\(\s*\n", text, re.S)
122
- if marker is None:
123
- return []
124
- body = text[marker.end() :]
125
- return [
126
- [int(value) for value in match.group(1).split()]
127
- for match in re.finditer(r"[0-9]+\(\s*([0-9\s]+)\)", body)
128
- ]
129
-
130
-
131
- def _polygon_area(points: list[tuple[float, float, float]], indices: list[int]) -> float:
132
- if len(indices) < 3:
133
- return 0.0
134
- origin = points[indices[0]]
135
- area = 0.0
136
- for left, right in zip(indices[1:-1], indices[2:]):
137
- a = tuple(points[left][axis] - origin[axis] for axis in range(3))
138
- b = tuple(points[right][axis] - origin[axis] for axis in range(3))
139
- cross = (
140
- a[1] * b[2] - a[2] * b[1],
141
- a[2] * b[0] - a[0] * b[2],
142
- a[0] * b[1] - a[1] * b[0],
143
- )
144
- area += 0.5 * math.sqrt(sum(value * value for value in cross))
145
- return area
146
-
147
-
148
- def _patch_geometry(case: Path, patch: str) -> tuple[list[float], list[int]]:
149
- specs = _boundary_specs(case)
150
- spec = specs.get(patch)
151
- mesh = case / "constant/polyMesh"
152
- points_path = foam_path(mesh, "points")
153
- owner_path = foam_path(mesh, "owner")
154
- if spec is None or points_path is None or owner_path is None:
155
- return [], []
156
- faces = _face_list(case)
157
- points = read_vector_list(points_path)
158
- owners = read_label_list(owner_path)
159
- start, count = spec["start_face"], spec["n_faces"]
160
- if start + count > len(faces) or start + count > len(owners):
161
- return [], []
162
- areas = [_polygon_area(points, faces[index]) for index in range(start, start + count)]
163
- return areas, owners[start : start + count]
164
-
165
-
166
- def _scalar_boundary_values(path: Path, patch: str) -> list[float] | None:
167
- """Read one scalar patch's ``value`` entry without trusting field names."""
168
- text = _text(path)
169
- anchor = text.find("boundaryField")
170
- block = _named_block(text, patch, max(anchor, 0))
171
- if block is None:
172
- return None
173
- uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block)
174
- if uniform:
175
- spec = _boundary_specs(path.parents[2] if len(path.parents) > 2 else path.parent)
176
- count = spec.get(patch, {}).get("n_faces", 1)
177
- return [float(uniform.group(1))] * int(count or 1)
178
- listed = re.search(
179
- r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;",
180
- block,
181
- re.S,
182
- )
183
- if listed is None:
184
- return None
185
- count = int(listed.group(1))
186
- values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))]
187
- return values[:count] if len(values) >= count else None
188
-
189
-
190
- def _field_boundary_scalar(path: Path, patch: str, face_count: int) -> list[float] | None:
191
- """Boundary scalar reader with an explicit face count from the mesh."""
192
- text = _text(path)
193
- anchor = text.find("boundaryField")
194
- block = _named_block(text, patch, max(anchor, 0))
195
- if block is None:
196
- return None
197
- uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block)
198
- if uniform:
199
- return [float(uniform.group(1))] * face_count
200
- listed = re.search(
201
- r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;",
202
- block,
203
- re.S,
204
- )
205
- if listed is None:
206
- return None
207
- count = int(listed.group(1))
208
- values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))]
209
- return values[:count] if len(values) >= count else None
210
-
211
-
212
- def _patch_sum_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]:
213
- specs = _boundary_specs(case)
214
- face_count = int(specs.get(patch, {}).get("n_faces", 0))
215
- if face_count <= 0:
216
- return [], [], [], "patch is absent from boundary contract"
217
- target_values = sorted({float(value) for value in targets})
218
- dirs = numeric_time_dirs(case)
219
- points: list[dict[str, float]] = []
220
- evidence: list[str] = []
221
- source_times: list[float] = []
222
- for target in target_values:
223
- nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None)
224
- if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)):
225
- continue
226
- actual_time, directory = nearest
227
- path = foam_path(directory, field)
228
- if path is None:
229
- continue
230
- values = _field_boundary_scalar(path, patch, face_count)
231
- if not values or any(not math.isfinite(value) for value in values):
232
- continue
233
- points.append({"time": actual_time, "value": float(sum(values))})
234
- evidence.append(evidence_path(case, path))
235
- source_times.append(actual_time)
236
- return points, sorted(set(evidence)), sorted(set(source_times)), None
237
-
238
-
239
- def _patch_average_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]:
240
- areas, owners = _patch_geometry(case, patch)
241
- if not areas or not owners or sum(areas) <= 0:
242
- return [], [], [], "patch geometry could not be reconstructed"
243
- target_values = sorted({float(value) for value in targets})
244
- dirs = numeric_time_dirs(case)
245
- points: list[dict[str, float]] = []
246
- evidence: list[str] = []
247
- source_times: list[float] = []
248
- for target in target_values:
249
- nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None)
250
- if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)):
251
- continue
252
- actual_time, directory = nearest
253
- path = foam_path(directory, field)
254
- if path is None:
255
- continue
256
- try:
257
- values = read_scalar_field_allow_uniform(path, max(owners) + 1)
258
- except (OSError, ValueError, RuntimeError):
259
- continue
260
- if len(values) <= max(owners):
261
- continue
262
- total_area = sum(areas)
263
- average = sum(area * values[owner] for area, owner in zip(areas, owners)) / total_area
264
- if not math.isfinite(average):
265
- continue
266
- points.append({"time": actual_time, "value": float(average)})
267
- evidence.append(evidence_path(case, path))
268
- source_times.append(actual_time)
269
- return points, sorted(set(evidence)), sorted(set(source_times)), None
270
-
271
-
272
- def _reference_times(reference: dict[str, Any], metric_names: Iterable[str]) -> list[float]:
273
- times: set[float] = set()
274
- for metric in metric_names:
275
- value = reference.get("qois", {}).get(metric)
276
- if not isinstance(value, dict):
277
- continue
278
- if value.get("kind") == "time_history":
279
- for point in value.get("points", []):
280
- if isinstance(point, dict) and isinstance(point.get("time"), (int, float)):
281
- times.add(float(point["time"]))
282
- elif value.get("kind") == "branched_time_histories":
283
- for branch in value.get("branches", {}).values():
284
- if isinstance(branch, dict):
285
- for point in branch.get("points", []):
286
- if isinstance(point, dict) and isinstance(point.get("time"), (int, float)):
287
- times.add(float(point["time"]))
288
- return sorted(times)
289
-
290
-
291
- def _history(quantity: str, points: list[dict[str, float]], dimensions: str | None = None) -> dict[str, Any]:
292
- value: dict[str, Any] = {"kind": "time_history", "quantity": quantity, "points": sorted(points, key=lambda item: item["time"])}
293
- if dimensions:
294
- value["field_dimensions"] = dimensions
295
- return value
296
-
297
-
298
- def recover_ercofta(case: Path, reference: dict[str, Any], variant: str) -> RecoveryEvidence:
299
- result = RecoveryEvidence()
300
- reference_times = _reference_times(reference, ("mass_flow_rate", "pressure_rise"))
301
- available_times = [time for time, _ in numeric_time_dirs(case)]
302
- expected_latest = max(reference_times, default=None)
303
- observed_latest = max(available_times, default=None)
304
- result.preflight.update({
305
- "reference_latest_time": expected_latest,
306
- "retained_latest_time": observed_latest,
307
- "time_semantics": "numeric_directory_name_exact_match",
308
- })
309
- if variant != "1" and expected_latest is not None and (observed_latest is None or observed_latest < expected_latest - 1e-10 * max(1.0, expected_latest)):
310
- result.reasons.append(
311
- f"retained result ends at {observed_latest!r}, before reference time {expected_latest!r}; no time rescaling is permitted"
312
- )
313
- result.preflight["status"] = "fail"
314
- return result
315
- mass_points, mass_refs, mass_times, mass_error = _patch_sum_history(case, "phi", "inlet", reference_times)
316
- pressure_points_in, pressure_refs_in, pressure_times_in, pressure_error_in = _patch_average_history(case, "p", "inlet", reference_times)
317
- pressure_points_out, pressure_refs_out, pressure_times_out, pressure_error_out = _patch_average_history(case, "p", "outlet", reference_times)
318
- result.preflight.update({
319
- "status": "pass" if mass_points or pressure_points_in else "fail",
320
- "mass_point_count": len(mass_points),
321
- "pressure_inlet_point_count": len(pressure_points_in),
322
- "pressure_outlet_point_count": len(pressure_points_out),
323
- })
324
- if mass_points:
325
- result.values["mass_flow_rate"] = _history("explicit_mass_flow", mass_points, field_dimensions(case, "phi"))
326
- result.evidence["mass_flow_rate"] = mass_refs
327
- result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1"
328
- result.source_times.extend(mass_times)
329
- if pressure_points_in and pressure_points_out:
330
- inlet = {round(point["time"], 12): point["value"] for point in pressure_points_in}
331
- outlet = {round(point["time"], 12): point["value"] for point in pressure_points_out}
332
- points = [{"time": time, "value": outlet[time] - inlet[time]} for time in sorted(set(inlet) & set(outlet))]
333
- if points:
334
- result.values["pressure_rise"] = {
335
- "kind": "time_history",
336
- "quantity": "pressure_rise",
337
- "definition": "outlet_minus_inlet_patch_owner_cell_area_average",
338
- "source_patches": {"inlet": "inlet", "outlet": "outlet"},
339
- "points": points,
340
- }
341
- result.evidence["pressure_rise"] = sorted(set(pressure_refs_in + pressure_refs_out))
342
- result.methods["pressure_rise"] = "retained_p_owner_cell_patch_area_average.v1"
343
- result.source_times.extend(pressure_times_in + pressure_times_out)
344
- for error in (mass_error, pressure_error_in, pressure_error_out):
345
- if error:
346
- result.reasons.append(error)
347
- if expected_latest is not None and not mass_points and not pressure_points_in:
348
- result.reasons.append(
349
- "no retained time directory matches the reference time grid; time units or scale are not inferred"
350
- )
351
- result.source_times = sorted(set(result.source_times))
352
- return result
353
-
354
-
355
- def _case_branch_dirs(case: Path) -> dict[str, Path]:
356
- parent = case.parent
357
- result = {"pBack_101325": case}
358
- for path in parent.glob("case_pBack_*"):
359
- match = re.fullmatch(r"case_pBack_([0-9]+)", path.name)
360
- if match and path.is_dir():
361
- result[f"pBack_{match.group(1)}"] = path
362
- return result
363
-
364
-
365
- def recover_nozzle(case: Path, reference: dict[str, Any], adapter: str, variant: str) -> RecoveryEvidence:
366
- result = RecoveryEvidence()
367
- reference_value = reference.get("qois", {}).get("mass_flow_rate", {})
368
- if variant == "4" and adapter == "easyfoam" and reference_value.get("kind") == "branched_time_histories":
369
- branches: dict[str, Any] = {}
370
- evidence: list[str] = []
371
- sources: dict[str, float] = {}
372
- for branch, history in reference_value.get("branches", {}).items():
373
- branch_case = _case_branch_dirs(case).get(branch)
374
- points = history.get("points", []) if isinstance(history, dict) else []
375
- target = [point.get("time") for point in points if isinstance(point, dict) and isinstance(point.get("time"), (int, float))]
376
- if branch_case is None or not target:
377
- result.reasons.append(f"missing retained branch directory or target time for {branch}")
378
- continue
379
- branch_points, refs, times, error = _patch_sum_history(branch_case, "phi", "inlet", target)
380
- if branch_points:
381
- branches[branch] = _history("explicit_mass_flow", branch_points, field_dimensions(branch_case, "phi"))
382
- # ``evidence_path`` is relative to each branch case. Add the
383
- # sibling directory explicitly so three otherwise identical
384
- # ``0.005/phi`` paths cannot be confused in the manifest.
385
- if branch_case != case:
386
- evidence.extend(f"../{branch_case.name}/{ref}" for ref in refs)
387
- else:
388
- evidence.extend(refs)
389
- if times:
390
- sources[branch] = max(times)
391
- elif error:
392
- result.reasons.append(f"{branch}: {error}")
393
- if branches:
394
- result.values["mass_flow_rate"] = {
395
- "kind": "branched_time_histories",
396
- "quantity": "explicit_mass_flow",
397
- "field_dimensions": field_dimensions(case, "phi"),
398
- "branches": branches,
399
- }
400
- result.evidence["mass_flow_rate"] = sorted(set(evidence))
401
- result.methods["mass_flow_rate"] = "retained_branch_phi_boundary_sum.v1"
402
- result.preflight.update({"status": "pass", "branches": sorted(branches), "source_times": sources})
403
- result.source_times.extend(sources.values())
404
- else:
405
- result.preflight["status"] = "fail"
406
- return result
407
- if variant == "2" and adapter == "foamagent" and reference_value.get("kind") == "time_history":
408
- targets = [point.get("time") for point in reference_value.get("points", []) if isinstance(point, dict) and isinstance(point.get("time"), (int, float))]
409
- points, refs, times, error = _patch_sum_history(case, "phi", "inlet", targets)
410
- if points:
411
- result.values["mass_flow_rate"] = _history("explicit_mass_flow", points, field_dimensions(case, "phi"))
412
- result.evidence["mass_flow_rate"] = refs
413
- result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1"
414
- result.source_times.extend(times)
415
- result.preflight.update({"status": "pass", "point_count": len(points), "source_times": times})
416
- else:
417
- result.preflight["status"] = "fail"
418
- if error:
419
- result.reasons.append(error)
420
- return result
421
- result.preflight["status"] = "not_applicable"
422
- return result
423
-
424
-
425
- def _final_fields(case: Path) -> tuple[float, Path] | None:
426
- for time, directory in reversed(numeric_time_dirs(case)):
427
- if all(foam_path(directory, name) is not None for name in ("C", "U", "rho", "p", "T")):
428
- return time, directory
429
- return None
430
-
431
-
432
- def recover_riemann(case: Path) -> RecoveryEvidence:
433
- result = RecoveryEvidence()
434
- final = _final_fields(case)
435
- if final is None:
436
- result.preflight = {"status": "fail", "reason": "final C/U/rho/p/T fields are not all retained"}
437
- return result
438
- time, directory = final
439
- try:
440
- centres = read_vector_list(foam_path(directory, "C")) # type: ignore[arg-type]
441
- velocity = read_vector_field_allow_uniform(foam_path(directory, "U"), len(centres)) # type: ignore[arg-type]
442
- rho = read_scalar_field_allow_uniform(foam_path(directory, "rho"), len(centres)) # type: ignore[arg-type]
443
- pressure = read_scalar_field_allow_uniform(foam_path(directory, "p"), len(centres)) # type: ignore[arg-type]
444
- temperature = read_scalar_field_allow_uniform(foam_path(directory, "T"), len(centres)) # type: ignore[arg-type]
445
- except (OSError, ValueError, RuntimeError) as exc:
446
- result.preflight = {"status": "fail", "reason": f"field decoding failed: {exc}"}
447
- return result
448
- if not all(len(values) == len(centres) for values in (velocity, rho, pressure, temperature)):
449
- result.preflight = {"status": "fail", "reason": "final fields have inconsistent cell counts"}
450
- return result
451
- x_target = min((point[0] for point in centres), key=lambda value: abs(value))
452
- y_target = min((point[1] for point in centres), key=lambda value: abs(value))
453
- horizontal_indices = [index for index, point in enumerate(centres) if abs(point[1] - y_target) <= 1e-10 * max(1.0, abs(y_target))]
454
- vertical_indices = [index for index, point in enumerate(centres) if abs(point[0] - x_target) <= 1e-10 * max(1.0, abs(x_target))]
455
- horizontal_indices.sort(key=lambda index: centres[index][0])
456
- vertical_indices.sort(key=lambda index: centres[index][1])
457
- columns_h = ["x", "rho", "U_x", "U_y", "U_z", "p", "T"]
458
- columns_v = ["y", "rho", "U_x", "U_y", "U_z", "p", "T"]
459
- rows_h = [[centres[i][0], rho[i], *velocity[i], pressure[i], temperature[i]] for i in horizontal_indices]
460
- rows_v = [[centres[i][1], rho[i], *velocity[i], pressure[i], temperature[i]] for i in vertical_indices]
461
- if len(rows_h) < 5 or len(rows_v) < 5:
462
- result.preflight = {"status": "fail", "reason": "centerline preflight retained fewer than five cells", "horizontal_count": len(rows_h), "vertical_count": len(rows_v)}
463
- return result
464
- root = evidence_path(case, directory / "C")
465
- refs = sorted({root, evidence_path(case, directory / "U"), evidence_path(case, directory / "rho"), evidence_path(case, directory / "p"), evidence_path(case, directory / "T")})
466
- profiles = {
467
- "kind": "named_profiles",
468
- "profiles": [
469
- {"profile_id": f"recovery/{time:g}/horizontal.xy", "columns": columns_h, "rows": rows_h},
470
- {"profile_id": f"recovery/{time:g}/vertical.xy", "columns": columns_v, "rows": rows_v},
471
- ],
472
- }
473
- result.values["centerline_profiles"] = profiles
474
- result.values["event_locations"] = profile_event_locations(profiles)
475
- result.evidence["centerline_profiles"] = refs
476
- result.evidence["event_locations"] = refs
477
- result.methods["centerline_profiles"] = "retained_final_cell_centerline_sampling.v1"
478
- result.methods["event_locations"] = "retained_final_cell_centerline_sampling_gradient_peaks.v1"
479
- result.source_times = [time]
480
- result.preflight = {
481
- "status": "pass",
482
- "source_time": time,
483
- "horizontal_cell_count": len(rows_h),
484
- "vertical_cell_count": len(rows_v),
485
- "selected_coordinates": {"x": x_target, "y": y_target},
486
- }
487
- if result.values["event_locations"] is None:
488
- result.values.pop("event_locations", None)
489
- result.evidence.pop("event_locations", None)
490
- result.methods.pop("event_locations", None)
491
- result.reasons.append("centerline profiles were available but no local pressure/rho gradient event was detected")
492
- return result
493
-
494
-
495
- def _nu_value(case: Path) -> tuple[float | None, str | None]:
496
- for path in (case / "constant/physicalProperties", case / "constant/transportProperties", case / "constant/thermophysicalProperties"):
497
- if not path.is_file():
498
- continue
499
- match = re.search(r"(?m)^\s*nu\s+(?:\[[^]]+\]\s*)?([-+0-9.eE]+)\s*;", _text(path))
500
- if match:
501
- return float(match.group(1)), evidence_path(case, path)
502
- return None, None
503
-
504
-
505
- def _vector_boundary_uniform(path: Path, patch: str) -> tuple[float, float, float] | None:
506
- text = _text(path)
507
- anchor = text.find("boundaryField")
508
- block = _named_block(text, patch, max(anchor, 0))
509
- if block is None:
510
- return None
511
- match = re.search(r"\bvalue\s+uniform\s*\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)\s*;", block)
512
- return tuple(float(match.group(index)) for index in range(1, 4)) if match else None
513
-
514
-
515
- def _first_cell_distance(case: Path) -> tuple[float | None, str | None]:
516
- candidates = sorted(case.glob("postProcessing/wallLawSets/*/yLine.csv"))
517
- for path in reversed(candidates):
518
- rows = []
519
- try:
520
- for line in path.read_text(encoding="utf-8", errors="ignore").splitlines()[1:]:
521
- parts = [float(item) for item in line.split(",")]
522
- if len(parts) >= 2:
523
- rows.append(abs(parts[1]))
524
- except (OSError, ValueError):
525
- continue
526
- positive = [value for value in rows if value > 0 and math.isfinite(value)]
527
- if positive:
528
- return min(positive), evidence_path(case, path)
529
- return None, None
530
-
531
-
532
- def recover_yplus(case: Path) -> RecoveryEvidence:
533
- result = RecoveryEvidence()
534
- final = next(((time, directory) for time, directory in reversed(numeric_time_dirs(case)) if foam_path(directory, "wallShearStress")), None)
535
- nu, nu_ref = _nu_value(case)
536
- distance, distance_ref = _first_cell_distance(case)
537
- if final is None or nu is None or distance is None:
538
- result.preflight = {"status": "fail", "final_wall_shear": bool(final), "nu": nu, "first_cell_distance": distance}
539
- result.reasons.append("wall shear, kinematic viscosity, or first-cell distance is absent")
540
- return result
541
- time, directory = final
542
- wall_patches = [name for name, spec in _boundary_specs(case).items() if str(spec.get("type")) == "wall"]
543
- values: list[float] = []
544
- shear_path = foam_path(directory, "wallShearStress")
545
- for patch in wall_patches:
546
- vector = _vector_boundary_uniform(shear_path, patch) if shear_path else None
547
- if vector is not None:
548
- values.append(math.sqrt(sum(component * component for component in vector)))
549
- if not values:
550
- result.preflight = {"status": "fail", "reason": "wallShearStress has no parseable wall patch value"}
551
- return result
552
- tau = statistics_mean(values)
553
- yplus = math.sqrt(max(tau, 0.0)) * distance / nu
554
- if not math.isfinite(yplus):
555
- result.preflight = {"status": "fail", "reason": "derived y+ is non-finite"}
556
- return result
557
- refs = [evidence_path(case, shear_path)] if shear_path else []
558
- refs.extend(item for item in (nu_ref, distance_ref) if item)
559
- result.values["first_cell_yplus"] = float(yplus)
560
- result.evidence["first_cell_yplus"] = sorted(set(refs))
561
- result.methods["first_cell_yplus"] = "retained_wall_shear_first_cell_distance.v1"
562
- result.source_times = [time]
563
- result.preflight = {"status": "pass", "source_time": time, "wall_patch_count": len(values), "tau_magnitude": tau, "nu": nu, "first_cell_distance": distance}
564
- result.reasons.append("derived endpoint is an auditable wall-shear estimate, not a substituted Spalding profile")
565
- return result
566
-
567
-
568
- def statistics_mean(values: list[float]) -> float:
569
- return sum(values) / len(values) if values else math.nan
570
-
571
-
572
- def _merge_candidate(candidate: dict[str, Any], recovery: RecoveryEvidence) -> dict[str, Any]:
573
- result = copy.deepcopy(candidate)
574
- qois = result.setdefault("qois", {})
575
- evidence = result.setdefault("evidence", {})
576
- methods = result.setdefault("metric_methods", {})
577
- resolver = result.setdefault("resolver_report", {})
578
- for metric, value in recovery.values.items():
579
- qois[metric] = value
580
- evidence[metric] = sorted(set(recovery.evidence.get(metric, [])))
581
- methods[metric] = recovery.methods.get(metric, "frozen_recovery.v1")
582
- resolver[metric] = {
583
- "status": "selected",
584
- "selected_evidence": evidence[metric],
585
- "method": methods[metric],
586
- "physical_validation": "metric_extractor_contract.v1",
587
- }
588
- required = list(result.get("required_metrics", []))
589
- missing = sorted(set(required) - set(qois))
590
- result["missing_metrics"] = missing
591
- result["status"] = "complete" if not missing and not result.get("extraction_errors") else "incomplete"
592
- health = result.setdefault("health", {})
593
- checks = health.setdefault("checks", {})
594
- checks["principal_qoi_complete"] = not missing
595
- checks["principal_extraction_error_free"] = not result.get("extraction_errors")
596
- validation_errors = [
597
- error for name, value in qois.items() if name in required for error in structured_qoi_errors(name, value)
598
- ]
599
- checks["structured_qoi_valid"] = not validation_errors
600
- health["status"] = "pass" if not missing and not validation_errors and not result.get("extraction_errors") else "incomplete"
601
- health["validation_errors"] = validation_errors + list(result.get("extraction_errors", []))
602
- return result
603
-
604
-
605
- def recover_case(
606
- case_id: str,
607
- case: Path,
608
- reference: dict[str, Any],
609
- *,
610
- adapter: str,
611
- design: dict[str, Any],
612
- ) -> dict[str, Any]:
613
- """Re-extract and, where justified, recover one selected incomplete case."""
614
- original = extract_contract_case(case, case_id, design)
615
- original_comparison = compare_case(reference, original, 1.0)
616
- family, variant = case_id.split("/", 1)
617
- recovery = RecoveryEvidence(preflight={"status": "not_applicable"})
618
- if family == "ERCOFTA_pump":
619
- recovery = recover_ercofta(case, reference, variant)
620
- elif family == "nozzleCDV":
621
- recovery = recover_nozzle(case, reference, adapter, variant)
622
- elif family == "riemann2D":
623
- recovery = recover_riemann(case)
624
- elif family == "yPlusVerification" and variant == "1" and adapter == "easyfoam":
625
- recovery = recover_yplus(case)
626
- elif family == "supersonicCrossJet" and variant == "1":
627
- recovery.reasons.append("declared interior pressure window contains no valid retained cell; global extrema are not an allowed proxy")
628
- recovery.preflight = {"status": "fail", "check": "declared_internal_window_nonempty", "observed_cell_count": 0}
629
- merged = _merge_candidate(original, recovery)
630
- comparison = compare_case(reference, merged, 1.0)
631
- if "incomplete" in str(comparison.get("status")):
632
- recovery_status = "irrecoverable_incomplete"
633
- elif comparison.get("status") == "out_of_tolerance":
634
- recovery_status = "recovered_out_of_tolerance"
635
- elif comparison.get("status") == "pass":
636
- recovery_status = "recovered_complete"
637
- else:
638
- recovery_status = "recovery_evaluation_error"
639
- return {
640
- "case_id": case_id,
641
- "family": family,
642
- "variant": variant,
643
- "case_dir": str(case.resolve()),
644
- "original": {
645
- "reextract_status": original_comparison.get("status"),
646
- "reextract_missing_metrics": original_comparison.get("missing_metrics", []),
647
- "reextract_out_of_tolerance_metrics": original_comparison.get("out_of_tolerance_metrics", []),
648
- "reextract_candidate_missing_metrics": original.get("missing_metrics", []),
649
- },
650
- "recovery": {
651
- "status": recovery_status,
652
- "version": RECOVERY_VERSION,
653
- "methods": recovery.methods,
654
- "source_evidence": recovery.evidence,
655
- "source_times": recovery.source_times,
656
- "preflight": recovery.preflight,
657
- "reasons": recovery.reasons,
658
- },
659
- "candidate": merged,
660
- "comparison": comparison,
661
- }
662
-
663
-
664
- def recovery_score_record(source: dict[str, Any], recovered: dict[str, Any]) -> dict[str, Any]:
665
- """Build a compact campaign-compatible record without rerunning checks."""
666
- original = source
667
- comparison = recovered["comparison"]
668
- execution = copy.deepcopy(original.get("execution", {}))
669
- numerical = copy.deepcopy(original.get("numerical", {}))
670
- execution_pass = execution.get("status") == "pass"
671
- numerical_pass = numerical.get("status") == "pass" or bool(numerical.get("pass"))
672
- qoi_pass = bool(comparison.get("physics_grounded_qoi_pass"))
673
- failure_categories: list[str] = []
674
- if not execution_pass:
675
- failure_categories.append("execution_failure")
676
- elif "incomplete" in str(comparison.get("status", "")):
677
- failure_categories.append("qoi_incomplete")
678
- elif comparison.get("status") == "out_of_tolerance":
679
- failure_categories.append("qoi_out_of_tolerance")
680
- return {
681
- "schema_version": "foambench.frozen_case_recovery.v1",
682
- "case_id": recovered["case_id"],
683
- "dataset": original.get("dataset", "extended"),
684
- "family": recovered["family"],
685
- "variant": recovered["variant"],
686
- "replicate": original.get("replicate", 1),
687
- "artifact": {
688
- "case_dir": recovered["case_dir"],
689
- "rollout_dir": original.get("artifact", {}).get("rollout_dir"),
690
- "workspace_dir": original.get("artifact", {}).get("workspace_dir"),
691
- },
692
- "execution": execution,
693
- "numerical": numerical,
694
- "qoi": {
695
- "status": "pass" if qoi_pass else comparison.get("status", "evaluation_error"),
696
- "physics_grounded_qoi_pass": qoi_pass,
697
- "effective_pass_ratio": float(comparison.get("qoi_pass_ratio", 0.0) or 0.0),
698
- "candidate": recovered["candidate"],
699
- "comparison": comparison,
700
- },
701
- "scores": {
702
- "execution_pass": execution_pass,
703
- "numerical_pass": numerical_pass,
704
- "physics_grounded_qoi_pass": qoi_pass,
705
- "end_to_end_pass": execution_pass and numerical_pass and qoi_pass,
706
- },
707
- "failure_categories": failure_categories,
708
- "recovery": recovered["recovery"],
709
- }
710
-
711
-
712
- def document_checksum(path: Path) -> dict[str, Any]:
713
- return {"path": str(path.resolve()), "sha256": sha256_file(path), "size_bytes": path.stat().st_size}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/health.py DELETED
@@ -1,69 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from .foam import final_time_dirs
7
- from .foam_field import scan_field
8
- from .foam_io import field_path
9
-
10
- SCALAR_FIELDS = (
11
- "p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", "nuTilda",
12
- "Qdot", "CH4", "O2", "CO2", "H2O", "N2", "alpha.water", "alpha.air",
13
- "h", "hTotal",
14
- )
15
- POSITIVE_FIELDS = {"T", "rho", "k", "epsilon", "omega", "nuTilda", "h", "hTotal"}
16
-
17
-
18
- def final_field_health(case_dir: Path | None) -> dict[str, Any]:
19
- latest, time_dirs, layout = final_time_dirs(case_dir)
20
- if not time_dirs:
21
- return {
22
- "status": "unavailable",
23
- "latest_time": latest,
24
- "checks": {},
25
- "reason": "no_final_time_directory",
26
- }
27
- parsed: list[str] = []
28
- nonfinite: list[str] = []
29
- bound_failures: list[str] = []
30
- parse_errors: dict[str, str] = {}
31
- bounds: dict[str, dict[str, float]] = {}
32
- for name in SCALAR_FIELDS:
33
- paths = [path for time_dir in time_dirs for path in [field_path(time_dir, name)] if path is not None]
34
- if not paths:
35
- continue
36
- records = [scan_field(path, case_dir) for path in paths]
37
- invalid = [record for record in records if not record.get("parse_ok")]
38
- if invalid:
39
- parse_errors[name] = str(invalid[0].get("error") or invalid[0].get("reason") or "internalField is not parseable")
40
- continue
41
- if any(not record.get("finite") for record in records):
42
- nonfinite.append(name)
43
- extrema = [record.get("internal") for record in records]
44
- lows = [float(item["min"]) for item in extrema if isinstance(item, dict) and isinstance(item.get("min"), (int, float))]
45
- highs = [float(item["max"]) for item in extrema if isinstance(item, dict) and isinstance(item.get("max"), (int, float))]
46
- if not lows or not highs:
47
- continue
48
- parsed.append(name)
49
- low, high = min(lows), max(highs)
50
- bounds[name] = {"min": low, "max": high}
51
- if name in POSITIVE_FIELDS and low < -1e-12:
52
- bound_failures.append(name)
53
- if name.startswith("alpha.") and (low < -1e-3 or high > 1.0 + 1e-3):
54
- bound_failures.append(f"{name}_bounds")
55
- checks = {
56
- "parsed_fields_finite": not nonfinite and not parse_errors,
57
- "applicable_field_bounds_valid": not bound_failures,
58
- }
59
- return {
60
- "status": "pass" if all(checks.values()) else "fail",
61
- "latest_time": latest,
62
- "layout": layout,
63
- "checks": checks,
64
- "parsed_fields": sorted(parsed),
65
- "nonfinite_fields": sorted(nonfinite),
66
- "field_bound_failures": sorted(bound_failures),
67
- "parse_errors": parse_errors,
68
- "bounds": bounds,
69
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/io.py DELETED
@@ -1,39 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import json
4
- import math
5
- from datetime import datetime, timezone
6
- from pathlib import Path
7
- from typing import Any
8
-
9
-
10
- def utc_now() -> str:
11
- return datetime.now(timezone.utc).isoformat()
12
-
13
-
14
- def read_json(path: Path) -> Any:
15
- return json.loads(path.read_text(encoding="utf-8"))
16
-
17
-
18
- def read_object(path: Path) -> dict[str, Any]:
19
- value = read_json(path)
20
- if not isinstance(value, dict):
21
- raise ValueError(f"expected JSON object: {path}")
22
- return value
23
-
24
-
25
- def write_json(path: Path, value: Any) -> None:
26
- path.parent.mkdir(parents=True, exist_ok=True)
27
- temporary = path.with_name(path.name + ".tmp")
28
- temporary.write_text(
29
- json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
30
- encoding="utf-8",
31
- )
32
- temporary.replace(path)
33
-
34
-
35
- def finite(value: Any) -> float | None:
36
- if isinstance(value, bool) or not isinstance(value, (int, float)):
37
- return None
38
- number = float(value)
39
- return number if math.isfinite(number) else None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/measurement_specs.py DELETED
@@ -1,45 +0,0 @@
1
- """Load the visible, reference-free Extended measurement contract."""
2
- from __future__ import annotations
3
-
4
- import hashlib
5
- import json
6
- from pathlib import Path
7
- from typing import Any
8
-
9
- ROOT = Path(__file__).resolve().parents[2]
10
- PATH = ROOT / "benchmarks/FoamBench_extended_openfoam13_measurement_specs.json"
11
- SCHEMA = "easyfoam.extbench.measurement.v1"
12
-
13
-
14
- def _sha(text: str) -> str:
15
- return hashlib.sha256(text.encode()).hexdigest()
16
-
17
-
18
- def load_measurement_spec(case_id: str, requirement: str | None = None) -> dict[str, Any] | None:
19
- """Return one case contract; reference values and tolerances are absent by construction."""
20
- if not PATH.is_file() or "/" not in case_id:
21
- return None
22
- document = json.loads(PATH.read_text(encoding="utf-8"))
23
- if document.get("schema_version") != "easyfoam.extbench.measurement_specs.v1":
24
- raise ValueError("unsupported measurement contract")
25
- spec = document.get("cases", {}).get(case_id)
26
- if not isinstance(spec, dict):
27
- return None
28
- if spec.get("measurement_schema") != SCHEMA:
29
- raise ValueError(f"invalid measurement schema for {case_id}")
30
- if requirement is not None:
31
- spec = dict(spec)
32
- spec["requirement_sha256"] = _sha(requirement)
33
- return spec
34
-
35
-
36
- def prompt_measurement_spec(case_id: str, requirement: str) -> str:
37
- spec = load_measurement_spec(case_id, requirement)
38
- if spec is None:
39
- return ""
40
- return (
41
- "Measurement contract for this ExtBench task (visible task definition; it contains no reference answer or tolerance):\n"
42
- + json.dumps(spec, ensure_ascii=False, indent=2)
43
- + "\nUse this contract to plan what fields, patches, probes, meshes, and saved times must be retained. "
44
- "Do not invent a proxy when a principal measurement is unavailable; report the missing evidence.\n\n"
45
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/mesh.py DELETED
@@ -1,54 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- import subprocess
5
- from pathlib import Path
6
- from typing import Any
7
-
8
- from .foam import FATAL_RE, NUMBER, read_text
9
-
10
-
11
- def parse_mesh_log(text: str, *, source: str) -> dict[str, Any]:
12
- failed_values = [int(value) for value in re.findall(r"Failed\s+(\d+)\s+mesh checks", text, re.I)]
13
- min_volumes = [float(value) for value in re.findall(rf"Min volume\s*=\s*({NUMBER})", text)]
14
- markers = {
15
- "fatal": FATAL_RE.search(text) is not None,
16
- "non_positive_cell_volume": min(min_volumes, default=float("inf")) <= 0,
17
- "negative_or_zero_volume": re.search(r"(?:negative|zero)\s+(?:cell\s+)?volumes?", text, re.I) is not None,
18
- "illegal_face": re.search(r"illegal\s+faces?", text, re.I) is not None,
19
- "open_cell": re.search(r"open\s+cells?", text, re.I) is not None,
20
- "non_manifold": re.search(r"non[- ]manifold", text, re.I) is not None,
21
- }
22
- available = "Mesh OK." in text or bool(failed_values) or bool(min_volumes)
23
- hard_failure = any(markers.values()) or max(failed_values, default=0) > 0
24
- return {
25
- "status": "unavailable" if not available else "fail" if hard_failure else "pass",
26
- "source": source,
27
- "failed_mesh_checks": max(failed_values, default=0),
28
- "min_volume": min(min_volumes) if min_volumes else None,
29
- "critical_markers": markers,
30
- }
31
-
32
-
33
- def mesh_evidence(log_paths: tuple[Path, ...]) -> dict[str, Any]:
34
- selected = [
35
- path for path in log_paths
36
- if "checkmesh" in path.name.lower() or "checkMesh" in read_text(path)[:4096]
37
- ]
38
- text = "\n".join(read_text(path) for path in selected)
39
- return parse_mesh_log(text, source=",".join(str(path) for path in selected))
40
-
41
-
42
- def run_check_mesh(case_dir: Path | None, timeout: float = 120.0) -> dict[str, Any]:
43
- if case_dir is None:
44
- return {"status": "unavailable", "source": "read_only_replay", "reason": "case_directory_missing"}
45
- command = ["checkMesh", "-case", str(case_dir), "-allTopology", "-allGeometry", "-noFunctionObjects"]
46
- try:
47
- completed = subprocess.run(command, capture_output=True, text=True, check=False, timeout=timeout)
48
- except (OSError, subprocess.TimeoutExpired) as exc:
49
- return {"status": "fail", "source": "read_only_replay", "command": command, "error": str(exc)}
50
- result = parse_mesh_log(completed.stdout + "\n" + completed.stderr, source="read_only_replay")
51
- result.update({"command": command, "return_code": completed.returncode})
52
- if completed.returncode != 0:
53
- result["status"] = "fail"
54
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/models.py DELETED
@@ -1,86 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass, field
4
- from pathlib import Path
5
- from typing import Any
6
-
7
- from .io import read_object
8
-
9
-
10
- @dataclass(frozen=True)
11
- class BenchmarkProfile:
12
- profile_id: str
13
- dataset: str
14
- benchmark_path: Path
15
- reference_qois_path: Path
16
- expected_case_count: int
17
- case_id_style: str = "family_variant"
18
- extractor: str = "field"
19
- required_qoi_fraction: float = 1.0
20
- reference_run_root: Path | None = None
21
- numerical_contract: dict[str, Any] = field(default_factory=dict)
22
-
23
- @classmethod
24
- def load(cls, path: Path, *, repository_root: Path | None = None) -> "BenchmarkProfile":
25
- path = path.resolve(strict=True)
26
- data = read_object(path)
27
- if repository_root:
28
- root = repository_root.resolve()
29
- else:
30
- root = next(
31
- (parent for parent in path.parents if (parent / "benchmarks").is_dir() and (parent / "schemas").is_dir()),
32
- path.parent,
33
- )
34
-
35
- def resolve(value: str | None) -> Path | None:
36
- if value is None:
37
- return None
38
- candidate = Path(value)
39
- return candidate.resolve() if candidate.is_absolute() else (root / candidate).resolve()
40
-
41
- membership = data.get("membership", {})
42
- qoi = data.get("qoi", {})
43
- return cls(
44
- profile_id=str(data["profile_id"]),
45
- dataset=str(data["dataset"]),
46
- benchmark_path=resolve(str(data["benchmark_path"])), # type: ignore[arg-type]
47
- reference_qois_path=resolve(str(data["reference_qois_path"])), # type: ignore[arg-type]
48
- expected_case_count=int(membership["expected_case_count"]),
49
- case_id_style=str(membership.get("case_id_style", "family_variant")),
50
- extractor=str(qoi.get("extractor", "field")),
51
- required_qoi_fraction=float(qoi.get("required_fraction", 1.0)),
52
- reference_run_root=resolve(data.get("reference_run_root")),
53
- numerical_contract=dict(data.get("numerical", {})),
54
- )
55
-
56
- def identity(self, case_id: str) -> tuple[str, str]:
57
- if "/" in case_id:
58
- return tuple(case_id.split("/", 1)) # type: ignore[return-value]
59
- return case_id, "1"
60
-
61
-
62
- @dataclass(frozen=True)
63
- class CaseArtifact:
64
- case_id: str
65
- dataset: str
66
- family: str
67
- variant: str
68
- replicate: int
69
- rollout_dir: Path
70
- case_dir: Path | None
71
- workspace_dir: Path | None = None
72
- manifest: dict[str, Any] = field(default_factory=dict)
73
- formal_run_records: tuple[Path, ...] = ()
74
- solver_logs: tuple[Path, ...] = ()
75
- workflow_path: Path | None = None
76
- evidence_summary_path: Path | None = None
77
-
78
- @property
79
- def duration_seconds(self) -> float | None:
80
- value = self.manifest.get("duration_seconds")
81
- return float(value) if isinstance(value, (int, float)) else None
82
-
83
- @property
84
- def token_usage(self) -> dict[str, Any]:
85
- value = self.manifest.get("token_usage")
86
- return dict(value) if isinstance(value, dict) else {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/numerical.py DELETED
@@ -1,253 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import math
4
- import re
5
- from pathlib import Path
6
- from typing import Any
7
-
8
- from .foam import FATAL_RE, NONFINITE_RE, NUMBER, final_time_dirs, read_logs
9
- from .health import final_field_health
10
- from .mesh import mesh_evidence, run_check_mesh
11
- from .models import CaseArtifact
12
- from .stability import numerical_scheme, steady_plateau
13
-
14
- RESIDUAL_RE = re.compile(
15
- rf"Solving for (?P<field>[^,\r\n]+),\s*Initial residual = (?P<initial>{NUMBER}),\s*Final residual = (?P<final>{NUMBER})"
16
- )
17
- COURANT_RE = re.compile(rf"Courant Number mean:\s*(?P<mean>{NUMBER})\s+max:\s*(?P<max>{NUMBER})")
18
- CONTINUITY_RE = re.compile(
19
- rf"(?:time step )?continuity errors\s*:\s*sum local = (?P<local>{NUMBER}),\s*global = (?P<global>{NUMBER}),\s*cumulative = (?P<cumulative>{NUMBER})",
20
- re.I,
21
- )
22
-
23
- DEFAULT_CONTRACT = {
24
- "final_window_fraction": 0.2,
25
- "minimum_final_window_samples": 5,
26
- "final_linear_residual": {"reference_factor": 10.0, "absolute_floor": 1e-3},
27
- "initial_residual": {"reference_factor": 10.0, "absolute_floor": 1e-3},
28
- "courant_final_p95": {"reference_factor": 3.0, "absolute_floor": 1.0},
29
- "courant_peak": {"reference_factor": 3.0, "absolute_floor": 2.0},
30
- "continuity_global_p95": {"reference_factor": 10.0, "absolute_floor": 1e-5},
31
- "continuity_cumulative_final": {"reference_factor": 10.0, "absolute_floor": 1e-3},
32
- }
33
-
34
-
35
- def percentile(values: list[float], fraction: float) -> float | None:
36
- if not values:
37
- return None
38
- ordered = sorted(values)
39
- position = (len(ordered) - 1) * fraction
40
- low, high = math.floor(position), math.ceil(position)
41
- if low == high:
42
- return ordered[low]
43
- return ordered[low] + (ordered[high] - ordered[low]) * (position - low)
44
-
45
-
46
- def final_window(values: list[float], contract: dict[str, Any] = DEFAULT_CONTRACT) -> list[float]:
47
- count = max(
48
- int(contract["minimum_final_window_samples"]),
49
- math.ceil(len(values) * float(contract["final_window_fraction"])),
50
- )
51
- return values[-min(len(values), count):]
52
-
53
-
54
- def parse_logs(paths: list[Path] | tuple[Path, ...], contract: dict[str, Any] = DEFAULT_CONTRACT) -> dict[str, Any]:
55
- text = read_logs(paths)
56
- residuals: dict[str, dict[str, list[float]]] = {}
57
- courants: list[float] = []
58
- continuity_global: list[float] = []
59
- continuity_cumulative: list[float] = []
60
- for match in RESIDUAL_RE.finditer(text):
61
- field = match.group("field").strip()
62
- values = residuals.setdefault(field, {"initial": [], "final": []})
63
- values["initial"].append(float(match.group("initial")))
64
- values["final"].append(float(match.group("final")))
65
- courants.extend(float(match.group("max")) for match in COURANT_RE.finditer(text))
66
- for match in CONTINUITY_RE.finditer(text):
67
- continuity_global.append(abs(float(match.group("global"))))
68
- continuity_cumulative.append(abs(float(match.group("cumulative"))))
69
- residual_summary = {
70
- field: {
71
- "sample_count": len(values["initial"]),
72
- "initial_final_window_p95": percentile(final_window(values["initial"], contract), 0.95),
73
- "final_final_window_p95": percentile(final_window(values["final"], contract), 0.95),
74
- }
75
- for field, values in sorted(residuals.items())
76
- }
77
- return {
78
- "log_paths": [str(path) for path in paths if path.is_file()],
79
- "fatal_marker": FATAL_RE.search(text) is not None,
80
- "nonfinite_marker": NONFINITE_RE.search(text) is not None,
81
- "residual_field_count": len(residuals),
82
- "residual_record_count": sum(len(values["initial"]) for values in residuals.values()),
83
- "residuals": residual_summary,
84
- "initial_residual_final_window_p95": max(
85
- (record["initial_final_window_p95"] for record in residual_summary.values()
86
- if record["initial_final_window_p95"] is not None),
87
- default=None,
88
- ),
89
- "final_residual_final_window_p95": max(
90
- (record["final_final_window_p95"] for record in residual_summary.values()
91
- if record["final_final_window_p95"] is not None),
92
- default=None,
93
- ),
94
- "courant_count": len(courants),
95
- "courant_peak": max(courants) if courants else None,
96
- "courant_final_window_p95": percentile(final_window(courants, contract), 0.95),
97
- "continuity_count": len(continuity_global),
98
- "continuity_global_final_window_p95": percentile(final_window(continuity_global, contract), 0.95),
99
- "continuity_cumulative_final": continuity_cumulative[-1] if continuity_cumulative else None,
100
- }
101
-
102
-
103
- def threshold(reference: float, key: str, contract: dict[str, Any] = DEFAULT_CONTRACT) -> float:
104
- policy = contract[key]
105
- return max(abs(reference) * float(policy["reference_factor"]), float(policy["absolute_floor"]))
106
-
107
-
108
- def compatible(
109
- candidate: float | None,
110
- reference: float | None,
111
- key: str,
112
- contract: dict[str, Any] = DEFAULT_CONTRACT,
113
- ) -> tuple[bool | None, float | None]:
114
- if reference is None:
115
- return None, None
116
- limit = threshold(reference, key, contract)
117
- return candidate is not None and math.isfinite(candidate) and candidate <= limit, limit
118
-
119
-
120
- def _field_health(candidate: dict[str, Any], case_dir: Path | None) -> tuple[bool | None, bool | None, dict[str, Any]]:
121
- health = candidate.get("health")
122
- if not isinstance(health, dict):
123
- health = final_field_health(case_dir)
124
- checks = health.get("checks", {})
125
- return checks.get("parsed_fields_finite"), checks.get("applicable_field_bounds_valid"), health
126
- checks = health.get("checks") if isinstance(health.get("checks"), dict) else {}
127
- finite = checks.get("all_parsed_fields_finite")
128
- bounds = checks.get("applicable_field_bounds_valid")
129
- if not isinstance(finite, bool) or not isinstance(bounds, bool):
130
- fallback = final_field_health(case_dir)
131
- fallback_checks = fallback.get("checks", {})
132
- finite = finite if isinstance(finite, bool) else fallback_checks.get("parsed_fields_finite")
133
- bounds = bounds if isinstance(bounds, bool) else fallback_checks.get("applicable_field_bounds_valid")
134
- health = {"candidate_health": health, "independent_field_health": fallback}
135
- return finite if isinstance(finite, bool) else None, bounds if isinstance(bounds, bool) else None, health
136
-
137
-
138
- def evaluate_numerical(
139
- artifact: CaseArtifact,
140
- *,
141
- execution_pass: bool,
142
- qoi_candidate: dict[str, Any],
143
- reference_logs: list[Path] | tuple[Path, ...] = (),
144
- reference_case_dir: Path | None = None,
145
- reference_qois: dict[str, Any] | None = None,
146
- reference_statistics: dict[str, Any] | None = None,
147
- steady_plateau_enabled: bool = False,
148
- check_mesh: bool = False,
149
- mesh_timeout: float = 120.0,
150
- contract: dict[str, Any] = DEFAULT_CONTRACT,
151
- ) -> dict[str, Any]:
152
- if not execution_pass:
153
- return {
154
- "schema_version": "foambench.numerical_validity.v2",
155
- "status": "not_evaluated_execution_failure",
156
- "pass": False,
157
- "checks": {},
158
- "failed_checks": [],
159
- }
160
- candidate = parse_logs(artifact.solver_logs, contract)
161
- reference = (dict(reference_statistics) if reference_statistics is not None
162
- else parse_logs(reference_logs, contract) if reference_logs else {})
163
- finite_fields, bounded_fields, health = _field_health(qoi_candidate, artifact.case_dir)
164
- mesh = mesh_evidence(artifact.solver_logs)
165
- if check_mesh and mesh["status"] == "unavailable":
166
- mesh = run_check_mesh(artifact.case_dir, mesh_timeout)
167
- latest, latest_dirs, layout = final_time_dirs(artifact.case_dir)
168
- scheme = numerical_scheme(artifact.case_dir) if artifact.case_dir else "unknown"
169
- plateau: dict[str, Any] = {"status": "not_applicable", "applicable": False}
170
- reference_plateau: dict[str, Any] = {"status": "not_applicable", "applicable": False}
171
- if steady_plateau_enabled and scheme == "steadyState" and reference_qois:
172
- reference_plateau = steady_plateau(reference_qois)
173
- baseline = {
174
- name: float(metric["relative_span"])
175
- for name, metric in reference_plateau.get("metrics", {}).items()
176
- if isinstance(metric, dict) and isinstance(metric.get("relative_span"), (int, float))
177
- }
178
- plateau = steady_plateau(qoi_candidate.get("qois", {}), baseline)
179
-
180
- relative = {
181
- "final_linear_residual_reference_compatible": compatible(
182
- candidate["final_residual_final_window_p95"], reference.get("final_residual_final_window_p95"),
183
- "final_linear_residual", contract,
184
- ),
185
- "initial_residual_reference_compatible": compatible(
186
- candidate["initial_residual_final_window_p95"], reference.get("initial_residual_final_window_p95"),
187
- "initial_residual", contract,
188
- ),
189
- "courant_final_reference_compatible": compatible(
190
- candidate["courant_final_window_p95"], reference.get("courant_final_window_p95"),
191
- "courant_final_p95", contract,
192
- ),
193
- "courant_peak_reference_compatible": compatible(
194
- candidate["courant_peak"], reference.get("courant_peak"), "courant_peak", contract,
195
- ),
196
- "continuity_reference_compatible": compatible(
197
- candidate["continuity_global_final_window_p95"], reference.get("continuity_global_final_window_p95"),
198
- "continuity_global_p95", contract,
199
- ),
200
- "continuity_cumulative_reference_compatible": compatible(
201
- candidate["continuity_cumulative_final"], reference.get("continuity_cumulative_final"),
202
- "continuity_cumulative_final", contract,
203
- ),
204
- }
205
- checks: dict[str, dict[str, Any]] = {
206
- "solver_log_present": {"status": "pass" if candidate["log_paths"] else "fail", "required": True},
207
- "no_fatal_marker": {"status": "fail" if candidate["fatal_marker"] else "pass", "required": True},
208
- "no_nonfinite_log_marker": {"status": "fail" if candidate["nonfinite_marker"] else "pass", "required": True},
209
- "residual_evidence_present": {
210
- "status": "pass" if candidate["residual_record_count"] else "fail",
211
- "required": True,
212
- },
213
- "final_fields_present": {"status": "pass" if latest_dirs else "fail", "required": True},
214
- "mesh_core_valid": {
215
- "status": mesh["status"],
216
- "required": mesh["status"] != "unavailable",
217
- },
218
- "steady_principal_qoi_plateau": {
219
- "status": plateau["status"],
220
- "required": bool(plateau.get("applicable")),
221
- },
222
- "all_parsed_final_fields_finite": {
223
- "status": "not_applicable" if finite_fields is None else "pass" if finite_fields else "fail",
224
- "required": finite_fields is not None,
225
- },
226
- "applicable_field_bounds_valid": {
227
- "status": "not_applicable" if bounded_fields is None else "pass" if bounded_fields else "fail",
228
- "required": bounded_fields is not None,
229
- },
230
- }
231
- for name, (passed, limit) in relative.items():
232
- checks[name] = {
233
- "status": "not_applicable" if passed is None else "pass" if passed else "fail",
234
- "required": passed is not None,
235
- "limit": limit,
236
- }
237
- failed = [name for name, value in checks.items() if value["required"] and value["status"] == "fail"]
238
- return {
239
- "schema_version": "foambench.numerical_validity.v2",
240
- "status": "pass" if not failed else "fail",
241
- "pass": not failed,
242
- "checks": checks,
243
- "failed_checks": failed,
244
- "candidate_logs": candidate,
245
- "reference_logs": reference or None,
246
- "candidate_latest_time": latest,
247
- "final_field_layout": layout,
248
- "field_health": health,
249
- "mesh": mesh,
250
- "time_scheme": scheme,
251
- "steady_plateau": plateau,
252
- "reference_steady_plateau": reference_plateau,
253
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/pipeline.py DELETED
@@ -1,166 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from .adapters import create_adapter
7
- from .aggregate import aggregate_results
8
- from .execution import evaluate_execution
9
- from .io import utc_now, write_json
10
- from .models import BenchmarkProfile, CaseArtifact
11
- from .numerical import evaluate_numerical
12
- from .profiles import expected_completion_time, load_assets
13
- from .qoi import evaluate_qoi
14
- from .reference import reference_case_dir, reference_log_paths, reference_statistics
15
- from .reporting import write_case_csv, write_summary_csv
16
- from .schema import validate
17
-
18
-
19
- def missing_artifact(case_id: str, profile: BenchmarkProfile, run_root: Path) -> CaseArtifact:
20
- family, variant = profile.identity(case_id)
21
- return CaseArtifact(
22
- case_id=case_id,
23
- dataset=profile.dataset,
24
- family=family,
25
- variant=variant,
26
- replicate=1,
27
- rollout_dir=run_root / family / variant / "replicate_001",
28
- case_dir=None,
29
- manifest={"status": "missing_rollout"},
30
- )
31
-
32
-
33
- def failure_categories(result: dict[str, Any]) -> list[str]:
34
- categories = []
35
- if not result["scores"]["execution_pass"]:
36
- categories.append("execution_failure")
37
- elif not result["scores"]["numerical_pass"]:
38
- categories.append("numerical_failure")
39
- if result["scores"]["execution_pass"] and not result["scores"]["physics_grounded_qoi_pass"]:
40
- qoi_status = result["qoi"].get("status")
41
- if qoi_status == "evaluation_error":
42
- categories.append("qoi_evaluation_error")
43
- else:
44
- categories.append("qoi_incomplete" if "incomplete" in str(qoi_status) else "qoi_out_of_tolerance")
45
- return categories
46
-
47
-
48
- def evaluate_case(
49
- artifact: CaseArtifact,
50
- profile: BenchmarkProfile,
51
- benchmark_case: dict[str, Any],
52
- reference: dict[str, Any],
53
- *,
54
- check_mesh: bool = False,
55
- mesh_timeout: float = 120.0,
56
- ) -> dict[str, Any]:
57
- execution = evaluate_execution(artifact, expected_completion_time(benchmark_case, reference))
58
- execution_pass = execution["status"] == "pass"
59
- qoi = evaluate_qoi(artifact, profile, reference, execution_pass=execution_pass)
60
- numerical = evaluate_numerical(
61
- artifact,
62
- execution_pass=execution_pass,
63
- qoi_candidate=qoi["candidate"],
64
- reference_logs=reference_log_paths(profile, artifact.case_id),
65
- reference_statistics=reference_statistics(profile, artifact.case_id),
66
- reference_case_dir=reference_case_dir(profile, artifact.case_id),
67
- # Numerical plateau is a stability check over available histories. It is
68
- # deliberately separate from the principal Physics-grounded QoI roles.
69
- reference_qois=dict(reference.get("qois", {})),
70
- steady_plateau_enabled=bool(profile.numerical_contract.get("steady_qoi_plateau")),
71
- check_mesh=check_mesh,
72
- mesh_timeout=mesh_timeout,
73
- )
74
- numerical_pass = bool(numerical.get("pass"))
75
- physics_grounded_qoi_pass = bool(qoi.get("physics_grounded_qoi_pass"))
76
- result = {
77
- "schema_version": "foambench.case_evaluation.v1",
78
- "case_id": artifact.case_id,
79
- "dataset": artifact.dataset,
80
- "family": artifact.family,
81
- "variant": artifact.variant,
82
- "replicate": artifact.replicate,
83
- "execution": execution,
84
- "numerical": numerical,
85
- "qoi": qoi,
86
- "scores": {
87
- "execution_pass": execution_pass,
88
- "numerical_pass": numerical_pass,
89
- "physics_grounded_qoi_pass": physics_grounded_qoi_pass,
90
- "end_to_end_pass": execution_pass and numerical_pass and physics_grounded_qoi_pass,
91
- },
92
- "resources": {
93
- "duration_seconds": artifact.duration_seconds,
94
- "token_usage": artifact.token_usage,
95
- },
96
- "artifact": {
97
- "rollout_dir": str(artifact.rollout_dir),
98
- "workspace_dir": str(artifact.workspace_dir) if artifact.workspace_dir else None,
99
- "case_dir": str(artifact.case_dir) if artifact.case_dir else None,
100
- },
101
- }
102
- result["failure_categories"] = failure_categories(result)
103
- return result
104
-
105
-
106
- def evaluate_campaign(
107
- profile: BenchmarkProfile,
108
- *,
109
- adapter_name: str,
110
- run_root: Path,
111
- output_dir: Path | None = None,
112
- check_mesh: bool = False,
113
- mesh_timeout: float = 120.0,
114
- ) -> dict[str, Any]:
115
- benchmark, references = load_assets(profile)
116
- adapter = create_adapter(adapter_name, run_root, profile)
117
- discovered = adapter.discover()
118
- unknown = sorted(set(discovered) - set(references))
119
- if unknown:
120
- raise ValueError("run contains cases outside the benchmark profile: " + ", ".join(unknown))
121
- results = []
122
- for case_id in sorted(references):
123
- artifact = discovered.get(case_id) or missing_artifact(case_id, profile, run_root)
124
- results.append(evaluate_case(
125
- artifact, profile, benchmark[case_id], references[case_id],
126
- check_mesh=check_mesh, mesh_timeout=mesh_timeout,
127
- ))
128
- overall = aggregate_results(results)
129
- families = {
130
- family: aggregate_results([row for row in results if row["family"] == family])
131
- for family in sorted({row["family"] for row in results})
132
- }
133
- report = {
134
- "schema_version": "foambench.campaign_evaluation.v1",
135
- "generated_at": utc_now(),
136
- "profile_id": profile.profile_id,
137
- "dataset": profile.dataset,
138
- "adapter": adapter_name,
139
- "run_root": str(run_root.resolve()),
140
- "reference_qois": str(profile.reference_qois_path),
141
- "definitions": {
142
- "execution_pass": "independent execution contract passed",
143
- "numerical_pass": "execution passed and independent numerical contract passed",
144
- "physics_grounded_qoi_pass": "execution passed and every principal Physics-grounded QoI passed its physical contract",
145
- "end_to_end_pass": "execution_pass AND numerical_pass AND physics_grounded_qoi_pass",
146
- },
147
- "overall": overall,
148
- "families": families,
149
- "cases": {row["case_id"]: row for row in results},
150
- }
151
- validate(report, "benchmark_evaluation.schema.json")
152
- if output_dir is not None:
153
- output_dir = output_dir.resolve()
154
- write_json(output_dir / "campaign_evaluation.json", report)
155
- write_json(output_dir / "summary.json", {
156
- key: report[key] for key in (
157
- "schema_version", "generated_at", "profile_id", "dataset", "adapter",
158
- "run_root", "definitions", "overall", "families",
159
- )
160
- })
161
- case_root = output_dir / "cases"
162
- for row in results:
163
- write_json(case_root / row["family"] / f"{row['variant']}.json", row)
164
- write_case_csv(output_dir / "cases.csv", results)
165
- write_summary_csv(output_dir / "summary.csv", overall, families)
166
- return report
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/preparation.py DELETED
@@ -1,172 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import re
4
- import subprocess
5
- from concurrent.futures import ThreadPoolExecutor, as_completed
6
- from pathlib import Path
7
- from typing import Any
8
-
9
- from .foam import read_text
10
- from .adapters import create_adapter
11
- from .execution import evaluate_execution
12
- from .io import write_json
13
- from .models import BenchmarkProfile, CaseArtifact
14
- from .profiles import expected_completion_time, load_assets
15
-
16
-
17
- WRITE_FORMAT_RE = re.compile(r"(?m)^\s*writeFormat\s+(ascii|binary)\s*;")
18
-
19
-
20
- def _patch_names(case_dir: Path) -> set[str]:
21
- boundary = case_dir / "constant" / "polyMesh" / "boundary"
22
- if not boundary.is_file():
23
- return set()
24
- text = boundary.read_text(encoding="utf-8", errors="ignore")
25
- return set(re.findall(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\n\s*\{", text))
26
-
27
-
28
- def _run(command: list[str], log: Any, timeout: int) -> dict[str, Any]:
29
- try:
30
- completed = subprocess.run(
31
- command,
32
- stdout=log,
33
- stderr=subprocess.STDOUT,
34
- check=False,
35
- text=True,
36
- timeout=timeout,
37
- )
38
- return {"command": command, "return_code": completed.returncode, "timed_out": False}
39
- except subprocess.TimeoutExpired:
40
- return {"command": command, "return_code": None, "timed_out": True}
41
- except OSError as exc:
42
- return {"command": command, "return_code": 127, "timed_out": False, "error": str(exc)}
43
-
44
-
45
- def prepare_case(artifact: CaseArtifact, output_root: Path) -> dict[str, Any]:
46
- case_dir = artifact.case_dir
47
- if case_dir is None:
48
- return {"case_id": artifact.case_id, "status": "skipped", "reason": "case_directory_missing"}
49
- case_output = output_root / artifact.family / artifact.variant
50
- case_output.mkdir(parents=True, exist_ok=True)
51
- log_path = case_output / "preparation.log"
52
- records: list[dict[str, Any]] = []
53
- control_path = case_dir / "system" / "controlDict"
54
- original_format_match = WRITE_FORMAT_RE.search(read_text(control_path))
55
- original_format = original_format_match.group(1) if original_format_match else None
56
- functions = ["writeCellCentres", "writeCellVolumes", "vorticity"]
57
- # Sampling is measurement-only and deterministic when the candidate has
58
- # explicitly declared the benchmark's system/sample dictionary. Do not
59
- # invent sample coordinates for cases that did not provide this contract.
60
- if (case_dir / "system" / "sample").is_file():
61
- functions.append("sample")
62
- patches = _patch_names(case_dir)
63
- if artifact.family == "supersonicCrossJet":
64
- # Patch names vary between the fixed reference (inlet1/inlet2) and
65
- # agent cases (inlet/jet). Resolve only semantically named patches.
66
- selected = sorted(name for name in patches if any(token in name.lower() for token in ("inlet", "jet")))
67
- functions.extend(f"patchFlowRate(phi,patch={name})" for name in selected)
68
- elif artifact.family in {"ERCOFTA_pump", "nozzleCDV"}:
69
- selected = sorted(name for name in patches if any(token in name.lower() for token in ("inlet", "outlet")))
70
- functions.extend(f"patchFlowRate(phi,patch={name})" for name in selected)
71
- functions.extend(f"patchAverage(p,patch={name})" for name in selected)
72
- with log_path.open("w", encoding="utf-8") as log:
73
- for function_name in functions:
74
- command = ["foamPostProcess", "-case", str(case_dir), "-func", function_name]
75
- # Preparation is intentionally endpoint-only. A single retained
76
- # endpoint cannot support a transient-history claim, so histories
77
- # remain diagnostic unless the candidate already saved them.
78
- command.append("-latestTime")
79
- record = _run(command, log, 300)
80
- record["required"] = function_name != "sample"
81
- records.append(record)
82
- if original_format == "binary":
83
- set_ascii = [
84
- "foamDictionary", "-case", str(case_dir), "system/controlDict",
85
- "-entry", "writeFormat", "-set", "ascii",
86
- ]
87
- restore = [
88
- "foamDictionary", "-case", str(case_dir), "system/controlDict",
89
- "-entry", "writeFormat", "-set", "binary",
90
- ]
91
- record = _run(set_ascii, log, 60)
92
- record["required"] = True
93
- records.append(record)
94
- try:
95
- record = _run([
96
- "foamFormatConvert", "-case", str(case_dir), "-latestTime",
97
- ], log, 300)
98
- record["required"] = True
99
- records.append(record)
100
- finally:
101
- record = _run(restore, log, 60)
102
- record["required"] = True
103
- records.append(record)
104
- failed = [
105
- record for record in records
106
- if record.get("required", True) and record.get("return_code") != 0
107
- ]
108
- optional_failures = [
109
- record for record in records
110
- if not record.get("required", True) and record.get("return_code") != 0
111
- ]
112
- result = {
113
- "case_id": artifact.case_id,
114
- "case_dir": str(case_dir),
115
- "status": "pass" if not failed else "fail",
116
- "role": "measurement_only",
117
- "original_write_format": original_format,
118
- "log": str(log_path),
119
- "commands": records,
120
- "optional_failures": optional_failures,
121
- }
122
- write_json(case_output / "preparation.json", result)
123
- return result
124
-
125
-
126
- def prepare_cases(artifacts: list[CaseArtifact], output_root: Path, jobs: int) -> dict[str, Any]:
127
- output_root.mkdir(parents=True, exist_ok=True)
128
- records = []
129
- with ThreadPoolExecutor(max_workers=max(1, jobs)) as executor:
130
- futures = {executor.submit(prepare_case, artifact, output_root): artifact for artifact in artifacts}
131
- for future in as_completed(futures):
132
- artifact = futures[future]
133
- try:
134
- records.append(future.result())
135
- except Exception as exc:
136
- records.append({"case_id": artifact.case_id, "status": "error", "error": str(exc)})
137
- records.sort(key=lambda record: record["case_id"])
138
- report = {
139
- "role": "measurement_only",
140
- "case_count": len(records),
141
- "pass_count": sum(record["status"] == "pass" for record in records),
142
- "fail_count": sum(record["status"] != "pass" for record in records),
143
- "cases": records,
144
- }
145
- write_json(output_root / "preparation_summary.json", report)
146
- return report
147
-
148
-
149
- def prepare_campaign(
150
- profile: BenchmarkProfile,
151
- *,
152
- adapter_name: str,
153
- run_root: Path,
154
- output_root: Path,
155
- jobs: int = 1,
156
- ) -> dict[str, Any]:
157
- """Prepare derived field QoIs for execution-complete field campaigns."""
158
- if profile.extractor not in {"field", "extended"}:
159
- raise ValueError("preparation is only applicable to field and Extended QoI profiles")
160
- benchmark, references = load_assets(profile)
161
- artifacts = create_adapter(adapter_name, run_root, profile).discover()
162
- eligible = []
163
- for case_id, artifact in artifacts.items():
164
- reference = references.get(case_id)
165
- if reference is None:
166
- continue
167
- execution = evaluate_execution(
168
- artifact, expected_completion_time(benchmark[case_id], reference)
169
- )
170
- if execution["status"] == "pass":
171
- eligible.append(artifact)
172
- return prepare_cases(eligible, output_root, jobs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/profiles.py DELETED
@@ -1,74 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from .io import read_object
7
- from .models import BenchmarkProfile
8
- from .schema import validate
9
-
10
-
11
- def load_assets(profile: BenchmarkProfile) -> tuple[dict[str, Any], dict[str, Any]]:
12
- benchmark = read_object(profile.benchmark_path)
13
- reference_document = read_object(profile.reference_qois_path)
14
- validate(reference_document, "foambench_qoi_reference.schema.json")
15
- references = reference_document.get("cases")
16
- if not isinstance(references, dict):
17
- raise ValueError(f"reference QoI file has no cases object: {profile.reference_qois_path}")
18
- if len(references) != profile.expected_case_count:
19
- raise ValueError(
20
- f"profile membership mismatch: expected {profile.expected_case_count}, got {len(references)}"
21
- )
22
- current_design = (
23
- read_object(profile.benchmark_path.parent / "FoamBench_extended_openfoam13_qoi_design.json")
24
- if profile.extractor == "extended" else None
25
- )
26
- for case_id, reference in references.items():
27
- principal = reference.get("principal_metrics", [])
28
- qois = reference.get("qois", {})
29
- tolerances = reference.get("tolerances", {})
30
- missing_values = sorted(set(principal) - set(qois))
31
- missing_tolerances = sorted(set(principal) - set(tolerances))
32
- if missing_values or missing_tolerances:
33
- raise ValueError(
34
- f"reference QoI contract incomplete for {case_id}: "
35
- f"missing_values={missing_values}, missing_tolerances={missing_tolerances}"
36
- )
37
- if profile.extractor == "extended":
38
- from .extbench import design_case_contract
39
-
40
- expected_branch, expected_principal = design_case_contract(case_id, current_design or {})
41
- if reference.get("branch_id") != expected_branch:
42
- raise ValueError(
43
- f"ExtBench branch drift for {case_id}: "
44
- f"reference={reference.get('branch_id')!r}, design={expected_branch!r}"
45
- )
46
- if set(principal) != set(expected_principal):
47
- raise ValueError(
48
- f"ExtBench principal-metric drift for {case_id}: "
49
- f"reference={sorted(principal)}, design={sorted(expected_principal)}"
50
- )
51
- benchmark_cases = benchmark.get("cases") if isinstance(benchmark.get("cases"), dict) else benchmark
52
- if not isinstance(benchmark_cases, dict):
53
- raise ValueError(f"benchmark has no case mapping: {profile.benchmark_path}")
54
- missing = sorted(set(references) - set(benchmark_cases))
55
- if missing:
56
- raise ValueError("benchmark is missing reference cases: " + ", ".join(missing))
57
- return benchmark_cases, references
58
-
59
-
60
- def expected_end_time(case: dict[str, Any]) -> float | None:
61
- text = case.get("system/controlDict")
62
- if not isinstance(text, str):
63
- return None
64
- import re
65
-
66
- match = re.search(r"(?m)^\s*endTime\s+([-+0-9.eE]+)\s*;", text)
67
- return float(match.group(1)) if match else None
68
-
69
-
70
- def expected_completion_time(case: dict[str, Any], reference: dict[str, Any]) -> float | None:
71
- latest = reference.get("latest_time")
72
- if isinstance(latest, (int, float)):
73
- return float(latest)
74
- return expected_end_time(case)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/profiles/advanced.json DELETED
@@ -1,19 +0,0 @@
1
- {
2
- "profile_id": "foambench.advanced.v1",
3
- "dataset": "advanced",
4
- "benchmark_path": "benchmarks/FoamBench_advanced_openfoam13_fixed_final.json",
5
- "reference_qois_path": "benchmarks/FoamBench_advanced_openfoam13_reference_qois.json",
6
- "membership": {
7
- "expected_case_count": 16,
8
- "case_id_style": "case_name"
9
- },
10
- "qoi": {
11
- "extractor": "field",
12
- "required_fraction": 1.0
13
- },
14
- "numerical": {
15
- "contract": "physics_grounded_qoi.v1",
16
- "steady_qoi_plateau": true,
17
- "reference_statistics_path": "benchmarks/reference_statistics/advanced.json"
18
- }
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/profiles/basic.json DELETED
@@ -1,19 +0,0 @@
1
- {
2
- "profile_id": "foambench.basic.v1",
3
- "dataset": "basic",
4
- "benchmark_path": "benchmarks/FoamBench_basic_openfoam13_fixed_final.json",
5
- "reference_qois_path": "benchmarks/FoamBench_basic_openfoam13_reference_qois.json",
6
- "membership": {
7
- "expected_case_count": 110,
8
- "case_id_style": "family_variant"
9
- },
10
- "qoi": {
11
- "extractor": "field",
12
- "required_fraction": 1.0
13
- },
14
- "numerical": {
15
- "contract": "physics_grounded_qoi.v1",
16
- "steady_qoi_plateau": true,
17
- "reference_statistics_path": "benchmarks/reference_statistics/basic.json"
18
- }
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/profiles/extended.json DELETED
@@ -1,19 +0,0 @@
1
- {
2
- "profile_id": "foambench.extended",
3
- "dataset": "extended",
4
- "benchmark_path": "benchmarks/FoamBench_extended_openfoam13_fixed.json",
5
- "reference_qois_path": "benchmarks/FoamBench_extended_openfoam13_reference_qois.json",
6
- "membership": {
7
- "expected_case_count": 100,
8
- "case_id_style": "family_variant"
9
- },
10
- "qoi": {
11
- "extractor": "extended",
12
- "required_fraction": 1.0
13
- },
14
- "numerical": {
15
- "contract": "foambench.qoi.design",
16
- "tolerances": "joint_physical_admissibility_and_reference_response_provisional",
17
- "reference_statistics_path": "benchmarks/reference_statistics/extended.json"
18
- }
19
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/qoi.py DELETED
@@ -1,79 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import Any
4
-
5
- from .comparison import compare_case
6
- from .extbench import extract_contract_case
7
-
8
- from .field_candidate import extract_field_candidate
9
- from .models import BenchmarkProfile, CaseArtifact
10
- from .schema import validate
11
-
12
-
13
- def empty_candidate(case_id: str, status: str, reason: str) -> dict[str, Any]:
14
- return {
15
- "schema_version": "foambench.qoi.candidate",
16
- "case_id": case_id,
17
- "status": status,
18
- "qois": {},
19
- "health": {"status": "not_assessed", "reason": reason},
20
- }
21
-
22
-
23
- def evaluate_qoi(
24
- artifact: CaseArtifact,
25
- profile: BenchmarkProfile,
26
- reference: dict[str, Any],
27
- *,
28
- execution_pass: bool,
29
- ) -> dict[str, Any]:
30
- if not execution_pass or artifact.case_dir is None:
31
- return {
32
- "status": "not_evaluated_execution_failure",
33
- "physics_grounded_qoi_pass": False,
34
- "effective_pass_ratio": 0.0,
35
- "candidate": empty_candidate(
36
- artifact.case_id, "not_evaluated_execution_failure", "execution_not_passed"
37
- ),
38
- "comparison": None,
39
- }
40
- try:
41
- if profile.extractor == "extended":
42
- candidate = extract_contract_case(artifact.case_dir, artifact.case_id)
43
- required = candidate.get("required_metrics", [])
44
- elif profile.extractor == "field":
45
- required = reference.get("principal_metrics")
46
- if not isinstance(required, list):
47
- required = list(reference.get("qois", {}))
48
- requested = list(reference.get("qois", {}))
49
- candidate = extract_field_candidate(
50
- artifact.case_dir,
51
- artifact.case_id,
52
- requested,
53
- required_metrics=required,
54
- log_paths=list(artifact.solver_logs),
55
- )
56
- else:
57
- raise ValueError(f"unknown QoI extractor: {profile.extractor}")
58
- validate(candidate, "foambench_qoi_candidate.schema.json")
59
- comparison = compare_case(reference, candidate, profile.required_qoi_fraction)
60
- validate(comparison, "foambench_qoi_comparison.schema.json")
61
- health = candidate.get("health")
62
- health_pass = not isinstance(health, dict) or health.get("status") in {None, "pass"}
63
- physics_grounded_qoi = bool(comparison.get("physics_grounded_qoi_pass") and health_pass)
64
- return {
65
- "status": "pass" if physics_grounded_qoi else str(comparison.get("status", "fail")),
66
- "physics_grounded_qoi_pass": physics_grounded_qoi,
67
- "effective_pass_ratio": float(comparison.get("qoi_pass_ratio", 0.0)) if health_pass else 0.0,
68
- "candidate": candidate,
69
- "comparison": comparison,
70
- }
71
- except Exception as exc:
72
- return {
73
- "status": "evaluation_error",
74
- "physics_grounded_qoi_pass": False,
75
- "effective_pass_ratio": 0.0,
76
- "candidate": empty_candidate(artifact.case_id, "error", str(exc)),
77
- "comparison": None,
78
- "error": str(exc),
79
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/qoi_glue.py DELETED
@@ -1,493 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Conservative LLM-assisted recovery for incomplete Extended QoI evidence.
3
-
4
- The model is an evidence router only. It selects an existing file/column and
5
- an allow-listed deterministic operation; this module computes the observation
6
- and validates the source locally. Reference QoI values are never included in
7
- the model packet.
8
- """
9
- from __future__ import annotations
10
-
11
- import copy
12
- import csv
13
- import hashlib
14
- import json
15
- import math
16
- import os
17
- import re
18
- import subprocess
19
- from pathlib import Path
20
- from typing import Any
21
-
22
-
23
- ROOT = Path(__file__).resolve().parents[2]
24
- GLUE_VERSION = "foambench.qoi_glue.v1"
25
- PLAN_SCHEMA = ROOT / "schemas/qoi_recovery_plan.schema.json"
26
- TABLE_SUFFIXES = {".csv", ".dat", ".raw", ".xy"}
27
- TIME_COLUMN = "Time"
28
- MASS_COLUMNS = {
29
- "rhophi",
30
- "massflow",
31
- "massflux",
32
- "sumphi",
33
- "areaintegratephi",
34
- }
35
- EXPECTED_BRANCHES = {"Re_tau_180", "Re_tau_395", "Re_tau_590"}
36
-
37
-
38
- def _enabled() -> bool:
39
- return os.environ.get("EVOLUTION_QOI_GLUE", "off").strip().lower() in {
40
- "1", "true", "on", "yes",
41
- }
42
-
43
-
44
- def _model() -> str:
45
- return (
46
- os.environ.get("evolution_QOI_GLUE_MODEL")
47
- or os.environ.get("evolution_EVALUATION_MODEL")
48
- or "gpt-5.6-terra"
49
- )
50
-
51
-
52
- def _reasoning() -> str | None:
53
- return (
54
- os.environ.get("evolution_QOI_GLUE_REASONING_EFFORT")
55
- or os.environ.get("evolution_EVALUATION_REASONING_EFFORT")
56
- or os.environ.get("evolution_REASONING_EFFORT")
57
- )
58
-
59
-
60
- def _timeout() -> float:
61
- raw = os.environ.get("EVOLUTION_QOI_GLUE_TIMEOUT", "180")
62
- try:
63
- return max(5.0, float(raw))
64
- except ValueError:
65
- return 180.0
66
-
67
-
68
- def _normalise(value: str) -> str:
69
- return re.sub(r"[^a-z0-9]", "", value.lower().replace("+", "plus"))
70
-
71
-
72
- def _finite(value: Any) -> float | None:
73
- if isinstance(value, bool) or not isinstance(value, (int, float)):
74
- return None
75
- result = float(value)
76
- return result if math.isfinite(result) else None
77
-
78
-
79
- def _safe_source(case_dir: Path, raw: Any) -> Path:
80
- if not isinstance(raw, str) or not raw or Path(raw).is_absolute():
81
- raise ValueError("source must be a relative case path")
82
- source = (case_dir / raw).resolve(strict=True)
83
- if not source.is_relative_to(case_dir.resolve(strict=True)):
84
- raise ValueError("source escapes the case directory")
85
- if not source.is_file():
86
- raise ValueError("source is not a file")
87
- return source
88
-
89
-
90
- def _evidence_path(case_dir: Path, source: Path) -> str:
91
- return source.relative_to(case_dir.resolve(strict=True)).as_posix()
92
-
93
-
94
- def _field_dimensions(case_dir: Path, field: str) -> str | None:
95
- for path in sorted(case_dir.rglob(field), reverse=True):
96
- if not path.is_file() or not path.parent.name.replace(".", "", 1).isdigit():
97
- continue
98
- text = path.read_bytes()[:4096].decode("ascii", errors="ignore")
99
- match = re.search(r"dimensions\s*\[([^]]+)\]", text)
100
- if match:
101
- return " ".join(match.group(1).split())
102
- return None
103
-
104
-
105
- def _named_numeric_rows(path: Path) -> tuple[list[str], list[list[float]]]:
106
- """Read a compatible numeric table without accepting arbitrary prose."""
107
- headers: list[list[str]] = []
108
- rows: list[list[float]] = []
109
- for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
110
- stripped = line.strip()
111
- if not stripped:
112
- continue
113
- if stripped.startswith("#"):
114
- names = stripped[1:].strip().replace(",", " ").replace("\t", " ").split()
115
- if names:
116
- headers.append(names)
117
- continue
118
- parts = stripped.replace("(", " ").replace(")", " ").replace(",", " ").split()
119
- if parts and all(re.fullmatch(r"[-+0-9.eE]+", item) for item in parts):
120
- rows.append([float(item) for item in parts])
121
- elif not rows and ("," in stripped or "\t" in stripped):
122
- names = [item.strip() for item in stripped.split(",")] if "," in stripped else stripped.split("\t")
123
- if names:
124
- headers.append(names)
125
- if not rows:
126
- return [], []
127
- width = len(rows[0])
128
- header = next((names for names in reversed(headers) if len(names) == width), [])
129
- return header, [row for row in rows if len(row) == width]
130
-
131
-
132
- def _case_fingerprint(case_dir: Path) -> str:
133
- digest = hashlib.sha256()
134
- for path in sorted(item for item in case_dir.rglob("*") if item.is_file()):
135
- relative = path.relative_to(case_dir).as_posix().encode("utf-8")
136
- digest.update(len(relative).to_bytes(8, "big"))
137
- digest.update(relative)
138
- digest.update(path.stat().st_size.to_bytes(8, "big"))
139
- with path.open("rb") as stream:
140
- for block in iter(lambda: stream.read(1024 * 1024), b""):
141
- digest.update(block)
142
- return digest.hexdigest()
143
-
144
-
145
- def _inventory(case_dir: Path) -> list[dict[str, Any]]:
146
- entries: list[dict[str, Any]] = []
147
- candidates = [item for item in case_dir.rglob("*") if item.is_file()]
148
- candidates.sort(key=lambda item: (item.suffix.lower() not in TABLE_SUFFIXES, str(item)))
149
- for path in candidates[:180]:
150
- relative = path.relative_to(case_dir).as_posix()
151
- item: dict[str, Any] = {"path": relative, "bytes": path.stat().st_size}
152
- if path.suffix.lower() in TABLE_SUFFIXES and path.stat().st_size <= 512 * 1024:
153
- sample = path.read_text(encoding="utf-8", errors="ignore")[:1600]
154
- item["sample"] = sample
155
- elif path.name in {"phi", "C", "U", "Vc", "p", "alpha.water"}:
156
- sample = path.read_bytes()[:4096].decode("ascii", errors="ignore")
157
- match = re.search(r"dimensions\s*\[([^]]+)\]", sample)
158
- if match:
159
- item["dimensions"] = " ".join(match.group(1).split())
160
- entries.append(item)
161
- return entries
162
-
163
-
164
- def build_packet(
165
- case_dir: Path,
166
- case_id: str,
167
- candidate: dict[str, Any],
168
- comparison: dict[str, Any],
169
- ) -> dict[str, Any]:
170
- """Create the small, reference-free packet supplied to the model."""
171
- return {
172
- "schema_version": GLUE_VERSION,
173
- "case_id": case_id,
174
- "family": case_id.split("/", 1)[0] if "/" in case_id else case_id,
175
- "required_metrics": list(candidate.get("required_metrics", [])),
176
- "missing_metrics": list(candidate.get("missing_metrics", [])),
177
- "extraction_errors": list(candidate.get("extraction_errors", [])),
178
- "comparison_status": comparison.get("status"),
179
- "allowed_operations": {
180
- "table_time_history": "Read an explicit Time plus one flux column; preserve signed values and phi dimensions.",
181
- "branch_spalding_table": "Split one labelled table by branch and compute branch wall-law scalars only when yPlus and spaldingYPlus columns exist.",
182
- },
183
- "files": _inventory(case_dir),
184
- }
185
-
186
-
187
- def _prompt(packet: dict[str, Any]) -> str:
188
- return (
189
- "You are a conservative CFD measurement-evidence router.\n"
190
- "Reference QoI values are unavailable and must not be requested or inferred.\n"
191
- "Do not calculate or emit QoI numbers. Return only JSON matching the supplied schema.\n"
192
- "Select an existing file and columns only when they are physically equivalent to a declared principal metric.\n"
193
- "Use status=unrecoverable when evidence is absent, ambiguous, a proxy, or has the wrong physical quantity.\n"
194
- "Allowed operations are exactly table_time_history and branch_spalding_table.\n\n"
195
- "Evidence packet:\n" + json.dumps(packet, ensure_ascii=False, indent=2)
196
- )
197
-
198
-
199
- def _cache_path(campaign_root: Path, case_dir: Path, case_id: str, missing: list[str], model: str) -> Path:
200
- identity = {
201
- "version": GLUE_VERSION,
202
- "case_id": case_id,
203
- "missing": sorted(missing),
204
- "model": model,
205
- "fingerprint": _case_fingerprint(case_dir),
206
- }
207
- key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode("utf-8")).hexdigest()
208
- return campaign_root / "cache" / "qoi_glue" / f"{key}.json"
209
-
210
-
211
- def _write_json(path: Path, value: Any) -> None:
212
- path.parent.mkdir(parents=True, exist_ok=True)
213
- temporary = path.with_name(path.name + ".tmp")
214
- temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
215
- temporary.replace(path)
216
-
217
-
218
- def _load_cached(path: Path) -> dict[str, Any] | None:
219
- if not path.is_file():
220
- return None
221
- try:
222
- value = json.loads(path.read_text(encoding="utf-8"))
223
- except (OSError, json.JSONDecodeError):
224
- return None
225
- return value if isinstance(value, dict) else None
226
-
227
-
228
- def _run_model(
229
- case_dir: Path,
230
- packet: dict[str, Any],
231
- artifact: Path,
232
- ) -> dict[str, Any]:
233
- from scripts.evolution_adapter_common import codex_exec_command
234
-
235
- model = _model()
236
- artifact.parent.mkdir(parents=True, exist_ok=True)
237
- final_message = artifact.with_suffix(".last_message.json")
238
- trajectory = artifact.with_suffix(".trajectory.jsonl")
239
- command = codex_exec_command(
240
- case_dir,
241
- final_message,
242
- model,
243
- output_schema=PLAN_SCHEMA if PLAN_SCHEMA.is_file() else None,
244
- reasoning_effort=_reasoning(),
245
- sandbox="read-only",
246
- )
247
- try:
248
- completed = subprocess.run(
249
- command,
250
- input=_prompt(packet),
251
- text=True,
252
- encoding="utf-8",
253
- errors="replace",
254
- stdout=subprocess.PIPE,
255
- stderr=subprocess.PIPE,
256
- cwd=case_dir,
257
- timeout=_timeout(),
258
- check=False,
259
- )
260
- except (OSError, subprocess.TimeoutExpired) as exc:
261
- return {
262
- "status": "unavailable",
263
- "model": model,
264
- "error": str(exc),
265
- "command": command,
266
- }
267
- trajectory.write_text(completed.stdout, encoding="utf-8")
268
- if completed.returncode != 0:
269
- return {
270
- "status": "unavailable",
271
- "model": model,
272
- "return_code": completed.returncode,
273
- "stderr_tail": completed.stderr[-2000:],
274
- "command": command,
275
- }
276
- try:
277
- plan = json.loads(final_message.read_text(encoding="utf-8"))
278
- except (OSError, json.JSONDecodeError) as exc:
279
- return {
280
- "status": "invalid_response",
281
- "model": model,
282
- "error": str(exc),
283
- "stderr_tail": completed.stderr[-2000:],
284
- }
285
- if not isinstance(plan, dict):
286
- return {"status": "invalid_response", "model": model, "error": "plan is not an object"}
287
- return {
288
- "status": "received",
289
- "model": model,
290
- "return_code": completed.returncode,
291
- "plan": plan,
292
- "stderr_tail": completed.stderr[-2000:],
293
- }
294
-
295
-
296
- def _validate_mapping(mapping: dict[str, Any], required: set[str]) -> None:
297
- metric = mapping.get("metric")
298
- if not isinstance(metric, str) or metric not in required:
299
- raise ValueError("mapping metric is not a missing principal metric")
300
- operation = mapping.get("operation")
301
- if operation not in {"table_time_history", "branch_spalding_table"}:
302
- raise ValueError("operation is not allow-listed")
303
- if operation == "table_time_history":
304
- column = mapping.get("column")
305
- if not isinstance(column, str) or not column:
306
- raise ValueError("table_time_history requires a column")
307
- if operation == "branch_spalding_table":
308
- if metric != "branchwise_wall_law_metrics":
309
- raise ValueError("branch_spalding_table has one supported metric")
310
- if mapping.get("branch_column") != "branch":
311
- raise ValueError("branch_spalding_table requires a branch column")
312
-
313
-
314
- def _execute_time_history(case_dir: Path, mapping: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
315
- source = _safe_source(case_dir, mapping.get("source"))
316
- header, rows = _named_numeric_rows(source)
317
- if TIME_COLUMN not in header:
318
- raise ValueError("table has no Time column")
319
- column = str(mapping["column"])
320
- if column not in header or _normalise(column) not in MASS_COLUMNS:
321
- raise ValueError("column is not an allow-listed explicit flux column")
322
- if "inlet" not in str(source).lower() and str(mapping.get("patch", "")).lower() not in {"inlet", "inlet1", "main"}:
323
- raise ValueError("mass-flow source is not identified as an inlet")
324
- dimensions = _field_dimensions(case_dir, "phi")
325
- quantity = {
326
- "1 0 -1 0 0 0 0": "explicit_mass_flow",
327
- "0 3 -1 0 0 0 0": "explicit_volumetric_flow",
328
- }.get(dimensions)
329
- if quantity is None:
330
- raise ValueError("phi dimensions are absent or unsupported")
331
- time_index, value_index = header.index(TIME_COLUMN), header.index(column)
332
- points = [
333
- {"time": row[time_index], "value": row[value_index]}
334
- for row in rows
335
- if math.isfinite(row[time_index]) and math.isfinite(row[value_index])
336
- ]
337
- if not points:
338
- raise ValueError("table has no finite history points")
339
- branch = "root"
340
- parent = source.relative_to(case_dir).parts
341
- if "postProcessing" in parent:
342
- branch = "/".join(parent[: parent.index("postProcessing")]) or "root"
343
- history: dict[str, Any] = {
344
- "kind": "time_history",
345
- "quantity": quantity,
346
- "field_dimensions": dimensions,
347
- "points": sorted(points, key=lambda item: item["time"]),
348
- }
349
- if branch != "root":
350
- history = {
351
- "kind": "branched_time_histories",
352
- "quantity": quantity,
353
- "field_dimensions": dimensions,
354
- "branches": {branch: history},
355
- }
356
- return history, [_evidence_path(case_dir, source)]
357
-
358
-
359
- def _csv_rows(path: Path) -> tuple[list[str], list[dict[str, str]]]:
360
- with path.open(newline="", encoding="utf-8", errors="ignore") as stream:
361
- reader = csv.DictReader(stream)
362
- rows = [dict(row) for row in reader if row]
363
- return list(reader.fieldnames or []), rows
364
-
365
-
366
- def _execute_branch_spalding(case_dir: Path, mapping: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
367
- source = _safe_source(case_dir, mapping.get("source"))
368
- columns, rows = _csv_rows(source)
369
- normalised = {_normalise(column): column for column in columns}
370
- branch_name = normalised.get("branch")
371
- y_name = normalised.get("yplus")
372
- predicted_name = normalised.get("spaldingyplus")
373
- if not branch_name or not y_name or not predicted_name:
374
- raise ValueError("branch table requires branch, yPlus, and spaldingYPlus columns")
375
- branches: dict[str, Any] = {}
376
- for branch in EXPECTED_BRANCHES:
377
- selected = [row for row in rows if row.get(branch_name) == branch]
378
- if not selected:
379
- raise ValueError(f"branch table is missing {branch}")
380
- errors: list[float] = []
381
- y_values: list[float] = []
382
- for row in selected:
383
- yplus = _finite(float(row[y_name])) if row.get(y_name) else None
384
- predicted = _finite(float(row[predicted_name])) if row.get(predicted_name) else None
385
- if yplus is None or predicted is None or yplus < 0 or predicted < 0:
386
- continue
387
- y_values.append(yplus)
388
- errors.append(math.log1p(yplus) - math.log1p(predicted))
389
- if not errors or not y_values:
390
- raise ValueError(f"branch {branch} has no finite wall-law rows")
391
- branches[branch] = {
392
- "first_cell_yplus": min(y_values),
393
- "spalding_log_rmse": math.sqrt(sum(item * item for item in errors) / len(errors)),
394
- }
395
- return {"kind": "branch_scalars", "branches": branches}, [_evidence_path(case_dir, source)]
396
-
397
-
398
- def apply_plan(
399
- case_dir: Path,
400
- candidate: dict[str, Any],
401
- plan: dict[str, Any],
402
- ) -> tuple[dict[str, Any], dict[str, Any]]:
403
- """Apply a validated plan; any ambiguity leaves the candidate unchanged."""
404
- if plan.get("status") != "recoverable":
405
- return copy.deepcopy(candidate), {"status": str(plan.get("status", "unrecoverable")), "reason": plan.get("reason")}
406
- mappings = plan.get("mappings")
407
- required = set(candidate.get("missing_metrics", []))
408
- if not isinstance(mappings, list) or not mappings:
409
- return copy.deepcopy(candidate), {"status": "invalid_plan", "reason": "recoverable plan has no mappings"}
410
- result = copy.deepcopy(candidate)
411
- selected: dict[str, Any] = {}
412
- try:
413
- for mapping in mappings:
414
- if not isinstance(mapping, dict):
415
- raise ValueError("mapping is not an object")
416
- _validate_mapping(mapping, required)
417
- metric = str(mapping["metric"])
418
- if metric in selected:
419
- raise ValueError(f"duplicate mapping for {metric}")
420
- if mapping["operation"] == "table_time_history":
421
- value, evidence = _execute_time_history(case_dir, mapping)
422
- method = "qoi_glue.table_time_history.v1"
423
- else:
424
- value, evidence = _execute_branch_spalding(case_dir, mapping)
425
- method = "qoi_glue.branch_spalding_table.v1"
426
- selected[metric] = {"value": value, "evidence": evidence, "method": method}
427
- except (OSError, ValueError, TypeError, KeyError) as exc:
428
- return copy.deepcopy(candidate), {"status": "rejected", "reason": str(exc), "plan": plan}
429
- qois = result.setdefault("qois", {})
430
- evidence = result.setdefault("evidence", {})
431
- methods = result.setdefault("metric_methods", {})
432
- resolver = result.setdefault("resolver_report", {})
433
- for metric, item in selected.items():
434
- qois[metric] = item["value"]
435
- evidence[metric] = item["evidence"]
436
- methods[metric] = item["method"]
437
- resolver[metric] = {
438
- "status": "selected",
439
- "selected_evidence": item["evidence"],
440
- "method": item["method"],
441
- "physical_validation": "qoi_glue.allowlisted_operation.v1",
442
- }
443
- required_metrics = list(result.get("required_metrics", []))
444
- missing = sorted(set(required_metrics) - set(qois))
445
- result["missing_metrics"] = missing
446
- extraction_errors = list(result.get("extraction_errors", []))
447
- result["status"] = "complete" if not missing and not extraction_errors else "incomplete"
448
- health = result.setdefault("health", {})
449
- health["status"] = "pass" if not missing and not extraction_errors else "incomplete"
450
- checks = health.setdefault("checks", {})
451
- checks["principal_qoi_complete"] = not missing
452
- checks["principal_extraction_error_free"] = not extraction_errors
453
- return result, {
454
- "status": "recovered_complete" if not missing and not extraction_errors else "recovered_partial",
455
- "metrics": sorted(selected),
456
- "evidence": {metric: item["evidence"] for metric, item in selected.items()},
457
- "methods": {metric: item["method"] for metric, item in selected.items()},
458
- "plan": plan,
459
- }
460
-
461
-
462
- def recover_with_llm(
463
- case_dir: Path,
464
- case_id: str,
465
- candidate: dict[str, Any],
466
- comparison: dict[str, Any],
467
- campaign_root: Path,
468
- ) -> tuple[dict[str, Any], dict[str, Any]]:
469
- """Recover one incomplete candidate, with one cached model call at most."""
470
- if not _enabled():
471
- return copy.deepcopy(candidate), {"status": "disabled", "version": GLUE_VERSION}
472
- missing = list(candidate.get("missing_metrics", []))
473
- if not missing:
474
- return copy.deepcopy(candidate), {"status": "not_needed", "version": GLUE_VERSION}
475
- model = _model()
476
- artifact = _cache_path(campaign_root, case_dir, case_id, missing, model)
477
- cached = _load_cached(artifact)
478
- if cached is None:
479
- packet = build_packet(case_dir, case_id, candidate, comparison)
480
- cached = _run_model(case_dir, packet, artifact)
481
- cached["version"] = GLUE_VERSION
482
- cached["case_id"] = case_id
483
- cached["missing_metrics"] = sorted(missing)
484
- _write_json(artifact, cached)
485
- plan = cached.get("plan") if isinstance(cached.get("plan"), dict) else {"status": cached.get("status", "unavailable")}
486
- recovered, detail = apply_plan(case_dir, candidate, plan)
487
- detail.update({
488
- "version": GLUE_VERSION,
489
- "artifact": str(artifact),
490
- "model": cached.get("model", model),
491
- "execution_status": cached.get("status"),
492
- })
493
- return recovered, detail
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/qoi_reference.py DELETED
@@ -1,566 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Build canonical FoamBench QoI reference datasets from completed runs.
3
-
4
- The extractor uses family-level principal result groups, volume-weighted
5
- generic diagnostics, and geometry-aware normalized probes. It never edits the
6
- benchmark source JSON.
7
- """
8
- from __future__ import annotations
9
-
10
- import argparse
11
- import json
12
- import math
13
- import os
14
- import re
15
- import subprocess
16
- import sys
17
- from concurrent.futures import ThreadPoolExecutor, as_completed
18
- from datetime import datetime, timezone
19
- from pathlib import Path
20
- from typing import Any, Callable
21
-
22
- ROOT = Path(__file__).resolve().parents[2]
23
- if str(ROOT) not in sys.path:
24
- sys.path.insert(0, str(ROOT))
25
-
26
- from benchmarks.evaluation.foam_io import field_path
27
- from benchmarks.evaluation.schema import validate
28
-
29
- try:
30
- from benchmarks.evaluation.field_extractor import (
31
- ExtractionError, FATAL_RE, extract_case_qois, latest_time_dir, magnitude,
32
- parse_log_metrics, parse_scalar_field, parse_vector_field, read_text,
33
- )
34
- except ImportError: # Direct script execution keeps the historical CLI working.
35
- from field_extractor import (
36
- ExtractionError, FATAL_RE, extract_case_qois, latest_time_dir, magnitude,
37
- parse_log_metrics, parse_scalar_field, parse_vector_field, read_text,
38
- )
39
-
40
-
41
- SCHEMA_VERSION = "foambench.reference_qois.v2"
42
- TOLERANCE_POLICY = "principal_relative_15pct_abs_floor_1e-8.v1"
43
- COMMON_SCALAR_FIELDS = (
44
- "p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega",
45
- "nuTilda", "Qdot", "CH4", "O2", "CO2", "H2O", "N2",
46
- "alpha.water", "h", "hTotal",
47
- )
48
- POSITIVE_FIELDS = {"T", "rho", "k", "epsilon", "omega", "nuTilda", "h", "hTotal"}
49
- ADVANCED_TEMPLATE = {
50
- "Cavity_LES": "Cavity",
51
- "Cavity_SA": "Cavity",
52
- "Cavity_geometry_1": "Cavity",
53
- "Cylinder_LES": "Cylinder",
54
- "Cylinder_SA": "Cylinder",
55
- "Diamond_Obstacle_KOMEGASST": "Obstacle",
56
- "Diamond_Obstacle_SA": "Obstacle",
57
- "Double_Square_SA": "Obstacle",
58
- "Rectangular_Obstacle_KOMEGASST": "Obstacle",
59
- "Rectangular_Obstacle_SA": "Obstacle",
60
- "counterFlowFlame2D_KE": "counterFlowFlame2D",
61
- "counterFlowFlame2D_SA": "counterFlowFlame2D",
62
- "nozzleFlow2D_SA": "Nozzle",
63
- "obliqueShock_KE": "Shock",
64
- "obliqueShock_LES": "Shock",
65
- "wedge_SA": "Shock",
66
- }
67
-
68
-
69
- def utc_now() -> str:
70
- return datetime.now(timezone.utc).isoformat()
71
-
72
-
73
- def write_json(path: Path, value: Any) -> None:
74
- path.parent.mkdir(parents=True, exist_ok=True)
75
- temporary = path.with_name(path.name + ".tmp")
76
- temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
77
- temporary.replace(path)
78
-
79
-
80
- def scalar_field(time_dir: Path, name: str) -> list[float]:
81
- path = field_path(time_dir, name)
82
- return parse_scalar_field(path) if path else []
83
-
84
-
85
- def vector_field(time_dir: Path, name: str) -> list[tuple[float, float, float]]:
86
- path = field_path(time_dir, name)
87
- return parse_vector_field(path) if path else []
88
-
89
-
90
- def align(values: list[Any], count: int) -> list[Any]:
91
- if len(values) == count:
92
- return values
93
- if len(values) == 1 and count:
94
- return values * count
95
- return []
96
-
97
-
98
- def weighted_mean(values: list[float], weights: list[float]) -> float | None:
99
- if not values or len(values) != len(weights):
100
- return None
101
- denominator = sum(weights)
102
- return sum(value * weight for value, weight in zip(values, weights)) / denominator if denominator else None
103
-
104
-
105
- def weighted_stats(values: list[float], weights: list[float]) -> dict[str, float]:
106
- pairs = [(value, weight) for value, weight in zip(values, weights) if math.isfinite(value) and math.isfinite(weight)]
107
- if not pairs:
108
- return {}
109
- clean_values = [value for value, _ in pairs]
110
- clean_weights = [weight for _, weight in pairs]
111
- mean = weighted_mean(clean_values, clean_weights)
112
- return {
113
- "min": min(clean_values),
114
- "max": max(clean_values),
115
- "volume_mean": float(mean),
116
- } if mean is not None else {}
117
-
118
-
119
- def bounds(centres: list[tuple[float, float, float]]) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
120
- return (
121
- tuple(min(point[axis] for point in centres) for axis in range(3)),
122
- tuple(max(point[axis] for point in centres) for axis in range(3)),
123
- )
124
-
125
-
126
- def normalized_point(centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> tuple[float, float, float]:
127
- low, high = bounds(centres)
128
- return tuple(low[axis] + fraction[axis] * (high[axis] - low[axis]) for axis in range(3))
129
-
130
-
131
- def nearest_index(centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> int:
132
- target = normalized_point(centres, fraction)
133
- low, high = bounds(centres)
134
- scale = [max(high[axis] - low[axis], 1e-12) for axis in range(3)]
135
- return min(
136
- range(len(centres)),
137
- key=lambda index: sum(((centres[index][axis] - target[axis]) / scale[axis]) ** 2 for axis in range(3)),
138
- )
139
-
140
-
141
- def scalar_probe(values: list[float], centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> float | None:
142
- return values[nearest_index(centres, fraction)] if len(values) == len(centres) else None
143
-
144
-
145
- def speed_probe(velocities: list[tuple[float, float, float]], centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> float | None:
146
- if len(velocities) != len(centres):
147
- return None
148
- x, y, z = velocities[nearest_index(centres, fraction)]
149
- return math.sqrt(x * x + y * y + z * z)
150
-
151
-
152
- def probe_drop(values: list[float], centres: list[tuple[float, float, float]]) -> float | None:
153
- upstream = scalar_probe(values, centres, (0.2, 0.5, 0.5))
154
- downstream = scalar_probe(values, centres, (0.8, 0.5, 0.5))
155
- return upstream - downstream if upstream is not None and downstream is not None else None
156
-
157
-
158
- def pressure_ratio(pressures: list[float]) -> float | None:
159
- positive = [value for value in pressures if math.isfinite(value) and value > 1e-12]
160
- return max(positive) / min(positive) if positive else None
161
-
162
-
163
- def thermo_parameters(case_dir: Path) -> tuple[float, float]:
164
- text = read_text(case_dir / "constant" / "physicalProperties")
165
- mol_weight_match = re.search(r"(?m)^\s*molWeight\s+([-+0-9.eE]+)\s*;", text)
166
- cp_match = re.search(r"(?m)^\s*Cp\s+([-+0-9.eE]+)\s*;", text)
167
- if not mol_weight_match or not cp_match:
168
- return 1.4, 0.7143
169
- mol_weight = float(mol_weight_match.group(1))
170
- cp = float(cp_match.group(1))
171
- gas_constant = 8314.46261815324 / mol_weight if mol_weight > 0 else 0.0
172
- gamma = cp / (cp - gas_constant) if cp > gas_constant else 1.4
173
- return gamma, gas_constant if gas_constant > 0 else 0.7143
174
-
175
-
176
- def mach_values(
177
- velocities: list[tuple[float, float, float]],
178
- temperatures: list[float],
179
- gamma: float,
180
- gas_constant: float,
181
- ) -> list[float]:
182
- if len(temperatures) == 1 and velocities:
183
- temperatures = temperatures * len(velocities)
184
- if len(velocities) != len(temperatures):
185
- return []
186
- return [
187
- speed / math.sqrt(gamma * gas_constant * temperature)
188
- for speed, temperature in zip(magnitude(velocities), temperatures)
189
- if temperature > 0 and math.isfinite(temperature)
190
- ]
191
-
192
-
193
- def shock_location(pressures: list[float], centres: list[tuple[float, float, float]]) -> float | None:
194
- if len(pressures) != len(centres) or len(pressures) < 2:
195
- return None
196
- low, high = bounds(centres)
197
- y_span = max(high[1] - low[1], 1e-12)
198
- z_span = max(high[2] - low[2], 1e-12)
199
- y_mid = 0.5 * (low[1] + high[1])
200
- z_mid = 0.5 * (low[2] + high[2])
201
- selected = [
202
- (point[0], value)
203
- for point, value in zip(centres, pressures)
204
- if abs(point[1] - y_mid) <= 0.08 * y_span and abs(point[2] - z_mid) <= 0.51 * z_span
205
- ]
206
- selected.sort()
207
- if len(selected) < 2:
208
- return None
209
- best_x, best_gradient = None, -1.0
210
- for (x0, p0), (x1, p1) in zip(selected, selected[1:]):
211
- dx = x1 - x0
212
- if dx <= 1e-12:
213
- continue
214
- gradient = abs(p1 - p0) / dx
215
- if gradient > best_gradient:
216
- best_x, best_gradient = 0.5 * (x0 + x1), gradient
217
- return best_x
218
-
219
-
220
- def phase_front(alpha: list[float], centres: list[tuple[float, float, float]]) -> float | None:
221
- wet = [point[0] for value, point in zip(alpha, centres) if value >= 0.5]
222
- return max(wet) if wet else None
223
-
224
-
225
- def add_metric(target: dict[str, float], name: str, value: float | None) -> None:
226
- if value is not None and math.isfinite(value):
227
- target[name] = float(value)
228
-
229
-
230
- def family_metrics(
231
- case_dir: Path,
232
- template: str,
233
- scalars: dict[str, list[float]],
234
- velocities: list[tuple[float, float, float]],
235
- vorticity: list[tuple[float, float, float]],
236
- centres: list[tuple[float, float, float]],
237
- volumes: list[float],
238
- ) -> tuple[str, dict[str, float]]:
239
- metrics: dict[str, float] = {}
240
- speed = magnitude(velocities)
241
- vort_mag = magnitude(vorticity)
242
- pressures = scalars.get("p", [])
243
- temperatures = scalars.get("T", [])
244
- gamma, gas_constant = thermo_parameters(case_dir)
245
- mach = mach_values(velocities, temperatures, gamma, gas_constant)
246
-
247
- if template == "BernardCells":
248
- group = "thermal_state"
249
- stats = weighted_stats(temperatures, volumes)
250
- add_metric(metrics, "T_volume_mean", stats.get("volume_mean"))
251
- add_metric(metrics, "T_max", stats.get("max"))
252
- elif template == "Cavity":
253
- group = "cavity_response"
254
- add_metric(metrics, "U_center_probe", speed_probe(velocities, centres, (0.5, 0.5, 0.5)))
255
- add_metric(metrics, "vorticity_volume_mean", weighted_mean(vort_mag, volumes))
256
- elif template == "Cylinder":
257
- group = "wake_response"
258
- add_metric(metrics, "U_wake_probe", speed_probe(velocities, centres, (0.75, 0.5, 0.5)))
259
- add_metric(metrics, "vorticity_volume_mean", weighted_mean(vort_mag, volumes))
260
- elif template == "counterFlowFlame2D":
261
- group = "flame_response"
262
- add_metric(metrics, "T_max", max(temperatures) if temperatures else None)
263
- add_metric(metrics, "CO2_volume_mean", weighted_mean(scalars.get("CO2", []), volumes))
264
- elif template == "damBreakWithObstacle":
265
- group = "free_surface_response"
266
- alpha = scalars.get("alpha.water", [])
267
- add_metric(metrics, "front_position", phase_front(alpha, centres))
268
- add_metric(metrics, "water_volume", sum(value * volume for value, volume in zip(alpha, volumes)))
269
- elif template == "forwardStep":
270
- group = "shock_response"
271
- add_metric(metrics, "shock_location", shock_location(pressures, centres))
272
- add_metric(metrics, "pressure_ratio", pressure_ratio(pressures))
273
- elif template in {"obliqueShock", "wedge", "Shock"}:
274
- group = "shock_response"
275
- add_metric(metrics, "pressure_ratio", pressure_ratio(pressures))
276
- add_metric(metrics, "Mach_volume_mean", weighted_mean(mach, volumes))
277
- elif template == "pitzDaily":
278
- group = "separation_response"
279
- add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres))
280
- add_metric(metrics, "U_downstream_probe", speed_probe(velocities, centres, (0.8, 0.5, 0.5)))
281
- elif template == "shallowWaterWithSquareBump":
282
- group = "surface_response"
283
- heights = scalars.get("h", [])
284
- fluxes = scalars.get("_hU_magnitude", [])
285
- froude = [flux / abs(height) / math.sqrt(9.81 * height) if height > 0 else 0.0 for flux, height in zip(fluxes, heights)]
286
- add_metric(metrics, "h_volume_mean", weighted_mean(heights, volumes))
287
- add_metric(metrics, "Froude_volume_mean", weighted_mean(froude, volumes))
288
- elif template == "squareBend":
289
- group = "bend_response"
290
- add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres))
291
- add_metric(metrics, "Mach_volume_mean", weighted_mean(mach, volumes))
292
- elif template == "Obstacle":
293
- group = "obstacle_response"
294
- add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres))
295
- add_metric(metrics, "U_wake_probe", speed_probe(velocities, centres, (0.8, 0.5, 0.5)))
296
- elif template == "Nozzle":
297
- group = "nozzle_response"
298
- add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres))
299
- add_metric(metrics, "U_outlet_probe", speed_probe(velocities, centres, (0.9, 0.5, 0.5)))
300
- else:
301
- raise ValueError(f"no QoI family template for {template}")
302
- return group, metrics
303
-
304
-
305
- def tolerance(value: float) -> dict[str, float]:
306
- margin = max(abs(value) * 0.15, 1e-8)
307
- return {
308
- "reference_value": value,
309
- "low": value - margin,
310
- "high": value + margin,
311
- "relative_tolerance": 0.15,
312
- "absolute_floor": 1e-8,
313
- }
314
-
315
-
316
- def prepare_case(case_dir: Path) -> dict[str, Any]:
317
- commands = (
318
- ("writeCellCentres",),
319
- ("writeCellVolumes",),
320
- ("vorticity",),
321
- )
322
- records = []
323
- log_path = case_dir / "qoi_postprocess.log"
324
- with log_path.open("w", encoding="utf-8") as log:
325
- for function_name, in commands:
326
- completed = subprocess.run(
327
- ["foamPostProcess", "-case", str(case_dir), "-func", function_name, "-latestTime"],
328
- stdout=log,
329
- stderr=subprocess.STDOUT,
330
- check=False,
331
- text=True,
332
- timeout=300,
333
- )
334
- records.append({"function": function_name, "return_code": completed.returncode})
335
- control_path = case_dir / "system" / "controlDict"
336
- control = read_text(control_path)
337
- if re.search(r"(?m)^\s*writeFormat\s+binary\s*;", control):
338
- set_ascii = subprocess.run(
339
- ["foamDictionary", "-case", str(case_dir), "system/controlDict", "-entry", "writeFormat", "-set", "ascii"],
340
- stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=60,
341
- )
342
- converted = subprocess.run(
343
- ["foamFormatConvert", "-case", str(case_dir), "-latestTime"],
344
- stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=300,
345
- )
346
- restored = subprocess.run(
347
- ["foamDictionary", "-case", str(case_dir), "system/controlDict", "-entry", "writeFormat", "-set", "binary"],
348
- stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=60,
349
- )
350
- records.append({
351
- "function": "convertLatestTimeToAscii",
352
- "return_code": converted.returncode,
353
- "set_ascii_return_code": set_ascii.returncode,
354
- "restore_binary_return_code": restored.returncode,
355
- })
356
- return {"case_dir": str(case_dir), "commands": records}
357
-
358
-
359
- def prepare_all(case_dirs: list[Path], jobs: int) -> list[dict[str, Any]]:
360
- records = []
361
- with ThreadPoolExecutor(max_workers=jobs) as executor:
362
- futures = {executor.submit(prepare_case, case_dir): case_dir for case_dir in case_dirs}
363
- for future in as_completed(futures):
364
- case_dir = futures[future]
365
- try:
366
- records.append(future.result())
367
- except Exception as exc: # keep the other reference cases extractable
368
- records.append({"case_dir": str(case_dir), "error": str(exc)})
369
- return sorted(records, key=lambda record: record["case_dir"])
370
-
371
-
372
- def case_id_from_dir(track: str, case_dir: Path) -> str:
373
- safe = case_dir.parent.name
374
- return safe.replace("__", "/", 1) if track == "basic" else safe
375
-
376
-
377
- def extract_case(track: str, case_dir: Path, execution: dict[tuple[str, str], dict[str, str]]) -> tuple[str, dict[str, Any]]:
378
- case_id = case_id_from_dir(track, case_dir)
379
- template = case_id.split("/", 1)[0] if track == "basic" else ADVANCED_TEMPLATE[case_id]
380
- latest_time, latest = latest_time_dir(case_dir)
381
- if latest is None:
382
- raise ValueError(f"no numeric time directory: {case_dir}")
383
- centres = vector_field(latest, "C")
384
- volumes = scalar_field(latest, "Vc")
385
- if not centres or not volumes:
386
- raise ValueError(f"missing C/Vc post-processing fields: {case_dir}")
387
- volumes = align(volumes, len(centres))
388
- if not volumes:
389
- raise ValueError(f"C/Vc field length mismatch: {case_dir}")
390
-
391
- scalars: dict[str, list[float]] = {}
392
- raw_nonfinite_fields: list[str] = []
393
- for name in COMMON_SCALAR_FIELDS:
394
- path = field_path(latest, name)
395
- if not path:
396
- continue
397
- raw = read_text(path)
398
- if re.search(r"(?i)(?<![A-Za-z])(?:nan|[-+]?inf)(?![A-Za-z])", raw):
399
- raw_nonfinite_fields.append(name)
400
- values = align(parse_scalar_field(path), len(centres))
401
- if values:
402
- scalars[name] = values
403
- velocities = align(vector_field(latest, "U"), len(centres))
404
- vorticity = align(vector_field(latest, "vorticity"), len(centres))
405
- h_u = align(vector_field(latest, "hU"), len(centres))
406
- if h_u:
407
- scalars["_hU_magnitude"] = magnitude(h_u)
408
-
409
- principal_group, principal = family_metrics(case_dir, template, scalars, velocities, vorticity, centres, volumes)
410
- if not principal:
411
- raise ValueError(f"no principal QoI extracted for {case_id}")
412
-
413
- diagnostics, fatal_logs = parse_log_metrics(case_dir)
414
- if velocities:
415
- for suffix, value in weighted_stats(magnitude(velocities), volumes).items():
416
- diagnostics[f"velocity_magnitude_{suffix}"] = value
417
- if vorticity:
418
- for suffix, value in weighted_stats(magnitude(vorticity), volumes).items():
419
- diagnostics[f"vorticity_magnitude_{suffix}"] = value
420
- field_bounds: dict[str, dict[str, float]] = {}
421
- for name, values in sorted(scalars.items()):
422
- if name.startswith("_"):
423
- continue
424
- stats = weighted_stats(values, volumes)
425
- if stats:
426
- field_bounds[name] = stats
427
- positivity_failures = [
428
- name for name in POSITIVE_FIELDS
429
- if name in field_bounds and field_bounds[name]["min"] < -1e-12
430
- ]
431
- if "alpha.water" in field_bounds:
432
- alpha = field_bounds["alpha.water"]
433
- if alpha["min"] < -1e-3 or alpha["max"] > 1 + 1e-3:
434
- positivity_failures.append("alpha.water_bounds")
435
- full_log = read_text(case_dir / "full_run.log")
436
- execution_record = execution.get((track, case_dir.parent.name), {})
437
- health_checks = {
438
- "execution_exit_zero": execution_record.get("exit_code") == "0",
439
- "no_fatal_marker": not fatal_logs and FATAL_RE.search(full_log) is None,
440
- "required_geometry_fields_available": bool(centres and volumes),
441
- "principal_qoi_complete": len(principal) == 2,
442
- "all_parsed_fields_finite": not raw_nonfinite_fields,
443
- "applicable_field_bounds_valid": not positivity_failures,
444
- }
445
- health_pass = all(health_checks.values())
446
- qois = {**principal, **diagnostics}
447
- roles = {name: "principal" for name in principal}
448
- roles.update({name: "diagnostic" for name in diagnostics})
449
- return case_id, {
450
- "track": track,
451
- "family": case_id.split("/", 1)[0] if track == "basic" else template,
452
- "source_case_id": case_id,
453
- "latest_time": latest_time,
454
- "principal_qoi_group": principal_group,
455
- "principal_metrics": sorted(principal),
456
- "qois": dict(sorted(qois.items())),
457
- "metric_roles": dict(sorted(roles.items())),
458
- "tolerances": {name: tolerance(value) for name, value in sorted(principal.items())},
459
- "field_diagnostics": field_bounds,
460
- "health": {
461
- "status": "pass" if health_pass else "fail",
462
- "checks": health_checks,
463
- "nonfinite_fields": raw_nonfinite_fields,
464
- "field_bound_failures": sorted(positivity_failures),
465
- "fatal_logs": fatal_logs,
466
- },
467
- "extraction": {
468
- "geometry": "cellCentres-normalized probes",
469
- "averaging": "cell-volume-weighted",
470
- "reference_run": "anonymous-reference/basic_advanced",
471
- },
472
- }
473
-
474
-
475
- def load_execution_summary(path: Path) -> dict[tuple[str, str], dict[str, str]]:
476
- lines = path.read_text(encoding="utf-8").splitlines()
477
- header = lines[0].split("\t")
478
- records = {}
479
- for line in lines[1:]:
480
- values = line.split("\t")
481
- record = dict(zip(header, values))
482
- records[(record["track"], record["case_id"])] = record
483
- return records
484
-
485
-
486
- def dataset(cases: dict[str, Any], tracks: list[str], run_manifest: dict[str, Any]) -> dict[str, Any]:
487
- selected = {case_id: record for case_id, record in cases.items() if record["track"] in tracks}
488
- family_counts: dict[str, int] = {}
489
- health_pass_count = 0
490
- for record in selected.values():
491
- family_counts[record["family"]] = family_counts.get(record["family"], 0) + 1
492
- health_pass_count += record["health"]["status"] == "pass"
493
- result = {
494
- "schema_version": SCHEMA_VERSION,
495
- "generated_at": utc_now(),
496
- "openfoam_version": "Foundation v13",
497
- "producer": "benchmarks/evaluation/qoi_reference.py",
498
- "design": "guide/foambench_basic_advanced_qoi_design.md",
499
- "tolerance_policy": TOLERANCE_POLICY,
500
- "source_run_manifest": run_manifest,
501
- "summary": {
502
- "tracks": tracks,
503
- "case_count": len(selected),
504
- "health_pass_count": health_pass_count,
505
- "health_fail_count": len(selected) - health_pass_count,
506
- "family_counts": dict(sorted(family_counts.items())),
507
- },
508
- "notes": [
509
- "Reference values come from the completed fixed-final OpenFOAM Foundation v13 run.",
510
- "Principal QoIs are family-defined; reference values and tolerances are case-specific.",
511
- "Generic field and solver statistics are diagnostics and do not receive principal-QoI weight.",
512
- "The 15% intervals are initial benchmark-consistency tolerances and should be refined with repeatability evidence.",
513
- ],
514
- "cases": dict(sorted(selected.items())),
515
- }
516
- validate(result, "foambench_qoi_reference.schema.json")
517
- return result
518
-
519
-
520
- def main() -> int:
521
- parser = argparse.ArgumentParser(description=__doc__)
522
- parser.add_argument("--run-root", type=Path, required=True)
523
- parser.add_argument("--output", type=Path, required=True)
524
- parser.add_argument("--basic-output", type=Path)
525
- parser.add_argument("--advanced-output", type=Path)
526
- parser.add_argument("--prepare-fields", action="store_true")
527
- parser.add_argument("--jobs", type=int, default=min(16, os.cpu_count() or 1))
528
- args = parser.parse_args()
529
-
530
- run_root = args.run_root.resolve(strict=True)
531
- materialized = run_root / "materialized"
532
- case_dirs = [
533
- path for track in ("basic", "advanced")
534
- for path in sorted((materialized / track).glob("*/case"))
535
- ]
536
- if len(case_dirs) != 126:
537
- raise ValueError(f"expected 126 materialized cases, found {len(case_dirs)}")
538
- if args.prepare_fields:
539
- preparation = prepare_all(case_dirs, max(1, args.jobs))
540
- write_json(run_root / "qoi_postprocess_summary.json", preparation)
541
-
542
- from benchmarks.evaluation.basic_advanced import build_references
543
-
544
- basic, advanced = build_references(run_root)
545
- combined = {
546
- **{key: value for key, value in basic.items() if key not in {"cases", "summary"}},
547
- "summary": {
548
- "tracks": ["basic", "advanced"],
549
- "case_count": len(basic["cases"]) + len(advanced["cases"]),
550
- "health_pass_count": len(basic["cases"]) + len(advanced["cases"]),
551
- "health_fail_count": 0,
552
- },
553
- "cases": {**basic["cases"], **advanced["cases"]},
554
- }
555
- validate(combined, "foambench_qoi_reference.schema.json")
556
- write_json(args.output, combined)
557
- if args.basic_output:
558
- write_json(args.basic_output, basic)
559
- if args.advanced_output:
560
- write_json(args.advanced_output, advanced)
561
- print(json.dumps(combined["summary"], ensure_ascii=False, indent=2))
562
- return 0
563
-
564
-
565
- if __name__ == "__main__":
566
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/reference.py DELETED
@@ -1,44 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from .models import BenchmarkProfile
6
-
7
-
8
- def reference_case_dir(profile: BenchmarkProfile, case_id: str) -> Path | None:
9
- root = profile.reference_run_root
10
- if root is None or not root.is_dir():
11
- return None
12
- safe = case_id.replace("/", "__")
13
- if profile.dataset in {"basic", "advanced"}:
14
- candidate = root / profile.dataset / safe / "case"
15
- return candidate if candidate.is_dir() else None
16
- parent = root / safe
17
- for name in ("full_run_case", "case"):
18
- candidate = parent / name
19
- if candidate.is_dir():
20
- return candidate
21
- return None
22
-
23
-
24
- def reference_log_paths(profile: BenchmarkProfile, case_id: str) -> tuple[Path, ...]:
25
- case = reference_case_dir(profile, case_id)
26
- return tuple(sorted(path for path in case.glob("log.*") if path.is_file())) if case else ()
27
-
28
-
29
- def reference_statistics(profile: BenchmarkProfile, case_id: str) -> dict | None:
30
- """Load compact reference diagnostics without a historical simulation tree."""
31
- import json
32
- from .numerical import DEFAULT_CONTRACT
33
- name = profile.numerical_contract.get("reference_statistics_path")
34
- if not name:
35
- return None
36
- path = Path(name)
37
- if not path.is_absolute():
38
- path = profile.benchmark_path.parent.parent / path
39
- data = json.loads(path.read_text(encoding="utf-8"))
40
- if data.get("parser_contract") != DEFAULT_CONTRACT:
41
- raise ValueError("Reference statistics parser contract differs from evaluator")
42
- if case_id not in data["cases"]:
43
- raise ValueError(f"Missing reference statistics for {case_id}")
44
- return data["cases"][case_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/reporting.py DELETED
@@ -1,89 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import csv
4
- from pathlib import Path
5
- from typing import Any
6
-
7
-
8
- CASE_COLUMNS = (
9
- "case_id", "dataset", "family", "variant", "replicate",
10
- "execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass",
11
- "qoi_status", "qoi_pass_ratio", "failure_categories",
12
- "duration_seconds", "input_tokens", "output_tokens",
13
- )
14
-
15
-
16
- def _token(usage: dict[str, Any], *names: str) -> Any:
17
- for name in names:
18
- if isinstance(usage.get(name), (int, float)):
19
- return usage[name]
20
- return ""
21
-
22
-
23
- def case_csv_row(result: dict[str, Any]) -> dict[str, Any]:
24
- scores = result["scores"]
25
- qoi = result["qoi"]
26
- resources = result.get("resources", {})
27
- usage = resources.get("token_usage") if isinstance(resources.get("token_usage"), dict) else {}
28
- return {
29
- "case_id": result["case_id"],
30
- "dataset": result["dataset"],
31
- "family": result["family"],
32
- "variant": result["variant"],
33
- "replicate": result["replicate"],
34
- "execution_pass": scores["execution_pass"],
35
- "numerical_pass": scores["numerical_pass"],
36
- "physics_grounded_qoi_pass": scores["physics_grounded_qoi_pass"],
37
- "end_to_end_pass": scores["end_to_end_pass"],
38
- "qoi_status": qoi.get("status", ""),
39
- "qoi_pass_ratio": qoi.get("effective_pass_ratio", ""),
40
- "failure_categories": ";".join(result.get("failure_categories", [])),
41
- "duration_seconds": resources.get("duration_seconds") or "",
42
- "input_tokens": _token(usage, "input_tokens", "prompt_tokens"),
43
- "output_tokens": _token(usage, "output_tokens", "completion_tokens"),
44
- }
45
-
46
-
47
- def write_case_csv(path: Path, results: list[dict[str, Any]]) -> None:
48
- path.parent.mkdir(parents=True, exist_ok=True)
49
- temporary = path.with_name(path.name + ".tmp")
50
- with temporary.open("w", encoding="utf-8", newline="") as stream:
51
- writer = csv.DictWriter(stream, fieldnames=CASE_COLUMNS)
52
- writer.writeheader()
53
- writer.writerows(case_csv_row(result) for result in results)
54
- temporary.replace(path)
55
-
56
-
57
- SUMMARY_COLUMNS = (
58
- "scope", "task_count", "execution_pass_count", "execution_pass_rate",
59
- "numerical_pass_count", "numerical_pass_rate_all_tasks",
60
- "physics_grounded_qoi_pass_count", "physics_grounded_qoi_pass_rate_all_tasks",
61
- "end_to_end_pass_count", "end_to_end_pass_rate",
62
- )
63
-
64
-
65
- def write_summary_csv(path: Path, overall: dict[str, Any], families: dict[str, Any]) -> None:
66
- path.parent.mkdir(parents=True, exist_ok=True)
67
- temporary = path.with_name(path.name + ".tmp")
68
- with temporary.open("w", encoding="utf-8", newline="") as stream:
69
- writer = csv.DictWriter(stream, fieldnames=SUMMARY_COLUMNS)
70
- writer.writeheader()
71
- for scope, summary in [("overall", overall), *sorted(families.items())]:
72
- writer.writerow({"scope": scope, **{key: summary.get(key) for key in SUMMARY_COLUMNS[1:]}})
73
- temporary.replace(path)
74
-
75
-
76
- def summary_table(summary: dict[str, Any]) -> str:
77
- total = int(summary["task_count"])
78
- rows = (
79
- ("Execution", "execution_pass_count", "execution_pass_rate"),
80
- ("Numerical", "numerical_pass_count", "numerical_pass_rate_all_tasks"),
81
- ("QoI", "physics_grounded_qoi_pass_count", "physics_grounded_qoi_pass_rate_all_tasks"),
82
- ("End-to-end", "end_to_end_pass_count", "end_to_end_pass_rate"),
83
- )
84
- lines = ["Metric Passed Rate", "----------- ----------- --------"]
85
- for label, count_key, rate_key in rows:
86
- rate = summary.get(rate_key)
87
- rendered = "n/a" if rate is None else f"{float(rate) * 100:.2f}%"
88
- lines.append(f"{label:<11} {int(summary[count_key]):>4}/{total:<6} {rendered:>8}")
89
- return "\n".join(lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/retained_fields.py DELETED
@@ -1,304 +0,0 @@
1
- """Reference-free measurements from retained OpenFOAM fields and static meshes.
2
-
3
- No subprocesses, field writes, fitted constants, or reference values. Unsupported
4
- encodings/BCs/meshes fail closed instead of substituting a different observable.
5
- """
6
- from __future__ import annotations
7
-
8
- import math
9
- import re
10
- import struct
11
- from pathlib import Path
12
-
13
- import numpy as np
14
-
15
- from .foam_arrays import _bytes, _format, _arch, foam_path, read_label_list, read_vector_list, read_scalar_field
16
-
17
-
18
- def _body(data: bytes) -> bytes:
19
- marker = data.find(b"// * * *")
20
- if marker < 0:
21
- raise ValueError("mesh header separator absent")
22
- return data[data.index(b"\n", marker) + 1:]
23
-
24
-
25
- def _binary_list(data: bytes, code: str, endian: str) -> tuple[list, bytes]:
26
- match = re.match(rb"\s*(\d+)\s*\(", data)
27
- if not match:
28
- raise ValueError("binary list header absent")
29
- count = int(match[1])
30
- start = match.end() # Do not strip bytes: 0x0a/0x20 can be data.
31
- end = start + count * struct.calcsize(endian + code)
32
- tail = data[end:]
33
- if not tail.startswith(b")"):
34
- raise ValueError("truncated binary list or invalid terminator")
35
- return list(struct.unpack(f"{endian}{count}{code}", data[start:end])), tail[1:]
36
-
37
-
38
- def read_faces(path: Path) -> list[list[int]]:
39
- data = _bytes(path)
40
- body = _body(data)
41
- if _format(data) == "binary":
42
- if not re.search(rb"class\s+faceCompactList\s*;", data[:data.find(b"// * * *")]):
43
- raise ValueError("only faceCompactList binary faces are supported")
44
- endian, labels, _ = _arch(data)
45
- code = "i" if labels == 32 else "q"
46
- offsets, tail = _binary_list(body, code, endian)
47
- indices, _ = _binary_list(tail, code, endian)
48
- if not offsets or offsets[0] != 0 or offsets[-1] != len(indices):
49
- raise ValueError("invalid compact face offsets")
50
- if any(b - a < 3 for a, b in zip(offsets, offsets[1:])):
51
- raise ValueError("invalid face size")
52
- return [indices[a:b] for a, b in zip(offsets, offsets[1:])]
53
- match = re.match(rb"\s*(\d+)\s*\(", body)
54
- if not match:
55
- raise ValueError("face list header absent")
56
- faces = []
57
- position = match.end()
58
- face_pattern = re.compile(rb"\s*(\d+)\s*\(([^()]*)\)")
59
- for _ in range(int(match[1])):
60
- row = face_pattern.match(body, position)
61
- if not row:
62
- raise ValueError("invalid ASCII face")
63
- face = [int(x) for x in row[2].split()]
64
- if len(face) != int(row[1]) or len(face) < 3:
65
- raise ValueError("face length mismatch")
66
- faces.append(face)
67
- position = row.end()
68
- if not body[position:].lstrip().startswith(b")"):
69
- raise ValueError("face count mismatch")
70
- return faces
71
-
72
-
73
- def static_mesh(case: Path) -> bool:
74
- if (case / "constant/dynamicMeshDict").exists():
75
- return False
76
- # OpenFOAM 13 can configure motion/topology changes in constant/polyMesh.
77
- if any((case / "constant/polyMesh" / name).exists() for name in ("mover", "topoChanger", "distributor")):
78
- return False
79
- return not any(path.is_dir() and (path / "polyMesh").exists()
80
- for path in case.iterdir() if _is_time(path.name))
81
-
82
-
83
- def _is_time(value: str) -> bool:
84
- try:
85
- return math.isfinite(float(value))
86
- except ValueError:
87
- return False
88
-
89
-
90
- def mesh_arrays(case: Path):
91
- mesh = case / "constant/polyMesh"
92
- paths = [foam_path(mesh, name) for name in ("points", "faces", "owner", "neighbour")]
93
- if any(path is None for path in paths):
94
- raise ValueError("incomplete retained polyMesh")
95
- points = np.asarray(read_vector_list(paths[0]), dtype=float)
96
- faces = read_faces(paths[1])
97
- owner = np.asarray(read_label_list(paths[2]), dtype=int)
98
- neighbour = np.asarray(read_label_list(paths[3]), dtype=int)
99
- if len(owner) != len(faces) or len(neighbour) > len(owner) or not len(owner):
100
- raise ValueError("mesh topology length mismatch")
101
- if np.min(owner) < 0 or (len(neighbour) and (np.min(neighbour) < 0 or np.max(neighbour) > np.max(owner))):
102
- raise ValueError("invalid cell indices")
103
- if not np.isfinite(points).all() or any(min(face) < 0 or max(face) >= len(points) for face in faces):
104
- raise ValueError("invalid mesh points/face indices")
105
- return points, faces, owner, neighbour, paths
106
-
107
-
108
- def planar_face_geometry(points, faces):
109
- """Oriented area and volume moments, grouped by face size for bounded cost."""
110
- origin = points.mean(axis=0)
111
- vectors = np.zeros((len(faces), 3))
112
- volumes = np.zeros(len(faces))
113
- moments = np.zeros((len(faces), 3))
114
- sizes = {}
115
- for i, face in enumerate(faces):
116
- sizes.setdefault(len(face), []).append(i)
117
- for size, ids in sizes.items():
118
- vertices = points[np.asarray([faces[i] for i in ids])] - origin
119
- center = vertices.mean(axis=1)
120
- nxt = np.roll(vertices, -1, axis=1)
121
- triangles = np.cross(vertices - center[:, None], nxt - center[:, None]) / 2
122
- area = triangles.sum(axis=1)
123
- norms = np.linalg.norm(area, axis=1)
124
- if np.any(norms <= 0):
125
- raise ValueError("degenerate face")
126
- distances = np.abs(np.einsum('fvi,fi->fv', vertices - center[:, None], area)) / norms[:, None]
127
- scale = np.max(np.linalg.norm(vertices - center[:, None], axis=2), axis=1)
128
- if np.any(distances > 1e-8 * scale[:, None]):
129
- raise ValueError("nonplanar face: native geometry evidence required")
130
- # Signed tetrahedra (origin, face center, edge endpoints).
131
- tetra = np.einsum('fi,fvi->fv', center, np.cross(vertices, nxt)) / 6
132
- vectors[ids] = area
133
- volumes[ids] = tetra.sum(axis=1)
134
- moments[ids] = np.sum(tetra[:, :, None] * (center[:, None] + vertices + nxt) / 4, axis=1)
135
- return origin, vectors, volumes, moments
136
-
137
-
138
- def derive_cell_geometry(case: Path):
139
- if not static_mesh(case):
140
- raise ValueError("static geometry derivation disabled for changing meshes")
141
- points, faces, owner, neighbour, paths = mesh_arrays(case)
142
- origin, areas, face_volumes, face_moments = planar_face_geometry(points, faces)
143
- count = int(owner.max()) + 1
144
- volumes = np.zeros(count)
145
- moments = np.zeros((count, 3))
146
- closure = np.zeros((count, 3))
147
- surface = np.zeros(count)
148
- for cells, sign, sl in ((owner, 1, slice(None)), (neighbour, -1, slice(0, len(neighbour)))):
149
- np.add.at(volumes, cells, sign * face_volumes[sl])
150
- np.add.at(moments, cells, sign * face_moments[sl])
151
- np.add.at(closure, cells, sign * areas[sl])
152
- np.add.at(surface, cells, np.linalg.norm(areas[sl], axis=1))
153
- if np.any(volumes <= 0) or not np.isfinite(volumes).all():
154
- raise ValueError("nonpositive/nonfinite reconstructed cell volume")
155
- if np.any(np.linalg.norm(closure, axis=1) > 1e-9 * surface):
156
- raise ValueError("cell face surface does not close")
157
- centers = moments / volumes[:, None] + origin
158
- if not np.isfinite(centers).all():
159
- raise ValueError("nonfinite cell centers")
160
- return volumes.tolist(), [tuple(row) for row in centers.tolist()], paths
161
-
162
-
163
- def boundary_specs(case: Path) -> dict:
164
- path = foam_path(case / "constant/polyMesh", "boundary")
165
- if path is None:
166
- raise ValueError("boundary file absent")
167
- text = _body(_bytes(path)).decode('ascii')
168
- result = {}
169
- for name, block in re.findall(r'([\w]+)\s*\{([^{}]*)\}', text):
170
- start = re.search(r'\bstartFace\s+(\d+)\s*;', block)
171
- size = re.search(r'\bnFaces\s+(\d+)\s*;', block)
172
- if start and size:
173
- result[name] = (int(start[1]), int(size[1]))
174
- return result
175
-
176
-
177
- def scalar_boundary(path: Path, patch: str, owners: list[int]) -> tuple[list[float], str]:
178
- data = _bytes(path)
179
- # Locate boundaryField after the internal payload, never inside binary data.
180
- internal = re.search(rb'internalField\s+nonuniform\s+List<scalar>\s*', data)
181
- if internal and _format(data) == 'binary':
182
- endian, _, bits = _arch(data)
183
- _, tail = _binary_list(data[internal.end():], 'f' if bits == 32 else 'd', endian)
184
- else:
185
- tail = data
186
- anchor = re.search(rb'\bboundaryField\s*\{', tail)
187
- if anchor is None:
188
- raise ValueError('boundaryField absent')
189
- tail = tail[anchor.end():]
190
- # Replace length-delimited binary lists before parsing braces. Binary bytes
191
- # may themselves contain braces, newlines or apparent dictionary keywords.
192
- arrays = {}
193
- if _format(data) == 'binary':
194
- endian, _, bits = _arch(data)
195
- parts = []
196
- while (match := re.search(rb'nonuniform\s+List<scalar>\s*', tail)) is not None:
197
- values, rest = _binary_list(tail[match.end():], 'f' if bits == 32 else 'd', endian)
198
- key = f'__array_{len(arrays)}'
199
- arrays[key] = values
200
- parts.append(tail[:match.start()] + key.encode())
201
- tail = rest
202
- tail = b''.join(parts) + tail
203
- text = tail.decode('ascii')
204
- blocks = dict(re.findall(r'([\w]+)\s*\{([^{}]*)\}', text))
205
- block = blocks.get(patch)
206
- if block is None:
207
- raise ValueError(f'patch {patch} has no explicit dictionary')
208
- bc = re.search(r'\btype\s+(\w+)\s*;', block)
209
- uniform = re.search(r'\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;', block)
210
- stored = re.search(r'\bvalue\s+(__array_\d+)\s*;', block)
211
- listed = re.search(r'\bvalue\s+nonuniform\s+List<scalar>\s+(\d+)\s*\(([^()]*)\)\s*;', block)
212
- if uniform:
213
- values, method = [float(uniform[1])] * len(owners), 'stored_boundary_value'
214
- elif stored:
215
- values, method = arrays[stored[1]], 'stored_boundary_value'
216
- elif listed:
217
- values, method = [float(x) for x in listed[2].split()], 'stored_boundary_value'
218
- if len(values) != int(listed[1]):
219
- raise ValueError('boundary list length mismatch')
220
- elif bc and bc[1] == 'zeroGradient' and path.name.removesuffix('.gz') == 'p':
221
- internal_values = read_scalar_field(path)
222
- if re.search(rb'internalField\s+uniform\s+', data):
223
- values = internal_values * len(owners)
224
- else:
225
- values = [internal_values[i] for i in owners]
226
- method = 'zeroGradient_exact_owner_value'
227
- else:
228
- raise ValueError(f'{patch}: unsupported boundary without stored values')
229
- if len(values) != len(owners) or not all(math.isfinite(x) for x in values):
230
- raise ValueError('boundary value count/nonfinite mismatch')
231
- return values, method
232
-
233
-
234
- def dimensions(path: Path) -> str | None:
235
- match = re.search(rb'\bdimensions\s*\[([^]]+)\]', _bytes(path)[:4096])
236
- return ' '.join(match[1].decode('ascii').split()) if match else None
237
-
238
-
239
- def pump_measurements(case: Path) -> tuple[dict, dict, list[str]]:
240
- """All retained positive times, with signed inlet phi and boundary p.
241
-
242
- Only the unique inlet/outlet names (case insensitive) are recognized. No
243
- reference times or values enter extraction; time alignment is comparator work.
244
- """
245
- values, evidence, errors = {}, {}, []
246
- try:
247
- if not static_mesh(case):
248
- raise ValueError('pump retained-field fallback requires a static mesh')
249
- points, faces, owner, _, paths = mesh_arrays(case)
250
- _, vectors, _, _ = planar_face_geometry(points, faces)
251
- areas = np.linalg.norm(vectors, axis=1)
252
- specs = boundary_specs(case)
253
- names = {}
254
- for role in ('inlet', 'outlet'):
255
- matches = [name for name in specs if name.lower() == role]
256
- if len(matches) != 1:
257
- raise ValueError(f'ambiguous or absent {role} patch')
258
- names[role] = matches[0]
259
- slices = {role: slice(specs[name][0], sum(specs[name])) for role, name in names.items()}
260
- if any(sl.stop > len(owner) or sl.start == sl.stop for sl in slices.values()):
261
- raise ValueError('invalid inlet/outlet face range')
262
- except (OSError, ValueError, RuntimeError) as exc:
263
- return {}, {}, [str(exc)]
264
- histories = {'mass_flow_rate': [], 'pressure_rise': []}
265
- phi_dimension: str | None = None
266
- refs = {key: set() for key in histories}
267
- boundary = foam_path(case / 'constant/polyMesh', 'boundary')
268
- mesh_refs = [str(p.relative_to(case)) for p in [*paths, boundary] if p]
269
- for directory in sorted((p for p in case.iterdir() if p.is_dir() and _is_time(p.name) and float(p.name) > 0), key=lambda p: float(p.name)):
270
- for metric, field in (('mass_flow_rate', 'phi'), ('pressure_rise', 'p')):
271
- path = foam_path(directory, field)
272
- if path is None:
273
- continue
274
- try:
275
- actual_dimensions = dimensions(path)
276
- allowed_dimensions = (
277
- {'1 0 -1 0 0 0 0', '0 3 -1 0 0 0 0'} if field == 'phi'
278
- else {'1 -1 -2 0 0 0 0', '0 2 -2 0 0 0 0'}
279
- )
280
- if actual_dimensions not in allowed_dimensions:
281
- raise ValueError('unsupported physical dimensions')
282
- if field == 'phi':
283
- phi_dimension = actual_dimensions
284
- inlet, _ = scalar_boundary(path, names['inlet'], owner[slices['inlet']].tolist())
285
- if field == 'phi':
286
- value = math.fsum(inlet)
287
- else:
288
- outlet, _ = scalar_boundary(path, names['outlet'], owner[slices['outlet']].tolist())
289
- value = float(np.average(outlet, weights=areas[slices['outlet']]) - np.average(inlet, weights=areas[slices['inlet']]))
290
- histories[metric].append({'time': float(directory.name), 'value': value})
291
- refs[metric].add(str(path.relative_to(case)))
292
- except (OSError, ValueError, RuntimeError, IndexError) as exc:
293
- errors.append(f'{directory.name}/{field}: {exc}')
294
- for metric, history in histories.items():
295
- if history:
296
- values[metric] = {'kind': 'time_history', 'quantity': (
297
- 'explicit_mass_flow' if phi_dimension == '1 0 -1 0 0 0 0' else 'explicit_volumetric_flow'
298
- ) if metric == 'mass_flow_rate' else 'pressure_rise', 'points': history}
299
- if metric == 'mass_flow_rate':
300
- values[metric]['field_dimensions'] = phi_dimension
301
- else:
302
- values[metric].update(definition='outlet_minus_inlet_patch_average', source_patches=names)
303
- evidence[metric] = sorted(refs[metric] | set(mesh_refs))
304
- return values, evidence, errors
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/schema.py DELETED
@@ -1,21 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
- from typing import Any
5
-
6
- from jsonschema import Draft202012Validator, FormatChecker
7
-
8
- from .io import read_object
9
-
10
-
11
- SCHEMA_ROOT = Path(__file__).resolve().parents[2] / "schemas"
12
-
13
-
14
- def validate(value: Any, schema_name: str) -> None:
15
- schema = read_object(SCHEMA_ROOT / schema_name)
16
- validator = Draft202012Validator(schema, format_checker=FormatChecker())
17
- errors = sorted(validator.iter_errors(value), key=lambda error: list(error.absolute_path))
18
- if errors:
19
- error = errors[0]
20
- location = ".".join(str(item) for item in error.absolute_path) or "<root>"
21
- raise ValueError(f"{schema_name} validation failed at {location}: {error.message}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
benchmarks/evaluation/stability.py DELETED
@@ -1,48 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import math
4
- import re
5
- from pathlib import Path
6
- from typing import Any
7
-
8
- from .foam_io import read_text
9
-
10
-
11
- def numerical_scheme(case_dir: Path) -> str:
12
- block = re.search(r"ddtSchemes\s*\{(?P<body>.*?)\}", read_text(case_dir / "system/fvSchemes"), re.S)
13
- default = re.search(r"\bdefault\s+([^;\s]+)", block.group("body")) if block else None
14
- return default.group(1) if default else "unknown"
15
-
16
-
17
- def steady_plateau(
18
- qois: dict[str, Any],
19
- baseline_spans: dict[str, float] | None = None,
20
- *,
21
- final_window_fraction: float = 0.2,
22
- minimum_snapshots: int = 3,
23
- ) -> dict[str, Any]:
24
- metrics = {}
25
- passed = True
26
- for name, value in sorted(qois.items()):
27
- if not isinstance(value, dict) or value.get("kind") != "time_history":
28
- continue
29
- points = value.get("points", [])
30
- samples = [float(point["value"]) for point in points if isinstance(point, dict)
31
- and isinstance(point.get("value"), (int, float))]
32
- if len(samples) < minimum_snapshots:
33
- metrics[name] = {"status": "fail", "sample_count": len(samples), "expected_minimum": minimum_snapshots}
34
- passed = False
35
- continue
36
- count = max(minimum_snapshots, math.ceil(len(samples) * final_window_fraction))
37
- selected = samples[-count:]
38
- span = (max(selected) - min(selected)) / max(abs(selected[-1]), 1e-12)
39
- limit = max(0.02, (baseline_spans or {}).get(name, 0.0) * 2.0)
40
- ok = span <= limit
41
- metrics[name] = {"status": "pass" if ok else "fail", "relative_span": span,
42
- "limit": limit, "sample_count": count}
43
- passed = passed and ok
44
- return {
45
- "status": "pass" if metrics and passed else "fail" if metrics else "not_applicable",
46
- "applicable": bool(metrics),
47
- "metrics": metrics,
48
- }