diff --git a/GUIDE.md b/GUIDE.md new file mode 100644 index 0000000000000000000000000000000000000000..b2e2b171233dfcd94bea4b47440212ce420ee943 --- /dev/null +++ b/GUIDE.md @@ -0,0 +1,71 @@ +# Usage guide / 使用指南 + +[English overview](README.md) · [中文介绍](README_zh.md) + +## Files and task identity / 文件与任务标识 + +`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. + +`data/extended.jsonl` 是 100 条 Ext 原创任务的索引,包含上述字段。使用 `(track, case_id)` 与参考 QoI、数值统计中的 `cases` 条目对应;Basic/Advanced 采用相同格式,并注明上游来源。 + +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. + +参考输入 JSON 保存 OpenFOAM 文件内容,部分 Ext 任务还包含多个参考分支。几何声明通过资产清单关联文件。参考输入与答案应置于求解智能体无法读取的位置。 + +## Optional evaluator / 可选评估器 + +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. + +评估器、格式定义和脚本集中在工具包中。请将其**解压到下载的仓库根目录**,保留相对路径。使用 Python 3.11/3.12 和独立评估环境,避免与最新 HF 数据加载依赖的 NumPy 版本冲突。 + +```bash +python -m zipfile -e tools/evaluation-tools.zip . +python -m pip install -r requirements.txt +python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json +python examples/inspect_task.py --track extended --case-id nozzleCDV/1 +``` + +These commands inspect data without running a model or CFD solver. The inspection output includes evaluator-side information; it is not an agent prompt. + +上述命令只检查数据,不调用模型或 CFD 求解器。任务查看命令包含评价侧信息,不应直接作为智能体提示词。 + +To export one reference input without solving it / 导出一个参考算例输入: + +```bash +python benchmarks/scripts/materialize_benchmark.py --benchmark benchmarks/FoamBench_extended_openfoam13_fixed.json --case-id nozzleCDV/1 --output-root outputs/reference-input +``` + +To evaluate an existing compatible run, replace `/path/to/run` with your retained artifacts / 评价已有运行结果时,将路径换成实际结果目录: + +```bash +python -m benchmarks.evaluation evaluate --profile benchmarks/evaluation/profiles/extended.json --adapter easyfoam --run-root /path/to/run --output outputs/evaluation +``` + +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. + +其他适配器支持上述三种布局,具体输入结构见解压后的目录。完整配置会将未运行任务计为失败,单任务运行不代表完整基准成绩。 + +## Metric fields and protocol / 指标字段与协议 + +| Metric / 指标 | Field under `overall` / 汇总字段 | +| --- | --- | +| ECR | `execution_pass_rate` | +| Numerical acceptance / 数值接受率 | `numerical_pass_rate_all_tasks` | +| QoI acceptance / 物理接受率 | `physics_grounded_qoi_pass_rate_all_tasks` | +| TAR | `end_to_end_pass_rate` | + +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. + +上述比例均以全部指定任务为分母,范围为 0–1。数值和物理接受以执行通过为前提,所有必需准则均需通过;条件通过率和部分质量分数属于辅助信息。Ext 保留原有 `provisional` 容差状态。当前 Basic/Advanced 实现将物理范围/特征作为必需准则,曲线、历史与激波位置作为参考一致性诊断;如需复现历史论文分数,应核对具体版本。空间覆盖按曲线与场的组合统计,执行终止条件允许提前收敛标记。 + +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. + +真实仿真需要 OpenFOAM **Foundation 13**。离线提取通常读取留存数据,但部分测量场或拓扑变化几何需要原生后处理工具。`--prepare` 会写入派生场,`--check-mesh` 可启动网格检查;处理重要运行结果时建议使用副本。 + +## Coverage, provenance and versions / 覆盖、来源与版本 + +- 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 个缺失条目已明确记录。 +- References are simulation-derived. Raw solution fields/logs, historical agent trajectories/checkpoints, and raw repeatability/negative-control/sensitivity experiment archives are not included. / 参考数据由仿真生成;本包未包含完整原始场、日志、历史智能体轨迹/检查点和重复验证、负对照、敏感性实验原始归档。 +- 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,几何来源见资产清单。 +- [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. / 来源清单包含工具包内部文件的哈希;验证报告记录检查结果,无需解压工具即可运行完整性检查。 +- **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 保留原有展开工具目录。报告实验时应同时固定数据和评估器版本。 diff --git a/LICENSE.md b/LICENSE.md index d682a0a2c5fee18d63d5c09604cac57660ab3867..05417748355235a3161cf67b5ea314647badb044 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,12 +1,12 @@ -# Component licenses and attribution - -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. - -| Component | Retained terms / notice | -| --- | --- | -| EasyFoam project code and original project material | Existing project Apache-2.0 license in `LICENSE`, subject to third-party exceptions | -| Inherited FoamBench Basic/Advanced task content | Upstream BSD-3-Clause notice in `LICENSES/FoamBench-BSD-3-Clause.txt`; retain applicable OpenFOAM/other embedded notices | -| 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` | -| Generated task catalogs | Projections of the corresponding task records; preserve their source attribution and applicable terms | - -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. +# Component licenses and attribution + +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. + +| Component | Retained terms / notice | +| --- | --- | +| EasyFoam project code and original project material | Existing project Apache-2.0 license in `LICENSE`, subject to third-party exceptions | +| Inherited FoamBench Basic/Advanced task content | Upstream BSD-3-Clause notice in `LICENSES/FoamBench-BSD-3-Clause.txt`; retain applicable OpenFOAM/other embedded notices | +| 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` | +| Generated task catalogs | Projections of the corresponding task records; preserve their source attribution and applicable terms | + +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. diff --git a/README.md b/README.md index f4316fbde5b257f4f7ef8e647d6f952e5f7f5f84..dc4be2a122c4d8397ca9ce97c907a2bfb4648b68 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ --- -pretty_name: ExtFoamBench — CFD Tasks, Evaluation Protocols and Offline Reference Data +pretty_name: ExtFoamBench — CFD Tasks, Geometry Assets and Evaluation Metrics language: - en license: other @@ -41,130 +41,61 @@ configs: # ExtFoamBench -**100 new CFD tasks, task-specific QoI acceptance rules, and offline reference data for evaluating OpenFOAM agents.** +**English** | [中文介绍](README_zh.md) -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**. +**100 CFD tasks · 7 geometry assets · task-specific physical evaluation** -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. +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**. -## Contributions and attribution +## Core resources -| Component | Task count | Task origin | Contribution in this release | -| --- | ---: | --- | --- | -| **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 | -| 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 | -| FoamBench Advanced | 16 | Existing FoamBench / CFDLLMBench, adapted for OpenFOAM Foundation 13 | Evaluation rules and offline reference data developed/generated by the EasyFoam authors | +| Resource | What it provides | Files | +| --- | --- | --- | +| **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) | +| **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) | +| **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) | -**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. +Each family has a baseline and nine variants: `yPlusVerification`, `risingBubble`, `supersonicCrossJet`, `nozzleCDV`, `MRF_stirredReactor`, `ERCOFTA_pump`, `compressibleBubbleCollapse`, `aerofoilNACA0012`, `drivaerFastback`, and `riemann2D`. -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. +The tasks are developed by the EasyFoam authors. Geometry assets are redistributed from attributed OpenFOAM 13 sources; their original notices are retained. -## ExtFoamBench coverage +## Evaluation -Each of the ten families contains ten tasks: a baseline and nine variants. +A task is assessed along three dimensions: **E** (execution completes), **N** (applicable numerical checks pass), and **Q** (all mandatory physical/QoI criteria pass). -| Family | Physical setting | -| --- | --- | -| `yPlusVerification` | Near-wall resolution and wall-law verification | -| `risingBubble` | Buoyancy-driven two-phase bubble motion | -| `supersonicCrossJet` | Supersonic cross-flow / jet interaction | -| `nozzleCDV` | Compressible converging-diverging nozzle flow | -| `MRF_stirredReactor` | Rotating stirred-reactor flow | -| `ERCOFTA_pump` | Rotating-pump pressure and flow response | -| `compressibleBubbleCollapse` | Compressible bubble-collapse dynamics | -| `aerofoilNACA0012` | Airfoil aerodynamic response | -| `drivaerFastback` | Vehicle external aerodynamics | -| `riemann2D` | Two-dimensional compressible Riemann flow | +- **ECR** = tasks passing E / all assigned tasks. +- **TAR** = tasks passing E, N and Q together / all assigned tasks. -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. +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. -## What is downloaded? +## Use the dataset -| Location | Contents | -| --- | --- | -| `data/*.jsonl` | Hub-readable task catalog: identifiers, original requirements, origin, and permitted geometry identifiers | -| `benchmarks/FoamBench_*_fixed*.json` | Reference case input dictionaries, including OpenFOAM files and any reference subcases | -| `benchmarks/FoamBench_*_reference_qois.json` | Offline reference QoIs, principal metrics, and acceptance tolerances for each track | -| `benchmarks/FoamBench_extended_*measurement_specs.json` | Per-task measurement definitions for ExtFoamBench | -| `benchmarks/FoamBench_extended_*qoi_design.json` | Family/branch QoI design and principal-versus-diagnostic roles | -| `benchmarks/FoamBench_extended_*evidence_contract.v1.json` | Evidence format and discovery contract | -| `benchmarks/reference_statistics/` | Parsed reference residual, Courant, continuity, and related numerical diagnostics | -| `benchmarks/assets/` | Seven geometry assets, original source locations, and SHA-256 checksums | -| `benchmarks/evaluation/`, `schemas/` | Offline evaluation implementation and validation schemas | -| `benchmarks/scripts/` | Reference materialization, extraction, comparison, and asset checking utilities | -| `metadata/` | Version, family coverage, missing-data inventory, and source checksums | -| `docs/` | Data format, evaluation, provenance, and release notes | - -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. - -## Quick start: inspect a task locally - -From the downloaded repository root, using Python 3.11 or 3.12: - -```bash -python examples/inspect_task.py --track extended --case-id nozzleCDV/1 -python scripts/verify_release.py -``` - -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. - -For the Hub task catalog, install `datasets` in a separate environment from the pinned evaluator dependencies, and use: +Install `datasets`, then load the default Extended track: ```python from datasets import load_dataset -tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test") +tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test", revision="v1.1.0") print(len(tasks)) # 100 print(tasks[0]["usr_requirement"]) ``` -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. - -## Quick start: validate the evaluator inputs - -```bash -python -m pip install -r requirements.txt -python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json -python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/basic.json -python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/advanced.json -python benchmarks/scripts/validate_benchmark_assets.py --benchmark benchmarks/FoamBench_extended_openfoam13_fixed.json --manifest benchmarks/assets/manifest.json -``` - -These checks require no OpenFOAM installation. Materialize one **reference input case** without solving it: +To download geometry, criteria and reference data as well: ```bash -python benchmarks/scripts/materialize_benchmark.py --benchmark benchmarks/FoamBench_basic_openfoam13_fixed_final.json --case-id Cavity/1 --output-root outputs/reference-input +hf download Eurus132/ExtFoamBench --repo-type dataset --revision v1.1.0 --local-dir ExtFoamBench ``` -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. - -## Evaluation: execution, numerics, and physics - -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**): - -```text -ECR = count(E passes) / number of assigned tasks -TAR = count(E and N and Q all pass) / number of assigned tasks -``` - -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. - -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. - -## Reference visibility and intended use - -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. - -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. +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. -## Data completeness and versioning +## Supporting resources -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. +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. -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). +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. -## Attribution and licenses +## Citation and licenses -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). +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. -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/`. +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. diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000000000000000000000000000000000000..b58145c5581ae02c5e7272e74ef6550a4d167592 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,60 @@ +# ExtFoamBench + +[English](README.md) | **中文介绍** + +**100 个 CFD 任务 · 7 个几何资产 · 面向任务物理响应的评价体系** + +ExtFoamBench 是 [EasyFoam 论文](https://openreview.net/forum?id=GhQ5YmhU8B)提出的 OpenFOAM 智能体评测基准。本仓库重点提供三部分:**ExtFoamBench 数据集、任务所需的几何资产,以及评价指标与接受准则**。 + +## 核心内容 + +| 资源 | 内容 | 文件入口 | +| --- | --- | --- | +| **ExtFoamBench 数据集** | 10 个任务家族、100 个任务,覆盖工况、几何与网格、物理模型、数值设置和多次运行工作流 | [任务列表](data/extended.jsonl) · [参考算例输入](benchmarks/FoamBench_extended_openfoam13_fixed.json) | +| **几何资产** | 适用于搅拌反应器、翼型和车辆算例的 7 个几何文件,附来源与校验值 | [几何目录](benchmarks/assets/) · [资产清单](benchmarks/assets/manifest.json) | +| **评价指标与准则** | 执行、数值和物理三个维度的评价,以及逐任务 QoI 定义、测量方式、参考比较与容差 | [测量规范](benchmarks/FoamBench_extended_openfoam13_measurement_specs.json) · [QoI 设计](benchmarks/FoamBench_extended_openfoam13_qoi_design.json) · [参考值与容差](benchmarks/FoamBench_extended_openfoam13_reference_qois.json) | + +每个家族包含 1 个基准任务和 9 个变体:`yPlusVerification`、`risingBubble`、`supersonicCrossJet`、`nozzleCDV`、`MRF_stirredReactor`、`ERCOFTA_pump`、`compressibleBubbleCollapse`、`aerofoilNACA0012`、`drivaerFastback` 和 `riemann2D`。 + +任务由 EasyFoam 作者设计。几何资产来自已注明出处的 OpenFOAM 13 资源,保留原有归属与许可说明。 + +## 评价方式 + +每个任务从三个维度评价:**E:执行完成;N:满足适用的数值条件;Q:所有必需的物理量/QoI 准则通过。** + +- **ECR(执行完成率)** = E 通过的任务数 / 全部指定任务数。 +- **TAR(任务接受率)** = E、N、Q 同时通过的任务数 / 全部指定任务数。 + +QoI 准则规定测什么、在哪里和什么时间测、如何比较,以及允许多大误差。缺失输出仍计入任务总数;诊断分数或连续质量分数不能覆盖必需准则的失败。 + +## 使用数据集 + +安装 `datasets` 后,读取默认的 Extended 任务: + +```python +from datasets import load_dataset + +tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test", revision="v1.1.0") +print(len(tasks)) # 100 +print(tasks[0]["usr_requirement"]) +``` + +同时下载几何资产、评价准则和参考数据: + +```bash +hf download Eurus132/ExtFoamBench --repo-type dataset --revision v1.1.0 --local-dir ExtFoamBench +``` + +任务表包含需求和元数据。参考算例输入和参考答案用于评价,应放在求解智能体无法读取的位置。这里的 `test` 表示基准评测任务,并非论文中技能演化实验的历史留出划分。 + +## 配套资源 + +为方便更广泛的比较,本仓库附带来自[上游 FoamBench](https://github.com/NLR-Theseus/cfdllmbench) 的 **Basic(110 个)**和 **Advanced(16 个)**任务。它们不是 EasyFoam 的原创任务;EasyFoam 作者为其提供了**评价准则和离线参考数据**。可选择 `basic`、`advanced` 或 `all`(226 个任务)浏览。 + +三组任务的离线 QoI 参考值和数值统计用于支持评价。[可选评价工具包](tools/evaluation-tools.zip)集中提供评估器、脚本和格式定义,需要时再解压。[使用指南](GUIDE.md)说明工具运行方法、数据覆盖情况和评价协议细节。[EasyFoam Skill 库](https://github.com/CAS-CLab/EasyFoam)独立发布。 + +## 引用与许可 + +使用 ExtFoamBench 或其评价/参考资源时,请引用 [EasyFoam](https://openreview.net/forum?id=GhQ5YmhU8B);使用 Basic/Advanced 时,同时注明 [FoamBench](https://github.com/NLR-Theseus/cfdllmbench) 的贡献。项目与第三方资源的许可见[组件许可证说明](LICENSE.md)。 + +**1.1.0** 版本精简了页面与文件组织,并增加中英文介绍。科学数据、接受准则和评分代码与 **1.0.0** 一致,旧版仍可下载。 diff --git a/SHA256SUMS b/SHA256SUMS index 9efbc54333445d72d65ea3b145b24efdda28e99b..795d272f5e1e4b8dfbff5436ccf713e15be004ba 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -1,5 +1,4 @@ fec9848fa0a1a2a2d7f78eebc2cac8239fe830c918d5776a684ed129beb203d9 .gitignore -b5375698c34737e22fabdf9cea774287609ce6edc3fa8c73791c3749e89c3bca benchmarks/__init__.py 0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f benchmarks/assets/manifest.json 0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz @@ -9,49 +8,6 @@ f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/ass d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117 benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540 benchmarks/assets/README.md -6488b16a905c9e6ae7d33f06bd55fbf276c917df54f53984f4f4ba3504f1710d benchmarks/evaluation/__init__.py -b965c21513f41de952a6f983700e961845746fd1b3df1c56ab1e7a612ca8be8f benchmarks/evaluation/__main__.py -dc4d21e3f45bd036f5a0d23ef2e9bf4406f4e34a76437472e3b9bbb25ff5bd40 benchmarks/evaluation/adapters/__init__.py -b8933e85b63abc1c792fdad5ddd76dedb2e0344e38ce6d2e8991ee760e7419ce benchmarks/evaluation/adapters/chatcfd.py -cdf7354b586bc67898bc2f3b44292aacd7fc9d7a58f0544efa9c603ac69a8f11 benchmarks/evaluation/adapters/coding_agent.py -260f1efc5943ef598fa02b3dae130101961fc0c2ce22080abec2b4836d850d63 benchmarks/evaluation/adapters/common.py -5ffd5d35e2431ae568b3e78b647aa85d091d01c124bcdacedcb6e68d4474339b benchmarks/evaluation/adapters/easyfoam.py -a33bcc116b3043c2b70a1342d0d3c71c30eac42f1ea286ca08b543f0e6496c40 benchmarks/evaluation/adapters/foamagent.py -513e63ba562da617ef6f665c452bec8c2d308ca1e716629ac6ca360494724849 benchmarks/evaluation/aggregate.py -1f8db418394f143b9ecb780eec4118ebde99885130cc30552f64735c5ea93307 benchmarks/evaluation/basic_advanced.py -9d4a6bc429e0ef9a751384be2d777101f7f2d91dfee7edbdc6e3e0d771154ccd benchmarks/evaluation/cli.py -eb44b8d8020e5f9c22f19880884ade107afd395246b0d9ad8f78b9a6a4d30280 benchmarks/evaluation/comparison.py -272bc7e44456c330fd7ac97685279538f8b0715d8aae3deb88366314fea1efc9 benchmarks/evaluation/evidence_contract.py -cd2e1ff40d7dcb830b4230d86e143652d1d93a1b007019e3583384486a242604 benchmarks/evaluation/execution.py -78cd982892e8ede31ee7e951cec87c7c595813a975bf4b111ea0d980b37633b5 benchmarks/evaluation/extbench.py -51d8bb69224ed37ae0de073700c5f9cfd403095f53fa16d633a3eb777e1a0b13 benchmarks/evaluation/field_candidate.py -95900ed3c04bc04846e2dd2dd6ae4f98c2fb0aba4b85978199c20b1a444f4c0e benchmarks/evaluation/field_extractor.py -3c6a38077eecae484f264cd46478b21687b21ca33f543f4f041d954bdfa98205 benchmarks/evaluation/foam.py -80bd6344a529cc574693053b97b14cccb209c40a099b01a942f8654ddf24c614 benchmarks/evaluation/foam_arrays.py -ce3a16fb9e29587eaabd816bdfda832bcdc83e3744ac233e1365b3350146ddf9 benchmarks/evaluation/foam_field.py -a043e6a9022c30aea8fa94b8f753f1608804c526644a1f851c23453b7482727a benchmarks/evaluation/foam_io.py -55bd6f2c61c4e3cef677e4cf428433ae9e3fb8b778efc10bb281e814fc2c5d05 benchmarks/evaluation/frozen_recovery.py -1cf606f832b4410908faaddeb439d0ca768cf134f4832f87f901c113a17d25da benchmarks/evaluation/health.py -83c7166635578af9b5ed7eaeac96c06df7b65ab0936dc39a5310e5c42a6003e4 benchmarks/evaluation/io.py -eb16a2dbd37f6ddb112adb6a92f5b3c1b8aa6295592d8f5430d7d3a24f0ff334 benchmarks/evaluation/measurement_specs.py -7f35b96268d62aca315d70f2c14a6bdda602bb51b70666fb1fa7667bc88a0cbf benchmarks/evaluation/mesh.py -75cdb75a677e47c786769d541e019085eb84a3de73b0539647143d869115d8ef benchmarks/evaluation/models.py -f87a0946dc0d29c656e362d56e3aa0cc68c495d6daecf5d17f429a916e6468ff benchmarks/evaluation/numerical.py -4921843f568f4ff06d4f02d270da87a8833d34dac2a448aae1a090caa68d2206 benchmarks/evaluation/pipeline.py -95d54ca4f2dea32c9223cc092db6ac1e93fd045ab3a47a965c10f035b6211bd3 benchmarks/evaluation/preparation.py -5e8791bf4840c8ea18d1f5c70ca922b100e7694a07e75f2c7fb47a9b834137a2 benchmarks/evaluation/profiles/advanced.json -a9976b3f6d2125a9ada142614052eb7d4cbc263ac8c1781f7b3fd4f0e567e2e4 benchmarks/evaluation/profiles/basic.json -8bbbc58e77b09da38eef2565e95b8d69c88b1db21ac696e9991b887e2394af85 benchmarks/evaluation/profiles/extended.json -5cf9b70b1ec3ae040d2e3b478e61d5c4e1bf838106621e3d3f7c1827670841a5 benchmarks/evaluation/profiles.py -305eba7114c1ae50521c05aa12ad95c9db35304af33665ea5e655bfd8f17c51b benchmarks/evaluation/qoi.py -af47ba704a5edcd8490261a7ddba07fe9204473ae4d19d3b09a7e4f7fb9f548f benchmarks/evaluation/qoi_glue.py -99a6af4a1f422bbb4f808602b744b2fa3660b4a7740e39ab24f3f4fcad9bda6b benchmarks/evaluation/qoi_reference.py -e0b13a6223ffa692f1297ba76b6817db4156bb3c3c3d2abfa96afc095d41511f benchmarks/evaluation/README.md -627725f472e89d9b97ff8cedf23d2ac92097a53f27f23d648f7be0bf943d33b1 benchmarks/evaluation/reference.py -159655e9dadb4367a59a7ea1a804856c5280b3bc025c2892f06fd0535e265bae benchmarks/evaluation/reporting.py -0c54e9671b9f7353cbc28ecf9798d678db4bfacaa5f7c184bf4e45ebef9ec4a7 benchmarks/evaluation/retained_fields.py -477332e61a0f668ff51db9817ec874706051d37c2dedf65b5ca43b73435c9583 benchmarks/evaluation/schema.py -b9ba1b4c4583e9b393c699d47bab71a82aed159519408062b631147bd70d25a5 benchmarks/evaluation/stability.py 74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027 benchmarks/FoamBench_advanced_openfoam13_fixed_final.json 31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63 benchmarks/FoamBench_advanced_openfoam13_reference_qois.json 50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523 benchmarks/FoamBench_basic_openfoam13_fixed_final.json @@ -64,39 +20,20 @@ fb1db5034a1d2688ad360c6b0810bab68c33d4c6dc1dc5bec29095e93b077393 benchmarks/Foa 6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b benchmarks/reference_statistics/advanced.json 3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72 benchmarks/reference_statistics/basic.json 637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9 benchmarks/reference_statistics/extended.json -5c1f78137dc1c7032363bb0ebf96cf01f19c9f2ffb48abd7fef39cb8b54a9f82 benchmarks/scripts/__init__.py -113840a36b914722ff422505b1ed128daf023ee20bf287ab8ebfcd1af938a786 benchmarks/scripts/build_extbench_reference.py -827836c6f2363f0104917b6573dc86935ffc58fd3b9dcdf0ca83cd5ce874f753 benchmarks/scripts/compare_foambench_qois.py -845727247e81e82d75abb0e05b62d1bd15f9a7d8512533b749b8a20e1631f6a5 benchmarks/scripts/extract_extbench_qois.py -1110f0962468820146307099c463c1be8a25cbc5c3729fd7abc116d7fe06d27a benchmarks/scripts/extract_foambench_candidate_qois.py -cf3c18a0329ac576fc05e35ba2f70f95f0c1d6668a86fe6a65d8402de41a1abe benchmarks/scripts/extract_foambench_qois.py -265ac1ec1fcc347c82e9351a86305d6f7bafaf3bd8ff69075904ebaf285ed2bc benchmarks/scripts/materialize_benchmark.py -fc1268f130f4b0800b5a75346198e97896bd5e74b07ea3face5d0e4afa0d6d2c benchmarks/scripts/recover_extbench_qoi.py -ca2f885342099b4a06f425d971bee5edc24b199b596000e9997f8940b23770b4 benchmarks/scripts/validate_benchmark_assets.py 488b6a139660cbcafd3de131c1e7e3c6758e71f609003e69cbfa1f9991afe95a data/advanced.jsonl 50a62e6ab16faa998dd1c284db6ecb4e8ac78ee226c8be4e0fb6cce741e7581f data/basic.jsonl edfd82f84456540c89844eae84143dc4897a93599b1b28f278a945de5826981e data/extended.jsonl -07019bf3f590423b1b0804e6a8ac1dacf97677cb23a4842c4e5a0e601c155974 docs/DATA_FORMAT.md -f0c1d691c071253fa66517e68349d9c2ee6c6d73f963a967c10173180693342b docs/EVALUATION.md -4f1353233c7d1d86da7f49d51a64f584805c435f8b052c37b37d30c84927530d docs/PROVENANCE.md -a3690d9a63846f36f58bd8e79e1ab974a4d46673a16943166e8ad0fd9b91faf1 docs/RELEASE_NOTES.md -c05b1930bed5658497b9ac9de230127c23a8541b274adfd270c995943773f4d5 examples/inspect_task.py +dfeed01d712c4915d2c2f0eccb60575de454eab740c97642ce9ed9d628346d50 GUIDE.md cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE -1c8f0e5ad4fe2f145137ef723f54d62e8891a2b1b3467c90bc33c4c6680c907f LICENSE.md +e3ef265ef148001bef8936ecef4074605705b28d47c5be54f73e44893f2f25f1 LICENSE.md 7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22 LICENSES/FoamBench-BSD-3-Clause.txt 8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903 LICENSES/GPL-3.txt 770397d605802346385b7c69ab27b919c1b734d653c6ed64b255349e5ffeaef2 metadata/coverage.json -a82a5872d4c62c7a0159ee23c684273e0eb61f4cd252f0db735e15e00364f95a metadata/families.json -ffc93609ac4a7d0f858696da211e1ec214409df51b8223d6833fd318b0d19f86 metadata/release.json -74105bd146098de3bbe19c995eed3b3e5c63cad8b9480d08db34333292fec1d5 metadata/source_manifest.json -9b912f908b65a553835273e3cfe3745b5d63f5d148ec1b719412db2471dbd0d7 metadata/validation.json -ba391bbb79dd26d51519409f44987afff3757513aa7bf9519b053795c2f156d8 README.md -df4bd25666834a74821035deda2154cd2922e3e0d2d00db0bd02f99ba4ad8caf requirements.txt -d49505bf35dffc763df91b13c8b5885e78b607af56d7aceba01e427c3fa19a6b schemas/benchmark_evaluation.schema.json -32a7f0865e9c851848fc775f9bde1125bd03749b4130d34fe95d5ffc62a700c0 schemas/benchmark_profile.schema.json -88fb894b919323c0457f1cb4bf934f72320d644299185127c164579343606425 schemas/foambench_qoi_candidate.schema.json -9204923e5b93e333459ccfc43394137deaee1bf19d6f01beaf8ada664806d7e8 schemas/foambench_qoi_comparison.schema.json -2ef632eb4ed82ad78213de6ee4b18aa36558916a106cb258505493c95285ac68 schemas/foambench_qoi_reference.schema.json -839a77fa504b7f13b2b6803c0ca2448df83418779cee2a2a5a5acdc18cd8760c schemas/qoi_recovery_plan.schema.json -73da798dd8c3ff74733a2a08a8d914d9e85c6d3184196dd0f2f8d0a45789a45a scripts/verify_release.py -59854984853104df5c353e2f681a15fc7924742f9a2e468c29af248dce45ce03 VERSION +678ee25dd7207becec717dda6f981ed42dc240575452e5f18db0fd4df93ba4f3 metadata/release.json +801975a7617517d8286bc8d91fa6e6041ad3e09433edcb1f9249750530e05902 metadata/source_manifest.json +a308986a00db26567dc02fc6c4651667bf742bfc2f1997a8ee700f8f2faa918a metadata/validation.json +fd31e2cca58d84ca3581c3fa8f3e2ee5f24edddf71adff196f7bc3785d3fef19 README.md +483b2e6058e6145e9dc4d62cadb650e7187d45d8a4c37e0f1a70dc7fd24d05a5 README_zh.md +15d37d4b5c2293675fb977568f43a34e2eed8951a4e245407771cf9e09a4fdf5 scripts/verify_release.py +6bf6fd0963a10c4a42e7de6529b4e75ca144e81716fa000cde8ea26d5c45a021 tools/evaluation-tools.zip +6ca2e3356014241331fb2b399428fca23c558e3f3d428edcf4f56eb0fe907069 VERSION diff --git a/VERSION b/VERSION index 3eefcb9dd5b38e2c1dc061052455dd97bcd51e6c..0698a2caf971d0ccacb17d2d951bfd58ac06a05f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0 +1.1.0 diff --git a/benchmarks/__init__.py b/benchmarks/__init__.py deleted file mode 100644 index 7d358702f21adf6849d7e18ba8458ff55d0d9990..0000000000000000000000000000000000000000 --- a/benchmarks/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""FoamBench assets and evaluation utilities.""" diff --git a/benchmarks/evaluation/README.md b/benchmarks/evaluation/README.md deleted file mode 100644 index 36fdca68dd4dd9cb285dcb7b6d6ce2ba93b026a9..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Standalone EasyFoam benchmark evaluator - -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. - -From the repository root: - -```bash -python -m pip install -r requirements.txt -python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json -``` - -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. diff --git a/benchmarks/evaluation/__init__.py b/benchmarks/evaluation/__init__.py deleted file mode 100644 index 3357a7bf8ef6fba5ec1016f0fe08677c6b964132..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -"""Dataset-independent FoamBench evaluation framework.""" - -from pathlib import Path -from typing import Any - -from .aggregate import aggregate_results -from .models import BenchmarkProfile, CaseArtifact - - -def evaluate_campaign( - profile: BenchmarkProfile, - *, - adapter_name: str, - run_root: Path, - output_dir: Path | None = None, - check_mesh: bool = False, - mesh_timeout: float = 120.0, -) -> dict[str, Any]: - """Evaluate a campaign without importing the full pipeline at package import time.""" - from .pipeline import evaluate_campaign as run_evaluation - - return run_evaluation( - profile, - adapter_name=adapter_name, - run_root=run_root, - output_dir=output_dir, - check_mesh=check_mesh, - mesh_timeout=mesh_timeout, - ) - -__all__ = ["BenchmarkProfile", "CaseArtifact", "aggregate_results", "evaluate_campaign"] diff --git a/benchmarks/evaluation/__main__.py b/benchmarks/evaluation/__main__.py deleted file mode 100644 index 8f7704a5691aad1e269786d5dba9c3445d84de01..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/__main__.py +++ /dev/null @@ -1,10 +0,0 @@ -import json -import sys - -from .cli import main - -try: - raise SystemExit(main()) -except (OSError, ValueError, RuntimeError, json.JSONDecodeError) as exc: - print(f"foambench-evaluate: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/evaluation/adapters/__init__.py b/benchmarks/evaluation/adapters/__init__.py deleted file mode 100644 index 83885653cafb00f5cda617fd79049e0d6ea93962..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -from .easyfoam import EasyFoamAdapter -from .foamagent import FoamAgentAdapter -from .chatcfd import ChatCFDAdapter -from .coding_agent import CodingAgentAdapter - -ADAPTERS = { - "easyfoam": EasyFoamAdapter, - "foamagent": FoamAgentAdapter, - "chatcfd": ChatCFDAdapter, - "coding-agent": CodingAgentAdapter, -} - - -def create_adapter(name: str, *args, **kwargs): - try: - adapter = ADAPTERS[name] - except KeyError as exc: - raise ValueError(f"unknown evaluation adapter: {name}") from exc - return adapter(*args, **kwargs) - - -__all__ = ["EasyFoamAdapter", "FoamAgentAdapter", "ChatCFDAdapter", "create_adapter"] diff --git a/benchmarks/evaluation/adapters/chatcfd.py b/benchmarks/evaluation/adapters/chatcfd.py deleted file mode 100644 index 64d93a0b5b1f58a286d5ec2a80ff7f76a0b19d7a..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/chatcfd.py +++ /dev/null @@ -1,85 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from ..io import read_object -from ..models import BenchmarkProfile, CaseArtifact -from .common import duration, token_usage - - -class ChatCFDAdapter: - """Normalize ChatCFD rollouts for the shared FoamBench scorer. - - ChatCFD writes a case_run.log and keeps its model accounting in either a - rollout manifest or qa_logs.jsonl. The adapter deliberately does not - infer case identity from generated files: a manifest is the reproducible - source of truth for benchmark membership. - """ - - def __init__(self, run_root: Path, profile: BenchmarkProfile): - self.run_root = run_root.resolve(strict=True) - self.profile = profile - - def discover(self) -> dict[str, CaseArtifact]: - artifacts: dict[str, CaseArtifact] = {} - for manifest_path in sorted(self.run_root.rglob("rollout_manifest.json")): - manifest = read_object(manifest_path) - case_id = manifest.get("case_id") - if not isinstance(case_id, str) or case_id in artifacts: - continue - rollout = manifest_path.parent - case_ref = manifest.get("case_path", "case") - case_dir = Path(case_ref) - if not case_dir.is_absolute(): - case_dir = rollout / case_dir - case_dir = case_dir.resolve() - family, variant = self.profile.identity(case_id) - logs = [p.resolve() for p in case_dir.glob("log.*") if p.is_file()] - logs.extend(p.resolve() for p in (case_dir / "case_run.log", case_dir / "Allrun.out", case_dir / "Allrun.err") if p.is_file()) - normalized = dict(manifest) - normalized["duration_seconds"] = duration(manifest) - normalized["token_usage"] = token_usage(manifest) - if manifest.get("resource_measurement") == "request-journal-v1": - # Shared CSV reporting uses input/output names. Preserve the - # raw journal totals and completeness flags alongside aliases. - usage = normalized["token_usage"] - usage["input_tokens"] = usage["prompt_tokens"] - usage["output_tokens"] = usage["response_tokens"] - # Task selection and generation/repair have separate logs. - qa_logs = {p.resolve() for p in (rollout / "qa_logs.jsonl", case_dir / "qa_logs.jsonl") if p.is_file()} - if not normalized["token_usage"] and qa_logs: - totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0} - for path in sorted(qa_logs): - for key, value in self._qa_usage(path).items(): - totals[key] += value - normalized["token_usage"] = totals - artifacts[case_id] = CaseArtifact( - case_id=case_id, - dataset=self.profile.dataset, - family=str(manifest.get("family") or family), - variant=str(manifest.get("variant") or variant), - replicate=int(manifest.get("replicate", 1)), - rollout_dir=rollout, - # Like Foam-Agent, ChatCFD supplies generic solver evidence, - # not an EasyFoam workflow workspace with formal run records. - workspace_dir=None, - case_dir=case_dir if case_dir.is_dir() else None, - manifest=normalized, - solver_logs=tuple(sorted(set(logs))), - ) - return artifacts - - @staticmethod - def _qa_usage(path: Path) -> dict[str, int]: - import json - totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0} - for line in path.read_text(encoding="utf-8").splitlines(): - try: - row = json.loads(line) - except json.JSONDecodeError: - continue - totals["calls"] += 1 - totals["prompt_tokens"] += int(row.get("prompt_tokens", 0) or 0) - totals["response_tokens"] += int(row.get("response_tokens", 0) or 0) - totals["reasoning_tokens"] += int(row.get("reasoning_tokens", 0) or 0) - return totals diff --git a/benchmarks/evaluation/adapters/coding_agent.py b/benchmarks/evaluation/adapters/coding_agent.py deleted file mode 100644 index 86cd546edd83130c3a93c4741e3e81537714a4a2..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/coding_agent.py +++ /dev/null @@ -1,48 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from ..io import read_object -from ..models import BenchmarkProfile, CaseArtifact - - -class CodingAgentAdapter: - """Use externally recorded output discovery; impose no agent-side file contract.""" - - def __init__(self, run_root: Path, profile: BenchmarkProfile): - self.run_root = run_root.resolve(strict=True) - self.profile = profile - - def discover(self) -> dict[str, CaseArtifact]: - result = {} - for path in sorted(self.run_root.glob("*/*/replicate_001/rollout_manifest.json")): - manifest = read_object(path) - if manifest.get("experiment_kind") != "requirement_only_coding_agent.v1": - raise ValueError(f"Unexpected experiment manifest: {path}") - case_id = manifest["case_id"] - if case_id in result: - raise ValueError(f"Duplicate case: {case_id}") - rollout = path.parent - workspace = rollout / "workspace" - ref = manifest.get("output_discovery", {}).get("case_ref") - case_dir = None - if isinstance(ref, str): - candidate = (workspace / ref).resolve() - if not candidate.is_relative_to(workspace.resolve()): - raise ValueError(f"Case escapes workspace: {ref}") - case_dir = candidate - logs = [] - for ref in manifest.get("solver_log_refs", []): - candidate = (rollout / ref).resolve() - if not candidate.is_relative_to(rollout.resolve()): - raise ValueError(f"Log escapes rollout: {ref}") - if candidate.is_file(): - logs.append(candidate) - family, variant = self.profile.identity(case_id) - result[case_id] = CaseArtifact( - case_id=case_id, dataset=self.profile.dataset, family=family, variant=variant, - replicate=1, rollout_dir=rollout, workspace_dir=workspace, case_dir=case_dir, - manifest={**manifest, "agent_mode": "coding-only", "domain_assets_enabled": False}, - solver_logs=tuple(logs), - ) - return result diff --git a/benchmarks/evaluation/adapters/common.py b/benchmarks/evaluation/adapters/common.py deleted file mode 100644 index 1025a23ab47daf7bfc3f1834b2ff02ae7b1d3a05..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/common.py +++ /dev/null @@ -1,71 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from ..io import read_object - - -def formal_records(workspace: Path) -> tuple[Path, ...]: - paths: list[Path] = [] - workflow_path = workspace / "workflow.json" - if workflow_path.is_file(): - workflow = read_object(workflow_path) - refs = workflow.get("artifacts", {}).get("run_records", []) - for ref in refs if isinstance(refs, list) else []: - if isinstance(ref, str): - paths.append(workspace / ref) - paths.extend(workspace.glob("runs/formal-*/run_record.json")) - unique = {path.resolve() for path in paths if path.is_file()} - return tuple(sorted(unique)) - - -def successful_formal_records(paths: tuple[Path, ...]) -> tuple[Path, ...]: - successful = [] - for path in paths: - record = read_object(path) - if record.get("mode") == "formal" and record.get("terminal_status") == "succeeded": - successful.append(path) - return tuple(successful) - - -def logs_from_records(workspace: Path, records: tuple[Path, ...]) -> tuple[Path, ...]: - logs: list[Path] = [] - for path in records: - record = read_object(path) - for command in record.get("commands", []) if isinstance(record.get("commands"), list) else []: - if not isinstance(command, dict): - continue - for key in ("stdout_ref", "stderr_ref"): - ref = command.get(key) - if isinstance(ref, str): - candidate = workspace / ref - if candidate.is_file(): - logs.append(candidate.resolve()) - return tuple(dict.fromkeys(logs)) - - -def token_usage(manifest: dict[str, Any]) -> dict[str, Any]: - usage = manifest.get("token_usage") - if isinstance(usage, dict): - return dict(usage) - attempts = manifest.get("attempts") - if isinstance(attempts, list) and attempts and isinstance(attempts[-1], dict): - usage = attempts[-1].get("token_usage") - return dict(usage) if isinstance(usage, dict) else {} - - -def duration(manifest: dict[str, Any]) -> float | None: - value = manifest.get("duration_seconds") - if isinstance(value, (int, float)): - return float(value) - process = manifest.get("process") - if isinstance(process, dict) and isinstance(process.get("duration_seconds"), (int, float)): - return float(process["duration_seconds"]) - attempts = manifest.get("attempts") - values = [ - float(item["duration_seconds"]) - for item in attempts if isinstance(attempts, list) and isinstance(item, dict) - and isinstance(item.get("duration_seconds"), (int, float)) - ] if isinstance(attempts, list) else [] - return sum(values) if values else None diff --git a/benchmarks/evaluation/adapters/easyfoam.py b/benchmarks/evaluation/adapters/easyfoam.py deleted file mode 100644 index f6e833ef7bdd10e7fefaa7bd8275e8f588d04c6f..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/easyfoam.py +++ /dev/null @@ -1,108 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from ..foam import FATAL_RE, final_log_time, normal_end -from ..foam_io import read_text -from ..io import read_object -from ..models import BenchmarkProfile, CaseArtifact -from .common import duration, formal_records, logs_from_records, successful_formal_records, token_usage - - -class EasyFoamAdapter: - """Normalize supported EasyFoam rollout layouts.""" - - def __init__(self, run_root: Path, profile: BenchmarkProfile): - self.run_root = run_root.resolve(strict=True) - self.profile = profile - - def discover(self) -> dict[str, CaseArtifact]: - artifacts: dict[str, CaseArtifact] = {} - legacy = sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json")) - current = sorted(self.run_root.rglob("run_manifest.json")) if not legacy else [] - for path in [*legacy, *current]: - manifest = read_object(path) - case_id = manifest.get("case_id") - if not isinstance(case_id, str) or case_id in artifacts: - continue - rollout = path.parent - workspace = self._workspace(rollout, manifest) - family, variant = self.profile.identity(case_id) - coding_only = manifest.get("agent_mode") == "coding-only" or manifest.get("domain_assets_enabled") is False - case_dir = workspace / "case" if workspace else None - if coding_only and case_dir and case_dir.is_dir(): - # Coding-only rollouts intentionally do not retain EasyFoam - # formal records. Avoid scanning their large workspaces for - # workflow/run-record artifacts before using generic logs. - records = () - generic_logs = [item for item in case_dir.glob("log.*") if item.is_file()] - generic_logs.extend( - item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file() - ) - logs = _successful_generic_logs(generic_logs) - else: - records = formal_records(workspace) if workspace and workspace.is_dir() else () - logs = logs_from_records(workspace, successful_formal_records(records)) if workspace else () - normalized = dict(manifest) - normalized["duration_seconds"] = duration(manifest) - normalized["token_usage"] = token_usage(manifest) - artifacts[case_id] = CaseArtifact( - case_id=case_id, - dataset=self.profile.dataset, - family=str(manifest.get("family") or family), - variant=str(manifest.get("variant") or variant), - replicate=int(manifest.get("replicate", 1)), - rollout_dir=rollout, - workspace_dir=workspace, - case_dir=case_dir, - manifest=normalized, - formal_run_records=records, - solver_logs=logs, - workflow_path=workspace / "workflow.json" if workspace else None, - evidence_summary_path=workspace / "evidence_summary.json" if workspace else None, - ) - return artifacts - - def _workspace(self, rollout: Path, manifest: dict) -> Path | None: - direct = rollout / "workspace" - if direct.is_dir(): - return direct.resolve() - ref = manifest.get("workspace_ref") - if isinstance(ref, str): - candidate = Path(ref) - if not candidate.is_absolute(): - candidate = self.run_root / candidate - return candidate.resolve() - return None - - -def _successful_generic_logs(paths: list[Path]) -> tuple[Path, ...]: - """Select final successful solver evidence without failed repair/postprocess logs.""" - canonical_paths = tuple(sorted({item.resolve() for item in paths if item.name == "log.foamRun"})) - if canonical_paths: - # log.foamRun is the runner's canonical solver log. Do not read - # multi-hundred-MB repair logs during artifact discovery; execution - # and numerical gates perform the substantive log checks later. - return canonical_paths - if paths: - # Avoid eagerly loading every repair/post-processing log merely to - # choose evidence. Prefer the newest generic log; gate parsing will - # validate its contents when it is actually evaluated. - existing = [item.resolve() for item in paths if item.is_file()] - if existing: - return (max(existing, key=lambda item: item.stat().st_mtime),) - evidence = [] - for path in sorted({item.resolve() for item in paths}): - text = read_text(path) - if FATAL_RE.search(text): - continue - evidence.append((path, text, final_log_time(text))) - canonical = [item for item in evidence if item[0].name == "log.foamRun"] - if canonical: - return tuple(item[0] for item in canonical) - timed = [item for item in evidence if item[2] is not None] - if timed: - latest = max(float(item[2]) for item in timed if item[2] is not None) - return tuple(item[0] for item in timed if item[2] == latest) - ended = [item for item in evidence if normal_end(item[1])] - return tuple(item[0] for item in (ended or evidence)) diff --git a/benchmarks/evaluation/adapters/foamagent.py b/benchmarks/evaluation/adapters/foamagent.py deleted file mode 100644 index 3b184bd1e91e101cb21cbb54017d792d27211048..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/adapters/foamagent.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from ..io import read_object -from ..models import BenchmarkProfile, CaseArtifact -from .common import duration, token_usage - - -class FoamAgentAdapter: - def __init__(self, run_root: Path, profile: BenchmarkProfile): - self.run_root = run_root.resolve(strict=True) - self.profile = profile - - def discover(self) -> dict[str, CaseArtifact]: - artifacts: dict[str, CaseArtifact] = {} - for path in sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json")): - manifest = read_object(path) - case_id = manifest.get("case_id") - if not isinstance(case_id, str) or case_id in artifacts: - continue - rollout = path.parent - case_dir = rollout / "case" - family, variant = self.profile.identity(case_id) - logs = [item for item in case_dir.glob("log.*") if item.is_file()] - logs.extend(item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file()) - process = manifest.get("process") if isinstance(manifest.get("process"), dict) else {} - attempts = manifest.get("attempts") if isinstance(manifest.get("attempts"), list) else [] - last_attempt = attempts[-1] if attempts and isinstance(attempts[-1], dict) else {} - normalized = dict(manifest) - normalized["return_code"] = process.get( - "return_code", last_attempt.get("return_code", manifest.get("return_code")) - ) - normalized["timed_out"] = bool(process.get( - "timed_out", last_attempt.get("timed_out", manifest.get("timed_out", False)) - )) - normalized["duration_seconds"] = duration(manifest) - normalized["token_usage"] = token_usage(manifest) - for metrics_path in (rollout / "llm_metrics.json", rollout / "attempt_001.llm_metrics.json"): - if metrics_path.is_file(): - normalized["token_usage"] = token_usage({"token_usage": read_object(metrics_path)}) - break - if isinstance(manifest.get("execution"), dict): - normalized["source_execution"] = manifest["execution"] - artifacts[case_id] = CaseArtifact( - case_id=case_id, - dataset=self.profile.dataset, - family=str(manifest.get("family") or family), - variant=str(manifest.get("variant") or variant), - replicate=int(manifest.get("replicate", 1)), - rollout_dir=rollout, - workspace_dir=None, - case_dir=case_dir, - manifest=normalized, - solver_logs=tuple(sorted({item.resolve() for item in logs})), - ) - return artifacts diff --git a/benchmarks/evaluation/aggregate.py b/benchmarks/evaluation/aggregate.py deleted file mode 100644 index b452dfad838c15c9b261add0402d581e09b6623a..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/aggregate.py +++ /dev/null @@ -1,100 +0,0 @@ -from __future__ import annotations - -import statistics -from collections import Counter -from typing import Any - - -def _rate(count: int, denominator: int) -> float | None: - return count / denominator if denominator else None - - -def aggregate_results(rows: list[dict[str, Any]]) -> dict[str, Any]: - total = len(rows) - execution = sum(bool(row.get("scores", {}).get("execution_pass")) for row in rows) - numerical = sum(bool(row.get("scores", {}).get("numerical_pass")) for row in rows) - qoi = sum( - bool( - row.get("scores", {}).get( - "physics_grounded_qoi_pass", - row.get("scores", {}).get("qoi_pass"), - ) - ) - for row in rows - ) - end_to_end = sum(bool(row.get("scores", {}).get("end_to_end_pass")) for row in rows) - ratios = [float(row.get("qoi", {}).get("effective_pass_ratio", 0.0)) for row in rows] - coverage = [ - float(comparison["qoi_coverage_fraction"]) - for row in rows - for comparison in [row.get("qoi", {}).get("comparison")] - if isinstance(comparison, dict) and isinstance(comparison.get("qoi_coverage_fraction"), (int, float)) - ] - failures = Counter( - failure - for row in rows - for failure in row.get("failure_categories", []) - ) - return { - "task_count": total, - "execution_pass_count": execution, - "execution_pass_rate": _rate(execution, total), - "numerical_pass_count": numerical, - "numerical_pass_rate_all_tasks": _rate(numerical, total), - "numerical_pass_rate_execution_pass": _rate(numerical, execution), - "physics_grounded_qoi_pass_count": qoi, - "physics_grounded_qoi_pass_rate_all_tasks": _rate(qoi, total), - "physics_grounded_qoi_pass_rate_execution_pass": _rate(qoi, execution), - "end_to_end_pass_count": end_to_end, - "end_to_end_pass_rate": _rate(end_to_end, total), - "mean_qoi_pass_ratio_all_tasks": statistics.fmean(ratios) if ratios else None, - "mean_qoi_coverage_evaluated": statistics.fmean(coverage) if coverage else None, - "failure_taxonomy": dict(sorted(failures.items())), - } - - -def aggregate_evolution(groups: dict[str, list[dict[str, Any]]]) -> dict[str, Any]: - """Paired repeated-split reporting. Duplicate tasks remain group-qualified.""" - metrics = ("execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass") - - def summarize(rows): - for row in rows: - for side in ("initial", "evolved"): - scores = row.get("reporting_scores", {}).get(side) - if not isinstance(scores, dict) or any(type(scores.get(key)) is not bool for key in metrics): - raise ValueError("independent reporting scores are missing; reward is not a pass metric") - if scores["end_to_end_pass"] != all(scores[key] for key in metrics[:3]): - raise ValueError("TAR is inconsistent with the three task-level checks") - return {metric: { - side: {"count": sum(row["reporting_scores"][side][metric] for row in rows), - "rate": statistics.fmean(row["reporting_scores"][side][metric] for row in rows)} - for side in ("initial", "evolved") - } | { - "gain": statistics.fmean(int(row["reporting_scores"]["evolved"][metric]) - int(row["reporting_scores"]["initial"][metric]) for row in rows), - "failed_to_passed": sum(not row["reporting_scores"]["initial"][metric] and row["reporting_scores"]["evolved"][metric] for row in rows), - "passed_to_failed": sum(row["reporting_scores"]["initial"][metric] and not row["reporting_scores"]["evolved"][metric] for row in rows), - } for metric in metrics} - - per_group = {} - all_rows = [] - for group_id, rows in groups.items(): - keys = {(row["dataset"], row["case_id"]) for row in rows} - if not rows or len(keys) != len(rows): - raise ValueError(f"empty or duplicate test tasks in group {group_id}") - per_group[group_id] = {"task_count": len(rows), "metrics": summarize(rows)} - all_rows.extend(dict(row, group_id=group_id) for row in rows) - families = {family: summarize([row for row in all_rows if row["family"] == family]) - for family in sorted({row["family"] for row in all_rows})} - means = {metric: {side: { - "mean": statistics.fmean(group["metrics"][metric][side]["rate"] for group in per_group.values()), - "min": min(group["metrics"][metric][side]["rate"] for group in per_group.values()), - "max": max(group["metrics"][metric][side]["rate"] for group in per_group.values()), - } for side in ("initial", "evolved")} for metric in metrics} - return {"groups": per_group, "group_rates": means, "families": families, - "family_equal_weight_rates": {metric: {side: statistics.fmean(family[metric][side]["rate"] for family in families.values()) - for side in ("initial", "evolved")} for metric in metrics}, - "test_records_per_condition": len(all_rows), - "unique_task_count": len({(row["dataset"], row["case_id"]) for row in all_rows}), - "test_frequency": dict(Counter(f"{row['dataset']}::{row['case_id']}" for row in all_rows)), - "interpretation": "Descriptive repeated splits; overlapping tasks and groups are not independent samples.", - "cases": all_rows} diff --git a/benchmarks/evaluation/basic_advanced.py b/benchmarks/evaluation/basic_advanced.py deleted file mode 100644 index 0586cfa67db837b406e31e74d13fb59bca469d10..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/basic_advanced.py +++ /dev/null @@ -1,807 +0,0 @@ -#!/usr/bin/env python3 -"""Structured QoIs shared by FoamBench Basic and Advanced references/candidates.""" -from __future__ import annotations - -import argparse -import json -import math -import re -import subprocess -from pathlib import Path -from typing import Any, Callable - -from .foam_arrays import FoamArrayError, foam_path, read_scalar_field, read_vector_field -from .foam_io import magnitude, read_text -from .io import utc_now, write_json -from .schema import validate - - -ADVANCED_TEMPLATE = { - "Cavity_LES": "Cavity", "Cavity_SA": "Cavity", "Cavity_geometry_1": "Cavity", - "Cylinder_LES": "Cylinder", "Cylinder_SA": "Cylinder", - "Diamond_Obstacle_KOMEGASST": "Obstacle", "Diamond_Obstacle_SA": "Obstacle", - "Double_Square_SA": "Obstacle", "Rectangular_Obstacle_KOMEGASST": "Obstacle", - "Rectangular_Obstacle_SA": "Obstacle", "counterFlowFlame2D_KE": "counterFlowFlame2D", - "counterFlowFlame2D_SA": "counterFlowFlame2D", "nozzleFlow2D_SA": "Nozzle", - "obliqueShock_KE": "Shock", "obliqueShock_LES": "Shock", "wedge_SA": "Shock", -} - -GROUPS = { - "BernardCells": "thermal_state", "Cavity": "cavity_response", "Cylinder": "wake_response", - "counterFlowFlame2D": "flame_response", "damBreakWithObstacle": "free_surface_response", - "forwardStep": "shock_response", "obliqueShock": "shock_response", "wedge": "shock_response", - "Shock": "shock_response", "pitzDaily": "separation_response", "Obstacle": "obstacle_response", - "shallowWaterWithSquareBump": "surface_response", "squareBend": "bend_response", - "Nozzle": "nozzle_response", -} - -PHYSICS_METRICS = { - "BernardCells": ("temperature_min", "temperature_max", "convection_mean_speed"), - "Cavity": ("response_speed_max", "reverse_flow_min_u"), - "Cylinder": ("wake_deficit_final",), - "counterFlowFlame2D": ("species_sum_max_error", "reaction_temperature_span"), - "damBreakWithObstacle": ("water_volume_relative_drift", "front_net_advance"), - "forwardStep": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"), - "obliqueShock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"), - "wedge": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"), - "Shock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"), - "pitzDaily": ("reverse_flow_volume_fraction", "streamwise_pressure_change_magnitude"), - "Obstacle": ("streamwise_pressure_change_magnitude",), - "shallowWaterWithSquareBump": ("mid_bump_height_relative_change",), - "squareBend": ("streamwise_pressure_change_magnitude",), - "Nozzle": ("flow_speed_max",), -} - -# Each family already extracts one spatial response profile. Making that -# profile mandatory adds field-structure discrimination without introducing -# another observable or extractor. Scalar envelopes remain the -# reference-independent admissibility check; profiles are the deliberately -# stricter, reference-anchored response-shape check. -PRINCIPAL_RESPONSE_PROFILES = { - "BernardCells": ("thermal_vertical_profile",), - "Cavity": ("centerline_velocity_profiles",), - "Cylinder": ("wake_velocity_profiles",), - "counterFlowFlame2D": ("reaction_zone_profile",), - "damBreakWithObstacle": ("free_surface_profile",), - "forwardStep": ("pressure_mach_profiles",), - "obliqueShock": ("pressure_mach_profiles",), - "wedge": ("pressure_mach_profiles",), - "Shock": ("pressure_mach_profiles",), - "pitzDaily": ("separation_profiles",), - "Obstacle": ("separation_profiles",), - "shallowWaterWithSquareBump": ("surface_profile",), - "squareBend": ("bend_axial_profile",), - "Nozzle": ("nozzle_axial_profile",), -} - - -def principal_metrics(template: str) -> tuple[str, ...]: - return PHYSICS_METRICS[template] + PRINCIPAL_RESPONSE_PROFILES[template] - - -def numeric_times(case: Path) -> list[tuple[float, Path]]: - result = [] - for child in case.iterdir(): - if child.is_dir(): - try: - result.append((float(child.name), child)) - except ValueError: - pass - return sorted(result) - - -def align(values: list[Any], count: int) -> list[Any]: - if len(values) == count: - return values - if len(values) == 1 and count: - return values * count - return [] - - -def scalars(directory: Path, name: str, count: int) -> list[float]: - path = foam_path(directory, name) - if path is None: - return [] - try: - return align(read_scalar_field(path), count) - except (FoamArrayError, OSError, ValueError): - return [] - - -def vectors(directory: Path, name: str, count: int) -> list[tuple[float, float, float]]: - path = foam_path(directory, name) - if path is None: - return [] - try: - return align(read_vector_field(path), count) - except (FoamArrayError, OSError, ValueError): - match = re.search( - r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)", - read_text(path), - ) - return [(float(match[1]), float(match[2]), float(match[3]))] * count if match else [] - - -def geometry(case: Path) -> tuple[list[tuple[float, float, float]], list[float], float, Path]: - times = numeric_times(case) - for time, directory in reversed(times): - c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc") - if c_path and v_path: - centres = read_vector_field(c_path) - volumes = align(read_scalar_field(v_path), len(centres)) - if centres and volumes: - return centres, volumes, time, directory - # C and Vc are measurement products, not required solver outputs. The - # independent evaluator also runs without prepare_campaign(), so recover - # the same geometric quantities directly from a retained static polyMesh. - # This uses no reference values and never writes into the frozen case. - if not times: - raise ValueError(f"no retained time directories for measurement: {case}") - from .retained_fields import derive_cell_geometry - try: - volumes, centres, _ = derive_cell_geometry(case) - except (ValueError, OSError) as exc: - raise ValueError(f"missing C/Vc and retained mesh geometry unavailable: {case}: {exc}") from exc - time, directory = times[-1] - count = raw_field_count(directory) - if count is not None and count != len(centres): - raise ValueError(f"retained field/mesh cell count mismatch: {case}") - return centres, volumes, time, directory - - -def raw_field_count(directory: Path) -> int | None: - for name, reader in (("alpha.water", read_scalar_field), ("h", read_scalar_field), - ("T", read_scalar_field), ("p", read_scalar_field), ("U", read_vector_field)): - path = foam_path(directory, name) - if path is None: - continue - try: - count = len(reader(path)) - except (FoamArrayError, OSError, ValueError): - continue - if count > 1: - return count - return None - - -def geometry_for_time( - case: Path, directory: Path, fallback_centres: list[tuple[float, float, float]], fallback_volumes: list[float], -) -> tuple[list[tuple[float, float, float]], list[float]]: - expected = raw_field_count(directory) - if expected in {None, len(fallback_centres)}: - return fallback_centres, fallback_volumes - c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc") - if not c_path or not v_path: - for function in ("writeCellCentres", "writeCellVolumes"): - completed = subprocess.run( - ["foamPostProcess", "-case", str(case), "-func", function, "-time", directory.name], - stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=False, - ) - if completed.returncode != 0: - raise ValueError(f"{case}: {function} failed at time {directory.name}") - c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc") - if not c_path or not v_path: - raise ValueError(f"{case}: no time-local C/Vc at {directory.name}") - centres = read_vector_field(c_path) - volumes = align(read_scalar_field(v_path), len(centres)) - if len(centres) != expected or not volumes: - raise ValueError(f"{case}: time-local geometry mismatch at {directory.name}") - return centres, volumes - - -def bounds(centres: list[tuple[float, float, float]]) -> tuple[list[float], list[float]]: - 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)]) - - -def primary_axis(spans: list[float]) -> int: - """Choose x/y/z deterministically when extents differ only by roundoff.""" - largest = max(spans) - return next(i for i, span in enumerate(spans) if math.isclose(span, largest, rel_tol=1e-12, abs_tol=0.0)) - - -def weighted(values: list[float], volumes: list[float]) -> float: - denominator = sum(volumes) - return sum(value * volume for value, volume in zip(values, volumes)) / denominator - - -def bins( - centres: list[tuple[float, float, float]], volumes: list[float], axis: int, - fields: dict[str, list[float]], *, count: int = 41, - selector: Callable[[tuple[float, float, float]], bool] | None = None, -) -> list[list[float]]: - low, high = bounds(centres) - span = high[axis] - low[axis] - groups: list[list[int]] = [[] for _ in range(count)] - for index, point in enumerate(centres): - if selector is not None and not selector(point): - continue - slot = min(count - 1, max(0, int((point[axis] - low[axis]) / max(span, 1e-30) * count))) - groups[slot].append(index) - rows = [] - for indices in groups: - if not indices: - continue - weights = [volumes[i] for i in indices] - row = [weighted([centres[i][axis] for i in indices], weights)] - for values in fields.values(): - row.append(weighted([values[i] for i in indices], weights)) - rows.append(row) - return rows - - -def profile(profile_id: str, coordinate: str, rows: list[list[float]], fields: list[str]) -> dict[str, Any]: - return {"profile_id": profile_id, "columns": [coordinate, *fields], "rows": rows} - - -def named_profiles(items: list[dict[str, Any]]) -> dict[str, Any]: - return {"kind": "named_profiles", "profiles": items} - - -def history(points: list[dict[str, float]]) -> dict[str, Any]: - return {"kind": "time_history", "points": points} - - -def velocity_fields(directory: Path, count: int) -> tuple[list[tuple[float, float, float]], dict[str, list[float]]]: - velocity = vectors(directory, "U", count) - if not velocity: - return [], {} - return velocity, { - "u": [v[0] for v in velocity], "v": [v[1] for v in velocity], - "speed": magnitude(velocity), - } - - -def thermo(case: Path) -> tuple[float, float]: - text = read_text(case / "constant" / "physicalProperties") - mw = re.search(r"(?m)^\s*molWeight\s+([-+0-9.eE]+)\s*;", text) - cp = re.search(r"(?m)^\s*Cp\s+([-+0-9.eE]+)\s*;", text) - if not mw or not cp: - return 1.4, 287.0 - gas = 8314.46261815324 / float(mw[1]) - heat = float(cp[1]) - return (heat / (heat - gas) if heat > gas else 1.4), gas - - -def state_fields(case: Path, directory: Path, count: int) -> dict[str, list[float]]: - _, fields = velocity_fields(directory, count) - for name in ( - "p", "p_rgh", "rho", "T", "CH4", "O2", "CO2", "H2O", "N2", "Qdot", - "alpha.water", "alpha.fuel", "h", - ): - values = scalars(directory, name, count) - if values: - fields[name] = values - if fields.get("T") and fields.get("speed"): - gamma, gas = thermo(case) - fields["Mach"] = [u / math.sqrt(gamma * gas * t) if t > 0 else 0.0 for u, t in zip(fields["speed"], fields["T"])] - hu = vectors(directory, "hU", count) - if hu and fields.get("h"): - fields["Froude"] = [ - q / h / math.sqrt(9.81 * h) if h > 1e-12 else 0.0 - for q, h in zip(magnitude(hu), fields["h"]) - ] - return fields - - -def line_profile( - profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float], - axis: int, fixed_axis: int, fraction: float, fields: dict[str, list[float]], names: list[str], -) -> dict[str, Any]: - low, high = bounds(centres) - target = low[fixed_axis] + fraction * (high[fixed_axis] - low[fixed_axis]) - target = min((point[fixed_axis] for point in centres), key=lambda value: abs(value - target)) - bandwidth = max((high[fixed_axis] - low[fixed_axis]) / 41.0, 1e-12) - selected = lambda point: abs(point[fixed_axis] - target) <= bandwidth - usable = {name: fields[name] for name in names if name in fields} - return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable, selector=selected), list(usable)) - - -def section_profile( - profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float], axis: int, - fields: dict[str, list[float]], names: list[str], -) -> dict[str, Any]: - usable = {name: fields[name] for name in names if name in fields} - return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable), list(usable)) - - -def histories( - case: Path, centres: list[tuple[float, float, float]], volumes: list[float], - measure: Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None], -) -> dict[str, Any]: - points = [] - for time, directory in numeric_times(case): - local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes) - fields = state_fields(case, directory, len(local_centres)) - value = measure(fields, local_centres, local_volumes) - if value is not None and math.isfinite(value): - points.append({"time": time, "value": float(value)}) - return history(points) - - -def shock_events(value: dict[str, Any]) -> dict[str, Any]: - events = [] - for item in value.get("profiles", []): - columns, rows = item["columns"], item["rows"] - if "p" not in columns or len(rows) < 2: - continue - p_index = columns.index("p") - candidates = [] - coordinate_min, coordinate_max = rows[0][0], rows[-1][0] - interior_low = coordinate_min + 0.05 * (coordinate_max - coordinate_min) - interior_high = coordinate_max - 0.05 * (coordinate_max - coordinate_min) - for left, right in zip(rows, rows[1:]): - dx = right[0] - left[0] - coordinate = 0.5 * (right[0] + left[0]) - if dx > 0 and interior_low < coordinate < interior_high: - candidates.append((abs(right[p_index] - left[p_index]) / dx, coordinate, dx)) - if candidates: - _, coordinate, cell = max(candidates) - events.append({"profile_id": item["profile_id"], "field": "p", "coordinate": coordinate, "local_cell_size": cell}) - return {"kind": "profile_feature_locations", "events": events} - - -def relative_drift(values: list[float]) -> float | None: - finite_values = [float(value) for value in values if math.isfinite(value)] - if len(finite_values) < 2: - return None - scale = max(abs(finite_values[0]), sum(abs(value) for value in finite_values) / len(finite_values), 1e-12) - return (max(finite_values) - min(finite_values)) / scale - - -def pressure_change( - pressure: list[float], centres: list[tuple[float, float, float]], volumes: list[float], axis: int, -) -> float | None: - if not pressure: - return None - cut = max(1, len(pressure) // 10) - ordered = sorted(zip(centres, pressure, volumes), key=lambda item: item[0][axis]) - first, last = ordered[:cut], ordered[-cut:] - return weighted([p for _, p, _ in first], [w for _, _, w in first]) - weighted( - [p for _, p, _ in last], [w for _, _, w in last] - ) - - -def inventory_series(case: Path, field_name: str) -> list[float]: - centres, volumes, _, _ = geometry(case) - values = [] - for _, directory in numeric_times(case): - local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes) - field = scalars(directory, field_name, len(local_centres)) - if field: - values.append(sum(value * volume for value, volume in zip(field, local_volumes))) - return values - - -def shock_pressure_jump_ratio(profiles: dict[str, Any]) -> float | None: - ratios = [] - for item in profiles.get("profiles", []): - columns, rows = item.get("columns", []), item.get("rows", []) - if "p" not in columns: - continue - index = columns.index("p") - for left, right in zip(rows, rows[1:]): - low, high = sorted((float(left[index]), float(right[index]))) - if low > 0: - ratios.append(high / low) - return max(ratios) if ratios else None - - -def family_qois(case: Path, template: str) -> dict[str, Any]: - centres, volumes, _, latest = geometry(case) - low, high = bounds(centres) - spans = [high[i] - low[i] for i in range(3)] - primary = primary_axis(spans) - secondary = 1 if primary == 0 else 0 - fields = state_fields(case, latest, len(centres)) - if fields.get("p"): - pressure_mean = weighted(fields["p"], volumes) - fields["p_gauge"] = [value - pressure_mean for value in fields["p"]] - qois: dict[str, Any] = {} - - def downstream_min_u(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None: - values = [u for point, u in zip(c, f.get("u", [])) if point[primary] >= low[primary] + 0.5 * spans[primary]] - return min(values) if values else None - - def middle_section_mean(name: str, fraction: float = 0.5) -> Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None]: - def measure(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None: - values = f.get(name, []) - if not values: - return None - local_low, local_high = bounds(c) - target = local_low[primary] + fraction * (local_high[primary] - local_low[primary]) - target = min((point[primary] for point in c), key=lambda value: abs(value - target)) - width = max((local_high[primary] - local_low[primary]) / 41.0, 1e-12) - selected = [(value, volume) for point, value, volume in zip(c, values, v) if abs(point[primary] - target) <= width] - return weighted([item[0] for item in selected], [item[1] for item in selected]) if selected else None - return measure - - def wake_deficit(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None: - streamwise = f.get("u", []) - if not streamwise: - return None - local_low, local_high = bounds(c) - span = local_high[primary] - local_low[primary] - width = max(span / 41.0, 1e-12) - section_values = [] - for fraction in (0.10, 0.65): - target = local_low[primary] + fraction * span - target = min((point[primary] for point in c), key=lambda value: abs(value - target)) - selected = [(u, volume) for point, u, volume in zip(c, streamwise, v) - if abs(point[primary] - target) <= width] - if not selected: - return None - section_values.append(weighted([item[0] for item in selected], [item[1] for item in selected])) - upstream, wake = section_values - return (upstream - wake) / max(abs(upstream), 1e-12) - - if template == "BernardCells": - qois["thermal_vertical_profile"] = named_profiles([ - line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["T", "u", "v", "speed"]) - ]) - qois["circulation_strength_history"] = histories(case, centres, volumes, lambda f, c, v: weighted(f["speed"], v) if f.get("speed") else None) - if fields.get("T"): - qois["temperature_min"] = min(fields["T"]) - qois["temperature_max"] = max(fields["T"]) - if fields.get("speed"): - qois["convection_mean_speed"] = weighted(fields["speed"], volumes) - elif template == "Cavity": - qois["centerline_velocity_profiles"] = named_profiles([ - line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["u", "v", "speed"]), - line_profile("horizontal_centerline", centres, volumes, 0, 1, 0.5, fields, ["u", "v", "speed"]), - ]) - 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) - if fields.get("speed"): - qois["response_speed_max"] = max(fields["speed"]) - if fields.get("u"): - qois["reverse_flow_min_u"] = min(fields["u"]) - elif template == "Cylinder": - qois["wake_velocity_profiles"] = named_profiles([ - line_profile(f"wake_x_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"]) - for fraction in (0.65, 0.80) - ]) - qois["wake_deficit_history"] = histories(case, centres, volumes, wake_deficit) - points = qois["wake_deficit_history"].get("points", []) - if points: - qois["wake_deficit_final"] = float(points[-1]["value"]) - elif template == "counterFlowFlame2D": - names = ["T", "CO2"] + (["Qdot"] if fields.get("Qdot") else []) - qois["reaction_zone_profile"] = named_profiles([section_profile("reaction_axis", centres, volumes, primary, fields, names)]) - if fields.get("Qdot"): - 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) - else: - qois["peak_temperature_history"] = histories(case, centres, volumes, lambda f, c, v: max(f["T"]) if f.get("T") else None) - species = [fields[name] for name in ("CH4", "O2", "CO2", "H2O", "N2") if fields.get(name)] - if len(species) == 5: - qois["species_sum_max_error"] = max(abs(sum(values) - 1.0) for values in zip(*species)) - if fields.get("T"): - qois["reaction_temperature_span"] = max(fields["T"]) - min(fields["T"]) - elif template == "damBreakWithObstacle": - 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)) - alpha = fields.get("alpha.water", []) - rows = [] - for slot in bins(centres, volumes, 0, {"alpha": alpha}): - x = slot[0] - width = spans[0] / 41 - wet_y = [p[1] for p, a in zip(centres, alpha) if abs(p[0] - x) <= width and a >= 0.5] - if wet_y: - rows.append([x, max(wet_y)]) - qois["free_surface_profile"] = named_profiles([profile("alpha_0.5_surface", "x", rows, ["surface_y"])]) - drift = relative_drift(inventory_series(case, "alpha.water")) - if drift is not None: - qois["water_volume_relative_drift"] = drift - front_points = qois["front_position_history"].get("points", []) - if len(front_points) >= 2: - qois["front_net_advance"] = float(front_points[-1]["value"]) - float(front_points[0]["value"]) - elif template in {"forwardStep", "obliqueShock", "wedge", "Shock"}: - profiles = named_profiles([ - line_profile(f"streamline_{fraction:.2f}", centres, volumes, primary, secondary, fraction, fields, ["p", "Mach", "u", "speed"]) - for fraction in (0.25, 0.50, 0.75) - ]) - qois["pressure_mach_profiles"] = profiles - qois["shock_feature_locations"] = shock_events(profiles) - if fields.get("Mach"): - qois["supersonic_volume_fraction"] = sum( - volume for mach, volume in zip(fields["Mach"], volumes) if mach > 1.0 - ) / sum(volumes) - jump = shock_pressure_jump_ratio(profiles) - if jump is not None: - qois["shock_pressure_jump_ratio"] = jump - elif template in {"pitzDaily", "Obstacle"}: - qois["separation_profiles"] = named_profiles([ - section_profile("streamwise_sections", centres, volumes, primary, fields, ["u", "v", "speed", "p_gauge"]), - *[line_profile(f"wake_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"]) for fraction in (0.65, 0.80)], - ]) - qois["recirculation_strength_history"] = histories(case, centres, volumes, downstream_min_u) - downstream = [ - (u, volume) for point, u, volume in zip(centres, fields.get("u", []), volumes) - if point[primary] >= low[primary] + 0.5 * spans[primary] - ] - if downstream: - qois["reverse_flow_volume_fraction"] = sum( - volume for u, volume in downstream if u < 0.0 - ) / sum(volume for _, volume in downstream) - change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary) - if change is not None: - qois["streamwise_pressure_change_magnitude"] = abs(change) - elif template == "shallowWaterWithSquareBump": - qois["surface_profile"] = named_profiles([section_profile("bump_axis", centres, volumes, primary, fields, ["h", "Froude"])]) - qois["mid_bump_height_history"] = histories(case, centres, volumes, middle_section_mean("h")) - height_points = qois["mid_bump_height_history"].get("points", []) - if len(height_points) >= 2: - first, last = float(height_points[0]["value"]), float(height_points[-1]["value"]) - qois["mid_bump_height_relative_change"] = abs(last - first) / max(abs(first), 1e-12) - elif template in {"squareBend", "Nozzle"}: - prefix = "bend" if template == "squareBend" else "nozzle" - qois[f"{prefix}_axial_profile"] = named_profiles([section_profile("axial_sections", centres, volumes, primary, fields, ["p", "p_rgh", "Mach", "u", "speed"])]) - def pressure_drop(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None: - return pressure_change(f.get("p") or f.get("p_rgh") or [], c, v, primary) - qois["pressure_drop_history"] = histories(case, centres, volumes, pressure_drop) - if template == "squareBend": - change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary) - if change is not None: - qois["streamwise_pressure_change_magnitude"] = abs(change) - else: - drift = relative_drift(inventory_series(case, "alpha.fuel")) - if drift is not None: - qois["transported_phase_inventory_relative_drift"] = drift - if fields.get("speed"): - qois["flow_speed_max"] = max(fields["speed"]) - else: - raise ValueError(f"no structured QoI family for {template}") - return qois - - -def structured_errors(name: str, value: Any) -> list[str]: - if isinstance(value, (int, float)) and not isinstance(value, bool): - return [] if math.isfinite(float(value)) else [f"{name}: non-finite scalar"] - if not isinstance(value, dict): - return [f"{name}: not structured"] - if value.get("kind") == "time_history": - return [] if len(value.get("points", [])) >= 2 else [f"{name}: fewer than two history points"] - if value.get("kind") == "named_profiles": - profiles = value.get("profiles", []) - 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"] - if value.get("kind") == "profile_feature_locations": - return [] if value.get("events") else [f"{name}: no feature events"] - return [f"{name}: unsupported kind"] - - -def extract( - case: Path, - case_id: str, - requested_metrics: list[str] | None = None, - *, - required_metrics: list[str] | None = None, - log_paths: list[Path] | None = None, -) -> dict[str, Any]: - family = case_id.split("/", 1)[0] - template = ADVANCED_TEMPLATE.get(case_id, family) - values = family_qois(case, template) - requested = requested_metrics or sorted(values) - required = required_metrics or requested - selected = {name: values[name] for name in requested if name in values} - missing = sorted(set(required) - set(selected)) - errors = [ - error for name, value in selected.items() if name in required - for error in structured_errors(name, value) - ] - _, _, latest_time, _ = geometry(case) - complete = not missing and not errors - return { - "schema_version": "foambench.qoi.candidate", "case_id": case_id, "family": template, - "latest_time": latest_time, "status": "complete" if complete else "incomplete", - "principal_qoi_group": GROUPS[template], - "principal_metrics": sorted(name for name in required if name in selected), - "required_metrics": required, "missing_metrics": missing, "qois": selected, - "health": {"status": "pass" if complete else "fail", "checks": { - "principal_qoi_complete": not missing, "structured_qoi_valid": not errors, - "measurement_geometry_available": True, "no_proxy_fallback": True, - }, "validation_errors": errors}, - } - - -FIELD_NORMALIZATION_FLOORS = { - "p": 1.0, "p_gauge": 1.0, "p_rgh": 1.0, "T": 0.1, "CO2": 1e-6, "Qdot": 1e-3, - "u": 1e-5, "v": 1e-5, "speed": 1e-5, "Mach": 1e-4, - "h": 1e-6, "Froude": 1e-4, "surface_y": 1e-6, -} -HISTORY_NORMALIZATION_FLOORS = { - "circulation_strength_history": 1e-6, "kinetic_energy_history": 1e-8, - "wake_deficit_history": 1e-4, "recirculation_strength_history": 1e-5, - "heat_release_history": 1e-3, "peak_temperature_history": 0.1, - "front_position_history": 1e-5, "mid_bump_height_history": 1e-6, - "pressure_drop_history": 1.0, -} - - -def tolerance(name: str, value: dict[str, Any], group: str) -> dict[str, Any]: - kind = value.get("kind") - if kind == "time_history": - return {"kind": kind, "normalized_rmse_max": 0.06 if group == "shock_response" else 0.08, - "normalized_linf_max": 0.15 if group == "shock_response" else 0.20, - "minimum_time_coverage": 1.0, - "normalization_floor": HISTORY_NORMALIZATION_FLOORS.get(name, 1e-8), "provisional": True} - if kind == "named_profiles": - columns = {column for item in value.get("profiles", []) for column in item.get("columns", [])[1:]} - return {"kind": kind, "normalized_l1_max": 0.05 if group == "shock_response" else 0.08, - "normalized_linf_max": 0.15 if group == "shock_response" else 0.20, - "normalization_floors": {column: FIELD_NORMALIZATION_FLOORS.get(column, 1e-8) for column in sorted(columns)}, - "criterion_role": "principal_response_shape", - "reference_independent": False, - "threshold_source": "reference_anchored_spatial_response_shape", - "provisional": True} - if kind == "profile_feature_locations": - return {"kind": kind, "maximum_cell_offset": 2.0, "physical_floor": 1e-10, "provisional": True} - raise ValueError(f"unsupported structured tolerance for {kind}") - - -def uniform_scalars(path: Path) -> list[float]: - return [ - float(match) - for match in re.findall(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", read_text(path)) - ] - - -def uniform_vector_magnitudes(path: Path) -> list[float]: - return [ - math.sqrt(sum(float(component) ** 2 for component in match)) - for match in re.findall( - r"\bvalue\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)\s*;", - read_text(path), - ) - ] - - -def physical_tolerance(template: str, name: str, case: Path) -> dict[str, Any]: - common: dict[str, Any] = { - "kind": "physics_range", - "criterion_role": "principal_physics", - "reference_independent": True, - } - if template == "BernardCells" and name in {"temperature_min", "temperature_max"}: - imposed = uniform_scalars(case / "0" / "T") - if len(imposed) < 2: - raise ValueError(f"{case}: cannot determine imposed temperature envelope") - low, high = min(imposed), max(imposed) - margin = max(1e-6, 0.02 * max(high - low, 1e-6)) - bounds = (low - margin, high + margin) - return {**common, "low": bounds[0], "high": bounds[1], - "threshold_source": "imposed_temperature_boundary_envelope", "provisional": False} - if template == "BernardCells" and name == "convection_mean_speed": - return {**common, "low": 1e-12, "high": 1e6, - "threshold_source": "nontrivial_buoyant_response", "provisional": True} - if template == "Cavity": - imposed = uniform_vector_magnitudes(case / "0" / "U") - lid_speed = max(imposed, default=0.0) - if lid_speed <= 0: - raise ValueError(f"{case}: cannot determine moving-wall speed") - if name == "response_speed_max": - return {**common, "low": 0.10 * lid_speed, "high": 1.0 * lid_speed, - "threshold_source": "lid_speed_response_envelope_tightened", "provisional": True} - if name == "reverse_flow_min_u": - return {**common, "low": -1.0 * lid_speed, "high": -0.05 * lid_speed, - "threshold_source": "main_vortex_reverse_flow_envelope_tightened", "provisional": True} - if template == "shallowWaterWithSquareBump" and name == "mid_bump_height_relative_change": - initial_depths = uniform_scalars(case / "0" / "h") - initial_depth = sum(initial_depths) / len(initial_depths) if initial_depths else 0.0 - # The shallow-water family changes regime with its prompt-specified - # initial depth. A single non-zero floor would accept a numerically - # stagnant response for the deeper cases. - low = 2e-4 if initial_depth <= 0.012 else 0.1 - return {**common, "low": low, "high": 1.0, - "threshold_source": "initial_depth_conditioned_bump_response", "provisional": True} - fixed = { - # These are first-stage family envelopes: they reject merely non-zero - # signatures while retaining the checked-in reference regimes. They - # are intentionally absolute and reference-independent; later runs can - # replace them with law-based relations or repeatability envelopes. - ("Cylinder", "wake_deficit_final"): (0.03, 0.15, "bounded_dimensionless_wake_deficit"), - ("counterFlowFlame2D", "species_sum_max_error"): (0.0, 5e-5, "species_mass_fraction_closure_tightened"), - ("counterFlowFlame2D", "reaction_temperature_span"): (500.0, 3000.0, "bounded_thermal_reaction_zone"), - ("damBreakWithObstacle", "water_volume_relative_drift"): (0.0, 5e-3, "closed_phase_volume_conservation_tightened"), - ("damBreakWithObstacle", "front_net_advance"): (0.03, 0.25, "bounded_downstream_free_surface_advance"), - ("forwardStep", "supersonic_volume_fraction"): (0.40, 1.0, "supersonic_regime_coverage_tightened"), - ("obliqueShock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"), - ("wedge", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"), - ("Shock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"), - ("forwardStep", "shock_pressure_jump_ratio"): (1.50, 20.0, "bounded_compressive_pressure_feature"), - ("obliqueShock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"), - ("wedge", "shock_pressure_jump_ratio"): (2.00, 6.50, "bounded_compressive_pressure_feature"), - ("Shock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"), - ("pitzDaily", "reverse_flow_volume_fraction"): (1e-3, 0.08, "bounded_separated_reverse_flow_signature"), - ("pitzDaily", "streamwise_pressure_change_magnitude"): (8.0, 140.0, "bounded_streamwise_pressure_response"), - ("Obstacle", "streamwise_pressure_change_magnitude"): (0.005, 10.0, "bounded_obstacle_pressure_response"), - ("squareBend", "streamwise_pressure_change_magnitude"): (3e4, 1.2e5, "bounded_bend_pressure_response"), - ("Nozzle", "flow_speed_max"): (100.0, 1000.0, "bounded_nozzle_flow_response"), - } - if (template, name) not in fixed: - raise ValueError(f"no physics tolerance for {template}/{name}") - low, high, source = fixed[(template, name)] - exact_sources = {"species_mass_fraction_closure", "closed_phase_volume_conservation"} - return {**common, "low": low, "high": high, "threshold_source": source, - "provisional": source not in exact_sources} - - -def diagnostic_scalar_tolerance(value: float) -> dict[str, Any]: - scale = max(abs(float(value)), 1e-12) - return { - "low": float(value) - 0.2 * scale, - "high": float(value) + 0.2 * scale, - "kind": "diagnostic_scalar_reference", - "provisional": True, - "threshold_source": "reference_diagnostic_relative_band", - } - - -def build_references(run_root: Path) -> tuple[dict[str, Any], dict[str, Any]]: - documents: dict[str, dict[str, Any]] = {} - for track in ("basic", "advanced"): - records = {} - for wrapper in sorted((run_root / "materialized" / track).iterdir()): - case = wrapper / "case" - if not case.is_dir(): - continue - case_id = wrapper.name.replace("__", "/", 1) if track == "basic" else wrapper.name - candidate = extract(case, case_id) - if candidate["status"] != "complete": - raise ValueError(f"{case_id}: {candidate['health'].get('validation_errors') or candidate['missing_metrics']}") - group, qois = candidate["principal_qoi_group"], candidate["qois"] - principal = list(principal_metrics(candidate["family"])) - missing_principal = sorted(set(principal) - set(qois)) - if missing_principal: - raise ValueError(f"{case_id}: missing physics metrics {missing_principal}") - roles = {name: "principal" if name in principal else "diagnostic" for name in qois} - tolerances = { - name: tolerance(name, value, group) - if isinstance(value, dict) and name in principal else ( - physical_tolerance(candidate["family"], name, case) - if name in principal else ( - diagnostic_scalar_tolerance(value) - if isinstance(value, (int, float)) and not isinstance(value, bool) - else tolerance(name, value, group) - ) - ) - for name, value in qois.items() - } - records[case_id] = { - "track": track, "family": candidate["family"], "source_case_id": case_id, - "latest_time": candidate["latest_time"], "principal_qoi_group": group, - "principal_metrics": sorted(principal), "qois": qois, - "metric_roles": roles, "tolerances": tolerances, - "health": candidate["health"], "extraction": { - "producer": "benchmarks/evaluation/basic_advanced.py", - "geometry": "field-derived physics metrics plus physical-coordinate reference diagnostics", - "reference_run": str(run_root), - }, - } - documents[track] = { - "schema_version": "foambench.reference_qois.v2", "generated_at": utc_now(), - "openfoam_version": "Foundation v13", "producer": "benchmarks/evaluation/basic_advanced.py", - "design": "guide/foambench_basic_advanced_qoi_design.md", - "tolerance_policy": "physics_grounded_scalar_and_response_shape_joint_gate.v2", - "summary": {"tracks": [track], "case_count": len(records), "health_pass_count": len(records), "health_fail_count": 0}, - "notes": ["Principal scalar QoIs are reference-independent family physics criteria extracted from retained fields.", - "One existing spatial response profile per family is also principal and must jointly pass its reference-anchored shape tolerance.", - "Other histories, profiles, and feature locations remain diagnostic and do not decide Physics-grounded pass.", - "Provisional physical-signature and response-shape limits require future valid-alternative calibration."], - "cases": records, - } - validate(documents[track], "foambench_qoi_reference.schema.json") - return documents["basic"], documents["advanced"] - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--run-root", required=True, type=Path) - parser.add_argument("--basic-output", required=True, type=Path) - parser.add_argument("--advanced-output", required=True, type=Path) - args = parser.parse_args() - basic, advanced = build_references(args.run_root.resolve(strict=True)) - write_json(args.basic_output, basic) - write_json(args.advanced_output, advanced) - print(json.dumps({"basic": len(basic["cases"]), "advanced": len(advanced["cases"])}, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/evaluation/cli.py b/benchmarks/evaluation/cli.py deleted file mode 100644 index 05e32d5af8fb3ec180d89e73f7a4aa4c9161302f..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/cli.py +++ /dev/null @@ -1,79 +0,0 @@ -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path - -from .io import read_object -from .models import BenchmarkProfile -from .pipeline import evaluate_campaign -from .preparation import prepare_campaign -from .profiles import load_assets -from .reporting import summary_table -from .schema import validate - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description="Evaluate FoamBench rollouts with a dataset-independent scorer.") - subparsers = parser.add_subparsers(dest="command", required=True) - validate = subparsers.add_parser("validate-profile", help="validate benchmark profile assets") - validate.add_argument("--profile", type=Path, required=True) - evaluate = subparsers.add_parser("evaluate", help="evaluate one rollout campaign") - evaluate.add_argument("--profile", type=Path, required=True) - evaluate.add_argument("--adapter", choices=("easyfoam", "foamagent", "chatcfd", "coding-agent"), required=True) - evaluate.add_argument("--run-root", type=Path, required=True) - evaluate.add_argument("--output", type=Path, required=True) - evaluate.add_argument( - "--prepare", action="store_true", - help="generate measurement-only C, Vc, and vorticity fields before evaluation", - ) - evaluate.add_argument("--prepare-jobs", type=int, default=1) - evaluate.add_argument( - "--check-mesh", action="store_true", - help="run read-only checkMesh when no retained mesh log is available", - ) - evaluate.add_argument("--mesh-timeout", type=float, default=120.0) - return parser - - -def main(argv: list[str] | None = None) -> int: - args = build_parser().parse_args(argv) - validate(read_object(args.profile), "benchmark_profile.schema.json") - profile = BenchmarkProfile.load(args.profile) - if args.command == "validate-profile": - benchmark, references = load_assets(profile) - print(json.dumps({ - "profile_id": profile.profile_id, - "dataset": profile.dataset, - "benchmark_case_count": len(benchmark), - "reference_case_count": len(references), - "status": "pass", - }, indent=2, sort_keys=True)) - return 0 - if args.prepare: - prepare_campaign( - profile, - adapter_name=args.adapter, - run_root=args.run_root, - output_root=args.output.resolve() / "preparation", - jobs=args.prepare_jobs, - ) - report = evaluate_campaign( - profile, - adapter_name=args.adapter, - run_root=args.run_root, - output_dir=args.output, - check_mesh=args.check_mesh, - mesh_timeout=args.mesh_timeout, - ) - print(summary_table(report["overall"])) - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, ValueError, RuntimeError) as exc: - print(f"foambench-evaluate: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/evaluation/comparison.py b/benchmarks/evaluation/comparison.py deleted file mode 100644 index 946206e34623d1714b26ab564f3232b6d2263ced..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/comparison.py +++ /dev/null @@ -1,750 +0,0 @@ -#!/usr/bin/env python3 -"""Compare candidate FoamBench QoIs with checked-in reference contracts. - -Coverage and numerical agreement are reported separately. Related field -statistics are scored as equal-weight QoI groups; ranges and runtime metrics -remain available as diagnostics but do not determine the group score. A -missing QoI means that the benchmark cannot assess that part of the result; it -is not relabelled as an out-of-tolerance value. -""" -from __future__ import annotations - -import argparse -import json -import math -import re -import sys -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - - -def finite(value: Any) -> float | None: - if isinstance(value, bool) or not isinstance(value, (int, float)): - return None - result = float(value) - return result if math.isfinite(result) else None - - -def scalar_observation(value: Any) -> float | None: - direct = finite(value) - if direct is not None: - return direct - if isinstance(value, dict) and value.get("kind") in {"scalar_ratio", "window_regression"}: - return finite(value.get("value")) - return None - - -def interpolate(points: list[dict[str, Any]], time: float) -> float | None: - rows = [(finite(item.get("time")), finite(item.get("value"))) for item in points if isinstance(item, dict)] - rows = sorted((t, v) for t, v in rows if t is not None and v is not None) - if not rows or time < rows[0][0] or time > rows[-1][0]: - return None - for index, (left_t, left_v) in enumerate(rows): - if abs(time - left_t) <= 1e-12 * max(1.0, abs(time)): - return left_v - if index + 1 < len(rows) and left_t < time < rows[index + 1][0]: - right_t, right_v = rows[index + 1] - weight = (time - left_t) / (right_t - left_t) - return left_v + weight * (right_v - left_v) - return None - - -def compare_history(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]: - reference_points = reference.get("points", []) - candidate_points = candidate.get("points", []) - pairs = [] - for point in reference_points if isinstance(reference_points, list) else []: - time, reference_value = finite(point.get("time")), finite(point.get("value")) if isinstance(point, dict) else (None, None) - if time is None or reference_value is None: - continue - candidate_value = interpolate(candidate_points if isinstance(candidate_points, list) else [], time) - if candidate_value is not None: - pairs.append((reference_value, candidate_value)) - required_coverage = finite(tolerance.get("minimum_time_coverage")) or 1.0 - coverage = len(pairs) / len(reference_points) if reference_points else 0.0 - if not pairs: - return {"status": "missing", "coverage_fraction": coverage} - floor = finite(tolerance.get("normalization_floor")) or 1e-12 - norm = max(math.sqrt(sum(ref * ref for ref, _ in pairs) / len(pairs)), floor) - errors = [cand - ref for ref, cand in pairs] - nrmse = math.sqrt(sum(error * error for error in errors) / len(errors)) / norm - nlinf = max(abs(error) for error in errors) / norm - rmse_limit = finite(tolerance.get("normalized_rmse_max")) - linf_limit = finite(tolerance.get("normalized_linf_max")) - valid = rmse_limit is not None and linf_limit is not None - passed = valid and coverage >= required_coverage and nrmse <= rmse_limit and nlinf <= linf_limit - return {"status": "within_tolerance" if passed else "invalid_contract" if not valid else "out_of_tolerance", - "coverage_fraction": coverage, "aligned_point_count": len(pairs), - "normalized_rmse": nrmse, "normalized_linf": nlinf, - "normalized_rmse_max": rmse_limit, "normalized_linf_max": linf_limit} - - -def profile_key(profile: dict[str, Any]) -> str: - """Normalize centerline aliases by the coordinate direction they sample.""" - name = Path(str(profile.get("profile_id", ""))).name.lower() - stem = Path(name).stem - if stem in {"centreline_y0", "centerline_y0", "centerliney", "horizontal", "horizontalcenterline", "horizontalcentreline"}: - return "horizontal.xy" - if stem in {"centreline_x0", "centerline_x0", "centerlinex", "vertical", "verticalcenterline", "verticalcentreline"}: - return "vertical.xy" - return name - - -def compare_profiles(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]: - references = {profile_key(item): item for item in reference.get("profiles", []) if isinstance(item, dict)} - candidates = {profile_key(item): item for item in candidate.get("profiles", []) if isinstance(item, dict)} - l1_limit, linf_limit = finite(tolerance.get("normalized_l1_max")), finite(tolerance.get("normalized_linf_max")) - if l1_limit is None or linf_limit is None: - return {"status": "invalid_contract"} - fields: list[dict[str, Any]] = [] - expected_fields = sum(max(0, len(item.get("columns", [])) - 1) for item in references.values()) - for key, ref_profile in references.items(): - cand_profile = candidates.get(key) - if cand_profile is None: - continue - ref_columns, cand_columns = ref_profile.get("columns", []), cand_profile.get("columns", []) - ref_rows, cand_rows = ref_profile.get("rows", []), cand_profile.get("rows", []) - if len(ref_columns) < 2 or ref_columns[0] not in cand_columns: - continue - cand_x = cand_columns.index(ref_columns[0]) - for field in ref_columns[1:]: - if field not in cand_columns: - continue - ref_i, cand_i = ref_columns.index(field), cand_columns.index(field) - cand_points = [{"time": row[cand_x], "value": row[cand_i]} for row in cand_rows] - pairs = [(row[ref_i], interpolate(cand_points, row[0])) for row in ref_rows] - pairs = [(ref, cand) for ref, cand in pairs if finite(ref) is not None and cand is not None] - if not pairs: - continue - declared_floors = tolerance.get("normalization_floors", {}) - field_floor = finite(declared_floors.get(field)) if isinstance(declared_floors, dict) else None - norm = max(sum(abs(ref) for ref, _ in pairs) / len(pairs), field_floor or finite(tolerance.get("normalization_floor")) or 1e-12) - errors = [abs(cand - ref) for ref, cand in pairs] - fields.append({"profile": key, "field": field, "normalized_l1": sum(errors) / len(errors) / norm, - "normalized_linf": max(errors) / norm}) - coverage = len(fields) / expected_fields if expected_fields else 0.0 - passed = bool(fields) and coverage == 1.0 and all(item["normalized_l1"] <= l1_limit and item["normalized_linf"] <= linf_limit for item in fields) - return {"status": "within_tolerance" if passed else "missing" if not fields else "out_of_tolerance", - "coverage_fraction": coverage, "observed_field_count": len(fields), - "expected_field_count": expected_fields, "fields": fields, - "normalized_l1_max": l1_limit, "normalized_linf_max": linf_limit} - - -def compare_events(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]: - def groups(value: dict[str, Any]) -> dict[tuple[str, str], list[dict[str, Any]]]: - result: dict[tuple[str, str], list[dict[str, Any]]] = {} - for event in value.get("events", []): - if isinstance(event, dict): - result.setdefault((profile_key({"profile_id": event.get("profile_id", "")}), str(event.get("field"))), []).append(event) - return result - refs, cands = groups(reference), groups(candidate) - cell_limit = finite(tolerance.get("maximum_cell_offset")) - if cell_limit is None: - return {"status": "invalid_contract"} - offsets = [] - for key, ref_events in refs.items(): - cand_events = cands.get(key, []) - available = list(cand_events) - for event in ref_events: - coordinate = finite(event.get("coordinate")) - if coordinate is None or not available: - continue - match = min( - available, - key=lambda item: abs(value - coordinate) if (value := finite(item.get("coordinate"))) is not None else math.inf, - ) - available.remove(match) - matched_coordinate = finite(match.get("coordinate")) - if matched_coordinate is None: - continue - cell = max(finite(event.get("local_cell_size")) or 0.0, finite(match.get("local_cell_size")) or 0.0, - finite(tolerance.get("physical_floor")) or 1e-12) - offsets.append(abs(matched_coordinate - coordinate) / cell) - expected = sum(len(items) for items in refs.values()) - coverage = len(offsets) / expected if expected else 0.0 - passed = expected > 0 and coverage == 1.0 and max(offsets, default=math.inf) <= cell_limit - return {"status": "within_tolerance" if passed else "missing" if not offsets else "out_of_tolerance", - "coverage_fraction": coverage, "maximum_cell_offset": max(offsets, default=None), "allowed_cell_offset": cell_limit} - - -def compare_structured(reference: dict[str, Any], candidate: Any, tolerance: dict[str, Any]) -> dict[str, Any]: - if not isinstance(candidate, dict) or candidate.get("kind") != reference.get("kind"): - return {"status": "missing"} - kind = reference.get("kind") - if kind == "time_history": - return compare_history(reference, candidate, tolerance) - if kind == "branched_time_histories": - ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {}) - results = {name: compare_history(value, cand_branches.get(name, {}), tolerance) - for name, value in ref_branches.items()} - passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values()) - return {"status": "within_tolerance" if passed else "out_of_tolerance", "branches": results, - "coverage_fraction": sum(item.get("coverage_fraction", 0.0) for item in results.values()) / len(results) if results else 0.0} - if kind == "named_profiles": - return compare_profiles(reference, candidate, tolerance) - if kind == "profile_feature_locations": - return compare_events(reference, candidate, tolerance) - if kind == "component_trajectory": - refs = {str(item.get("component_id")): item for item in reference.get("series", [])} - cands = {str(item.get("component_id")): item for item in candidate.get("series", [])} - results = {key: compare_history({"points": item.get("points", [])}, {"points": cands.get(key, {}).get("points", [])}, tolerance) - for key, item in refs.items()} - passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values()) - return {"status": "within_tolerance" if passed else "out_of_tolerance", "components": results} - if kind == "component_scalars": - refs = {str(item.get("component_id")): finite(item.get("value")) for item in reference.get("components", [])} - cands = {str(item.get("component_id")): finite(item.get("value")) for item in candidate.get("components", [])} - relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12 - if relative is None: - return {"status": "invalid_contract"} - 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} - physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high")) - observed = [value for value in cands.values() if value is not None] - physically_valid = all( - (physical_low is None or value >= physical_low) - and (physical_high is None or value <= physical_high) - for value in observed - ) - passed = len(errors) == len(refs) and physically_valid and all(error <= relative for error in errors.values()) - return {"status": "within_tolerance" if passed else "missing" if not errors else "out_of_tolerance", - "relative_errors": errors, "physical_bounds_pass": physically_valid, - "physical_low": physical_low, "physical_high": physical_high} - if kind == "branch_scalars": - ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {}) - relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12 - if relative is None: - return {"status": "invalid_contract"} - errors: dict[str, Any] = {} - for branch, ref_metrics in ref_branches.items(): - cand_metrics = cand_branches.get(branch, {}) - errors[branch] = { - name: abs(float(cand_metrics[name]) - float(ref)) / max(abs(float(ref)), floor) - for name, ref in ref_metrics.items() - if name in cand_metrics and finite(ref) is not None and finite(cand_metrics[name]) is not None - } - complete = set(errors) == set(ref_branches) and all(set(errors[b]) == set(ref_branches[b]) for b in ref_branches) - physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high")) - observed = [value for branch in cand_branches.values() if isinstance(branch, dict) for value in branch.values() - if finite(value) is not None] - physically_valid = all( - (physical_low is None or float(value) >= physical_low) - and (physical_high is None or float(value) <= physical_high) - for value in observed - ) - passed = complete and physically_valid and all(error <= relative for branch in errors.values() for error in branch.values()) - return {"status": "within_tolerance" if passed else "missing" if not complete else "out_of_tolerance", - "relative_errors": errors, "relative_max": relative, - "physical_bounds_pass": physically_valid, "physical_low": physical_low, - "physical_high": physical_high} - scalar_ref, scalar_cand = scalar_observation(reference), scalar_observation(candidate) - if scalar_ref is not None and scalar_cand is not None: - relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12 - if relative is None: - return {"status": "invalid_contract"} - error = abs(scalar_cand - scalar_ref) / max(abs(scalar_ref), floor) - physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high")) - physically_valid = ( - (physical_low is None or scalar_cand >= physical_low) - and (physical_high is None or scalar_cand <= physical_high) - ) - passed = error <= relative and physically_valid - return {"status": "within_tolerance" if passed else "out_of_tolerance", - "relative_error": error, "relative_max": relative, "physical_bounds_pass": physically_valid, - "physical_low": physical_low, "physical_high": physical_high} - return {"status": "invalid_contract", "reason": f"unsupported structured kind {kind!r}"} - - -def comparison_quality(result: dict[str, Any]) -> float: - """Map comparison distance to [0, 1] without changing strict status.""" - status = result.get("status") - if status == "within_tolerance": - return 1.0 - if status in {"missing", "invalid_contract"}: - return 0.0 - distances: list[float] = [] - for key in ("relative_error", "normalized_rmse", "normalized_l1", "maximum_cell_offset"): - value = finite(result.get(key)) - limit = finite(result.get({ - "relative_error": "relative_max", - "normalized_rmse": "normalized_rmse_max", - "normalized_l1": "normalized_l1_max", - "maximum_cell_offset": "allowed_cell_offset", - }[key])) - if value is not None and limit is not None and limit > 0: - distances.append(value / limit) - for value in result.get("fields", []) if isinstance(result.get("fields"), list) else []: - if isinstance(value, dict): - q = comparison_quality({ - "status": "within_tolerance" if value.get("normalized_l1", math.inf) <= (result.get("normalized_l1_max") or 0.0) else "out_of_tolerance", - "normalized_l1": value.get("normalized_l1"), - "normalized_l1_max": result.get("normalized_l1_max"), - }) - distances.append(1.0 - q) - for value in result.get("branches", {}).values() if isinstance(result.get("branches"), dict) else []: - if isinstance(value, dict): - distances.append(1.0 - comparison_quality(value)) - ratio = sum(distances) / len(distances) if distances else 1.0 - return max(0.0, min(1.0, 1.0 / (1.0 + ratio))) - - -def load_cases(path: Path) -> dict[str, Any]: - data = json.loads(path.read_text(encoding="utf-8")) - cases = data.get("cases") if isinstance(data, dict) else None - if not isinstance(cases, dict): - raise ValueError(f"JSON has no cases object: {path}") - return cases - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") - temporary.replace(path) - - -STAT_SUFFIX_RE = re.compile(r"_(?:min|max|mean|range)$") -SCORING_POLICY = "grouped_qois" -EXPLICIT_SCORING_POLICY = "explicit_principal_qoi_group" - - -def case_scoring_policy(reference: dict[str, Any]) -> str: - return EXPLICIT_SCORING_POLICY if isinstance(reference.get("metric_roles"), dict) else SCORING_POLICY - - -def metric_role(name: str, explicit_roles: dict[str, Any] | None = None) -> str: - """Classify metrics without changing the extracted raw values. - - Residual and Courant values remain useful diagnostics, while ``range`` is - a deterministic derivative of min/max. All other legacy measurements are - scored, but related statistics are aggregated as one QoI group below. - """ - explicit = explicit_roles.get(name) if explicit_roles else None - if explicit in {"principal", "scored"}: - return "scored" - if explicit in {"diagnostic", "redundant"}: - return explicit - if "residual" in name or "courant" in name: - return "diagnostic" - if name.endswith("_range"): - return "redundant" - return "scored" - - -def metric_group(name: str, principal_group: str | None = None, - explicit_roles: dict[str, Any] | None = None) -> str: - if principal_group and explicit_roles and explicit_roles.get(name) in {"principal", "scored"}: - return principal_group - if name in {"center_u", "center_v", "center_w", "center_speed"}: - return "center_velocity" - return STAT_SUFFIX_RE.sub("", name) - - -def comparison_outcome(*, missing: list[str], out_of_tolerance: list[str], - invalid_contract: list[str], accepted: bool) -> str: - if invalid_contract: - return "invalid_contract" - if accepted: - return "pass" - if missing and out_of_tolerance: - return "incomplete_and_out_of_tolerance" - if missing: - return "incomplete" - return "out_of_tolerance" - - -def rollout_status(comparison: dict[str, Any]) -> str: - """Map a QoI result to a rollout status after execution has passed.""" - return { - "pass": "scientifically_validated", - "incomplete": "execution_passed_qoi_incomplete", - "out_of_tolerance": "execution_passed_qoi_out_of_tolerance", - "incomplete_and_out_of_tolerance": "execution_passed_qoi_incomplete_and_out_of_tolerance", - "invalid_contract": "execution_passed_qoi_evaluation_error", - "error": "execution_passed_qoi_evaluation_error", - }.get(str(comparison.get("status")), "execution_passed_qoi_evaluation_error") - - -def compare_case(reference: dict[str, Any], candidate: dict[str, Any], required_fraction: float) -> dict[str, Any]: - references = reference.get("qois") if isinstance(reference.get("qois"), dict) else {} - tolerances = reference.get("tolerances") if isinstance(reference.get("tolerances"), dict) else {} - candidates = candidate.get("qois") if isinstance(candidate.get("qois"), dict) else {} - explicit_roles = reference.get("metric_roles") if isinstance(reference.get("metric_roles"), dict) else None - principal_group = reference.get("principal_qoi_group") if isinstance(reference.get("principal_qoi_group"), str) else None - role_for = lambda name: metric_role(name, explicit_roles) - metrics: dict[str, Any] = {} - passed = 0 - out_of_tolerance: list[str] = [] - missing: list[str] = [] - invalid_contract: list[str] = [] - diagnostic_out_of_tolerance: list[str] = [] - diagnostic_missing: list[str] = [] - redundant_metric_count = 0 - groups: dict[str, dict[str, Any]] = {} - for name, reference_value in sorted(references.items()): - role = role_for(name) - group = metric_group(name, principal_group, explicit_roles) - if role == "redundant": - redundant_metric_count += 1 - value = finite(candidates.get(name)) - metrics[name] = { - "status": "available" if value is not None else "missing", - "role": role, - "group": group, - "reference_value": reference_value, - "candidate_value": value, - } - continue - group_record = groups.setdefault(group, { - "role": "scored" if role == "scored" else role, - "metrics": [], - "passed_metric_count": 0, - "observed_metric_count": 0, - "invalid_metric_count": 0, - "quality_sum": 0.0, - "coverage_fraction": 1.0, - }) - group_record["metrics"].append(name) - tolerance = tolerances.get(name) if isinstance(tolerances.get(name), dict) else {} - if isinstance(reference_value, dict): - result = compare_structured(reference_value, candidates.get(name), tolerance) - result["quality"] = comparison_quality(result) - status = result.get("status") - is_missing = status == "missing" - is_invalid = status == "invalid_contract" - is_pass = status == "within_tolerance" - structured_coverage = finite(result.get("coverage_fraction")) - if structured_coverage is not None: - group_record["coverage_fraction"] = min( - group_record["coverage_fraction"], structured_coverage - ) - elif is_missing: - group_record["coverage_fraction"] = 0.0 - if is_missing: - missing.append(name) - if role == "diagnostic": - diagnostic_missing.append(name) - elif is_invalid and role == "scored": - invalid_contract.append(name) - group_record["invalid_metric_count"] += 1 - else: - group_record["observed_metric_count"] += int(role == "scored") - if role == "scored": - passed += int(is_pass) - group_record["passed_metric_count"] += int(is_pass) - group_record["quality_sum"] += float(result["quality"]) - if not is_pass: - out_of_tolerance.append(name) - elif role == "diagnostic" and not is_pass: - diagnostic_out_of_tolerance.append(name) - metrics[name] = {"role": role, "group": group, "reference_value": reference_value, - "candidate_value": candidates.get(name), **result} - continue - value = finite(candidates.get(name)) - low, high = finite(tolerance.get("low")), finite(tolerance.get("high")) - if value is None: - missing.append(name) - group_record["coverage_fraction"] = 0.0 - if role == "diagnostic": - diagnostic_missing.append(name) - metrics[name] = { - "status": "missing", - "role": role, - "group": group, - "reference_value": reference_value, - "quality": 0.0, - } - continue - if low is None or high is None: - group_record["coverage_fraction"] = 0.0 - if role == "scored": - invalid_contract.append(name) - group_record["invalid_metric_count"] += 1 - metrics[name] = { - "status": "invalid_contract" if role == "scored" else "available_without_tolerance", - "role": role, - "group": group, - "reference_value": reference_value, - "candidate_value": value, - "quality": 0.0, - } - continue - physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high")) - physical_pass = ( - (physical_low is None or value >= physical_low) - and (physical_high is None or value <= physical_high) - ) - is_pass = low <= value <= high and physical_pass - tolerance_span = max(high - low, 1e-12) - distance = 0.0 if is_pass else min(abs(value - min(max(value, low), high)) / tolerance_span, 1.0) - quality = 1.0 if is_pass else max(0.0, 1.0 - distance) - if role == "scored": - passed += int(is_pass) - group_record["observed_metric_count"] += 1 - group_record["passed_metric_count"] += int(is_pass) - group_record["quality_sum"] += quality - if not is_pass: - out_of_tolerance.append(name) - elif role == "diagnostic" and not is_pass: - diagnostic_out_of_tolerance.append(name) - metrics[name] = { - "status": "within_tolerance" if is_pass else "out_of_tolerance", - "role": role, - "group": group, - "reference_value": reference_value, - "candidate_value": value, - "low": low, - "high": high, - "absolute_error": abs(value - float(reference_value)), - "criterion_role": tolerance.get("criterion_role"), - "threshold_source": tolerance.get("threshold_source"), - "reference_independent": tolerance.get("reference_independent", False), - "provisional": tolerance.get("provisional"), - "physical_bounds_pass": physical_pass, - "physical_low": physical_low, - "physical_high": physical_high, - "physical_threshold_source": tolerance.get("physical_threshold_source"), - "quality": quality, - } - scored_groups = { - name: record for name, record in groups.items() if record["role"] == "scored" - } - scored_metrics = [name for name in references if role_for(name) == "scored"] - scored_missing = [name for name in missing if role_for(name) == "scored"] - scored_count = len(scored_metrics) - extracted_count = sum(record["observed_metric_count"] for record in scored_groups.values()) - evaluated_count = extracted_count - coverage = extracted_count / scored_count if scored_count else 0.0 - metric_value_pass_fraction = passed / evaluated_count if evaluated_count else None - metric_joint_pass_fraction = passed / scored_count if scored_count else 0.0 - group_scores: dict[str, dict[str, Any]] = {} - for group_name, record in sorted(scored_groups.items()): - member_count = len(record["metrics"]) - group_score = record["quality_sum"] / member_count if member_count else 0.0 - group_coverage = ( - min(record["observed_metric_count"] / member_count, record["coverage_fraction"]) - if member_count else 0.0 - ) - group_scores[group_name] = { - "score": group_score, - "coverage_fraction": group_coverage, - "metric_count": member_count, - "observed_metric_count": record["observed_metric_count"], - "passed_metric_count": record["passed_metric_count"], - "metrics": record["metrics"], - } - qoi_pass_ratio = ( - sum(item["score"] for item in group_scores.values()) / len(group_scores) - if group_scores else 0.0 - ) - qoi_coverage_fraction = ( - sum(item["coverage_fraction"] for item in group_scores.values()) / len(group_scores) - if group_scores else 0.0 - ) - # Continuous quality is intentionally separate from the strict scientific - # acceptance bit. It exposes partial QoI agreement to Evolution without - # weakening the all-groups physics-grounded contract. - qoi_quality = qoi_pass_ratio * qoi_coverage_fraction - physics_grounded_accepted = bool( - scored_groups - and not scored_missing - and not invalid_contract - and not out_of_tolerance - and passed == scored_count - and all( - item["coverage_fraction"] == 1.0 - for item in group_scores.values() - ) - ) - threshold_pass = bool( - scored_groups - and qoi_coverage_fraction == 1.0 - and qoi_pass_ratio >= required_fraction - ) - outcome = comparison_outcome( - missing=scored_missing, - out_of_tolerance=out_of_tolerance, - invalid_contract=invalid_contract, - accepted=physics_grounded_accepted, - ) - diagnostic_names = [name for name in references if role_for(name) == "diagnostic"] - diagnostic_observed = [ - name for name in diagnostic_names - if metrics.get(name, {}).get("status") not in {None, "missing", "invalid_contract"} - ] - diagnostic_passed = [ - name for name in diagnostic_names if metrics.get(name, {}).get("status") == "within_tolerance" - ] - return { - "schema_version": "foambench.qoi.case_comparison.v3", - "scoring_policy": case_scoring_policy(reference), - "status": outcome, - "coverage_status": "complete" if scored_count and not scored_missing else "incomplete", - "value_status": ( - "not_assessed" if not scored_count - else "within_tolerance" if metric_value_pass_fraction is not None and metric_value_pass_fraction >= required_fraction - else "out_of_tolerance" - ), - "required_metric_count": scored_count, - "extracted_metric_count": extracted_count, - "evaluated_metric_count": evaluated_count, - "passed_metric_count": passed, - "coverage_fraction": coverage, - "value_pass_fraction": metric_value_pass_fraction, - "joint_pass_fraction": metric_joint_pass_fraction, - "qoi_pass_ratio": qoi_pass_ratio, - "qoi_quality": qoi_quality, - "qoi_coverage_fraction": qoi_coverage_fraction, - "group_count": len(group_scores), - "group_scores": group_scores, - "physics_grounded_qoi_pass": physics_grounded_accepted, - "threshold_pass": threshold_pass, - "diagnostic_metric_count": sum(len(record["metrics"]) for record in groups.values() if record["role"] == "diagnostic"), - "diagnostic_observed_metric_count": len(diagnostic_observed), - "diagnostic_passed_metric_count": len(diagnostic_passed), - "diagnostic_reference_coverage_fraction": ( - len(diagnostic_observed) / len(diagnostic_names) if diagnostic_names else None - ), - "diagnostic_reference_pass_fraction": ( - len(diagnostic_passed) / len(diagnostic_observed) if diagnostic_observed else None - ), - "redundant_metric_count": redundant_metric_count, - # Raw metric fractions remain available above; the canonical case-level - # quality score is qoi_pass_ratio. - "pass_fraction": metric_joint_pass_fraction, - "required_fraction": required_fraction, - "missing_metrics": missing, - "scored_missing_metrics": scored_missing, - "diagnostic_missing_metrics": diagnostic_missing, - "out_of_tolerance_metrics": out_of_tolerance, - "diagnostic_out_of_tolerance_metrics": diagnostic_out_of_tolerance, - "invalid_contract_metrics": invalid_contract, - "metrics": metrics, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--reference-qois", required=True, type=Path) - parser.add_argument("--candidate-qois", required=True, type=Path) - parser.add_argument("--case-id", action="append") - parser.add_argument( - "--required-fraction", - type=float, - default=1.0, - help="Optional observed-value/QoI-ratio threshold; physics_grounded_qoi_pass always requires every scored group.", - ) - parser.add_argument("--output", type=Path) - parser.add_argument("--json", action="store_true") - args = parser.parse_args() - if not 0 < args.required_fraction <= 1: - parser.error("--required-fraction must be in (0, 1]") - - references = load_cases(args.reference_qois.resolve(strict=True)) - candidates = load_cases(args.candidate_qois.resolve(strict=True)) - selected = args.case_id or sorted(references) - unknown = sorted(set(selected) - set(references)) - if unknown: - raise ValueError("unknown reference case IDs: " + ", ".join(unknown)) - - results: dict[str, Any] = {} - missing_cases: list[str] = [] - for case_id in selected: - candidate = candidates.get(case_id) - if not isinstance(candidate, dict): - missing_cases.append(case_id) - missing_metrics = sorted(references[case_id].get("qois", {})) - results[case_id] = { - "scoring_policy": case_scoring_policy(references[case_id]), - "status": "missing_candidate_case", - "coverage_status": "incomplete", - "value_status": "not_assessed", - "required_metric_count": len(missing_metrics), - "extracted_metric_count": 0, - "evaluated_metric_count": 0, - "passed_metric_count": 0, - "coverage_fraction": 0.0, - "value_pass_fraction": None, - "joint_pass_fraction": 0.0, - "qoi_pass_ratio": 0.0, - "qoi_coverage_fraction": 0.0, - "group_count": 0, - "pass_fraction": 0.0, - "missing_metrics": missing_metrics, - "out_of_tolerance_metrics": [], - "invalid_contract_metrics": [], - } - else: - results[case_id] = compare_case(references[case_id], candidate, args.required_fraction) - - family_rows: dict[str, list[dict[str, Any]]] = {} - for case_id, result in results.items(): - if "pass_fraction" in result: - reference_family = references.get(case_id, {}).get("family") - family = reference_family if isinstance(reference_family, str) and reference_family else case_id.split("/", 1)[0] - family_rows.setdefault(family, []).append(result) - def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]: - assessed = [row["value_pass_fraction"] for row in rows if row.get("value_pass_fraction") is not None] - qoi_ratios = [row["qoi_pass_ratio"] for row in rows if row.get("qoi_pass_ratio") is not None] - return { - "case_count": len(rows), - "passed_case_count": sum(row["status"] == "pass" for row in rows), - "incomplete_case_count": sum(bool(row.get("missing_metrics")) for row in rows), - "out_of_tolerance_case_count": sum(bool(row.get("out_of_tolerance_metrics")) for row in rows), - "macro_coverage_fraction": sum(row["coverage_fraction"] for row in rows) / len(rows), - "macro_value_pass_fraction": sum(assessed) / len(assessed) if assessed else None, - "macro_joint_pass_fraction": sum(row["joint_pass_fraction"] for row in rows) / len(rows), - "macro_qoi_pass_ratio": sum(qoi_ratios) / len(qoi_ratios) if qoi_ratios else 0.0, - "macro_qoi_coverage_fraction": sum(row.get("qoi_coverage_fraction", 0.0) for row in rows) / len(rows), - } - - families = {family: summarize(rows) for family, rows in sorted(family_rows.items())} - passed_cases = sum(result.get("status") == "pass" for result in results.values()) - aggregate = summarize(list(results.values())) if results else { - "incomplete_case_count": 0, - "out_of_tolerance_case_count": 0, - "macro_coverage_fraction": 0.0, - "macro_value_pass_fraction": None, - "macro_joint_pass_fraction": 0.0, - "macro_qoi_pass_ratio": 0.0, - "macro_qoi_coverage_fraction": 0.0, - } - policies = {result.get("scoring_policy", SCORING_POLICY) for result in results.values()} - report = { - "schema_version": "foambench.qoi.comparison.v3", - "scoring_policy": policies.pop() if len(policies) == 1 else "mixed", - "generated_at": datetime.now(timezone.utc).isoformat(), - "status": "pass" if passed_cases == len(selected) and not missing_cases else "fail", - "case_count": len(selected), - "passed_case_count": passed_cases, - "case_pass_fraction": passed_cases / len(selected) if selected else 0.0, - "incomplete_case_count": aggregate["incomplete_case_count"], - "out_of_tolerance_case_count": aggregate["out_of_tolerance_case_count"], - "macro_coverage_fraction": aggregate["macro_coverage_fraction"], - "macro_value_pass_fraction": aggregate["macro_value_pass_fraction"], - "macro_joint_pass_fraction": aggregate["macro_joint_pass_fraction"], - "macro_qoi_pass_ratio": aggregate["macro_qoi_pass_ratio"], - "macro_qoi_coverage_fraction": aggregate["macro_qoi_coverage_fraction"], - "missing_cases": missing_cases, - "families": families, - "cases": results, - } - if args.output: - write_json(args.output.resolve(), report) - if args.json or not args.output: - print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) - else: - print( - f"comparison: {args.output.resolve()} " - f"(physics_grounded={passed_cases}/{len(selected)}, " - f"qoi_pass_ratio={report['macro_qoi_pass_ratio']:.4f})" - ) - return 0 if report["status"] == "pass" else 1 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, ValueError, json.JSONDecodeError) as exc: - print(f"compare_foambench_qois.py: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/evaluation/evidence_contract.py b/benchmarks/evaluation/evidence_contract.py deleted file mode 100644 index cb01f7bc6559afc5e470de7f42607d8d7a08c593..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/evidence_contract.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Canonical evidence discovery for the Extended FoamBench contract. - -The resolver deliberately separates *where/how an agent writes a file* from -the physical quantity represented by its contents. Callers still validate -headers, units, time semantics, and dimensions before using a file as QoI -evidence; this module only provides deterministic semantic routing. -""" -from __future__ import annotations - -import re -import json -from pathlib import Path -from typing import Any - - -CANONICAL_ALIASES: dict[str, tuple[str, ...]] = { - "force_coefficients": ("forcecoeffs", "forcecoefficients", "forcecoefficient", "aerodynamicloads", "aeroloads", "loads"), - "patch_flux": ("patchflowrate", "patchflow", "massflow", "massflux", "rhophi", "fluxhistory"), - "patch_pressure": ("patchaverage", "patchintegrate", "pressurerise", "pressuredifference", "patchpressure"), - "wall_law_profile": ("spaldingcomparison", "uplusyplus", "walllawprofile", "velocityprofile", "wallprofile"), - "centerline_profile": ("centerline", "centreline", "horizontal", "vertical", "px0", "py0", "rhox0", "rhoy0"), - "bubble_geometry": ("bubblegeometry", "bubblemetrics", "interfacegeometry"), -} - -CONTRACT_VERSION = "foambench.evidence.contract.v1" -CONTRACT_FILE = Path(__file__).resolve().parents[1] / "FoamBench_extended_openfoam13_evidence_contract.v1.json" - -# A manifest may use the QoI name instead of the routing kind. This mapping -# keeps that interface stable while allowing metric extractors to retain their -# own physical validation rules. -METRIC_KINDS = { - "Cd": "force_coefficients", "Cl": "force_coefficients", "Cm": "force_coefficients", - "Cd_mean": "force_coefficients", "Cd_rms": "force_coefficients", - "Cl_mean": "force_coefficients", "Cl_rms": "force_coefficients", - "first_cell_yplus": "wall_law_profile", "spalding_log_rmse": "wall_law_profile", - "centerline_profiles": "centerline_profile", "event_locations": "centerline_profile", - "mass_flow_rate": "patch_flux", "volumetric_flow_rate": "patch_flux", - "pressure_rise": "patch_pressure", "pressure_rise_history": "patch_pressure", -} - - -def compact_name(value: str) -> str: - return re.sub(r"[^a-z0-9]", "", value.lower()) - - -def evidence_roots(case: Path) -> tuple[Path, ...]: - parent = case.parent - roots = ( - case / "postProcessing", case / "postprocessing", case / "results", case / "outputs", - parent / "postProcessing", parent / "postprocessing", parent / "results", parent / "outputs", - parent / "evidence", parent / "reports", - ) - return tuple(dict.fromkeys(root for root in roots if root.is_dir())) - - -def _manifest_paths(case: Path) -> tuple[Path, ...]: - """Locate the optional agent-emitted manifest without trusting its paths.""" - return tuple(dict.fromkeys((case / "evidence/qoi_manifest.v1.json", case.parent / "evidence/qoi_manifest.v1.json"))) - - -def declared_evidence(case: Path, kind: str) -> list[Path]: - """Return manifest-declared files for *kind* after path containment checks.""" - paths: list[Path] = [] - accepted_metrics = {kind, *[metric for metric, mapped in METRIC_KINDS.items() if mapped == kind]} - for manifest_path in _manifest_paths(case): - try: - payload = json.loads(manifest_path.read_text(encoding="utf-8")) - except (OSError, ValueError, TypeError): - continue - entries = payload.get("entries", []) if isinstance(payload, dict) else [] - if not isinstance(entries, list): - continue - for entry in entries: - if not isinstance(entry, dict) or entry.get("metric") not in accepted_metrics and entry.get("kind") != kind: - continue - raw = entry.get("path") - if not isinstance(raw, str) or not raw: - continue - candidate = (manifest_path.parent.parent / raw).resolve() - allowed = tuple(root.resolve() for root in evidence_roots(case)) - if candidate.is_file() and any(candidate == root or root in candidate.parents for root in allowed): - paths.append(candidate) - return sorted(set(paths)) - - -def resolve_evidence(case: Path, kind: str, *, suffixes: tuple[str, ...] = ()) -> list[Path]: - """Return files whose path semantically addresses canonical evidence kind. - - This function never parses or promotes a file. The metric-specific - extractor remains responsible for schema/header/unit validation. - """ - aliases = CANONICAL_ALIASES.get(kind, (kind,)) - paths: set[Path] = set(declared_evidence(case, kind)) - for root in evidence_roots(case): - for path in root.rglob("*"): - if not path.is_file(): - continue - if suffixes and path.suffix.lower() not in suffixes: - continue - compact = compact_name(str(path)) - if any(compact_name(alias) in compact for alias in aliases): - paths.add(path) - return sorted(paths) - - -def canonical_evidence_manifest() -> dict[str, object]: - """Machine-readable resolver contract for reports and future agents.""" - fallback = { - "schema_version": CONTRACT_VERSION, - "normalization": "lowercase_ascii_alphanumeric_path_matching", - "kinds": {key: list(value) for key, value in CANONICAL_ALIASES.items()}, - "content_validation": "required_by_metric_extractor", - "proxy_policy": "semantic routing never authorizes a proxy metric", - } - try: - payload = json.loads(CONTRACT_FILE.read_text(encoding="utf-8")) - except (OSError, ValueError, TypeError): - return fallback - return payload if isinstance(payload, dict) else fallback diff --git a/benchmarks/evaluation/execution.py b/benchmarks/evaluation/execution.py deleted file mode 100644 index 9d37479fa61904ccd51d3fd64dff75bae6bb89d3..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/execution.py +++ /dev/null @@ -1,62 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from .adapters.common import successful_formal_records -from .foam import FATAL_RE, converged_early, final_log_time, latest_time_dir, normal_end, read_logs -from .models import CaseArtifact - - -def evaluate_execution(artifact: CaseArtifact, expected_time: float | None) -> dict[str, Any]: - case_dir = artifact.case_dir - latest, _ = latest_time_dir(case_dir) - logs = artifact.solver_logs - text = read_logs(logs) - log_time = final_log_time(text) - successful = successful_formal_records(artifact.formal_run_records) - requires_formal_record = ( - artifact.workspace_dir is not None - and artifact.manifest.get("agent_mode") != "coding-only" - and artifact.manifest.get("domain_assets_enabled") is not False - ) - manifest_status = str(artifact.manifest.get("status", "")) - timed_out = bool(artifact.manifest.get("timed_out")) or manifest_status == "timed_out" - process_ok = artifact.manifest.get("return_code") in {None, 0} - observed_time = max(value for value in (latest, log_time) if value is not None) if any( - value is not None for value in (latest, log_time) - ) else None - reached = observed_time is not None and ( - expected_time is None - or observed_time >= expected_time - max(1e-12, abs(expected_time) * 1e-9) - or converged_early(text) - ) - checks = { - "case_directory_exists": bool(case_dir and case_dir.is_dir()), - "control_dict_exists": bool(case_dir and (case_dir / "system" / "controlDict").is_file()), - "agent_not_timed_out": not timed_out, - "agent_process_succeeded": process_ok, - "formal_run_succeeded": bool(successful) if requires_formal_record else True, - "solver_log_exists": bool(logs), - "no_fatal_log_marker": FATAL_RE.search(text) is None, - "latest_time_exists": latest is not None, - "stop_condition_reached": reached, - } - # Some retained run records omit the literal OpenFOAM "End" line from the - # selected stdout ref. Keep it as evidence rather than a hard requirement. - evidence = { - "normal_end_marker": normal_end(text), - "converged_early_marker": converged_early(text), - "formal_run_records": [str(path) for path in successful], - "solver_logs": [str(path) for path in logs], - } - failed = [name for name, passed in checks.items() if not passed] - return { - "schema_version": "foambench.execution.v2", - "status": "pass" if not failed else "fail", - "expected_latest_time": expected_time, - "candidate_latest_time": latest, - "candidate_final_log_time": log_time, - "checks": checks, - "failed_checks": failed, - "evidence": evidence, - } diff --git a/benchmarks/evaluation/extbench.py b/benchmarks/evaluation/extbench.py deleted file mode 100644 index e3ebc3eab5f39bb77c676cce2b2a0b914013b6ef..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/extbench.py +++ /dev/null @@ -1,1572 +0,0 @@ -#!/usr/bin/env python3 -"""Extract and audit Extended FoamBench QoIs without fallback proxies.""" -from __future__ import annotations - -import argparse -import csv -import json -import math -import re -import statistics -from pathlib import Path -from typing import Any - -from .evidence_contract import canonical_evidence_manifest, evidence_roots, resolve_evidence -from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_field, read_vector_list -from .io import utc_now, write_json -from .retained_fields import derive_cell_geometry, pump_measurements, static_mesh -from .measurement_specs import load_measurement_spec - -ROOT = Path(__file__).resolve().parents[2] -DEFAULT_DESIGN = ROOT / "benchmarks/FoamBench_extended_openfoam13_qoi_design.json" -NUMERIC = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$") - - -def named_numeric_rows(path: Path) -> tuple[list[str], list[list[float]]]: - """Read a whitespace/CSV table using the last compatible header.""" - headers: list[list[str]] = [] - rows: list[list[float]] = [] - try: - for line in path.read_text(errors="ignore").splitlines(): - stripped = line.strip() - if not stripped: - continue - if stripped.startswith("#"): - names = stripped[1:].strip().replace(",", " ").split() - if names: - headers.append(names) - continue - parts = stripped.replace("(", " ").replace(")", " ").replace(",", " ").split() - if parts and all(NUMERIC.match(value) for value in parts): - rows.append([float(value) for value in parts]) - elif (not rows and ("," in stripped or "\t" in stripped) - and any(re.search(r"[A-Za-z_]", value) and not NUMERIC.fullmatch(value) for value in parts)): - names = [item.strip() for item in stripped.split(",")] if "," in stripped else stripped.split("\t") - if names: - headers.append(names) - except OSError: - return [], [] - if not rows: - return [], [] - width = len(rows[0]) - header = next((names for names in reversed(headers) if len(names) == width), []) - return header, [row for row in rows if len(row) == width] - - -def matching_files(case: Path, needles: tuple[str, ...], suffixes: tuple[str, ...] = ()) -> list[Path]: - """Find explicit post-processing evidence in the case or its workspace.""" - parent = case.parent - roots = [case / "postProcessing", case / "results", parent / "postProcessing", parent / "postprocessing", parent / "results"] - paths: list[Path] = [] - for root in roots: - if not root.is_dir(): - continue - paths.extend(path for path in root.rglob("*") if path.is_file() - and (not suffixes or path.suffix.lower() in suffixes) - and any(needle.lower() in str(path).lower() for needle in needles)) - return sorted(set(paths)) - - -def evidence_path(case: Path, path: Path) -> str: - """Serialize evidence paths for both native case and sibling workspace outputs.""" - try: - return str(path.relative_to(case)) - except ValueError: - return "../" + str(path.relative_to(case.parent)) - - -def design_case_contract(case_id: str, design: dict[str, Any]) -> tuple[str | None, list[str]]: - """Return the branch and principal metrics for one family/variant.""" - if "/" not in case_id: - raise ValueError(f"case id must be family/variant: {case_id}") - family_name, variant = case_id.split("/", 1) - family = next((item for item in design.get("families", []) if item.get("family") == family_name), None) - if family is None: - raise ValueError(f"design has no family for {case_id}") - return required_metrics(family, variant) - - -def design_case_conditionals(case_id: str, design: dict[str, Any]) -> list[str]: - if "/" not in case_id: - raise ValueError(f"case id must be family/variant: {case_id}") - family_name, variant = case_id.split("/", 1) - family = next((item for item in design.get("families", []) if item.get("family") == family_name), None) - if family is None: - raise ValueError(f"design has no family for {case_id}") - for branch in family.get("branches", []): - if variant in branch.get("cases", []): - return [item["name"] for item in branch.get("conditional_qois", [])] - return [] - - -def extract_contract_case(case: Path, case_id: str, design: dict[str, Any] | None = None) -> dict[str, Any]: - """Extract one candidate using only the design contract.""" - selected_design = design or json.loads(DEFAULT_DESIGN.read_text(encoding="utf-8")) - branch_id, metrics = design_case_contract(case_id, selected_design) - measurement_spec = load_measurement_spec(case_id) - if measurement_spec is not None: - declared = [item.get("metric") for item in measurement_spec.get("principal_measurements", [])] - if declared != metrics: - raise ValueError(f"measurement contract drift for {case_id}: {declared!r} != {metrics!r}") - conditionals = design_case_conditionals(case_id, selected_design) - result = extract_case( - case, case_id.split("/", 1)[0], case_id.split("/", 1)[1], metrics, - conditional_metrics=conditionals, - ) - result["branch_id"] = branch_id - result["conditional_metrics"] = conditionals - result["contract_version"] = selected_design.get("schema_version") - if measurement_spec is not None: - result["measurement_contract"] = measurement_spec - return result - - -def locate_case(run_root: Path, family: str, variant: str) -> Path | None: - candidates = ( - run_root / f"{family}__{variant}" / "full_run_case", - run_root / f"{family}__{variant}" / "case", - run_root / family / variant / "full_run_case", - run_root / family / variant / "case", - run_root / family / variant, - ) - return next((path for path in candidates if path.is_dir()), None) - - -def required_metrics(family: dict[str, Any], variant: str) -> tuple[str | None, list[str]]: - for branch in family.get("branches", []): - if variant in branch.get("cases", []): - metrics = [item["name"] for item in branch.get("principal_qois", [])] - return branch.get("id"), metrics - return None, [] - - -def final_fraction(values: list[float], fraction: float = 0.2, minimum: int = 5) -> list[float]: - if not values: - return [] - count = min(len(values), max(minimum, math.ceil(len(values) * fraction))) - return values[-count:] - - -def force_coefficients(case: Path) -> tuple[dict[str, list[float]], list[str]]: - files = matching_files(case, ("forcecoeffs.dat",), (".dat", ".csv", ".raw")) - files.extend(resolve_evidence(case, "force_coefficients", suffixes=(".dat", ".csv", ".raw"))) - # Content-addressed fallback: a different agent may call this table - # loads.csv or aero_coefficients.dat. The header is the physical contract. - candidates = [path for root in evidence_roots(case) for path in root.rglob("*") - if path.is_file() and path.suffix.lower() in {".dat", ".csv", ".raw"}] - for path in candidates: - if path in files: - continue - header, _ = named_numeric_rows(path) - if "Time" in header and any(name in header for name in ("Cd", "Cl", "Cm")): - files.append(path) - files = sorted(set(files)) - columns: dict[str, list[float]] = {} - evidence: list[str] = [] - for path in files: - header, rows = named_numeric_rows(path) - if not header or "Time" not in header: - continue - for name in ("Cd", "Cl", "Cm"): - if name not in header: - continue - index = header.index(name) - columns.setdefault(name, []).extend( - row[index] for row in rows if math.isfinite(row[index]) - ) - evidence.append(evidence_path(case, path)) - return columns, evidence - - -def extract_force_metric(case: Path, metric: str) -> tuple[float | None, list[str], str]: - columns, evidence = force_coefficients(case) - base = metric.removesuffix("_mean").removesuffix("_rms") - values = final_fraction(columns.get(base, [])) - if not values: - return None, [], "header_addressed_force_coefficients.v1" - if metric.endswith("_rms"): - mean = statistics.fmean(values) - value = math.sqrt(statistics.fmean((item - mean) ** 2 for item in values)) - else: - value = statistics.fmean(values) - return value, evidence, "header_addressed_force_coefficients.v1" - - -def spalding_metrics_from_files(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]: - log_errors: list[float] = [] - first_yplus: list[float] = [] - evidence: list[str] = [] - for path in files: - header, rows = named_numeric_rows(path) - normalized = { - re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): index - for index, name in enumerate(header) - } - y_index = next( - (normalized[name] for name in ("yplus", "firstcellyplus", "yplusmin", "firstcellyplusmin") if name in normalized), - None, - ) - predicted_index = next( - (normalized[name] for name in ("spaldingyplus", "yplusspaldingup", "yplusspaldinguplus", "yplusspalding") if name in normalized), - None, - ) - if y_index is None: - continue - # Zero is a valid observed wall resolution. Missing evidence is an - # absent row, not a non-positive value. - 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] - if y_values: - first_yplus.append(min(y_values)) - if predicted_index is None: - # A first-cell summary is valid endpoint evidence, but it cannot - # be relabelled as a profile residual. - evidence.append(evidence_path(relative_to, path)) - continue - valid = [ - (row[y_index], row[predicted_index]) for row in rows - if len(row) > max(y_index, predicted_index) - and math.isfinite(row[y_index]) and math.isfinite(row[predicted_index]) - and row[y_index] >= 0 and row[predicted_index] >= 0 - ] - if not valid: - continue - log_errors.extend( - math.log1p(yplus) - math.log1p(predicted) - for yplus, predicted in valid - ) - evidence.append(evidence_path(relative_to, path)) - result: dict[str, float] = {} - if log_errors: - result["spalding_log_rmse"] = math.sqrt(statistics.fmean(value * value for value in log_errors)) - if first_yplus: - result["first_cell_yplus"] = statistics.fmean(first_yplus) - return result, evidence - - -def standard_yplus_metrics(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]: - """Read OpenFOAM's standard ``yPlus.dat`` patch summary. - - The standard table has the schema ``Time patch min max average``. It is - therefore intentionally parsed separately from ``named_numeric_rows``, - which rejects the non-numeric patch column. A zero average remains a - valid observation. - """ - rows: list[tuple[float, str, float, float, float]] = [] - evidence: list[str] = [] - for path in files: - if path.name.lower() != "yplus.dat": - continue - try: - for line in path.read_text(encoding="utf-8", errors="ignore").splitlines(): - parts = line.split() - if len(parts) < 5 or parts[0].startswith("#"): - continue - try: - time = float(parts[0]) - minimum, maximum, average = float(parts[2]), float(parts[3]), float(parts[4]) - except ValueError: - continue - if all(math.isfinite(value) for value in (time, minimum, maximum, average)): - rows.append((time, parts[1], minimum, maximum, average)) - except OSError: - continue - if rows: - evidence.append(evidence_path(relative_to, path)) - if not rows: - return {}, [] - final_time = max(row[0] for row in rows) - final_rows = [row for row in rows if abs(row[0] - final_time) <= 1e-12 * max(1.0, abs(final_time))] - # Symmetric wall patches are one declared response; average their final - # values while retaining the source file as auditable evidence. - return {"first_cell_yplus": statistics.fmean(row[4] for row in final_rows)}, sorted(set(evidence)) - - -def spalding_metrics(case: Path) -> tuple[dict[str, float], list[str]]: - files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv")) - # OpenFOAM's standard yPlus function object writes ``yPlus.dat`` with a - # non-numeric patch-name column (``Time patch min max average``). It is - # intentionally handled by ``standard_yplus_metrics`` below, so discover - # it by basename instead of sending it through ``named_numeric_rows``. - for root in evidence_roots(case): - files.extend( - path for path in root.rglob("*") - if path.is_file() and path.name.lower() == "yplus.dat" - ) - # The rollout measurement writer emits an explicit wall table instead of - # a Spalding profile. yPlus_min is valid endpoint evidence; it is not - # treated as a profile residual. - files.extend(matching_files(case, ("yplus_wall.csv",), (".csv",))) - # Accept semantically equivalent wall tables even when the file name is - # agent-specific, provided the table contains a y+ column. - for root in evidence_roots(case): - for path in root.rglob("*"): - if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}: - continue - header, _ = named_numeric_rows(path) - normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")) for name in header} - if "yplus" in normalized or "firstcellyplus" in normalized: - files.append(path) - files = sorted(set(files)) - standard_values, standard_evidence = standard_yplus_metrics(files, case) - wall_files = [path for path in files if path.name.lower() == "yplus_wall.csv"] - wall_values: list[float] = [] - wall_evidence: list[str] = [] - for path in wall_files: - try: - with path.open(newline="", encoding="utf-8", errors="ignore") as handle: - for row in csv.DictReader(handle): - raw = row.get("yPlus_min") or row.get("yplus_min") or row.get("first_cell_yplus") - if raw is not None: - value = float(raw) - if math.isfinite(value) and value >= 0: - wall_values.append(value) - if wall_values: - wall_evidence.append(evidence_path(case, path)) - except (OSError, ValueError): - continue - # Branch-labelled evidence is handled separately for the multi-Re case. - files = [path for path in files if "branches" not in tuple(evidence_path(case, path).split("/"))] - values, evidence = spalding_metrics_from_files([path for path in files if path not in wall_files], case) - if "first_cell_yplus" not in values: - # CSV profile variants use a header with a literal ``y+`` token or a - # yplus column and do not necessarily contain a yPlus_min summary. - for path in files: - if path in wall_files: - continue - header, rows = named_numeric_rows(path) - normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): i for i, name in enumerate(header)} - index = next((normalized[name] for name in ("yplus", "firstcellyplus") if name in normalized), None) - if index is not None: - vals = [row[index] for row in rows if len(row) > index and math.isfinite(row[index]) and row[index] >= 0] - if vals: - values["first_cell_yplus"] = vals[0] - evidence.append(evidence_path(case, path)) - break - if wall_values: - # The final row is the retained endpoint; using the mean would mix - # initialization transients with the declared final wall resolution. - values["first_cell_yplus"] = wall_values[-1] - evidence.extend(wall_evidence) - if "first_cell_yplus" not in values and standard_values: - values.update(standard_values) - evidence.extend(standard_evidence) - return values, sorted(set(evidence)) - - -def branchwise_spalding_metrics(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - branches: dict[str, Any] = {} - evidence: list[str] = [] - files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv")) - by_branch: dict[str, list[Path]] = {} - for path in files: - match = re.search(r"Re_tau_(180|395|590)", str(path)) - if match: - by_branch.setdefault(f"Re_tau_{match.group(1)}", []).append(path) - for branch, branch_files in sorted(by_branch.items()): - values, refs = spalding_metrics_from_files(sorted(branch_files), case) - if {"spalding_log_rmse", "first_cell_yplus"} <= set(values): - branches[branch] = values - evidence.extend(refs) - expected = {"Re_tau_180", "Re_tau_395", "Re_tau_590"} - if set(branches) != expected: - return None, sorted(set(evidence)) - return {"kind": "branch_scalars", "branches": branches}, sorted(set(evidence)) - - -def stirrer_power_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - files = matching_files(case, ("surfaceFieldValue.dat",), (".dat",)) - points: list[dict[str, float]] = [] - evidence: list[str] = [] - for path in files: - header, rows = named_numeric_rows(path) - fields = [name for name in header if name != "Time" and "stressUSf" in name] - if "Time" not in header or not fields: - continue - time_index, power_index = header.index("Time"), header.index(fields[0]) - points.extend({"time": row[time_index], "value": row[power_index]} for row in rows if math.isfinite(row[power_index])) - evidence.append(evidence_path(case, path)) - if not points: - return None, [] - points.sort(key=lambda item: item["time"]) - return {"kind": "time_history", "quantity": "surface_integrated_stressUSf_power", "points": points}, evidence - - -def named_sample_profiles(case: Path, names: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]: - profiles: list[dict[str, Any]] = [] - evidence: list[str] = [] - roots = [case, *evidence_roots(case)] - candidates: list[Path] = [] - for root in roots: - candidates.extend(item for item in root.rglob("*") if item.is_file() and ( - item.name in names or (item.suffix.lower() == ".csv" and item.parent.name.lower() == "profiles") - )) - for path in sorted(set(candidates)): - header, rows = named_numeric_rows(path) - if len(header) < 2 or not rows or not profile_has_physical_columns(header): - continue - profiles.append({ - "profile_id": evidence_path(case, path), - "columns": header, - "rows": rows, - }) - evidence.append(evidence_path(case, path)) - if not profiles: - return None, [] - return {"kind": "named_profiles", "profiles": profiles}, evidence - - -def result_profile_tables(case: Path, tokens: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]: - """Read explicit profile tables from workspace/results when named output - files use a family-specific filename instead of horizontal.xy/vertical.xy. - """ - profiles: list[dict[str, Any]] = [] - evidence: list[str] = [] - roots = list(evidence_roots(case)) - resolved = resolve_evidence(case, "centerline_profile", suffixes=(".csv", ".dat", ".raw", ".xy")) - for root in roots: - if not root.is_dir(): - continue - for path in sorted(root.rglob("*")): - if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}: - continue - if path not in resolved and not any(token.lower() in path.name.lower() for token in tokens): - continue - header, rows = named_numeric_rows(path) - if len(header) < 2 or not rows or not profile_has_physical_columns(header): - continue - profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows}) - evidence.append(evidence_path(case, path)) - if not profiles: - return None, [] - return {"kind": "named_profiles", "profiles": profiles}, sorted(set(evidence)) - - -def profile_has_physical_columns(header: list[str]) -> bool: - """Require a coordinate and at least one sampled physical field.""" - normalized = [re.sub(r"[^a-z0-9]", "", name.lower()) for name in header] - has_coordinate = any(name in {"x", "y", "z", "coordinate", "position", "arc"} or name.startswith(("x", "y", "z")) for name in normalized) - has_field = any( - name in {"p", "rho", "u", "ux", "uy", "uz"} - or name.startswith(("px", "py", "pz", "rhox", "rhoy", "rhoz")) - for name in normalized - ) - return has_coordinate and has_field - - -def named_profiles_containing(case: Path, tokens: tuple[str, ...], required_columns: tuple[str, ...] = ()) -> tuple[dict[str, Any] | None, list[str]]: - """Read explicitly named sample tables; never infer a physical metric from field extrema.""" - profiles: list[dict[str, Any]] = [] - evidence: list[str] = [] - for root in (case, *evidence_roots(case)): - for path in sorted(item for item in root.rglob("*") if item.is_file() and path_like_sample(item, tokens)): - header, rows = named_numeric_rows(path) - if len(header) < 2 or not rows or any(column not in header for column in required_columns): - continue - profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows}) - evidence.append(evidence_path(case, path)) - return ({"kind": "named_profiles", "profiles": profiles}, evidence) if profiles else (None, []) - - -def path_like_sample(path: Path, tokens: tuple[str, ...]) -> bool: - name = path.name.lower() - return path.suffix.lower() in {".xy", ".raw", ".dat", ".csv"} and any(token.lower() in name for token in tokens) - - -def field_dimensions(case: Path, field: str) -> str | None: - for path in sorted(case.rglob(field), reverse=True): - if not path.is_file() or not path.parent.name.replace(".", "", 1).isdigit(): - continue - header = path.read_bytes()[:4096].decode("ascii", errors="ignore") - match = re.search(r"dimensions\s*\[([^]]+)\]", header) - if match: - return " ".join(match.group(1).split()) - return None - - -def evidence_branch(case: Path, path: Path) -> str: - try: - parts = path.relative_to(case).parts - except ValueError: - parts = path.relative_to(case.parent).parts - try: - index = parts.index("postProcessing") - except ValueError: - return "root" - return "/".join(parts[:index]) or "root" - - -def explicit_mass_flow_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - branch_points: dict[str, list[dict[str, float]]] = {} - evidence: list[str] = [] - candidates = matching_files(case, ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi"), (".dat", ".raw", ".csv")) - # Some benchmark variants materialize several nested operating-point cases; - # accept their postProcessing evidence without flattening those branches. - if not candidates: - candidates = sorted(path for path in case.rglob("*") if path.is_file() - and path.suffix.lower() in {".dat", ".raw", ".csv"} - and any(token.lower() in str(path).lower() - for token in ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi"))) - for path in candidates: - patch_match = re.search(r"patch=([^)/]+)", str(path)) - if patch_match is not None and patch_match.group(1).lower() not in {"inlet", "inlet1", "main", "mainstream"}: - # The principal pump/nozzle response is the declared inlet flow; - # do not concatenate inlet and outlet fluxes into one history. - continue - header, rows = named_numeric_rows(path) - mass_columns = [column for column in header if any(token in column.lower() for token in ("rhophi", "massflow", "massflux", "sum(phi)"))] - if "Time" not in header or not mass_columns: - continue - t_index, value_index = header.index("Time"), header.index(mass_columns[0]) - branch = evidence_branch(case, path) - branch_points.setdefault(branch, []).extend( - {"time": row[t_index], "value": row[value_index]} - for row in rows if math.isfinite(row[value_index]) - ) - evidence.append(evidence_path(case, path)) - if not branch_points: - return None, [] - dimensions = field_dimensions(case, "phi") - quantity = { - "1 0 -1 0 0 0 0": "explicit_mass_flow", - "0 3 -1 0 0 0 0": "explicit_volumetric_flow", - }.get(dimensions, "explicit_flux_unknown_dimensions") - branches = { - branch: {"kind": "time_history", "quantity": quantity, - "points": sorted(points, key=lambda item: item["time"])} - for branch, points in sorted(branch_points.items()) - } - if set(branches) == {"root"}: - result = branches["root"] - else: - result = {"kind": "branched_time_histories", "quantity": quantity, "branches": branches} - result["field_dimensions"] = dimensions - return result, sorted(set(evidence)) - - -def explicit_patch_pressure(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - histories: dict[str, list[dict[str, float]]] = {} - evidence: list[str] = [] - for path in matching_files(case, ("patchAverage", "patchIntegrate", "pressureRise", "pressure_rise"), (".dat", ".raw", ".csv")): - header, rows = named_numeric_rows(path) - pressure_columns = [column for column in header if column != "Time" and any(token in column.lower() for token in ("p", "pressure"))] - match = re.search(r"patch=([^)/]+)", str(path)) - if "Time" not in header or not pressure_columns or not match: - continue - patch_name = match.group(1) - t_index, value_index = header.index("Time"), header.index(pressure_columns[0]) - histories.setdefault(patch_name, []).extend({"time": row[t_index], "value": row[value_index]} for row in rows if math.isfinite(row[value_index])) - evidence.append(evidence_path(case, path)) - inlet_name = next((name for name in histories if "inlet" in name.lower()), None) - outlet_name = next((name for name in histories if "outlet" in name.lower()), None) - if inlet_name is None or outlet_name is None: - return None, [] - inlet = {round(point["time"], 12): point["value"] for point in histories[inlet_name]} - outlet = {round(point["time"], 12): point["value"] for point in histories[outlet_name]} - points = [ - {"time": time, "value": outlet[time] - inlet[time]} - for time in sorted(set(inlet) & set(outlet)) - ] - if not points: - return None, [] - return { - "kind": "time_history", - "quantity": "pressure_rise", - "definition": "outlet_minus_inlet_patch_average", - "source_patches": {"inlet": inlet_name, "outlet": outlet_name}, - "points": points, - }, sorted(set(evidence)) - - -def crossjet_inlet_mass_flux_ratio(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - fluxes: dict[str, list[tuple[float, float]]] = {} - evidence: list[str] = [] - for path in resolve_evidence(case, "patch_flux", suffixes=(".dat", ".raw", ".csv")): - match = re.search(r"patch=([^)/]+)", str(path)) - if match is None: - match = re.search(r"(?m)^\s*#\s*Selection\s*:\s*patch\(([^)]+)\)", path.read_text(errors="ignore")) - if match is None: - continue - patch = match.group(1).lower() - canonical = ( - "inlet1" if patch in {"inlet1", "inlet", "main", "mainstream", "maininlet", "mainflowinlet"} - else "inlet2" if patch in {"inlet2", "jet", "injection", "jetinlet"} - else None - ) - if canonical is None: - continue - header, rows = named_numeric_rows(path) - columns = [column for column in header if column != "Time" and "sum(phi)" in column] - if "Time" not in header or not columns: - continue - ti, vi = header.index("Time"), header.index(columns[0]) - fluxes.setdefault(canonical, []).extend((row[ti], row[vi]) for row in rows) - evidence.append(evidence_path(case, path)) - if not all(fluxes.get(patch) for patch in ("inlet1", "inlet2")): - return None, [] - main = sorted(fluxes["inlet1"])[-1] - jet = sorted(fluxes["inlet2"])[-1] - if main[1] == 0: - return None, [] - return { - "kind": "scalar_ratio", - "quantity": "jet_to_mainstream_mass_flux_ratio", - "value": abs(jet[1] / main[1]), - "mainstream_flux": main[1], - "jet_flux": jet[1], - "time": min(main[0], jet[0]), - "patch_aliases": {"mainstream": "inlet1", "jet": "inlet2"}, - }, sorted(set(evidence)) - - -def phase_volume_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - points: list[dict[str, float]] = [] - evidence: list[str] = [] - for time, directory in numeric_time_dirs(case): - alpha_path = foam_path(directory, "alpha.water") - volume_path = foam_path(directory, "Vc") - if alpha_path is None or volume_path is None: - continue - try: - alpha = read_scalar_field(alpha_path) - volumes = read_scalar_field(volume_path) - except (OSError, ValueError, RuntimeError): - continue - if len(alpha) != len(volumes) or not volumes: - continue - total = sum(volumes) - if total <= 0: - continue - points.append({"time": time, "value": sum(a * v for a, v in zip(alpha, volumes)) / total}) - evidence.extend((evidence_path(case, alpha_path), evidence_path(case, volume_path))) - if not points: - return None, [] - return {"kind": "time_history", "quantity": "volume_weighted_alpha_water", "points": points}, sorted(set(evidence)) - - -def volume_average_speed_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - points: list[dict[str, float]] = [] - evidence: list[str] = [] - for time, directory in numeric_time_dirs(case): - velocity_path = foam_path(directory, "U") - volume_path = foam_path(directory, "Vc") - if velocity_path is None or volume_path is None: - continue - try: - velocity = read_vector_field(velocity_path) - volumes = read_scalar_field(volume_path) - except (OSError, ValueError, RuntimeError): - continue - if len(velocity) != len(volumes) or not volumes: - continue - total = sum(volumes) - if total <= 0: - continue - value = sum(math.sqrt(u * u + v * v + w * w) * volume - for (u, v, w), volume in zip(velocity, volumes)) / total - if not math.isfinite(value): - continue - points.append({"time": time, "value": value}) - evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path))) - if not points: - return None, [] - return {"kind": "time_history", "quantity": "volume_average_speed", "points": points}, sorted(set(evidence)) - - -def volume_speed_rms_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]: - points: list[dict[str, float]] = [] - evidence: list[str] = [] - for time, directory in numeric_time_dirs(case): - velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc") - if velocity_path is None or volume_path is None: - continue - try: - velocity, volumes = read_vector_field(velocity_path), read_scalar_field(volume_path) - except (OSError, ValueError, RuntimeError): - continue - if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0: - continue - speeds = [math.sqrt(u * u + v * v + w * w) for u, v, w in velocity] - total = sum(volumes) - mean = sum(speed * volume for speed, volume in zip(speeds, volumes)) / total - rms = math.sqrt(sum((speed - mean) ** 2 * volume for speed, volume in zip(speeds, volumes)) / total) - if math.isfinite(rms): - points.append({"time": time, "value": rms}) - evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path))) - if not points: - return None, [] - return {"kind": "time_history", "quantity": "volume_speed_spatial_rms", "points": points}, sorted(set(evidence)) - - -def volume_average_speed_final(case: Path) -> tuple[float | None, list[str]]: - """Extract a final-state mixing response from retained U and cell volumes.""" - for _, directory in reversed(numeric_time_dirs(case)): - velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc") - if velocity_path is None: - continue - try: - # Retained agent fields can contain a uniform internal U while Vc - # still has one volume per cell. Decode the concrete array first - # so the uniform vector is expanded using an observed cell count. - if volume_path is not None: - volumes = read_scalar_field(volume_path) - geometry_evidence = [volume_path] - else: - from .retained_fields import derive_cell_geometry - volumes, _, geometry_evidence = derive_cell_geometry(case) - try: - velocity = read_vector_field(velocity_path) - except (ValueError, RuntimeError): - velocity = read_vector_field_allow_uniform(velocity_path, len(volumes)) - if volume_path is not None and len(volumes) == 1 and len(velocity) > 1: - volumes = volumes * len(velocity) - except (OSError, ValueError, RuntimeError): - continue - if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0: - continue - total = sum(volumes) - value = sum(math.sqrt(u * u + v * v + w * w) * volume - for (u, v, w), volume in zip(velocity, volumes)) / total - if math.isfinite(value): - return value, [evidence_path(case, path) for path in [velocity_path, *geometry_evidence]] - return None, [] - - -def read_vector_field_allow_uniform(path: Path, count: int) -> list[tuple[float, float, float]]: - try: - return read_vector_field(path) - except (ValueError, RuntimeError): - text = path.read_text(encoding="ascii", errors="ignore") - match = re.search(r"internalField\s+uniform\s+\(([^)]+)\)", text) - if match is None: - raise - values = [float(item) for item in match.group(1).split()] - if len(values) != 3: - raise ValueError(f"invalid uniform vector field: {path}") - return [(values[0], values[1], values[2])] * count - - -def read_scalar_field_allow_uniform(path: Path, count: int) -> list[float]: - """Read a scalar field while preserving the semantics of a uniform field.""" - try: - values = read_scalar_field(path) - except (ValueError, RuntimeError): - text = path.read_text(encoding="ascii", errors="ignore") - match = re.search(r"internalField\s+uniform\s+([^;]+);", text) - if match is None: - raise - return [float(match.group(1).strip())] * count - if len(values) == 1 and count > 1: - # OpenFOAM permits a uniform field to be serialized as one value. - return values * count - return values - - -def crossjet_interior_pressure_span(case: Path) -> tuple[float | None, list[str]]: - """Return the pressure response in the declared internal CrossJet window. - - The span is deliberately computed from the retained pressure field rather - than from ``grad(p)``. This remains extractable for references that store - ``p`` as a uniform field and avoids treating a missing/zero post-processing - gradient as a shock observable. - """ - for _, directory in reversed(numeric_time_dirs(case)): - centre_path, pressure_path = foam_path(directory, "C"), foam_path(directory, "p") - if pressure_path is None: - continue - try: - if centre_path is not None: - centres = read_vector_field(centre_path) - geometry_evidence = [centre_path] - else: - from .retained_fields import derive_cell_geometry - _, centres, geometry_evidence = derive_cell_geometry(case) - pressure = read_scalar_field_allow_uniform(pressure_path, len(centres)) - except (OSError, ValueError, RuntimeError): - continue - if len(pressure) != len(centres): - continue - values = [value for (x, y, _), value in zip(centres, pressure) - if -1.0 <= x <= 1.0 and 0.1 <= y <= 0.95] - if values: - return max(values) - min(values), [evidence_path(case, path) for path in [*geometry_evidence, pressure_path]] - return None, [] - - -def crossjet_interior_pressure_gradient_max(case: Path) -> tuple[float | None, list[str]]: - """Return the maximum interior pressure span.""" - return crossjet_interior_pressure_span(case) - - -def profile_event_locations(profiles: dict[str, Any]) -> dict[str, Any] | None: - events: list[dict[str, Any]] = [] - for profile in profiles.get("profiles", []): - columns = profile.get("columns", []) - rows = profile.get("rows", []) - if len(columns) < 2 or len(rows) < 5: - continue - coordinate_index = 0 - for field in ("p", "rho"): - field_index = next((index for index, name in enumerate(columns) - if name.lower() == field or name.lower().startswith(field + "_")), None) - if field_index is None: - continue - gradients: list[tuple[int, float, float]] = [] - for index in range(len(rows) - 1): - spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index]) - if spacing <= 0: - continue - gradient = abs(rows[index + 1][field_index] - rows[index][field_index]) / spacing - coordinate = (rows[index + 1][coordinate_index] + rows[index][coordinate_index]) / 2 - gradients.append((index, coordinate, gradient)) - if not gradients: - continue - peak = max(value for _, _, value in gradients) - threshold = 0.05 * peak - candidates = [ - item for position, item in enumerate(gradients) - if item[2] >= threshold - and (position == 0 or item[2] >= gradients[position - 1][2]) - and (position == len(gradients) - 1 or item[2] > gradients[position + 1][2]) - ] - selected: list[tuple[int, float, float]] = [] - for candidate in sorted(candidates, key=lambda item: item[2], reverse=True): - if all(abs(candidate[0] - item[0]) >= 4 for item in selected): - selected.append(candidate) - if len(selected) == 12: - break - for index, coordinate, magnitude in sorted(selected, key=lambda item: item[1]): - local_spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index]) - events.append({ - "profile_id": profile["profile_id"], - "field": field, - "coordinate": coordinate, - "gradient_magnitude": magnitude, - "local_cell_size": local_spacing, - }) - if not events: - return None - return { - "kind": "profile_feature_locations", - "detector": "local_abs_gradient_peaks.v1", - "relative_prominence": 0.05, - "minimum_separation_samples": 4, - "maximum_features_per_field_profile": 12, - "events": events, - } - - -def final_riemann_profiles(profiles: dict[str, Any]) -> dict[str, Any]: - """Select each centerline's latest saved time and use its physical axis. - - OpenFOAM raw sets may prefix x/y/z with arc distance. Preserve the sampled - values, but put x (horizontal) or y (vertical) first for event detection. - """ - from .comparison import profile_key - selected: dict[str, tuple[float, dict[str, Any]]] = {} - for profile in profiles.get("profiles", []): - key = profile_key(profile) - axis = {"horizontal.xy": "x", "vertical.xy": "y"}.get(key) - columns = profile.get("columns", []) - if axis is None or axis not in columns: - continue - try: - time = float(Path(profile["profile_id"]).parent.name) - except ValueError: - time = -math.inf - if key in selected and time < selected[key][0]: - continue - order = [columns.index(axis)] + [i for i, name in enumerate(columns) if name != axis] - normalized = {**profile, "columns": [columns[i] for i in order], - "rows": [[row[i] for i in order] for row in profile["rows"]]} - selected[key] = (time, normalized) - return {"kind": "named_profiles", "profiles": [item[1] for item in selected.values()]} - - -def numeric_time_dirs(case: Path) -> list[tuple[float, Path]]: - result: list[tuple[float, Path]] = [] - for path in case.iterdir(): - if not path.is_dir(): - continue - try: - result.append((float(path.name), path)) - except ValueError: - pass - return sorted(result) - - -def mesh_dir(case: Path, time_dir: Path) -> Path: - local = time_dir / "polyMesh" - return local if local.is_dir() else case / "constant/polyMesh" - - -def connected_components(active: set[int], owner: list[int], neighbour: list[int]) -> list[list[int]]: - adjacency: dict[int, list[int]] = {cell: [] for cell in active} - for left, right in zip(owner, neighbour): - if left in active and right in active: - adjacency[left].append(right) - adjacency[right].append(left) - components: list[list[int]] = [] - unseen = set(active) - while unseen: - seed = unseen.pop() - stack = [seed] - component = [seed] - while stack: - for cell in adjacency[stack.pop()]: - if cell in unseen: - unseen.remove(cell) - stack.append(cell) - component.append(cell) - components.append(component) - return components - - -def component_geometry( - cells: list[int], gas: list[float], volumes: list[float], centres: list[tuple[float, float, float]], volume_factor: float -) -> dict[str, float]: - weights = [max(0.0, min(1.0, gas[cell])) * volumes[cell] for cell in cells] - volume = sum(weights) - if volume <= 0: - return {} - centroid = [sum(weight * centres[cell][axis] for weight, cell in zip(weights, cells)) / volume for axis in range(3)] - xx = sum(weight * (centres[cell][0] - centroid[0]) ** 2 for weight, cell in zip(weights, cells)) / volume - yy = sum(weight * (centres[cell][1] - centroid[1]) ** 2 for weight, cell in zip(weights, cells)) / volume - xy = sum(weight * (centres[cell][0] - centroid[0]) * (centres[cell][1] - centroid[1]) for weight, cell in zip(weights, cells)) / volume - root = math.sqrt(max(0.0, (xx - yy) ** 2 + 4 * xy * xy)) - major = max(0.0, (xx + yy + root) / 2) - minor = max(0.0, (xx + yy - root) / 2) - aspect = math.sqrt(major / minor) if minor > 0 else None - return { - "volume": volume, - "centroid_x": centroid[0], - "centroid_y": centroid[1], - "centroid_z": centroid[2], - "aspect_ratio": aspect, - "equivalent_radius_3d": (3 * volume * volume_factor / (4 * math.pi)) ** (1 / 3), - } - - -def axisymmetric_volume_factor(case: Path) -> float: - boundary = case / "constant/polyMesh/boundary" - if not boundary.is_file() or "wedge" not in boundary.read_text(encoding="utf-8", errors="ignore"): - return 1.0 - points_path = foam_path(case / "constant/polyMesh", "points") - if points_path is None: - return 1.0 - angles = [math.atan2(y, x) for x, y, _ in read_vector_list(points_path) if x > 0] - if not angles: - return 1.0 - wedge_angle = max(angles) - min(angles) - return 2 * math.pi / wedge_angle if wedge_angle > 0 else 1.0 - - -def bubble_history(case: Path) -> tuple[list[dict[str, Any]], list[str], list[str]]: - history: list[dict[str, Any]] = [] - evidence: list[str] = [] - errors: list[str] = [] - dynamic = not static_mesh(case) - volume_factor = axisymmetric_volume_factor(case) - cached_geometry: tuple[list[float], list[tuple[float, float, float]]] | None = None - cached_topology: tuple[list[int], list[int]] | None = None - time_dirs = numeric_time_dirs(case) - if not dynamic: - for _, directory in reversed(time_dirs): - volume_path = foam_path(directory, "Vc") - centre_path = foam_path(directory, "C") - if volume_path and centre_path: - cached_geometry = (read_scalar_field(volume_path), read_vector_field(centre_path)) - break - topology_dir = case / "constant/polyMesh" - owner_path = foam_path(topology_dir, "owner") - neighbour_path = foam_path(topology_dir, "neighbour") - if owner_path and neighbour_path: - cached_topology = (read_label_list(owner_path), read_label_list(neighbour_path)) - if cached_geometry is None: - try: - volumes, centres, mesh_paths = derive_cell_geometry(case) - cached_geometry = (volumes, centres) - evidence.extend(evidence_path(case, path) for path in mesh_paths) - boundary_path = foam_path(topology_dir, "boundary") - if boundary_path: - evidence.append(evidence_path(case, boundary_path)) - except (OSError, ValueError, RuntimeError) as exc: - errors.append(f"retained mesh geometry: {exc}") - previous_tracks: dict[int, tuple[float, float, float]] = {} - next_track = 1 - for time, directory in time_dirs: - alpha_path = foam_path(directory, "alpha.water") - if alpha_path is None: - continue - volume_path = foam_path(directory, "Vc") - centre_path = foam_path(directory, "C") - try: - if cached_geometry is not None and not dynamic: - geometry = cached_geometry - elif volume_path and centre_path: - geometry = (read_scalar_field(volume_path), read_vector_field(centre_path)) - if not dynamic: - cached_geometry = geometry - else: - errors.append(f"{directory.name}: missing C/Vc measurement fields") - continue - topology_dir = mesh_dir(case, directory) - owner_path = foam_path(topology_dir, "owner") - neighbour_path = foam_path(topology_dir, "neighbour") - if (owner_path is None or neighbour_path is None) and dynamic: - # Dynamic solvers may not retain a polyMesh in every output - # directory. Reuse the immutable mesh topology only when it - # is present and the field length remains compatible. - owner_path = foam_path(case / "constant/polyMesh", "owner") - neighbour_path = foam_path(case / "constant/polyMesh", "neighbour") - if cached_topology is not None and not dynamic: - topology = cached_topology - elif owner_path and neighbour_path: - topology = (read_label_list(owner_path), read_label_list(neighbour_path)) - if not dynamic: - cached_topology = topology - else: - errors.append(f"{directory.name}: missing owner/neighbour topology") - continue - volumes, centres = geometry - alpha = read_scalar_field_allow_uniform(alpha_path, len(volumes)) - if not (len(alpha) == len(volumes) == len(centres)): - errors.append(f"{directory.name}: alpha/C/Vc length mismatch") - continue - gas = [1.0 - value for value in alpha] - active = {index for index, value in enumerate(gas) if value >= 0.5} - components = connected_components(active, *topology) - geometries = [component_geometry(item, gas, volumes, centres, volume_factor) for item in components] - geometries = sorted((item for item in geometries if item), key=lambda item: item["volume"], reverse=True) - if geometries: - cutoff = geometries[0]["volume"] * 1e-4 - geometries = [item for item in geometries if item["volume"] >= cutoff] - available = set(previous_tracks) - for item in geometries: - point = (item["centroid_x"], item["centroid_y"], item["centroid_z"]) - if available: - track = min(available, key=lambda key: sum((a - b) ** 2 for a, b in zip(point, previous_tracks[key]))) - available.remove(track) - else: - track = next_track - next_track += 1 - item["track_id"] = track - previous_tracks = { - item["track_id"]: (item["centroid_x"], item["centroid_y"], item["centroid_z"]) - for item in geometries - } - history.append({"time": time, "components": geometries}) - evidence.extend(evidence_path(case, path) for path in (alpha_path, volume_path, centre_path) if path) - except (OSError, ValueError, RuntimeError) as exc: - errors.append(f"{directory.name}: {exc}") - # A dynamic case may intentionally retain geometry/topology only at the - # endpoint. Earlier missing derived fields make the optional trajectory - # incomplete, but must not invalidate endpoint principal QoIs when the - # final saved state was successfully measured. - if history and history[-1].get("time") == (time_dirs[-1][0] if time_dirs else None): - errors = [] - return history, sorted(set(evidence)), errors - - -def component_trajectory(history: list[dict[str, Any]], field: str, all_components: bool = False) -> dict[str, Any] | None: - rows = [item for item in history if item["components"]] - if not rows: - return None - tracks = sorted({component["track_id"] for item in rows for component in item["components"]}) if all_components else [rows[0]["components"][0]["track_id"]] - series = [] - for track in tracks: - points = [] - omitted_invalid = 0 - for item in rows: - component = next((part for part in item["components"] if part["track_id"] == track), None) - if component is not None: - value = component[field] - if value is None: - omitted_invalid += 1 - continue - points.append({"time": item["time"], "value": value}) - series.append({ - "component_id": track, - "points": points, - "omitted_invalid_sample_count": omitted_invalid, - "quality_note": "degenerate_component_geometry_samples_omitted" if omitted_invalid else None, - }) - return {"kind": "component_trajectory", "component_identity": "nearest_centroid_continuation", "series": series} - - -def collapse_events(radius: dict[str, Any]) -> dict[str, Any]: - events = [] - for series in radius["series"]: - points = series["points"] - 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) - censored = index is None - if points: - index = min(range(len(points)), key=lambda i: points[i]["value"]) if index is None else index - events.append({"component_id": series["component_id"], "time": points[index]["time"], "radius": points[index]["value"], "censored_at_time_boundary": censored}) - status = "complete" if events and all(not event["censored_at_time_boundary"] for event in events) else "censored" - return {"kind": "component_events", "status": status, "detector": "first_strict_rebound_minimum_else_global_minimum", "events": events} - - -def rise_velocity(centroid: dict[str, Any]) -> dict[str, Any] | None: - points = centroid["series"][0]["points"] - if len(points) < 3: - return None - end = points[-1]["time"] - selected = [point for point in points if 0.3 * end <= point["time"] <= 0.7 * end] - if len(selected) < 2: - return None - times = [point["time"] for point in selected] - values = [point["value"] for point in selected] - mt, my = statistics.fmean(times), statistics.fmean(values) - denominator = sum((time - mt) ** 2 for time in times) - if denominator == 0: - return None - slope = sum((time - mt) * (value - my) for time, value in zip(times, values)) / denominator - return {"kind": "window_regression", "value": slope, "window": [times[0], times[-1]], "normalized_window": [0.3, 0.7], "sample_count": len(times)} - - -def bubble_metrics(case: Path, family: str) -> tuple[dict[str, Any], list[str], list[str]]: - history, evidence, errors = bubble_history(case) - if family == "risingBubble": - centroid = component_trajectory(history, "centroid_y") - aspect = component_trajectory(history, "aspect_ratio") - values: dict[str, Any] = {} - if centroid: - values["bubble_centroid_y_history"] = centroid - values["bubble_centroid_y_final"] = final_component_scalar(centroid, "bubble_centroid_y_final") - velocity = rise_velocity(centroid) - if velocity: - values["rise_velocity"] = velocity - if aspect: - values["shape_aspect_ratio_history"] = aspect - values["shape_aspect_ratio_final"] = final_component_scalar(aspect, "shape_aspect_ratio_final") - radius = component_trajectory(history, "equivalent_radius_3d") - if radius: - values["equivalent_radius_final"] = final_component_scalar(radius, "equivalent_radius_final") - return values, evidence, errors - radius = component_trajectory(history, "equivalent_radius_3d", all_components=True) - if not radius: - return {}, evidence, errors - event = collapse_events(radius) - values = { - "equivalent_radius_history": radius, - "equivalent_radius_final": final_component_scalar(radius, "equivalent_radius_final", all_components=True), - "final_component_count": len(radius.get("series", [])), - "collapse_time_censored_diagnostic": event, - } - minima = [] - for series in radius.get("series", []): - observed = [point for point in series.get("points", []) - if isinstance(point.get("value"), (int, float)) and math.isfinite(point["value"])] - if observed: - point = min(observed, key=lambda item: item["value"]) - minima.append({"component_id": series.get("component_id"), "time": point["time"], "value": point["value"]}) - if minima: - values["minimum_observed_equivalent_radius"] = { - "kind": "component_scalars", "quantity": "minimum_observed_equivalent_radius", "components": minima - } - if event["status"] == "complete": - values["collapse_time"] = event - return values, evidence, errors - - -def final_component_scalar( - trajectory: dict[str, Any], quantity: str, *, all_components: bool = False -) -> dict[str, Any]: - """Return the last valid connected-component observation. - - The full trajectory remains available as a diagnostic, while this endpoint - response can be recovered when only the final field was retained. - """ - series = trajectory.get("series", []) if isinstance(trajectory, dict) else [] - components = [] - selected = series if all_components else series[:1] - for item in selected: - points = [point for point in item.get("points", []) - if isinstance(point, dict) and isinstance(point.get("value"), (int, float)) - and math.isfinite(float(point["value"]))] - if points: - point = points[-1] - components.append({"component_id": item.get("component_id"), "time": point["time"], "value": point["value"]}) - return {"kind": "component_scalars", "quantity": quantity, "components": components} - - -def structured_qoi_errors(name: str, value: Any) -> list[str]: - errors: list[str] = [] - if isinstance(value, (int, float)): - return [] if not isinstance(value, bool) and math.isfinite(float(value)) else [f"{name}: non-finite scalar"] - if not isinstance(value, dict): - return [f"{name}: unsupported QoI value"] - kind = value.get("kind") - if kind in {"time_history", "window_regression", "scalar_ratio"}: - if kind == "time_history": - points = value.get("points") - if not isinstance(points, list) or not points: - return [f"{name}: empty time history"] - for point in points: - if not isinstance(point, dict) or not all( - isinstance(point.get(key), (int, float)) and math.isfinite(float(point[key])) - for key in ("time", "value") - ): - errors.append(f"{name}: invalid time-history point") - break - elif not isinstance(value.get("value"), (int, float)) or not math.isfinite(float(value["value"])): - errors.append(f"{name}: invalid scalar object") - elif kind == "branched_time_histories": - branches = value.get("branches") - if not isinstance(branches, dict) or not branches: - errors.append(f"{name}: no branches") - else: - for branch, history in branches.items(): - errors.extend(structured_qoi_errors(f"{name}/{branch}", history)) - elif kind == "branch_scalars": - branches = value.get("branches") - if not isinstance(branches, dict) or not branches: - errors.append(f"{name}: no scalar branches") - else: - for branch, metrics in branches.items(): - if not isinstance(metrics, dict) or not metrics or any( - not isinstance(item, (int, float)) or isinstance(item, bool) or not math.isfinite(float(item)) - for item in metrics.values() - ): - errors.append(f"{name}/{branch}: invalid branch scalar") - elif kind == "component_scalars": - components = value.get("components") - if not isinstance(components, list) or not components: - errors.append(f"{name}: no component scalars") - elif any(not isinstance(item.get("value"), (int, float)) or not math.isfinite(float(item["value"])) - for item in components if isinstance(item, dict)): - errors.append(f"{name}: invalid component scalar") - elif kind == "component_trajectory": - series = value.get("series") - if not isinstance(series, list) or not series: - errors.append(f"{name}: no component trajectories") - else: - for item in series: - points = item.get("points", []) if isinstance(item, dict) else [] - valid = [point for point in points if isinstance(point, dict) - and isinstance(point.get("value"), (int, float)) - and math.isfinite(float(point["value"]))] - if len(valid) < 2: - errors.append(f"{name}: component has fewer than two valid points") - elif kind == "named_profiles": - profiles = value.get("profiles") - if not isinstance(profiles, list) or not profiles: - errors.append(f"{name}: no named profiles") - elif any(not profile.get("rows") or len(profile.get("columns", [])) < 2 for profile in profiles): - errors.append(f"{name}: empty or unlabelled profile") - elif kind in {"profile_events", "profile_feature_locations"}: - if not isinstance(value.get("events"), list): - errors.append(f"{name}: invalid event collection") - else: - errors.append(f"{name}: unknown structured kind {kind!r}") - return errors - - -def extract_case( - case: Path, - family: str, - variant: str, - metrics: list[str], - *, - conditional_metrics: list[str] | None = None, -) -> dict[str, Any]: - values: dict[str, Any] = {} - evidence: dict[str, list[str]] = {} - methods: dict[str, str] = {} - spalding, spalding_evidence = spalding_metrics(case) if family == "yPlusVerification" else ({}, []) - branchwise_spalding, branchwise_spalding_evidence = branchwise_spalding_metrics(case) if family == "yPlusVerification" else (None, []) - bubbles, bubble_evidence, bubble_errors = bubble_metrics(case, family) if family in {"risingBubble", "compressibleBubbleCollapse"} else ({}, [], []) - stirrer_power, stirrer_evidence = stirrer_power_history(case) if family == "MRF_stirredReactor" else (None, []) - riemann_profiles, riemann_evidence = named_sample_profiles(case, ("horizontal.xy", "vertical.xy")) if family == "riemann2D" else (None, []) - if family == "riemann2D" and riemann_profiles is None: - riemann_profiles, riemann_evidence = result_profile_tables(case, ("centreline", "centerline", "p_x", "p_y", "rho_x", "rho_y")) - if riemann_profiles is not None: - riemann_profiles = final_riemann_profiles(riemann_profiles) - riemann_events = profile_event_locations(riemann_profiles) if riemann_profiles is not None else None - nozzle_profiles, nozzle_evidence = named_profiles_containing(case, ("centerline",), ("p",)) if family == "nozzleCDV" else (None, []) - crossjet_profiles, crossjet_evidence = named_profiles_containing(case, ("trajectory", "centerline", "section"), ()) if family == "supersonicCrossJet" else (None, []) - mass_flow, mass_flow_evidence = explicit_mass_flow_history(case) if family in {"ERCOFTA_pump", "nozzleCDV"} else (None, []) - patch_pressure, patch_pressure_evidence = explicit_patch_pressure(case) if family == "ERCOFTA_pump" else (None, []) - retained_values, retained_evidence, retained_errors = {}, {}, [] - if family == "ERCOFTA_pump": - retained_values, retained_evidence, retained_errors = pump_measurements(case) - crossjet_flux_ratio, crossjet_flux_evidence = crossjet_inlet_mass_flux_ratio(case) if family == "supersonicCrossJet" else (None, []) - phase_volume, phase_volume_evidence = phase_volume_history(case) if family == "MRF_stirredReactor" else (None, []) - average_speed, average_speed_evidence = volume_average_speed_history(case) if family == "MRF_stirredReactor" else (None, []) - speed_rms, speed_rms_evidence = volume_speed_rms_history(case) if family == "MRF_stirredReactor" else (None, []) - speed_final, speed_final_evidence = volume_average_speed_final(case) if family == "MRF_stirredReactor" else (None, []) - pressure_span, pressure_span_evidence = crossjet_interior_pressure_span(case) if family == "supersonicCrossJet" else (None, []) - conditional_metrics = conditional_metrics or [] - requested_metrics = list(dict.fromkeys([*metrics, *conditional_metrics])) - for metric in requested_metrics: - if metric in {"Cd", "Cl", "Cm", "Cd_mean", "Cd_rms", "Cl_mean", "Cl_rms"}: - value, refs, method = extract_force_metric(case, metric) - elif metric in spalding: - value, refs, method = spalding[metric], spalding_evidence, "spalding_named_profile_or_endpoint.v1" - elif metric == "branchwise_wall_law_metrics" and branchwise_spalding is not None: - value, refs, method = branchwise_spalding, branchwise_spalding_evidence, "branchwise_spalding_metrics.v1" - elif metric in bubbles: - value, refs, method = bubbles[metric], bubble_evidence, "connected_gas_component_history.v1" - elif metric == "stirrer_power_history" and stirrer_power is not None: - value, refs, method = stirrer_power, stirrer_evidence, "named_stirrer_power_history.v1" - elif metric == "phase_volume_fraction_history" and phase_volume is not None: - value, refs, method = phase_volume, phase_volume_evidence, "volume_weighted_phase_fraction.v1" - elif metric == "volume_average_speed_history" and average_speed is not None: - value, refs, method = average_speed, average_speed_evidence, "volume_weighted_speed.v1" - elif metric == "volume_speed_rms_history" and speed_rms is not None: - value, refs, method = speed_rms, speed_rms_evidence, "volume_weighted_speed_rms.v1" - elif metric == "volume_average_speed_final" and speed_final is not None: - value, refs, method = speed_final, speed_final_evidence, "volume_weighted_final_speed.v1" - elif metric == "centerline_profiles" and riemann_profiles is not None: - value, refs, method = riemann_profiles, riemann_evidence, "named_centerline_profiles.v1" - elif metric == "event_locations" and riemann_events is not None: - value, refs, method = riemann_events, riemann_evidence, "local_abs_gradient_peaks.v1" - elif metric == "centerline_pressure_profile" and nozzle_profiles is not None: - value, refs, method = nozzle_profiles, nozzle_evidence, "named_centerline_pressure_profile.v1" - elif metric in retained_values: - # The retained-field measurement is the canonical path. Agent - # emitted tables remain useful evidence, but a one-point table or - # a table with a different time grid must not mask a complete - # history available in the original fields. - value, refs, method = retained_values[metric], retained_evidence[metric], "retained_boundary_field_measurement.v1" - elif metric == "mass_flow_rate" and mass_flow is not None: - value, refs, method = mass_flow, mass_flow_evidence, "explicit_mass_flux_history.v1" - elif metric == "volumetric_flow_rate" and mass_flow is not None: - value, refs, method = mass_flow, mass_flow_evidence, "explicit_volumetric_flux_history.v1" - elif metric == "pressure_rise" and patch_pressure is not None: - value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1" - elif metric == "pressure_rise_history" and patch_pressure is not None: - value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1" - elif metric == "jet_centerline_trajectory" and crossjet_profiles is not None: - value, refs, method = crossjet_profiles, crossjet_evidence, "declared_jet_trajectory_profile.v1" - elif metric == "jet_to_mainstream_mass_flux_ratio" and crossjet_flux_ratio is not None: - value, refs, method = crossjet_flux_ratio, crossjet_flux_evidence, "named_inlet_mass_flux_ratio.v1" - elif metric == "interior_pressure_span" and pressure_span is not None: - value, refs, method = pressure_span, pressure_span_evidence, "internal_pressure_span_from_p_field.v1" - else: - value, refs, method = None, [], "not_implemented_without_declared_v3_evidence" - if value is not None and (not isinstance(value, float) or math.isfinite(value)): - values[metric] = value - evidence[metric] = refs - methods[metric] = method - extraction_errors = list(bubble_errors) - if "stirrer_power_history" in metrics and stirrer_power is None: - extraction_errors.append("stirrer_power_history: no named stirrer power evidence") - missing = sorted(set(metrics) - set(values)) - principal_values = {name: values[name] for name in metrics if name in values} - conditional_values = {name: values[name] for name in conditional_metrics if name in values} - validation_errors = [ - error for name, value in principal_values.items() - for error in structured_qoi_errors(name, value) - ] - diagnostic_qois = {name: value for name, value in bubbles.items() if name not in metrics} - if family == "yPlusVerification": - for name, value in spalding.items(): - if name not in metrics: - diagnostic_qois[name] = value - if branchwise_spalding is not None and "branchwise_wall_law_metrics" not in metrics: - diagnostic_qois["branchwise_wall_law_metrics"] = branchwise_spalding - if stirrer_power is not None and "stirrer_power_history" not in metrics: - diagnostic_qois["stirrer_power_history"] = stirrer_power - if phase_volume is not None and "phase_volume_fraction_history" not in metrics: - diagnostic_qois["phase_volume_fraction_history"] = phase_volume - if nozzle_profiles is not None and "centerline_pressure_profile" not in metrics: - diagnostic_qois["centerline_pressure_profile"] = nozzle_profiles - if crossjet_profiles is not None and "jet_centerline_trajectory" not in metrics: - diagnostic_qois["jet_centerline_trajectory"] = crossjet_profiles - complete = not missing and not validation_errors and not extraction_errors - resolver = { - metric: { - "status": "selected" if metric in evidence else "unresolved", - "selected_evidence": sorted(set(evidence.get(metric, []))), - "method": methods.get(metric), - "physical_validation": "metric_extractor_contract.v1", - } - for metric in requested_metrics - } - return { - "schema_version": "foambench.qoi.candidate", - "case_id": f"{family}/{variant}", - "family": family, - "required_metrics": metrics, - "missing_metrics": missing, - "qois": principal_values, - "conditional_qois": conditional_values, - "conditional_status": { - name: "available" if name in conditional_values else "not_assessed_missing_evidence" - for name in conditional_metrics - }, - "diagnostic_qois": diagnostic_qois, - "evidence": evidence, - "metric_methods": methods, - "evidence_contract": canonical_evidence_manifest(), - "resolver_report": resolver, - "extraction_errors": extraction_errors, - "retained_field_diagnostics": retained_errors, - "status": "complete" if complete else "incomplete", - "health": { - "status": "pass" if complete else "incomplete", - "checks": { - "principal_qoi_complete": not missing, - "structured_qoi_valid": not validation_errors, - "principal_extraction_error_free": not extraction_errors, - "no_proxy_fallback": True, - }, - "validation_errors": [*validation_errors, *extraction_errors], - }, - } - - -def metric_anomalies(cases: dict[str, dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - grouped: dict[tuple[str, str, str], list[tuple[str, float]]] = {} - anomalies: list[dict[str, Any]] = [] - review: list[dict[str, Any]] = [] - for case_id, record in cases.items(): - for metric, value in record.get("qois", {}).items(): - if isinstance(value, (int, float)): - grouped.setdefault((record["family"], str(record.get("branch_id")), metric), []).append((case_id, float(value))) - elif isinstance(value, dict) and value.get("kind") == "component_trajectory": - expected_components = 2 if case_id == "compressibleBubbleCollapse/10" else 1 - if len(value.get("series", [])) != expected_components: - review.append({ - "type": "unexpected_component_count", - "case_id": case_id, - "family": record["family"], - "metric": metric, - "expected": expected_components, - "observed": len(value.get("series", [])), - "interpretation": "review physical breakup versus threshold or mesh-induced disconnection", - }) - for series in value.get("series", []): - for point in series.get("points", []): - sample = point.get("value") - if not isinstance(sample, (int, float)) or not math.isfinite(sample): - anomalies.append({ - "type": "invalid_trajectory_point", - "case_id": case_id, - "family": record["family"], - "branch_id": record.get("branch_id"), - "metric": metric, - "component_id": series.get("component_id"), - "time": point.get("time"), - "value": sample, - "quality_flag": point.get("quality_flag"), - }) - for (family, branch, metric), rows in sorted(grouped.items()): - values = [value for _, value in rows] - if any(not math.isfinite(value) for value in values): - anomalies.append({"type": "nonfinite", "family": family, "branch_id": branch, "metric": metric}) - continue - if values and all(value == 0 for value in values): - anomalies.append({"type": "all_zero", "family": family, "branch_id": branch, "metric": metric, "case_count": len(values)}) - if len(values) >= 2 and max(values) == min(values): - anomalies.append({"type": "constant_metric", "family": family, "branch_id": branch, "metric": metric, "value": values[0]}) - nonzero = [abs(value) for value in values if value != 0] - if len(nonzero) >= 2 and max(nonzero) / min(nonzero) > 1e6: - 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"}) - if len(values) >= 5: - median = statistics.median(values) - deviations = [abs(value - median) for value in values] - mad = statistics.median(deviations) - if mad > 0: - for case_id, value in rows: - score = abs(value - median) / mad - if score > 8: - 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"}) - elif any(value != median for value in values): - for case_id, value in rows: - if value != median: - 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"}) - return anomalies, review - - -def extract_campaign(run_roots: Path | list[Path], design: dict[str, Any]) -> dict[str, Any]: - roots = [run_roots] if isinstance(run_roots, Path) else list(run_roots) - cases: dict[str, dict[str, Any]] = {} - missing_case_dirs: list[str] = [] - for family in design.get("families", []): - family_name = family["family"] - variants = sorted({variant for branch in family.get("branches", []) for variant in branch.get("cases", [])}, key=int) - for variant in variants: - branch, metrics = required_metrics(family, variant) - conditionals = [ - item["name"] for item in next( - item for item in family.get("branches", []) if variant in item.get("cases", []) - ).get("conditional_qois", []) - ] - case_id = f"{family_name}/{variant}" - case_dir = None - for root in roots: - case_dir = locate_case(root, family_name, variant) - if case_dir is not None: - break - if case_dir is None: - missing_case_dirs.append(case_id) - continue - record = extract_case( - case_dir, family_name, variant, metrics, conditional_metrics=conditionals - ) - record["branch_id"] = branch - record["case_dir"] = str(case_dir) - cases[case_id] = record - complete = sum(record["status"] == "complete" for record in cases.values()) - anomalies, review = metric_anomalies(cases) - design_findings = [ - { - "type": "reference_configuration_mismatch", - "case_id": "compressibleBubbleCollapse/2", - "severity": "resolved_by_contract_scope", - "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.", - "evidence": "compressibleBubbleCollapse__2/full_run_case/system/setFieldsDict", - "action": "Retain the materialized_single_bubble_response branch unless separate radius subcases are generated.", - }, - { - "type": "axisymmetric_geometry_mismatch", - "case_id": "compressibleBubbleCollapse/10", - "severity": "resolved_by_contract_scope", - "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.", - "evidence": "compressibleBubbleCollapse__10/full_run_case/system/setFieldsDict and constant/polyMesh/boundary", - "action": "Retain the axisymmetric_ring_interaction branch unless a genuinely 3D two-bubble case is materialized.", - }, - { - "type": "reference_coverage_gap", - "severity": "blocking", - "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.", - "evidence": "anonymous-reference/extended/riemann2D", - "action": "validate and import the ten separate Riemann runs into the unified current audit; do not synthesize profiles", - }, - ] - if any(root.name == "materialized" and root.parent.name.startswith("riemann2d_parallel") for root in roots): - design_findings[-1]["severity"] = "resolved_for_current_audit" - 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." - return { - "schema_version": "foambench.qoi_extraction_audit.v1", - "generated_at": utc_now(), - "run_roots": [str(root) for root in roots], - "case_count": len(cases), - "complete_case_count": complete, - "coverage_fraction": complete / len(cases) if cases else 0.0, - "missing_case_dirs": missing_case_dirs, - "structural_anomalies": anomalies, - "review_candidates": review, - "design_findings": design_findings, - "cases": cases, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--run-root", type=Path, action="append", required=True, help="reference run root; repeat to merge independent materialized campaigns") - parser.add_argument("--design", type=Path, default=DEFAULT_DESIGN) - parser.add_argument("--output", type=Path, required=True) - args = parser.parse_args() - design = json.loads(args.design.read_text(encoding="utf-8")) - roots = [root.resolve(strict=True) for root in args.run_root] - report = extract_campaign(roots, design) - write_json(args.output.resolve(), report) - 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)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/evaluation/field_candidate.py b/benchmarks/evaluation/field_candidate.py deleted file mode 100644 index d54275f8f83d94d377db3fe59a133cc4a492ca73..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/field_candidate.py +++ /dev/null @@ -1,23 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from .basic_advanced import extract - - -def extract_field_candidate( - case_dir: Path, - case_id: str, - requested_metrics: list[str], - *, - required_metrics: list[str] | None = None, - log_paths: list[Path] | None = None, -) -> dict[str, Any]: - return extract( - case_dir, - case_id, - requested_metrics, - required_metrics=required_metrics, - log_paths=log_paths, - ) diff --git a/benchmarks/evaluation/field_extractor.py b/benchmarks/evaluation/field_extractor.py deleted file mode 100644 index 2702caa4d1c615dced38cea4a95a739ff5be9069..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/field_extractor.py +++ /dev/null @@ -1,421 +0,0 @@ -#!/usr/bin/env python3 -"""Extract the numeric signatures used by the FoamBench v13 QoI contracts. - -The definitions in this module intentionally preserve the extractor that -produced the checked-in reference JSON files. Candidate runs must use this -same implementation so reference and candidate values have identical field, -ordering, and proxy definitions. -""" -from __future__ import annotations - -import argparse -import json -import math -import re -import sys -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.foam_io import field_path, magnitude, read_text - - -NUMBER_RE = re.compile(r"[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?") -VECTOR_RE = re.compile(r"\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)") -RESIDUAL_RE = re.compile( - r"Solving for (?P[^,]+), Initial residual = (?P[-+0-9.eE]+), " - r"Final residual = (?P[-+0-9.eE]+), No Iterations (?P\d+)" -) -COURANT_RE = re.compile(r"Courant Number mean:\s*(?P[-+0-9.eE]+)\s+max:\s*(?P[-+0-9.eE]+)") -FATAL_RE = re.compile( - r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))", - re.I, -) - -FAMILY_PROBLEM_TYPES = { - "BernardCells": "buoyant_thermal_convection", - "Cavity": "lid_driven_cavity", - "Cylinder": "cylinder_wake", - "counterFlowFlame2D": "counterflow_flame", - "damBreakWithObstacle": "free_surface_vof", - "forwardStep": "compressible_shock", - "obliqueShock": "compressible_shock", - "pitzDaily": "separated_internal_flow", - "shallowWaterWithSquareBump": "shallow_water_bump", - "squareBend": "compressible_bend", - "wedge": "compressible_shock", -} -FAMILY_ALIASES = {name.lower(): name for name in FAMILY_PROBLEM_TYPES} - - -class ExtractionError(RuntimeError): - """Raised when a field exists but cannot be interpreted safely.""" - - -def utc_now() -> str: - return datetime.now(timezone.utc).isoformat() - - -def write_json(path: Path, data: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") - temporary.replace(path) - - -def strip_comments(text: str) -> str: - return re.sub(r"//.*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S)) - - -def foam_entry(text: str, key: str) -> str | None: - match = re.search(rf"^\s*{re.escape(key)}\s+([^;\s]+)\s*;", strip_comments(text), re.M) - return match.group(1) if match else None - - -def latest_time_dir(case_dir: Path) -> tuple[float | None, Path | None]: - choices: list[tuple[float, Path]] = [] - if not case_dir.is_dir(): - return None, None - for child in case_dir.iterdir(): - if not child.is_dir(): - continue - try: - choices.append((float(child.name), child)) - except ValueError: - continue - return max(choices, key=lambda item: item[0]) if choices else (None, None) - - -def clean_internal_field_text(text: str) -> str: - marker = text.find("internalField") - if marker < 0: - return "" - text = text[marker:] - boundary = text.find("boundaryField") - return text[:boundary] if boundary >= 0 else text - - -def ensure_ascii_field(path: Path, text: str) -> None: - header = text[: min(len(text), 4096)] - if re.search(r"\bformat\s+binary\s*;", header): - raise ExtractionError( - f"binary OpenFOAM field is not supported directly: {path}; " - "convert the latest time to ASCII with foamFormatConvert before evaluation" - ) - - -def parse_scalar_field(path: Path) -> list[float]: - raw = read_text(path) - ensure_ascii_field(path, raw) - text = clean_internal_field_text(raw) - if not text: - return [] - uniform = re.search(r"internalField\s+uniform\s+([-+0-9.eE]+)", text) - if uniform: - return [float(uniform.group(1))] - start, end = text.find("("), text.rfind(")") - body = text[start + 1 : end] if start >= 0 and end > start else text - return [float(token) for token in NUMBER_RE.findall(body)] - - -def parse_vector_field(path: Path) -> list[tuple[float, float, float]]: - raw = read_text(path) - ensure_ascii_field(path, raw) - text = clean_internal_field_text(raw) - if not text: - return [] - uniform = re.search( - r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)", text - ) - if uniform: - return [(float(uniform.group(1)), float(uniform.group(2)), float(uniform.group(3)))] - return [(float(m.group(1)), float(m.group(2)), float(m.group(3))) for m in VECTOR_RE.finditer(text)] - - -def scalar(latest: Path | None, name: str) -> list[float]: - path = field_path(latest, name) - return parse_scalar_field(path) if path else [] - - -def vector(latest: Path | None, name: str) -> list[tuple[float, float, float]]: - path = field_path(latest, name) - return parse_vector_field(path) if path else [] - - -def finite_values(values: list[float]) -> list[float]: - return [value for value in values if math.isfinite(value)] - - -def stats(values: list[float]) -> dict[str, float]: - values = finite_values(values) - if not values: - return {} - low, high = min(values), max(values) - return {"min": low, "max": high, "mean": sum(values) / len(values), "range": high - low} - - -def add_stats(qois: dict[str, float], prefix: str, values: list[float]) -> None: - qois.update({f"{prefix}_{suffix}": value for suffix, value in stats(values).items()}) - - -def add_common_field_qois(qois: dict[str, float], latest: Path | None) -> None: - velocities = vector(latest, "U") - if velocities: - add_stats(qois, "velocity_magnitude", magnitude(velocities)) - x, y, z = velocities[len(velocities) // 2] - qois.update({"center_u": x, "center_v": y, "center_w": z, "center_speed": math.sqrt(x*x + y*y + z*z)}) - for name in ("p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", "nuTilda"): - values = scalar(latest, name) - if values: - add_stats(qois, name.replace(".", "_"), values) - vorticity = vector(latest, "vorticity") - if vorticity: - add_stats(qois, "vorticity_magnitude", magnitude(vorticity)) - - -def add_compressible_qois(qois: dict[str, float], latest: Path | None) -> None: - temperatures = scalar(latest, "T") - speeds = magnitude(vector(latest, "U")) - if temperatures and speeds: - mach = [ - speed / math.sqrt(1.4 * 0.7143 * temperature) - for speed, temperature in zip(speeds, temperatures) - if temperature > 0 - ] - add_stats(qois, "mach", mach) - pressures = scalar(latest, "p") - if pressures: - summary = stats(pressures) - mean, low, high = summary.get("mean"), summary.get("min"), summary.get("max") - if mean is not None and low is not None and high is not None and abs(mean) > 1e-12: - qois["pressure_ratio_max_over_mean"] = high / mean - qois["pressure_ratio_max_over_min"] = high / max(abs(low), 1e-12) - if len(pressures) > 1: - qois["shock_strength_proxy_max_dp_index"] = max(abs(b - a) for a, b in zip(pressures, pressures[1:])) - - -def add_flame_qois(qois: dict[str, float], latest: Path | None) -> None: - qdot = scalar(latest, "Qdot") - if qdot: - add_stats(qois, "Qdot", qdot) - qois["integrated_Qdot_proxy"] = sum(finite_values(qdot)) - for species in ("CH4", "O2", "CO2", "H2O", "N2", "Ydefault"): - values = scalar(latest, species) - if values: - add_stats(qois, species, values) - - -def add_vof_qois(qois: dict[str, float], latest: Path | None) -> None: - alpha = scalar(latest, "alpha.water") - if not alpha: - return - clipped = [min(1.0, max(0.0, value)) for value in alpha if math.isfinite(value)] - add_stats(qois, "alpha_water", clipped) - if clipped: - qois["alpha_water_volume_proxy"] = sum(clipped) - qois["alpha_water_wet_fraction"] = sum(value > 0.5 for value in clipped) / len(clipped) - last_wet = max((index for index, value in enumerate(clipped) if value > 0.5), default=0) - qois["alpha_water_front_index_fraction"] = last_wet / max(len(clipped) - 1, 1) - - -def add_shallow_water_qois(qois: dict[str, float], latest: Path | None) -> None: - heights, total_heights, fluxes = scalar(latest, "h"), scalar(latest, "hTotal"), vector(latest, "hU") - if heights: - add_stats(qois, "h", heights) - if total_heights: - add_stats(qois, "hTotal", total_heights) - velocities: list[float] = [] - froude: list[float] = [] - for height, flux in zip(heights, fluxes): - if abs(height) <= 1e-12: - continue - speed = math.sqrt(sum(component * component for component in flux)) / abs(height) - velocities.append(speed) - if height > 0: - froude.append(speed / math.sqrt(9.81 * height)) - add_stats(qois, "shallow_velocity", velocities) - add_stats(qois, "froude", froude) - - -def infer_family(case_id: str) -> str: - first = case_id.split("/", 1)[0] - return FAMILY_ALIASES.get(first.lower(), first) - - -def infer_problem_type(family: str, latest: Path | None) -> str: - if family in FAMILY_PROBLEM_TYPES: - return FAMILY_PROBLEM_TYPES[family] - names = {path.name.removesuffix(".gz") for path in latest.iterdir() if path.is_file()} if latest else set() - if "alpha.water" in names: - return "free_surface_vof" - if {"h", "hU"} & names: - return "shallow_water_bump" - if "Qdot" in names or {"CH4", "O2"} & names: - return "counterflow_flame" - if {"p", "T", "U"} <= names: - return "compressible_flow" - return "generic_cfd" - - -def parse_log_metrics(case_dir: Path, log_paths: list[Path] | None = None) -> tuple[dict[str, float], list[str]]: - """Extract residual/Courant metrics from case logs and optional run logs. - - FoamAgent writes solver output into ``case/log.*``. EasyFoam keeps the - same output under ``workspace/runs/formal-*/`` and records the paths in - ``run_record.json``. ``log_paths`` lets an offline evaluator consume that - evidence without copying or modifying the generated case. - """ - candidates = sorted( - {path for pattern in ("log.foamRun*", "log.*") for path in case_dir.glob(pattern) if path.is_file()}, - key=lambda path: (path.name != "log.foamRun", path.name), - ) - if log_paths: - candidates.extend(path for path in log_paths if path.is_file() and path not in candidates) - texts = [(path, read_text(path)) for path in candidates] - residuals: list[float] = [] - courants: list[float] = [] - fatal_logs: list[str] = [] - for path, text in texts: - if FATAL_RE.search(text): - fatal_logs.append(path.name) - residuals.extend(float(match.group("final")) for match in RESIDUAL_RE.finditer(text)) - courants.extend(float(match.group("max")) for match in COURANT_RE.finditer(text)) - qois: dict[str, float] = {} - if residuals: - qois.update({"max_final_residual": max(residuals), "last_final_residual": residuals[-1]}) - if courants: - qois.update({"max_courant": max(courants), "last_courant": courants[-1]}) - return qois, fatal_logs - - -def required_metrics(reference_path: Path | None, case_id: str) -> tuple[list[str] | None, dict[str, Any] | None]: - if reference_path is None: - return None, None - data = json.loads(reference_path.read_text(encoding="utf-8")) - cases = data.get("cases") if isinstance(data, dict) else None - if not isinstance(cases, dict) or not isinstance(cases.get(case_id), dict): - raise ValueError(f"case {case_id!r} is absent from reference contract {reference_path}") - record = cases[case_id] - qois = record.get("qois") - if not isinstance(qois, dict): - raise ValueError(f"case {case_id!r} has no qois object in {reference_path}") - return sorted(qois), record - - -def extract_case_qois( - case_dir: Path, - case_id: str, - reference_path: Path | None = None, - log_paths: list[Path] | None = None, -) -> dict[str, Any]: - case_dir = case_dir.resolve(strict=True) - latest_time, latest = latest_time_dir(case_dir) - family = infer_family(case_id) - problem_type = infer_problem_type(family, latest) - required, reference = required_metrics(reference_path, case_id) - if reference and isinstance(reference.get("problem_type"), str): - problem_type = reference["problem_type"] - - qois, fatal_logs = parse_log_metrics(case_dir, log_paths=log_paths) - add_common_field_qois(qois, latest) - if problem_type in {"compressible_shock", "compressible_flow", "compressible_bend"}: - add_compressible_qois(qois, latest) - if problem_type == "counterflow_flame": - add_flame_qois(qois, latest) - if problem_type == "free_surface_vof": - add_vof_qois(qois, latest) - if problem_type == "shallow_water_bump": - add_shallow_water_qois(qois, latest) - qois = {name: value for name, value in sorted(qois.items()) if math.isfinite(float(value))} - missing = sorted(set(required or []) - set(qois)) - unexpected = sorted(set(qois) - set(required or [])) if required is not None else [] - control = read_text(case_dir / "system" / "controlDict") - return { - "schema_version": "foambench.qoi.candidate.v1", - "generated_at": utc_now(), - "producer": "benchmarks/evaluation/qoi_reference.py", - "case_id": case_id, - "family": family, - "problem_type": problem_type, - "application": foam_entry(control, "application"), - "solver": foam_entry(control, "solver"), - "latest_time": latest_time, - "qois": qois, - "coverage": { - "required_count": len(required) if required is not None else None, - "extracted_required_count": len(required) - len(missing) if required is not None else None, - "fraction": (len(required) - len(missing)) / len(required) if required else None, - "missing_metrics": missing, - "unexpected_metrics": unexpected, - }, - "fatal_logs": fatal_logs, - "status": "complete" if latest and not missing and not fatal_logs else "incomplete", - } - - -def find_case_dirs(root: Path) -> list[Path]: - return sorted({control.parents[1] for control in root.rglob("system/controlDict")}) - - -def infer_case_id(case_dir: Path, root: Path) -> str: - relative = case_dir.resolve().relative_to(root.resolve()) - parts = list(relative.parts) - if parts and parts[-1] in {"case", "workspace"}: - parts.pop() - if len(parts) >= 2 and parts[-1].startswith("replicate_"): - parts.pop() - return "/".join(parts[-2:]) if len(parts) >= 2 else (parts[0] if parts else case_dir.name) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--case", type=Path, action="append", default=[]) - parser.add_argument("--case-id", action="append", default=[]) - parser.add_argument("--root", type=Path) - parser.add_argument("--reference-qois", type=Path) - parser.add_argument("--output", type=Path) - parser.add_argument("--require-complete", action="store_true") - parser.add_argument("--json", action="store_true") - args = parser.parse_args() - - explicit_cases = [path.resolve(strict=True) for path in args.case] - if args.case_id and len(args.case_id) != len(explicit_cases): - parser.error("--case-id count must match --case count") - selected = [(path, args.case_id[index]) for index, path in enumerate(explicit_cases)] - if args.root: - root = args.root.resolve(strict=True) - selected.extend((path, infer_case_id(path, root)) for path in find_case_dirs(root) if path not in explicit_cases) - if not selected: - parser.error("provide --case or --root") - - records: dict[str, Any] = {} - for case_dir, case_id in selected: - records[case_id] = extract_case_qois(case_dir, case_id, args.reference_qois) - incomplete = sorted(case_id for case_id, record in records.items() if record["status"] != "complete") - report = { - "schema_version": "foambench.qoi.candidates.v1", - "generated_at": utc_now(), - "case_count": len(records), - "complete_count": len(records) - len(incomplete), - "incomplete_cases": incomplete, - "cases": records, - } - if args.output: - write_json(args.output.resolve(), report) - if args.json or not args.output: - print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) - else: - print(f"qoi_report: {args.output.resolve()} ({report['complete_count']}/{len(records)} complete)") - return 1 if args.require_complete and incomplete else 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, ValueError, ExtractionError, json.JSONDecodeError) as exc: - print(f"extract_foambench_qois.py: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/evaluation/foam.py b/benchmarks/evaluation/foam.py deleted file mode 100644 index 0a417b823ffe1433552225508e5b09bf4445e17c..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/foam.py +++ /dev/null @@ -1,84 +0,0 @@ -from __future__ import annotations - -import re -from pathlib import Path - -from .foam_io import read_text - -NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?" -TIME_RE = re.compile(rf"(?m)^\s*Time\s*=\s*({NUMBER})\s*s?\s*$") -FATAL_RE = re.compile( - r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))", - re.I, -) -NONFINITE_RE = re.compile(r"(? tuple[float | None, list[Path], str]: - if case_dir is None or not case_dir.is_dir(): - return None, [], "missing" - values: list[tuple[float, Path]] = [] - for path in case_dir.iterdir(): - if not path.is_dir(): - continue - try: - value = float(path.name) - except ValueError: - continue - if value > 0: - values.append((value, path)) - if values: - latest = max(value for value, _ in values) - return latest, [path for value, path in values if value == latest], "reconstructed" - processors = sorted( - (path for path in case_dir.iterdir() if path.is_dir() and re.fullmatch(r"processor\d+", path.name)), - key=lambda path: int(path.name[9:]), - ) - processor_times = [] - for processor in processors: - found = [] - for path in processor.iterdir(): - if not path.is_dir(): - continue - try: - value = float(path.name) - except ValueError: - continue - if value > 0: - found.append((value, path)) - processor_times.append(sorted(found)) - if processors and all(processor_times): - common = set(value for value, _ in processor_times[0]) - for values in processor_times[1:]: - common.intersection_update(value for value, _ in values) - if not common: - return None, [], "missing" - latest = max(common) - selected = [ - next(path for value, path in values if value == latest) - for values in processor_times - ] - return latest, selected, "decomposed" - return None, [], "missing" - - -def latest_time_dir(case_dir: Path | None) -> tuple[float | None, Path | None]: - latest, directories, _ = final_time_dirs(case_dir) - return latest, directories[0] if directories else None - - -def read_logs(paths: tuple[Path, ...] | list[Path]) -> str: - return "\n".join(read_text(path) for path in paths if path.is_file()) - - -def normal_end(log_text: str) -> bool: - return re.search(r"(?m)^\s*End\s*$", log_text) is not None - - -def converged_early(log_text: str) -> bool: - return re.search(r"solution converged|convergence criterion satisfied", log_text, re.I) is not None - - -def final_log_time(log_text: str) -> float | None: - values = [float(match.group(1)) for match in TIME_RE.finditer(log_text)] - return values[-1] if values else None diff --git a/benchmarks/evaluation/foam_arrays.py b/benchmarks/evaluation/foam_arrays.py deleted file mode 100644 index a0180f66bf6db8e744b20fa2d9e12a57aef08fee..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/foam_arrays.py +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env python3 -"""Read complete OpenFOAM primitive arrays for v3 scientific QoIs.""" -from __future__ import annotations - -import gzip -import re -import struct -from pathlib import Path -from typing import Literal - - -NUMBER = rb"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?" - - -class FoamArrayError(RuntimeError): - """Raised when a primitive array cannot be decoded unambiguously.""" - - -def _bytes(path: Path) -> bytes: - return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes() - - -def _header(data: bytes) -> bytes: - end = data.find(b"// * * *") - return data[: end if end >= 0 else min(len(data), 4096)] - - -def _format(data: bytes) -> Literal["ascii", "binary"]: - match = re.search(rb"\bformat\s+(ascii|binary)\s*;", _header(data)) - if not match: - raise FoamArrayError("OpenFOAM header has no format entry") - return match.group(1).decode("ascii") # type: ignore[return-value] - - -def _arch(data: bytes) -> tuple[str, int, int]: - match = re.search(rb'\barch\s+"([^\"]+)"\s*;', _header(data)) - arch = match.group(1).decode("ascii") if match else "LSB;label=32;scalar=64" - endian = ">" if arch.startswith("MSB") else "<" - label = int(re.search(r"label=(32|64)", arch).group(1)) if "label=" in arch else 32 - scalar = int(re.search(r"scalar=(32|64)", arch).group(1)) if "scalar=" in arch else 64 - return endian, label, scalar - - -def _list_payload(data: bytes, marker: bytes | None = None) -> tuple[int, bytes]: - if marker is None: - header_end = data.find(b"// * * *") - search = data[header_end if header_end >= 0 else 0 :] - match = re.search(rb"\b(\d+)\s*\(", search) - offset = (header_end if header_end >= 0 else 0) + (match.end() if match else 0) - else: - match = re.search(marker + rb"\s+(\d+)\s*\(", data) - offset = match.end() if match else 0 - if not match: - raise FoamArrayError("OpenFOAM nonuniform list header was not found") - while offset < len(data) and data[offset : offset + 1] in (b"\n", b"\r"): - offset += 1 - return int(match.group(1)), data[offset:] - - -def _ascii_body(payload: bytes) -> bytes: - end = payload.rfind(b")") - return payload[:end] if end >= 0 else payload - - -def read_scalar_field(path: Path) -> list[float]: - data = _bytes(path) - uniform = re.search(rb"internalField\s+uniform\s+(" + NUMBER + rb")", data) - if uniform: - return [float(uniform.group(1))] - count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List") - if _format(data) == "ascii": - values = [float(token) for token in re.findall(NUMBER, _ascii_body(payload))[:count]] - else: - endian, _, scalar_bits = _arch(data) - code = "f" if scalar_bits == 32 else "d" - size = scalar_bits // 8 - values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size])) - if len(values) != count: - raise FoamArrayError(f"{path}: declared {count} scalars but decoded {len(values)}") - return values - - -def read_vector_field(path: Path) -> list[tuple[float, float, float]]: - data = _bytes(path) - count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List") - return _decode_vectors(path, data, count, payload) - - -def read_vector_list(path: Path) -> list[tuple[float, float, float]]: - data = _bytes(path) - count, payload = _list_payload(data) - return _decode_vectors(path, data, count, payload) - - -def _decode_vectors(path: Path, data: bytes, count: int, payload: bytes) -> list[tuple[float, float, float]]: - if _format(data) == "ascii": - rows = re.findall(rb"\(\s*(" + NUMBER + rb")\s+(" + NUMBER + rb")\s+(" + NUMBER + rb")\s*\)", _ascii_body(payload)) - values = [(float(x), float(y), float(z)) for x, y, z in rows[:count]] - else: - endian, _, scalar_bits = _arch(data) - code = "f" if scalar_bits == 32 else "d" - size = scalar_bits // 8 - flat = struct.unpack(f"{endian}{count * 3}{code}", payload[: count * 3 * size]) - values = list(zip(flat[0::3], flat[1::3], flat[2::3])) - if len(values) != count: - raise FoamArrayError(f"{path}: declared {count} vectors but decoded {len(values)}") - return values - - -def read_label_list(path: Path) -> list[int]: - data = _bytes(path) - count, payload = _list_payload(data) - if _format(data) == "ascii": - values = [int(token) for token in re.findall(rb"[-+]?\d+", _ascii_body(payload))[:count]] - else: - endian, label_bits, _ = _arch(data) - code = "i" if label_bits == 32 else "q" - size = label_bits // 8 - values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size])) - if len(values) != count: - raise FoamArrayError(f"{path}: declared {count} labels but decoded {len(values)}") - return values - - -def foam_path(directory: Path, name: str) -> Path | None: - for candidate in (directory / name, directory / f"{name}.gz"): - if candidate.is_file(): - return candidate - return None diff --git a/benchmarks/evaluation/foam_field.py b/benchmarks/evaluation/foam_field.py deleted file mode 100644 index 6bd6e3602342825656398d87ab353d81ae4005d5..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/foam_field.py +++ /dev/null @@ -1,155 +0,0 @@ -from __future__ import annotations - -import gzip -import math -import mmap -import re -import struct -from pathlib import Path -from typing import Any, Iterable - -NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?" -NONFINITE_RE = re.compile(r"(?(?:vol|surface|point)(?:Scalar|Vector|SphericalTensor|SymmTensor|Tensor)Field)\s*;" -) -FORMAT_RE = re.compile(r"\bformat\s+(?Pascii|binary)\s*;") -OBJECT_RE = re.compile(r"\bobject\s+(?P[^;\s]+)\s*;") -LIST_RE = re.compile( - rb"nonuniform\s+(?:List<)?(?Pscalar|vector|sphericalTensor|symmTensor|tensor|label)>?" - rb"\s+(?P\d+)\s*\(" -) -COMPONENTS = {"scalar": 1, "vector": 3, "sphericalTensor": 1, "symmTensor": 6, "tensor": 9, "label": 1} - - -def _stats(values: Iterable[float]) -> dict[str, Any]: - low, high, count, nonfinite = math.inf, -math.inf, 0, 0 - for value in values: - count += 1 - if math.isfinite(value): - low, high = min(low, value), max(high, value) - else: - nonfinite += 1 - return { - "count": count, - "finite": nonfinite == 0, - "nonfinite_count": nonfinite, - "min": None if low == math.inf else low, - "max": None if high == -math.inf else high, - } - - -def _binary_list_stats( - data: bytes | mmap.mmap, - match: re.Match[bytes], - width: int, - byte_order: str, -) -> dict[str, Any]: - kind = match.group("type").decode("ascii") - count = int(match.group("count")) - item_count = count * COMPONENTS[kind] - start, end = match.end(), match.end() + item_count * width - if end > len(data) or not bytes(data[end : min(len(data), end + 16)]).lstrip().startswith(b")"): - raise ValueError("binary field list does not match its declaration") - unpacked = struct.iter_unpack(byte_order + ("d" if width == 8 else "f"), memoryview(data)[start:end]) - result = _stats(item[0] for item in unpacked) - result.update({"value_type": kind, "element_count": count, "components": COMPONENTS[kind]}) - return result - - -def _binary_internal_data( - data: bytes | mmap.mmap, - header: str, -) -> tuple[list[dict[str, Any]], dict[str, Any] | None]: - width_match = re.search(r"scalar=(32|64)", header) - preferred = int(width_match.group(1)) // 8 if width_match else 8 - byte_order = ">" if "MSB" in header else "<" - records = [] - for match in LIST_RE.finditer(data): - for width in (preferred, 4 if preferred == 8 else 8): - try: - record = _binary_list_stats(data, match, width, byte_order) - record["offset"] = match.start() - records.append(record) - break - except ValueError: - continue - internal_marker, boundary_marker = data.find(b"internalField"), data.find(b"boundaryField") - internal = next( - (record for record in records if record["offset"] > internal_marker and (boundary_marker < 0 or record["offset"] < boundary_marker)), - None, - ) - if internal is None and internal_marker >= 0: - stop = boundary_marker if boundary_marker > internal_marker else min(len(data), internal_marker + 1024) - section = bytes(data[internal_marker:stop]).decode("ascii", errors="ignore") - uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section) - if uniform: - internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1))) - return records, internal - - -def _binary_internal(path: Path, header: str) -> tuple[list[dict[str, Any]], dict[str, Any] | None]: - if path.suffix == ".gz": - with gzip.open(path, "rb") as stream: - return _binary_internal_data(stream.read(), header) - with path.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: - return _binary_internal_data(data, header) - - -def _ascii_internal(raw: bytes) -> tuple[list[dict[str, Any]], dict[str, Any] | None, bool]: - text = raw.decode("utf-8", errors="replace") - marker = text.find("internalField") - boundary = text.find("boundaryField", marker + 1) if marker >= 0 else -1 - section = text[marker : boundary if boundary >= 0 else len(text)] if marker >= 0 else "" - uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section) - if uniform: - internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1))) - return [internal], internal, NONFINITE_RE.search(section) is not None - listed = re.search( - rf"internalField\s+nonuniform\s+(?:List<)?(?Pscalar|vector|sphericalTensor|symmTensor|tensor)>?" - rf"\s+(?P\d+)\s*\((?P.*?)\)\s*;", - section, - re.S, - ) - if not listed: - return [], None, NONFINITE_RE.search(section) is not None - values = [float(token) for token in re.findall(NUMBER, listed.group("body"))] - internal = _stats(values) - kind, count = listed.group("type"), int(listed.group("count")) - internal["count_matches_declaration"] = len(values) == count * COMPONENTS[kind] - return [internal], internal, NONFINITE_RE.search(section) is not None - - -def scan_field(path: Path, base: Path | None = None) -> dict[str, Any]: - base = base or path.parent - try: - if path.suffix == ".gz": - with gzip.open(path, "rb") as stream: - header_bytes = stream.read(4096) - else: - header_bytes = path.read_bytes()[:4096] - header = header_bytes.decode("ascii", errors="ignore") - field_class, field_format = FIELD_CLASS_RE.search(header), FORMAT_RE.search(header) - if not field_class or not field_format: - return {"status": "skip", "reason": "not_a_supported_field", "parse_ok": False} - if field_format.group("format") == "binary": - records, internal = _binary_internal(path, header) - nonfinite = any(not record["finite"] for record in records) - else: - raw = gzip.open(path, "rb").read() if path.suffix == ".gz" else path.read_bytes() - records, internal, marker = _ascii_internal(raw) - nonfinite = marker or any(not record["finite"] for record in records) - parse_ok = internal is not None and all(record.get("count_matches_declaration", True) for record in records) - object_match = OBJECT_RE.search(header) - return { - "path": str(path.relative_to(base)) if path.is_relative_to(base) else str(path), - "status": "pass" if parse_ok and not nonfinite else "fail", - "class": field_class.group("class"), - "format": field_format.group("format"), - "field": object_match.group("object") if object_match else path.name.removesuffix(".gz"), - "internal": internal, - "finite": not nonfinite, - "parse_ok": parse_ok, - } - except (OSError, ValueError, struct.error) as exc: - return {"status": "fail", "finite": False, "parse_ok": False, "error": str(exc)} diff --git a/benchmarks/evaluation/foam_io.py b/benchmarks/evaluation/foam_io.py deleted file mode 100644 index cf5689bef6386b7dfc49cc87f32daf702baefd8a..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/foam_io.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Small shared OpenFOAM file helpers used by evaluators and CLI extractors.""" -from __future__ import annotations - -import gzip -import math -from pathlib import Path - - -def read_text(path: Path) -> str: - try: - if path.suffix == ".gz": - with gzip.open(path, "rt", encoding="utf-8", errors="ignore") as stream: - return stream.read() - return path.read_text(encoding="utf-8", errors="replace") - except OSError: - return "" - - -def field_path(time_dir: Path | None, name: str) -> Path | None: - if time_dir is None: - return None - for candidate in (time_dir / name, time_dir / f"{name}.gz"): - if candidate.is_file(): - return candidate - return None - - -def magnitude(values: list[tuple[float, float, float]]) -> list[float]: - return [math.sqrt(x * x + y * y + z * z) for x, y, z in values] diff --git a/benchmarks/evaluation/frozen_recovery.py b/benchmarks/evaluation/frozen_recovery.py deleted file mode 100644 index c67a791e22c712235340056508057326d1cfdfac..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/frozen_recovery.py +++ /dev/null @@ -1,713 +0,0 @@ -#!/usr/bin/env python3 -"""Deterministic QoI recovery for already-finished Extended FoamBench runs. - -This module deliberately has no solver or OpenFOAM command dependency. It -reads only the retained case files named by an existing campaign artifact and -returns a new candidate document in memory. The command-line driver writes -the audit products to a separate directory; neither the frozen run nor its -original QoI document is modified. -""" -from __future__ import annotations - -import copy -import gzip -import hashlib -import json -import math -import re -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any, Iterable - -from .comparison import compare_case -from .extbench import ( - extract_contract_case, - evidence_path, - field_dimensions, - numeric_time_dirs, - profile_event_locations, - read_scalar_field_allow_uniform, - read_vector_field_allow_uniform, - structured_qoi_errors, -) -from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_list - - -RECOVERY_VERSION = "foambench.frozen_qoi_recovery.v1" - - -@dataclass -class RecoveryEvidence: - """Values and audit information produced by one recovery branch.""" - - values: dict[str, Any] = field(default_factory=dict) - evidence: dict[str, list[str]] = field(default_factory=dict) - methods: dict[str, str] = field(default_factory=dict) - source_times: list[float] = field(default_factory=list) - preflight: dict[str, Any] = field(default_factory=dict) - reasons: list[str] = field(default_factory=list) - - -def sha256_file(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for block in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(block) - return digest.hexdigest() - - -def _raw_bytes(path: Path) -> bytes: - return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes() - - -def _text(path: Path) -> str: - return _raw_bytes(path).decode("utf-8", errors="ignore") - - -def _named_block(text: str, name: str, start: int = 0) -> str | None: - match = re.search(r"(?m)^\s*" + re.escape(name) + r"\s*\{", text[start:]) - if match is None: - return None - left = start + match.end() - depth, index = 1, left - while index < len(text) and depth: - char = text[index] - if char == "{": - depth += 1 - elif char == "}": - depth -= 1 - index += 1 - return text[left : index - 1] if depth == 0 else None - - -def _boundary_block(case: Path, patch: str) -> str | None: - path = foam_path(case / "constant/polyMesh", "boundary") - if path is None: - return None - text = _text(path) - anchor = text.find("object boundary") - return _named_block(text, patch, max(anchor, 0)) - - -def _boundary_specs(case: Path) -> dict[str, dict[str, Any]]: - path = foam_path(case / "constant/polyMesh", "boundary") - if path is None: - return {} - text = _text(path) - anchor = max(text.find("object boundary"), 0) - result: dict[str, dict[str, Any]] = {} - names = re.finditer(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\{", text[anchor:]) - for match in names: - name = match.group(1) - block = _named_block(text, name, anchor + match.start()) - if block is None: - continue - start_match = re.search(r"\bstartFace\s+([0-9]+)\s*;", block) - count_match = re.search(r"\bnFaces\s+([0-9]+)\s*;", block) - if start_match and count_match: - result[name] = { - "start_face": int(start_match.group(1)), - "n_faces": int(count_match.group(1)), - "type": (re.search(r"\btype\s+([^;\s]+)\s*;", block) or [None, ""])[1], - } - return result - - -def _face_list(case: Path) -> list[list[int]]: - path = foam_path(case / "constant/polyMesh", "faces") - if path is None: - return [] - text = _text(path) - marker = re.search(r"\bobject\s+faces\s*;.*?\n\s*[0-9]+\s*\(\s*\n", text, re.S) - if marker is None: - return [] - body = text[marker.end() :] - return [ - [int(value) for value in match.group(1).split()] - for match in re.finditer(r"[0-9]+\(\s*([0-9\s]+)\)", body) - ] - - -def _polygon_area(points: list[tuple[float, float, float]], indices: list[int]) -> float: - if len(indices) < 3: - return 0.0 - origin = points[indices[0]] - area = 0.0 - for left, right in zip(indices[1:-1], indices[2:]): - a = tuple(points[left][axis] - origin[axis] for axis in range(3)) - b = tuple(points[right][axis] - origin[axis] for axis in range(3)) - cross = ( - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ) - area += 0.5 * math.sqrt(sum(value * value for value in cross)) - return area - - -def _patch_geometry(case: Path, patch: str) -> tuple[list[float], list[int]]: - specs = _boundary_specs(case) - spec = specs.get(patch) - mesh = case / "constant/polyMesh" - points_path = foam_path(mesh, "points") - owner_path = foam_path(mesh, "owner") - if spec is None or points_path is None or owner_path is None: - return [], [] - faces = _face_list(case) - points = read_vector_list(points_path) - owners = read_label_list(owner_path) - start, count = spec["start_face"], spec["n_faces"] - if start + count > len(faces) or start + count > len(owners): - return [], [] - areas = [_polygon_area(points, faces[index]) for index in range(start, start + count)] - return areas, owners[start : start + count] - - -def _scalar_boundary_values(path: Path, patch: str) -> list[float] | None: - """Read one scalar patch's ``value`` entry without trusting field names.""" - text = _text(path) - anchor = text.find("boundaryField") - block = _named_block(text, patch, max(anchor, 0)) - if block is None: - return None - uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block) - if uniform: - spec = _boundary_specs(path.parents[2] if len(path.parents) > 2 else path.parent) - count = spec.get(patch, {}).get("n_faces", 1) - return [float(uniform.group(1))] * int(count or 1) - listed = re.search( - r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;", - block, - re.S, - ) - if listed is None: - return None - count = int(listed.group(1)) - values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))] - return values[:count] if len(values) >= count else None - - -def _field_boundary_scalar(path: Path, patch: str, face_count: int) -> list[float] | None: - """Boundary scalar reader with an explicit face count from the mesh.""" - text = _text(path) - anchor = text.find("boundaryField") - block = _named_block(text, patch, max(anchor, 0)) - if block is None: - return None - uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block) - if uniform: - return [float(uniform.group(1))] * face_count - listed = re.search( - r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;", - block, - re.S, - ) - if listed is None: - return None - count = int(listed.group(1)) - values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))] - return values[:count] if len(values) >= count else None - - -def _patch_sum_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]: - specs = _boundary_specs(case) - face_count = int(specs.get(patch, {}).get("n_faces", 0)) - if face_count <= 0: - return [], [], [], "patch is absent from boundary contract" - target_values = sorted({float(value) for value in targets}) - dirs = numeric_time_dirs(case) - points: list[dict[str, float]] = [] - evidence: list[str] = [] - source_times: list[float] = [] - for target in target_values: - nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None) - if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)): - continue - actual_time, directory = nearest - path = foam_path(directory, field) - if path is None: - continue - values = _field_boundary_scalar(path, patch, face_count) - if not values or any(not math.isfinite(value) for value in values): - continue - points.append({"time": actual_time, "value": float(sum(values))}) - evidence.append(evidence_path(case, path)) - source_times.append(actual_time) - return points, sorted(set(evidence)), sorted(set(source_times)), None - - -def _patch_average_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]: - areas, owners = _patch_geometry(case, patch) - if not areas or not owners or sum(areas) <= 0: - return [], [], [], "patch geometry could not be reconstructed" - target_values = sorted({float(value) for value in targets}) - dirs = numeric_time_dirs(case) - points: list[dict[str, float]] = [] - evidence: list[str] = [] - source_times: list[float] = [] - for target in target_values: - nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None) - if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)): - continue - actual_time, directory = nearest - path = foam_path(directory, field) - if path is None: - continue - try: - values = read_scalar_field_allow_uniform(path, max(owners) + 1) - except (OSError, ValueError, RuntimeError): - continue - if len(values) <= max(owners): - continue - total_area = sum(areas) - average = sum(area * values[owner] for area, owner in zip(areas, owners)) / total_area - if not math.isfinite(average): - continue - points.append({"time": actual_time, "value": float(average)}) - evidence.append(evidence_path(case, path)) - source_times.append(actual_time) - return points, sorted(set(evidence)), sorted(set(source_times)), None - - -def _reference_times(reference: dict[str, Any], metric_names: Iterable[str]) -> list[float]: - times: set[float] = set() - for metric in metric_names: - value = reference.get("qois", {}).get(metric) - if not isinstance(value, dict): - continue - if value.get("kind") == "time_history": - for point in value.get("points", []): - if isinstance(point, dict) and isinstance(point.get("time"), (int, float)): - times.add(float(point["time"])) - elif value.get("kind") == "branched_time_histories": - for branch in value.get("branches", {}).values(): - if isinstance(branch, dict): - for point in branch.get("points", []): - if isinstance(point, dict) and isinstance(point.get("time"), (int, float)): - times.add(float(point["time"])) - return sorted(times) - - -def _history(quantity: str, points: list[dict[str, float]], dimensions: str | None = None) -> dict[str, Any]: - value: dict[str, Any] = {"kind": "time_history", "quantity": quantity, "points": sorted(points, key=lambda item: item["time"])} - if dimensions: - value["field_dimensions"] = dimensions - return value - - -def recover_ercofta(case: Path, reference: dict[str, Any], variant: str) -> RecoveryEvidence: - result = RecoveryEvidence() - reference_times = _reference_times(reference, ("mass_flow_rate", "pressure_rise")) - available_times = [time for time, _ in numeric_time_dirs(case)] - expected_latest = max(reference_times, default=None) - observed_latest = max(available_times, default=None) - result.preflight.update({ - "reference_latest_time": expected_latest, - "retained_latest_time": observed_latest, - "time_semantics": "numeric_directory_name_exact_match", - }) - 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)): - result.reasons.append( - f"retained result ends at {observed_latest!r}, before reference time {expected_latest!r}; no time rescaling is permitted" - ) - result.preflight["status"] = "fail" - return result - mass_points, mass_refs, mass_times, mass_error = _patch_sum_history(case, "phi", "inlet", reference_times) - pressure_points_in, pressure_refs_in, pressure_times_in, pressure_error_in = _patch_average_history(case, "p", "inlet", reference_times) - pressure_points_out, pressure_refs_out, pressure_times_out, pressure_error_out = _patch_average_history(case, "p", "outlet", reference_times) - result.preflight.update({ - "status": "pass" if mass_points or pressure_points_in else "fail", - "mass_point_count": len(mass_points), - "pressure_inlet_point_count": len(pressure_points_in), - "pressure_outlet_point_count": len(pressure_points_out), - }) - if mass_points: - result.values["mass_flow_rate"] = _history("explicit_mass_flow", mass_points, field_dimensions(case, "phi")) - result.evidence["mass_flow_rate"] = mass_refs - result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1" - result.source_times.extend(mass_times) - if pressure_points_in and pressure_points_out: - inlet = {round(point["time"], 12): point["value"] for point in pressure_points_in} - outlet = {round(point["time"], 12): point["value"] for point in pressure_points_out} - points = [{"time": time, "value": outlet[time] - inlet[time]} for time in sorted(set(inlet) & set(outlet))] - if points: - result.values["pressure_rise"] = { - "kind": "time_history", - "quantity": "pressure_rise", - "definition": "outlet_minus_inlet_patch_owner_cell_area_average", - "source_patches": {"inlet": "inlet", "outlet": "outlet"}, - "points": points, - } - result.evidence["pressure_rise"] = sorted(set(pressure_refs_in + pressure_refs_out)) - result.methods["pressure_rise"] = "retained_p_owner_cell_patch_area_average.v1" - result.source_times.extend(pressure_times_in + pressure_times_out) - for error in (mass_error, pressure_error_in, pressure_error_out): - if error: - result.reasons.append(error) - if expected_latest is not None and not mass_points and not pressure_points_in: - result.reasons.append( - "no retained time directory matches the reference time grid; time units or scale are not inferred" - ) - result.source_times = sorted(set(result.source_times)) - return result - - -def _case_branch_dirs(case: Path) -> dict[str, Path]: - parent = case.parent - result = {"pBack_101325": case} - for path in parent.glob("case_pBack_*"): - match = re.fullmatch(r"case_pBack_([0-9]+)", path.name) - if match and path.is_dir(): - result[f"pBack_{match.group(1)}"] = path - return result - - -def recover_nozzle(case: Path, reference: dict[str, Any], adapter: str, variant: str) -> RecoveryEvidence: - result = RecoveryEvidence() - reference_value = reference.get("qois", {}).get("mass_flow_rate", {}) - if variant == "4" and adapter == "easyfoam" and reference_value.get("kind") == "branched_time_histories": - branches: dict[str, Any] = {} - evidence: list[str] = [] - sources: dict[str, float] = {} - for branch, history in reference_value.get("branches", {}).items(): - branch_case = _case_branch_dirs(case).get(branch) - points = history.get("points", []) if isinstance(history, dict) else [] - target = [point.get("time") for point in points if isinstance(point, dict) and isinstance(point.get("time"), (int, float))] - if branch_case is None or not target: - result.reasons.append(f"missing retained branch directory or target time for {branch}") - continue - branch_points, refs, times, error = _patch_sum_history(branch_case, "phi", "inlet", target) - if branch_points: - branches[branch] = _history("explicit_mass_flow", branch_points, field_dimensions(branch_case, "phi")) - # ``evidence_path`` is relative to each branch case. Add the - # sibling directory explicitly so three otherwise identical - # ``0.005/phi`` paths cannot be confused in the manifest. - if branch_case != case: - evidence.extend(f"../{branch_case.name}/{ref}" for ref in refs) - else: - evidence.extend(refs) - if times: - sources[branch] = max(times) - elif error: - result.reasons.append(f"{branch}: {error}") - if branches: - result.values["mass_flow_rate"] = { - "kind": "branched_time_histories", - "quantity": "explicit_mass_flow", - "field_dimensions": field_dimensions(case, "phi"), - "branches": branches, - } - result.evidence["mass_flow_rate"] = sorted(set(evidence)) - result.methods["mass_flow_rate"] = "retained_branch_phi_boundary_sum.v1" - result.preflight.update({"status": "pass", "branches": sorted(branches), "source_times": sources}) - result.source_times.extend(sources.values()) - else: - result.preflight["status"] = "fail" - return result - if variant == "2" and adapter == "foamagent" and reference_value.get("kind") == "time_history": - targets = [point.get("time") for point in reference_value.get("points", []) if isinstance(point, dict) and isinstance(point.get("time"), (int, float))] - points, refs, times, error = _patch_sum_history(case, "phi", "inlet", targets) - if points: - result.values["mass_flow_rate"] = _history("explicit_mass_flow", points, field_dimensions(case, "phi")) - result.evidence["mass_flow_rate"] = refs - result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1" - result.source_times.extend(times) - result.preflight.update({"status": "pass", "point_count": len(points), "source_times": times}) - else: - result.preflight["status"] = "fail" - if error: - result.reasons.append(error) - return result - result.preflight["status"] = "not_applicable" - return result - - -def _final_fields(case: Path) -> tuple[float, Path] | None: - for time, directory in reversed(numeric_time_dirs(case)): - if all(foam_path(directory, name) is not None for name in ("C", "U", "rho", "p", "T")): - return time, directory - return None - - -def recover_riemann(case: Path) -> RecoveryEvidence: - result = RecoveryEvidence() - final = _final_fields(case) - if final is None: - result.preflight = {"status": "fail", "reason": "final C/U/rho/p/T fields are not all retained"} - return result - time, directory = final - try: - centres = read_vector_list(foam_path(directory, "C")) # type: ignore[arg-type] - velocity = read_vector_field_allow_uniform(foam_path(directory, "U"), len(centres)) # type: ignore[arg-type] - rho = read_scalar_field_allow_uniform(foam_path(directory, "rho"), len(centres)) # type: ignore[arg-type] - pressure = read_scalar_field_allow_uniform(foam_path(directory, "p"), len(centres)) # type: ignore[arg-type] - temperature = read_scalar_field_allow_uniform(foam_path(directory, "T"), len(centres)) # type: ignore[arg-type] - except (OSError, ValueError, RuntimeError) as exc: - result.preflight = {"status": "fail", "reason": f"field decoding failed: {exc}"} - return result - if not all(len(values) == len(centres) for values in (velocity, rho, pressure, temperature)): - result.preflight = {"status": "fail", "reason": "final fields have inconsistent cell counts"} - return result - x_target = min((point[0] for point in centres), key=lambda value: abs(value)) - y_target = min((point[1] for point in centres), key=lambda value: abs(value)) - horizontal_indices = [index for index, point in enumerate(centres) if abs(point[1] - y_target) <= 1e-10 * max(1.0, abs(y_target))] - vertical_indices = [index for index, point in enumerate(centres) if abs(point[0] - x_target) <= 1e-10 * max(1.0, abs(x_target))] - horizontal_indices.sort(key=lambda index: centres[index][0]) - vertical_indices.sort(key=lambda index: centres[index][1]) - columns_h = ["x", "rho", "U_x", "U_y", "U_z", "p", "T"] - columns_v = ["y", "rho", "U_x", "U_y", "U_z", "p", "T"] - rows_h = [[centres[i][0], rho[i], *velocity[i], pressure[i], temperature[i]] for i in horizontal_indices] - rows_v = [[centres[i][1], rho[i], *velocity[i], pressure[i], temperature[i]] for i in vertical_indices] - if len(rows_h) < 5 or len(rows_v) < 5: - result.preflight = {"status": "fail", "reason": "centerline preflight retained fewer than five cells", "horizontal_count": len(rows_h), "vertical_count": len(rows_v)} - return result - root = evidence_path(case, directory / "C") - refs = sorted({root, evidence_path(case, directory / "U"), evidence_path(case, directory / "rho"), evidence_path(case, directory / "p"), evidence_path(case, directory / "T")}) - profiles = { - "kind": "named_profiles", - "profiles": [ - {"profile_id": f"recovery/{time:g}/horizontal.xy", "columns": columns_h, "rows": rows_h}, - {"profile_id": f"recovery/{time:g}/vertical.xy", "columns": columns_v, "rows": rows_v}, - ], - } - result.values["centerline_profiles"] = profiles - result.values["event_locations"] = profile_event_locations(profiles) - result.evidence["centerline_profiles"] = refs - result.evidence["event_locations"] = refs - result.methods["centerline_profiles"] = "retained_final_cell_centerline_sampling.v1" - result.methods["event_locations"] = "retained_final_cell_centerline_sampling_gradient_peaks.v1" - result.source_times = [time] - result.preflight = { - "status": "pass", - "source_time": time, - "horizontal_cell_count": len(rows_h), - "vertical_cell_count": len(rows_v), - "selected_coordinates": {"x": x_target, "y": y_target}, - } - if result.values["event_locations"] is None: - result.values.pop("event_locations", None) - result.evidence.pop("event_locations", None) - result.methods.pop("event_locations", None) - result.reasons.append("centerline profiles were available but no local pressure/rho gradient event was detected") - return result - - -def _nu_value(case: Path) -> tuple[float | None, str | None]: - for path in (case / "constant/physicalProperties", case / "constant/transportProperties", case / "constant/thermophysicalProperties"): - if not path.is_file(): - continue - match = re.search(r"(?m)^\s*nu\s+(?:\[[^]]+\]\s*)?([-+0-9.eE]+)\s*;", _text(path)) - if match: - return float(match.group(1)), evidence_path(case, path) - return None, None - - -def _vector_boundary_uniform(path: Path, patch: str) -> tuple[float, float, float] | None: - text = _text(path) - anchor = text.find("boundaryField") - block = _named_block(text, patch, max(anchor, 0)) - if block is None: - return None - match = re.search(r"\bvalue\s+uniform\s*\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)\s*;", block) - return tuple(float(match.group(index)) for index in range(1, 4)) if match else None - - -def _first_cell_distance(case: Path) -> tuple[float | None, str | None]: - candidates = sorted(case.glob("postProcessing/wallLawSets/*/yLine.csv")) - for path in reversed(candidates): - rows = [] - try: - for line in path.read_text(encoding="utf-8", errors="ignore").splitlines()[1:]: - parts = [float(item) for item in line.split(",")] - if len(parts) >= 2: - rows.append(abs(parts[1])) - except (OSError, ValueError): - continue - positive = [value for value in rows if value > 0 and math.isfinite(value)] - if positive: - return min(positive), evidence_path(case, path) - return None, None - - -def recover_yplus(case: Path) -> RecoveryEvidence: - result = RecoveryEvidence() - final = next(((time, directory) for time, directory in reversed(numeric_time_dirs(case)) if foam_path(directory, "wallShearStress")), None) - nu, nu_ref = _nu_value(case) - distance, distance_ref = _first_cell_distance(case) - if final is None or nu is None or distance is None: - result.preflight = {"status": "fail", "final_wall_shear": bool(final), "nu": nu, "first_cell_distance": distance} - result.reasons.append("wall shear, kinematic viscosity, or first-cell distance is absent") - return result - time, directory = final - wall_patches = [name for name, spec in _boundary_specs(case).items() if str(spec.get("type")) == "wall"] - values: list[float] = [] - shear_path = foam_path(directory, "wallShearStress") - for patch in wall_patches: - vector = _vector_boundary_uniform(shear_path, patch) if shear_path else None - if vector is not None: - values.append(math.sqrt(sum(component * component for component in vector))) - if not values: - result.preflight = {"status": "fail", "reason": "wallShearStress has no parseable wall patch value"} - return result - tau = statistics_mean(values) - yplus = math.sqrt(max(tau, 0.0)) * distance / nu - if not math.isfinite(yplus): - result.preflight = {"status": "fail", "reason": "derived y+ is non-finite"} - return result - refs = [evidence_path(case, shear_path)] if shear_path else [] - refs.extend(item for item in (nu_ref, distance_ref) if item) - result.values["first_cell_yplus"] = float(yplus) - result.evidence["first_cell_yplus"] = sorted(set(refs)) - result.methods["first_cell_yplus"] = "retained_wall_shear_first_cell_distance.v1" - result.source_times = [time] - result.preflight = {"status": "pass", "source_time": time, "wall_patch_count": len(values), "tau_magnitude": tau, "nu": nu, "first_cell_distance": distance} - result.reasons.append("derived endpoint is an auditable wall-shear estimate, not a substituted Spalding profile") - return result - - -def statistics_mean(values: list[float]) -> float: - return sum(values) / len(values) if values else math.nan - - -def _merge_candidate(candidate: dict[str, Any], recovery: RecoveryEvidence) -> dict[str, Any]: - result = copy.deepcopy(candidate) - qois = result.setdefault("qois", {}) - evidence = result.setdefault("evidence", {}) - methods = result.setdefault("metric_methods", {}) - resolver = result.setdefault("resolver_report", {}) - for metric, value in recovery.values.items(): - qois[metric] = value - evidence[metric] = sorted(set(recovery.evidence.get(metric, []))) - methods[metric] = recovery.methods.get(metric, "frozen_recovery.v1") - resolver[metric] = { - "status": "selected", - "selected_evidence": evidence[metric], - "method": methods[metric], - "physical_validation": "metric_extractor_contract.v1", - } - required = list(result.get("required_metrics", [])) - missing = sorted(set(required) - set(qois)) - result["missing_metrics"] = missing - result["status"] = "complete" if not missing and not result.get("extraction_errors") else "incomplete" - health = result.setdefault("health", {}) - checks = health.setdefault("checks", {}) - checks["principal_qoi_complete"] = not missing - checks["principal_extraction_error_free"] = not result.get("extraction_errors") - validation_errors = [ - error for name, value in qois.items() if name in required for error in structured_qoi_errors(name, value) - ] - checks["structured_qoi_valid"] = not validation_errors - health["status"] = "pass" if not missing and not validation_errors and not result.get("extraction_errors") else "incomplete" - health["validation_errors"] = validation_errors + list(result.get("extraction_errors", [])) - return result - - -def recover_case( - case_id: str, - case: Path, - reference: dict[str, Any], - *, - adapter: str, - design: dict[str, Any], -) -> dict[str, Any]: - """Re-extract and, where justified, recover one selected incomplete case.""" - original = extract_contract_case(case, case_id, design) - original_comparison = compare_case(reference, original, 1.0) - family, variant = case_id.split("/", 1) - recovery = RecoveryEvidence(preflight={"status": "not_applicable"}) - if family == "ERCOFTA_pump": - recovery = recover_ercofta(case, reference, variant) - elif family == "nozzleCDV": - recovery = recover_nozzle(case, reference, adapter, variant) - elif family == "riemann2D": - recovery = recover_riemann(case) - elif family == "yPlusVerification" and variant == "1" and adapter == "easyfoam": - recovery = recover_yplus(case) - elif family == "supersonicCrossJet" and variant == "1": - recovery.reasons.append("declared interior pressure window contains no valid retained cell; global extrema are not an allowed proxy") - recovery.preflight = {"status": "fail", "check": "declared_internal_window_nonempty", "observed_cell_count": 0} - merged = _merge_candidate(original, recovery) - comparison = compare_case(reference, merged, 1.0) - if "incomplete" in str(comparison.get("status")): - recovery_status = "irrecoverable_incomplete" - elif comparison.get("status") == "out_of_tolerance": - recovery_status = "recovered_out_of_tolerance" - elif comparison.get("status") == "pass": - recovery_status = "recovered_complete" - else: - recovery_status = "recovery_evaluation_error" - return { - "case_id": case_id, - "family": family, - "variant": variant, - "case_dir": str(case.resolve()), - "original": { - "reextract_status": original_comparison.get("status"), - "reextract_missing_metrics": original_comparison.get("missing_metrics", []), - "reextract_out_of_tolerance_metrics": original_comparison.get("out_of_tolerance_metrics", []), - "reextract_candidate_missing_metrics": original.get("missing_metrics", []), - }, - "recovery": { - "status": recovery_status, - "version": RECOVERY_VERSION, - "methods": recovery.methods, - "source_evidence": recovery.evidence, - "source_times": recovery.source_times, - "preflight": recovery.preflight, - "reasons": recovery.reasons, - }, - "candidate": merged, - "comparison": comparison, - } - - -def recovery_score_record(source: dict[str, Any], recovered: dict[str, Any]) -> dict[str, Any]: - """Build a compact campaign-compatible record without rerunning checks.""" - original = source - comparison = recovered["comparison"] - execution = copy.deepcopy(original.get("execution", {})) - numerical = copy.deepcopy(original.get("numerical", {})) - execution_pass = execution.get("status") == "pass" - numerical_pass = numerical.get("status") == "pass" or bool(numerical.get("pass")) - qoi_pass = bool(comparison.get("physics_grounded_qoi_pass")) - failure_categories: list[str] = [] - if not execution_pass: - failure_categories.append("execution_failure") - elif "incomplete" in str(comparison.get("status", "")): - failure_categories.append("qoi_incomplete") - elif comparison.get("status") == "out_of_tolerance": - failure_categories.append("qoi_out_of_tolerance") - return { - "schema_version": "foambench.frozen_case_recovery.v1", - "case_id": recovered["case_id"], - "dataset": original.get("dataset", "extended"), - "family": recovered["family"], - "variant": recovered["variant"], - "replicate": original.get("replicate", 1), - "artifact": { - "case_dir": recovered["case_dir"], - "rollout_dir": original.get("artifact", {}).get("rollout_dir"), - "workspace_dir": original.get("artifact", {}).get("workspace_dir"), - }, - "execution": execution, - "numerical": numerical, - "qoi": { - "status": "pass" if qoi_pass else comparison.get("status", "evaluation_error"), - "physics_grounded_qoi_pass": qoi_pass, - "effective_pass_ratio": float(comparison.get("qoi_pass_ratio", 0.0) or 0.0), - "candidate": recovered["candidate"], - "comparison": comparison, - }, - "scores": { - "execution_pass": execution_pass, - "numerical_pass": numerical_pass, - "physics_grounded_qoi_pass": qoi_pass, - "end_to_end_pass": execution_pass and numerical_pass and qoi_pass, - }, - "failure_categories": failure_categories, - "recovery": recovered["recovery"], - } - - -def document_checksum(path: Path) -> dict[str, Any]: - return {"path": str(path.resolve()), "sha256": sha256_file(path), "size_bytes": path.stat().st_size} diff --git a/benchmarks/evaluation/health.py b/benchmarks/evaluation/health.py deleted file mode 100644 index 6829c3425d572d22ce9be682511d7db6079cae8e..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/health.py +++ /dev/null @@ -1,69 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from .foam import final_time_dirs -from .foam_field import scan_field -from .foam_io import field_path - -SCALAR_FIELDS = ( - "p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", "nuTilda", - "Qdot", "CH4", "O2", "CO2", "H2O", "N2", "alpha.water", "alpha.air", - "h", "hTotal", -) -POSITIVE_FIELDS = {"T", "rho", "k", "epsilon", "omega", "nuTilda", "h", "hTotal"} - - -def final_field_health(case_dir: Path | None) -> dict[str, Any]: - latest, time_dirs, layout = final_time_dirs(case_dir) - if not time_dirs: - return { - "status": "unavailable", - "latest_time": latest, - "checks": {}, - "reason": "no_final_time_directory", - } - parsed: list[str] = [] - nonfinite: list[str] = [] - bound_failures: list[str] = [] - parse_errors: dict[str, str] = {} - bounds: dict[str, dict[str, float]] = {} - for name in SCALAR_FIELDS: - paths = [path for time_dir in time_dirs for path in [field_path(time_dir, name)] if path is not None] - if not paths: - continue - records = [scan_field(path, case_dir) for path in paths] - invalid = [record for record in records if not record.get("parse_ok")] - if invalid: - parse_errors[name] = str(invalid[0].get("error") or invalid[0].get("reason") or "internalField is not parseable") - continue - if any(not record.get("finite") for record in records): - nonfinite.append(name) - extrema = [record.get("internal") for record in records] - lows = [float(item["min"]) for item in extrema if isinstance(item, dict) and isinstance(item.get("min"), (int, float))] - highs = [float(item["max"]) for item in extrema if isinstance(item, dict) and isinstance(item.get("max"), (int, float))] - if not lows or not highs: - continue - parsed.append(name) - low, high = min(lows), max(highs) - bounds[name] = {"min": low, "max": high} - if name in POSITIVE_FIELDS and low < -1e-12: - bound_failures.append(name) - if name.startswith("alpha.") and (low < -1e-3 or high > 1.0 + 1e-3): - bound_failures.append(f"{name}_bounds") - checks = { - "parsed_fields_finite": not nonfinite and not parse_errors, - "applicable_field_bounds_valid": not bound_failures, - } - return { - "status": "pass" if all(checks.values()) else "fail", - "latest_time": latest, - "layout": layout, - "checks": checks, - "parsed_fields": sorted(parsed), - "nonfinite_fields": sorted(nonfinite), - "field_bound_failures": sorted(bound_failures), - "parse_errors": parse_errors, - "bounds": bounds, - } diff --git a/benchmarks/evaluation/io.py b/benchmarks/evaluation/io.py deleted file mode 100644 index 58bbfc60dae8b33faa6b1261176e8ccd0004aaa4..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/io.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -import json -import math -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - - -def utc_now() -> str: - return datetime.now(timezone.utc).isoformat() - - -def read_json(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8")) - - -def read_object(path: Path) -> dict[str, Any]: - value = read_json(path) - if not isinstance(value, dict): - raise ValueError(f"expected JSON object: {path}") - return value - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - temporary.write_text( - json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", - encoding="utf-8", - ) - temporary.replace(path) - - -def finite(value: Any) -> float | None: - if isinstance(value, bool) or not isinstance(value, (int, float)): - return None - number = float(value) - return number if math.isfinite(number) else None diff --git a/benchmarks/evaluation/measurement_specs.py b/benchmarks/evaluation/measurement_specs.py deleted file mode 100644 index f3366e83fc6d289d6995f3f41a21e5391e1e5117..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/measurement_specs.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Load the visible, reference-free Extended measurement contract.""" -from __future__ import annotations - -import hashlib -import json -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -PATH = ROOT / "benchmarks/FoamBench_extended_openfoam13_measurement_specs.json" -SCHEMA = "easyfoam.extbench.measurement.v1" - - -def _sha(text: str) -> str: - return hashlib.sha256(text.encode()).hexdigest() - - -def load_measurement_spec(case_id: str, requirement: str | None = None) -> dict[str, Any] | None: - """Return one case contract; reference values and tolerances are absent by construction.""" - if not PATH.is_file() or "/" not in case_id: - return None - document = json.loads(PATH.read_text(encoding="utf-8")) - if document.get("schema_version") != "easyfoam.extbench.measurement_specs.v1": - raise ValueError("unsupported measurement contract") - spec = document.get("cases", {}).get(case_id) - if not isinstance(spec, dict): - return None - if spec.get("measurement_schema") != SCHEMA: - raise ValueError(f"invalid measurement schema for {case_id}") - if requirement is not None: - spec = dict(spec) - spec["requirement_sha256"] = _sha(requirement) - return spec - - -def prompt_measurement_spec(case_id: str, requirement: str) -> str: - spec = load_measurement_spec(case_id, requirement) - if spec is None: - return "" - return ( - "Measurement contract for this ExtBench task (visible task definition; it contains no reference answer or tolerance):\n" - + json.dumps(spec, ensure_ascii=False, indent=2) - + "\nUse this contract to plan what fields, patches, probes, meshes, and saved times must be retained. " - "Do not invent a proxy when a principal measurement is unavailable; report the missing evidence.\n\n" - ) diff --git a/benchmarks/evaluation/mesh.py b/benchmarks/evaluation/mesh.py deleted file mode 100644 index 29f46f4f3dac0e698ea6f4c50ed96c7443403302..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/mesh.py +++ /dev/null @@ -1,54 +0,0 @@ -from __future__ import annotations - -import re -import subprocess -from pathlib import Path -from typing import Any - -from .foam import FATAL_RE, NUMBER, read_text - - -def parse_mesh_log(text: str, *, source: str) -> dict[str, Any]: - failed_values = [int(value) for value in re.findall(r"Failed\s+(\d+)\s+mesh checks", text, re.I)] - min_volumes = [float(value) for value in re.findall(rf"Min volume\s*=\s*({NUMBER})", text)] - markers = { - "fatal": FATAL_RE.search(text) is not None, - "non_positive_cell_volume": min(min_volumes, default=float("inf")) <= 0, - "negative_or_zero_volume": re.search(r"(?:negative|zero)\s+(?:cell\s+)?volumes?", text, re.I) is not None, - "illegal_face": re.search(r"illegal\s+faces?", text, re.I) is not None, - "open_cell": re.search(r"open\s+cells?", text, re.I) is not None, - "non_manifold": re.search(r"non[- ]manifold", text, re.I) is not None, - } - available = "Mesh OK." in text or bool(failed_values) or bool(min_volumes) - hard_failure = any(markers.values()) or max(failed_values, default=0) > 0 - return { - "status": "unavailable" if not available else "fail" if hard_failure else "pass", - "source": source, - "failed_mesh_checks": max(failed_values, default=0), - "min_volume": min(min_volumes) if min_volumes else None, - "critical_markers": markers, - } - - -def mesh_evidence(log_paths: tuple[Path, ...]) -> dict[str, Any]: - selected = [ - path for path in log_paths - if "checkmesh" in path.name.lower() or "checkMesh" in read_text(path)[:4096] - ] - text = "\n".join(read_text(path) for path in selected) - return parse_mesh_log(text, source=",".join(str(path) for path in selected)) - - -def run_check_mesh(case_dir: Path | None, timeout: float = 120.0) -> dict[str, Any]: - if case_dir is None: - return {"status": "unavailable", "source": "read_only_replay", "reason": "case_directory_missing"} - command = ["checkMesh", "-case", str(case_dir), "-allTopology", "-allGeometry", "-noFunctionObjects"] - try: - completed = subprocess.run(command, capture_output=True, text=True, check=False, timeout=timeout) - except (OSError, subprocess.TimeoutExpired) as exc: - return {"status": "fail", "source": "read_only_replay", "command": command, "error": str(exc)} - result = parse_mesh_log(completed.stdout + "\n" + completed.stderr, source="read_only_replay") - result.update({"command": command, "return_code": completed.returncode}) - if completed.returncode != 0: - result["status"] = "fail" - return result diff --git a/benchmarks/evaluation/models.py b/benchmarks/evaluation/models.py deleted file mode 100644 index c9e1bf9d512385515fdb78b08972a7e07d3bb231..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/models.py +++ /dev/null @@ -1,86 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any - -from .io import read_object - - -@dataclass(frozen=True) -class BenchmarkProfile: - profile_id: str - dataset: str - benchmark_path: Path - reference_qois_path: Path - expected_case_count: int - case_id_style: str = "family_variant" - extractor: str = "field" - required_qoi_fraction: float = 1.0 - reference_run_root: Path | None = None - numerical_contract: dict[str, Any] = field(default_factory=dict) - - @classmethod - def load(cls, path: Path, *, repository_root: Path | None = None) -> "BenchmarkProfile": - path = path.resolve(strict=True) - data = read_object(path) - if repository_root: - root = repository_root.resolve() - else: - root = next( - (parent for parent in path.parents if (parent / "benchmarks").is_dir() and (parent / "schemas").is_dir()), - path.parent, - ) - - def resolve(value: str | None) -> Path | None: - if value is None: - return None - candidate = Path(value) - return candidate.resolve() if candidate.is_absolute() else (root / candidate).resolve() - - membership = data.get("membership", {}) - qoi = data.get("qoi", {}) - return cls( - profile_id=str(data["profile_id"]), - dataset=str(data["dataset"]), - benchmark_path=resolve(str(data["benchmark_path"])), # type: ignore[arg-type] - reference_qois_path=resolve(str(data["reference_qois_path"])), # type: ignore[arg-type] - expected_case_count=int(membership["expected_case_count"]), - case_id_style=str(membership.get("case_id_style", "family_variant")), - extractor=str(qoi.get("extractor", "field")), - required_qoi_fraction=float(qoi.get("required_fraction", 1.0)), - reference_run_root=resolve(data.get("reference_run_root")), - numerical_contract=dict(data.get("numerical", {})), - ) - - def identity(self, case_id: str) -> tuple[str, str]: - if "/" in case_id: - return tuple(case_id.split("/", 1)) # type: ignore[return-value] - return case_id, "1" - - -@dataclass(frozen=True) -class CaseArtifact: - case_id: str - dataset: str - family: str - variant: str - replicate: int - rollout_dir: Path - case_dir: Path | None - workspace_dir: Path | None = None - manifest: dict[str, Any] = field(default_factory=dict) - formal_run_records: tuple[Path, ...] = () - solver_logs: tuple[Path, ...] = () - workflow_path: Path | None = None - evidence_summary_path: Path | None = None - - @property - def duration_seconds(self) -> float | None: - value = self.manifest.get("duration_seconds") - return float(value) if isinstance(value, (int, float)) else None - - @property - def token_usage(self) -> dict[str, Any]: - value = self.manifest.get("token_usage") - return dict(value) if isinstance(value, dict) else {} diff --git a/benchmarks/evaluation/numerical.py b/benchmarks/evaluation/numerical.py deleted file mode 100644 index 129785cfb619c6d765adfd41db41a744c34ddb3e..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/numerical.py +++ /dev/null @@ -1,253 +0,0 @@ -from __future__ import annotations - -import math -import re -from pathlib import Path -from typing import Any - -from .foam import FATAL_RE, NONFINITE_RE, NUMBER, final_time_dirs, read_logs -from .health import final_field_health -from .mesh import mesh_evidence, run_check_mesh -from .models import CaseArtifact -from .stability import numerical_scheme, steady_plateau - -RESIDUAL_RE = re.compile( - rf"Solving for (?P[^,\r\n]+),\s*Initial residual = (?P{NUMBER}),\s*Final residual = (?P{NUMBER})" -) -COURANT_RE = re.compile(rf"Courant Number mean:\s*(?P{NUMBER})\s+max:\s*(?P{NUMBER})") -CONTINUITY_RE = re.compile( - rf"(?:time step )?continuity errors\s*:\s*sum local = (?P{NUMBER}),\s*global = (?P{NUMBER}),\s*cumulative = (?P{NUMBER})", - re.I, -) - -DEFAULT_CONTRACT = { - "final_window_fraction": 0.2, - "minimum_final_window_samples": 5, - "final_linear_residual": {"reference_factor": 10.0, "absolute_floor": 1e-3}, - "initial_residual": {"reference_factor": 10.0, "absolute_floor": 1e-3}, - "courant_final_p95": {"reference_factor": 3.0, "absolute_floor": 1.0}, - "courant_peak": {"reference_factor": 3.0, "absolute_floor": 2.0}, - "continuity_global_p95": {"reference_factor": 10.0, "absolute_floor": 1e-5}, - "continuity_cumulative_final": {"reference_factor": 10.0, "absolute_floor": 1e-3}, -} - - -def percentile(values: list[float], fraction: float) -> float | None: - if not values: - return None - ordered = sorted(values) - position = (len(ordered) - 1) * fraction - low, high = math.floor(position), math.ceil(position) - if low == high: - return ordered[low] - return ordered[low] + (ordered[high] - ordered[low]) * (position - low) - - -def final_window(values: list[float], contract: dict[str, Any] = DEFAULT_CONTRACT) -> list[float]: - count = max( - int(contract["minimum_final_window_samples"]), - math.ceil(len(values) * float(contract["final_window_fraction"])), - ) - return values[-min(len(values), count):] - - -def parse_logs(paths: list[Path] | tuple[Path, ...], contract: dict[str, Any] = DEFAULT_CONTRACT) -> dict[str, Any]: - text = read_logs(paths) - residuals: dict[str, dict[str, list[float]]] = {} - courants: list[float] = [] - continuity_global: list[float] = [] - continuity_cumulative: list[float] = [] - for match in RESIDUAL_RE.finditer(text): - field = match.group("field").strip() - values = residuals.setdefault(field, {"initial": [], "final": []}) - values["initial"].append(float(match.group("initial"))) - values["final"].append(float(match.group("final"))) - courants.extend(float(match.group("max")) for match in COURANT_RE.finditer(text)) - for match in CONTINUITY_RE.finditer(text): - continuity_global.append(abs(float(match.group("global")))) - continuity_cumulative.append(abs(float(match.group("cumulative")))) - residual_summary = { - field: { - "sample_count": len(values["initial"]), - "initial_final_window_p95": percentile(final_window(values["initial"], contract), 0.95), - "final_final_window_p95": percentile(final_window(values["final"], contract), 0.95), - } - for field, values in sorted(residuals.items()) - } - return { - "log_paths": [str(path) for path in paths if path.is_file()], - "fatal_marker": FATAL_RE.search(text) is not None, - "nonfinite_marker": NONFINITE_RE.search(text) is not None, - "residual_field_count": len(residuals), - "residual_record_count": sum(len(values["initial"]) for values in residuals.values()), - "residuals": residual_summary, - "initial_residual_final_window_p95": max( - (record["initial_final_window_p95"] for record in residual_summary.values() - if record["initial_final_window_p95"] is not None), - default=None, - ), - "final_residual_final_window_p95": max( - (record["final_final_window_p95"] for record in residual_summary.values() - if record["final_final_window_p95"] is not None), - default=None, - ), - "courant_count": len(courants), - "courant_peak": max(courants) if courants else None, - "courant_final_window_p95": percentile(final_window(courants, contract), 0.95), - "continuity_count": len(continuity_global), - "continuity_global_final_window_p95": percentile(final_window(continuity_global, contract), 0.95), - "continuity_cumulative_final": continuity_cumulative[-1] if continuity_cumulative else None, - } - - -def threshold(reference: float, key: str, contract: dict[str, Any] = DEFAULT_CONTRACT) -> float: - policy = contract[key] - return max(abs(reference) * float(policy["reference_factor"]), float(policy["absolute_floor"])) - - -def compatible( - candidate: float | None, - reference: float | None, - key: str, - contract: dict[str, Any] = DEFAULT_CONTRACT, -) -> tuple[bool | None, float | None]: - if reference is None: - return None, None - limit = threshold(reference, key, contract) - return candidate is not None and math.isfinite(candidate) and candidate <= limit, limit - - -def _field_health(candidate: dict[str, Any], case_dir: Path | None) -> tuple[bool | None, bool | None, dict[str, Any]]: - health = candidate.get("health") - if not isinstance(health, dict): - health = final_field_health(case_dir) - checks = health.get("checks", {}) - return checks.get("parsed_fields_finite"), checks.get("applicable_field_bounds_valid"), health - checks = health.get("checks") if isinstance(health.get("checks"), dict) else {} - finite = checks.get("all_parsed_fields_finite") - bounds = checks.get("applicable_field_bounds_valid") - if not isinstance(finite, bool) or not isinstance(bounds, bool): - fallback = final_field_health(case_dir) - fallback_checks = fallback.get("checks", {}) - finite = finite if isinstance(finite, bool) else fallback_checks.get("parsed_fields_finite") - bounds = bounds if isinstance(bounds, bool) else fallback_checks.get("applicable_field_bounds_valid") - health = {"candidate_health": health, "independent_field_health": fallback} - return finite if isinstance(finite, bool) else None, bounds if isinstance(bounds, bool) else None, health - - -def evaluate_numerical( - artifact: CaseArtifact, - *, - execution_pass: bool, - qoi_candidate: dict[str, Any], - reference_logs: list[Path] | tuple[Path, ...] = (), - reference_case_dir: Path | None = None, - reference_qois: dict[str, Any] | None = None, - reference_statistics: dict[str, Any] | None = None, - steady_plateau_enabled: bool = False, - check_mesh: bool = False, - mesh_timeout: float = 120.0, - contract: dict[str, Any] = DEFAULT_CONTRACT, -) -> dict[str, Any]: - if not execution_pass: - return { - "schema_version": "foambench.numerical_validity.v2", - "status": "not_evaluated_execution_failure", - "pass": False, - "checks": {}, - "failed_checks": [], - } - candidate = parse_logs(artifact.solver_logs, contract) - reference = (dict(reference_statistics) if reference_statistics is not None - else parse_logs(reference_logs, contract) if reference_logs else {}) - finite_fields, bounded_fields, health = _field_health(qoi_candidate, artifact.case_dir) - mesh = mesh_evidence(artifact.solver_logs) - if check_mesh and mesh["status"] == "unavailable": - mesh = run_check_mesh(artifact.case_dir, mesh_timeout) - latest, latest_dirs, layout = final_time_dirs(artifact.case_dir) - scheme = numerical_scheme(artifact.case_dir) if artifact.case_dir else "unknown" - plateau: dict[str, Any] = {"status": "not_applicable", "applicable": False} - reference_plateau: dict[str, Any] = {"status": "not_applicable", "applicable": False} - if steady_plateau_enabled and scheme == "steadyState" and reference_qois: - reference_plateau = steady_plateau(reference_qois) - baseline = { - name: float(metric["relative_span"]) - for name, metric in reference_plateau.get("metrics", {}).items() - if isinstance(metric, dict) and isinstance(metric.get("relative_span"), (int, float)) - } - plateau = steady_plateau(qoi_candidate.get("qois", {}), baseline) - - relative = { - "final_linear_residual_reference_compatible": compatible( - candidate["final_residual_final_window_p95"], reference.get("final_residual_final_window_p95"), - "final_linear_residual", contract, - ), - "initial_residual_reference_compatible": compatible( - candidate["initial_residual_final_window_p95"], reference.get("initial_residual_final_window_p95"), - "initial_residual", contract, - ), - "courant_final_reference_compatible": compatible( - candidate["courant_final_window_p95"], reference.get("courant_final_window_p95"), - "courant_final_p95", contract, - ), - "courant_peak_reference_compatible": compatible( - candidate["courant_peak"], reference.get("courant_peak"), "courant_peak", contract, - ), - "continuity_reference_compatible": compatible( - candidate["continuity_global_final_window_p95"], reference.get("continuity_global_final_window_p95"), - "continuity_global_p95", contract, - ), - "continuity_cumulative_reference_compatible": compatible( - candidate["continuity_cumulative_final"], reference.get("continuity_cumulative_final"), - "continuity_cumulative_final", contract, - ), - } - checks: dict[str, dict[str, Any]] = { - "solver_log_present": {"status": "pass" if candidate["log_paths"] else "fail", "required": True}, - "no_fatal_marker": {"status": "fail" if candidate["fatal_marker"] else "pass", "required": True}, - "no_nonfinite_log_marker": {"status": "fail" if candidate["nonfinite_marker"] else "pass", "required": True}, - "residual_evidence_present": { - "status": "pass" if candidate["residual_record_count"] else "fail", - "required": True, - }, - "final_fields_present": {"status": "pass" if latest_dirs else "fail", "required": True}, - "mesh_core_valid": { - "status": mesh["status"], - "required": mesh["status"] != "unavailable", - }, - "steady_principal_qoi_plateau": { - "status": plateau["status"], - "required": bool(plateau.get("applicable")), - }, - "all_parsed_final_fields_finite": { - "status": "not_applicable" if finite_fields is None else "pass" if finite_fields else "fail", - "required": finite_fields is not None, - }, - "applicable_field_bounds_valid": { - "status": "not_applicable" if bounded_fields is None else "pass" if bounded_fields else "fail", - "required": bounded_fields is not None, - }, - } - for name, (passed, limit) in relative.items(): - checks[name] = { - "status": "not_applicable" if passed is None else "pass" if passed else "fail", - "required": passed is not None, - "limit": limit, - } - failed = [name for name, value in checks.items() if value["required"] and value["status"] == "fail"] - return { - "schema_version": "foambench.numerical_validity.v2", - "status": "pass" if not failed else "fail", - "pass": not failed, - "checks": checks, - "failed_checks": failed, - "candidate_logs": candidate, - "reference_logs": reference or None, - "candidate_latest_time": latest, - "final_field_layout": layout, - "field_health": health, - "mesh": mesh, - "time_scheme": scheme, - "steady_plateau": plateau, - "reference_steady_plateau": reference_plateau, - } diff --git a/benchmarks/evaluation/pipeline.py b/benchmarks/evaluation/pipeline.py deleted file mode 100644 index e16b2937dc4bea4c5b68d4135162cdafb6f7404b..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/pipeline.py +++ /dev/null @@ -1,166 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from .adapters import create_adapter -from .aggregate import aggregate_results -from .execution import evaluate_execution -from .io import utc_now, write_json -from .models import BenchmarkProfile, CaseArtifact -from .numerical import evaluate_numerical -from .profiles import expected_completion_time, load_assets -from .qoi import evaluate_qoi -from .reference import reference_case_dir, reference_log_paths, reference_statistics -from .reporting import write_case_csv, write_summary_csv -from .schema import validate - - -def missing_artifact(case_id: str, profile: BenchmarkProfile, run_root: Path) -> CaseArtifact: - family, variant = profile.identity(case_id) - return CaseArtifact( - case_id=case_id, - dataset=profile.dataset, - family=family, - variant=variant, - replicate=1, - rollout_dir=run_root / family / variant / "replicate_001", - case_dir=None, - manifest={"status": "missing_rollout"}, - ) - - -def failure_categories(result: dict[str, Any]) -> list[str]: - categories = [] - if not result["scores"]["execution_pass"]: - categories.append("execution_failure") - elif not result["scores"]["numerical_pass"]: - categories.append("numerical_failure") - if result["scores"]["execution_pass"] and not result["scores"]["physics_grounded_qoi_pass"]: - qoi_status = result["qoi"].get("status") - if qoi_status == "evaluation_error": - categories.append("qoi_evaluation_error") - else: - categories.append("qoi_incomplete" if "incomplete" in str(qoi_status) else "qoi_out_of_tolerance") - return categories - - -def evaluate_case( - artifact: CaseArtifact, - profile: BenchmarkProfile, - benchmark_case: dict[str, Any], - reference: dict[str, Any], - *, - check_mesh: bool = False, - mesh_timeout: float = 120.0, -) -> dict[str, Any]: - execution = evaluate_execution(artifact, expected_completion_time(benchmark_case, reference)) - execution_pass = execution["status"] == "pass" - qoi = evaluate_qoi(artifact, profile, reference, execution_pass=execution_pass) - numerical = evaluate_numerical( - artifact, - execution_pass=execution_pass, - qoi_candidate=qoi["candidate"], - reference_logs=reference_log_paths(profile, artifact.case_id), - reference_statistics=reference_statistics(profile, artifact.case_id), - reference_case_dir=reference_case_dir(profile, artifact.case_id), - # Numerical plateau is a stability check over available histories. It is - # deliberately separate from the principal Physics-grounded QoI roles. - reference_qois=dict(reference.get("qois", {})), - steady_plateau_enabled=bool(profile.numerical_contract.get("steady_qoi_plateau")), - check_mesh=check_mesh, - mesh_timeout=mesh_timeout, - ) - numerical_pass = bool(numerical.get("pass")) - physics_grounded_qoi_pass = bool(qoi.get("physics_grounded_qoi_pass")) - result = { - "schema_version": "foambench.case_evaluation.v1", - "case_id": artifact.case_id, - "dataset": artifact.dataset, - "family": artifact.family, - "variant": artifact.variant, - "replicate": artifact.replicate, - "execution": execution, - "numerical": numerical, - "qoi": qoi, - "scores": { - "execution_pass": execution_pass, - "numerical_pass": numerical_pass, - "physics_grounded_qoi_pass": physics_grounded_qoi_pass, - "end_to_end_pass": execution_pass and numerical_pass and physics_grounded_qoi_pass, - }, - "resources": { - "duration_seconds": artifact.duration_seconds, - "token_usage": artifact.token_usage, - }, - "artifact": { - "rollout_dir": str(artifact.rollout_dir), - "workspace_dir": str(artifact.workspace_dir) if artifact.workspace_dir else None, - "case_dir": str(artifact.case_dir) if artifact.case_dir else None, - }, - } - result["failure_categories"] = failure_categories(result) - return result - - -def evaluate_campaign( - profile: BenchmarkProfile, - *, - adapter_name: str, - run_root: Path, - output_dir: Path | None = None, - check_mesh: bool = False, - mesh_timeout: float = 120.0, -) -> dict[str, Any]: - benchmark, references = load_assets(profile) - adapter = create_adapter(adapter_name, run_root, profile) - discovered = adapter.discover() - unknown = sorted(set(discovered) - set(references)) - if unknown: - raise ValueError("run contains cases outside the benchmark profile: " + ", ".join(unknown)) - results = [] - for case_id in sorted(references): - artifact = discovered.get(case_id) or missing_artifact(case_id, profile, run_root) - results.append(evaluate_case( - artifact, profile, benchmark[case_id], references[case_id], - check_mesh=check_mesh, mesh_timeout=mesh_timeout, - )) - overall = aggregate_results(results) - families = { - family: aggregate_results([row for row in results if row["family"] == family]) - for family in sorted({row["family"] for row in results}) - } - report = { - "schema_version": "foambench.campaign_evaluation.v1", - "generated_at": utc_now(), - "profile_id": profile.profile_id, - "dataset": profile.dataset, - "adapter": adapter_name, - "run_root": str(run_root.resolve()), - "reference_qois": str(profile.reference_qois_path), - "definitions": { - "execution_pass": "independent execution contract passed", - "numerical_pass": "execution passed and independent numerical contract passed", - "physics_grounded_qoi_pass": "execution passed and every principal Physics-grounded QoI passed its physical contract", - "end_to_end_pass": "execution_pass AND numerical_pass AND physics_grounded_qoi_pass", - }, - "overall": overall, - "families": families, - "cases": {row["case_id"]: row for row in results}, - } - validate(report, "benchmark_evaluation.schema.json") - if output_dir is not None: - output_dir = output_dir.resolve() - write_json(output_dir / "campaign_evaluation.json", report) - write_json(output_dir / "summary.json", { - key: report[key] for key in ( - "schema_version", "generated_at", "profile_id", "dataset", "adapter", - "run_root", "definitions", "overall", "families", - ) - }) - case_root = output_dir / "cases" - for row in results: - write_json(case_root / row["family"] / f"{row['variant']}.json", row) - write_case_csv(output_dir / "cases.csv", results) - write_summary_csv(output_dir / "summary.csv", overall, families) - return report diff --git a/benchmarks/evaluation/preparation.py b/benchmarks/evaluation/preparation.py deleted file mode 100644 index cc4763925d3a13e9aad1c5cbfc7e7bcf1b46eca2..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/preparation.py +++ /dev/null @@ -1,172 +0,0 @@ -from __future__ import annotations - -import re -import subprocess -from concurrent.futures import ThreadPoolExecutor, as_completed -from pathlib import Path -from typing import Any - -from .foam import read_text -from .adapters import create_adapter -from .execution import evaluate_execution -from .io import write_json -from .models import BenchmarkProfile, CaseArtifact -from .profiles import expected_completion_time, load_assets - - -WRITE_FORMAT_RE = re.compile(r"(?m)^\s*writeFormat\s+(ascii|binary)\s*;") - - -def _patch_names(case_dir: Path) -> set[str]: - boundary = case_dir / "constant" / "polyMesh" / "boundary" - if not boundary.is_file(): - return set() - text = boundary.read_text(encoding="utf-8", errors="ignore") - return set(re.findall(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\n\s*\{", text)) - - -def _run(command: list[str], log: Any, timeout: int) -> dict[str, Any]: - try: - completed = subprocess.run( - command, - stdout=log, - stderr=subprocess.STDOUT, - check=False, - text=True, - timeout=timeout, - ) - return {"command": command, "return_code": completed.returncode, "timed_out": False} - except subprocess.TimeoutExpired: - return {"command": command, "return_code": None, "timed_out": True} - except OSError as exc: - return {"command": command, "return_code": 127, "timed_out": False, "error": str(exc)} - - -def prepare_case(artifact: CaseArtifact, output_root: Path) -> dict[str, Any]: - case_dir = artifact.case_dir - if case_dir is None: - return {"case_id": artifact.case_id, "status": "skipped", "reason": "case_directory_missing"} - case_output = output_root / artifact.family / artifact.variant - case_output.mkdir(parents=True, exist_ok=True) - log_path = case_output / "preparation.log" - records: list[dict[str, Any]] = [] - control_path = case_dir / "system" / "controlDict" - original_format_match = WRITE_FORMAT_RE.search(read_text(control_path)) - original_format = original_format_match.group(1) if original_format_match else None - functions = ["writeCellCentres", "writeCellVolumes", "vorticity"] - # Sampling is measurement-only and deterministic when the candidate has - # explicitly declared the benchmark's system/sample dictionary. Do not - # invent sample coordinates for cases that did not provide this contract. - if (case_dir / "system" / "sample").is_file(): - functions.append("sample") - patches = _patch_names(case_dir) - if artifact.family == "supersonicCrossJet": - # Patch names vary between the fixed reference (inlet1/inlet2) and - # agent cases (inlet/jet). Resolve only semantically named patches. - selected = sorted(name for name in patches if any(token in name.lower() for token in ("inlet", "jet"))) - functions.extend(f"patchFlowRate(phi,patch={name})" for name in selected) - elif artifact.family in {"ERCOFTA_pump", "nozzleCDV"}: - selected = sorted(name for name in patches if any(token in name.lower() for token in ("inlet", "outlet"))) - functions.extend(f"patchFlowRate(phi,patch={name})" for name in selected) - functions.extend(f"patchAverage(p,patch={name})" for name in selected) - with log_path.open("w", encoding="utf-8") as log: - for function_name in functions: - command = ["foamPostProcess", "-case", str(case_dir), "-func", function_name] - # Preparation is intentionally endpoint-only. A single retained - # endpoint cannot support a transient-history claim, so histories - # remain diagnostic unless the candidate already saved them. - command.append("-latestTime") - record = _run(command, log, 300) - record["required"] = function_name != "sample" - records.append(record) - if original_format == "binary": - set_ascii = [ - "foamDictionary", "-case", str(case_dir), "system/controlDict", - "-entry", "writeFormat", "-set", "ascii", - ] - restore = [ - "foamDictionary", "-case", str(case_dir), "system/controlDict", - "-entry", "writeFormat", "-set", "binary", - ] - record = _run(set_ascii, log, 60) - record["required"] = True - records.append(record) - try: - record = _run([ - "foamFormatConvert", "-case", str(case_dir), "-latestTime", - ], log, 300) - record["required"] = True - records.append(record) - finally: - record = _run(restore, log, 60) - record["required"] = True - records.append(record) - failed = [ - record for record in records - if record.get("required", True) and record.get("return_code") != 0 - ] - optional_failures = [ - record for record in records - if not record.get("required", True) and record.get("return_code") != 0 - ] - result = { - "case_id": artifact.case_id, - "case_dir": str(case_dir), - "status": "pass" if not failed else "fail", - "role": "measurement_only", - "original_write_format": original_format, - "log": str(log_path), - "commands": records, - "optional_failures": optional_failures, - } - write_json(case_output / "preparation.json", result) - return result - - -def prepare_cases(artifacts: list[CaseArtifact], output_root: Path, jobs: int) -> dict[str, Any]: - output_root.mkdir(parents=True, exist_ok=True) - records = [] - with ThreadPoolExecutor(max_workers=max(1, jobs)) as executor: - futures = {executor.submit(prepare_case, artifact, output_root): artifact for artifact in artifacts} - for future in as_completed(futures): - artifact = futures[future] - try: - records.append(future.result()) - except Exception as exc: - records.append({"case_id": artifact.case_id, "status": "error", "error": str(exc)}) - records.sort(key=lambda record: record["case_id"]) - report = { - "role": "measurement_only", - "case_count": len(records), - "pass_count": sum(record["status"] == "pass" for record in records), - "fail_count": sum(record["status"] != "pass" for record in records), - "cases": records, - } - write_json(output_root / "preparation_summary.json", report) - return report - - -def prepare_campaign( - profile: BenchmarkProfile, - *, - adapter_name: str, - run_root: Path, - output_root: Path, - jobs: int = 1, -) -> dict[str, Any]: - """Prepare derived field QoIs for execution-complete field campaigns.""" - if profile.extractor not in {"field", "extended"}: - raise ValueError("preparation is only applicable to field and Extended QoI profiles") - benchmark, references = load_assets(profile) - artifacts = create_adapter(adapter_name, run_root, profile).discover() - eligible = [] - for case_id, artifact in artifacts.items(): - reference = references.get(case_id) - if reference is None: - continue - execution = evaluate_execution( - artifact, expected_completion_time(benchmark[case_id], reference) - ) - if execution["status"] == "pass": - eligible.append(artifact) - return prepare_cases(eligible, output_root, jobs) diff --git a/benchmarks/evaluation/profiles.py b/benchmarks/evaluation/profiles.py deleted file mode 100644 index 2a5aa19e172fe32ab8191e1f6b549d5f3b0c65f7..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/profiles.py +++ /dev/null @@ -1,74 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from .io import read_object -from .models import BenchmarkProfile -from .schema import validate - - -def load_assets(profile: BenchmarkProfile) -> tuple[dict[str, Any], dict[str, Any]]: - benchmark = read_object(profile.benchmark_path) - reference_document = read_object(profile.reference_qois_path) - validate(reference_document, "foambench_qoi_reference.schema.json") - references = reference_document.get("cases") - if not isinstance(references, dict): - raise ValueError(f"reference QoI file has no cases object: {profile.reference_qois_path}") - if len(references) != profile.expected_case_count: - raise ValueError( - f"profile membership mismatch: expected {profile.expected_case_count}, got {len(references)}" - ) - current_design = ( - read_object(profile.benchmark_path.parent / "FoamBench_extended_openfoam13_qoi_design.json") - if profile.extractor == "extended" else None - ) - for case_id, reference in references.items(): - principal = reference.get("principal_metrics", []) - qois = reference.get("qois", {}) - tolerances = reference.get("tolerances", {}) - missing_values = sorted(set(principal) - set(qois)) - missing_tolerances = sorted(set(principal) - set(tolerances)) - if missing_values or missing_tolerances: - raise ValueError( - f"reference QoI contract incomplete for {case_id}: " - f"missing_values={missing_values}, missing_tolerances={missing_tolerances}" - ) - if profile.extractor == "extended": - from .extbench import design_case_contract - - expected_branch, expected_principal = design_case_contract(case_id, current_design or {}) - if reference.get("branch_id") != expected_branch: - raise ValueError( - f"ExtBench branch drift for {case_id}: " - f"reference={reference.get('branch_id')!r}, design={expected_branch!r}" - ) - if set(principal) != set(expected_principal): - raise ValueError( - f"ExtBench principal-metric drift for {case_id}: " - f"reference={sorted(principal)}, design={sorted(expected_principal)}" - ) - benchmark_cases = benchmark.get("cases") if isinstance(benchmark.get("cases"), dict) else benchmark - if not isinstance(benchmark_cases, dict): - raise ValueError(f"benchmark has no case mapping: {profile.benchmark_path}") - missing = sorted(set(references) - set(benchmark_cases)) - if missing: - raise ValueError("benchmark is missing reference cases: " + ", ".join(missing)) - return benchmark_cases, references - - -def expected_end_time(case: dict[str, Any]) -> float | None: - text = case.get("system/controlDict") - if not isinstance(text, str): - return None - import re - - match = re.search(r"(?m)^\s*endTime\s+([-+0-9.eE]+)\s*;", text) - return float(match.group(1)) if match else None - - -def expected_completion_time(case: dict[str, Any], reference: dict[str, Any]) -> float | None: - latest = reference.get("latest_time") - if isinstance(latest, (int, float)): - return float(latest) - return expected_end_time(case) diff --git a/benchmarks/evaluation/profiles/advanced.json b/benchmarks/evaluation/profiles/advanced.json deleted file mode 100644 index d1c0bf76660739dd16fd08bdd302489d3f8f6eb5..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/profiles/advanced.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "profile_id": "foambench.advanced.v1", - "dataset": "advanced", - "benchmark_path": "benchmarks/FoamBench_advanced_openfoam13_fixed_final.json", - "reference_qois_path": "benchmarks/FoamBench_advanced_openfoam13_reference_qois.json", - "membership": { - "expected_case_count": 16, - "case_id_style": "case_name" - }, - "qoi": { - "extractor": "field", - "required_fraction": 1.0 - }, - "numerical": { - "contract": "physics_grounded_qoi.v1", - "steady_qoi_plateau": true, - "reference_statistics_path": "benchmarks/reference_statistics/advanced.json" - } -} diff --git a/benchmarks/evaluation/profiles/basic.json b/benchmarks/evaluation/profiles/basic.json deleted file mode 100644 index 7e1915a057e14896decbf7cc87d81fbfe7915c04..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/profiles/basic.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "profile_id": "foambench.basic.v1", - "dataset": "basic", - "benchmark_path": "benchmarks/FoamBench_basic_openfoam13_fixed_final.json", - "reference_qois_path": "benchmarks/FoamBench_basic_openfoam13_reference_qois.json", - "membership": { - "expected_case_count": 110, - "case_id_style": "family_variant" - }, - "qoi": { - "extractor": "field", - "required_fraction": 1.0 - }, - "numerical": { - "contract": "physics_grounded_qoi.v1", - "steady_qoi_plateau": true, - "reference_statistics_path": "benchmarks/reference_statistics/basic.json" - } -} diff --git a/benchmarks/evaluation/profiles/extended.json b/benchmarks/evaluation/profiles/extended.json deleted file mode 100644 index 42957f6a72678559870890415fbb1585f4096951..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/profiles/extended.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "profile_id": "foambench.extended", - "dataset": "extended", - "benchmark_path": "benchmarks/FoamBench_extended_openfoam13_fixed.json", - "reference_qois_path": "benchmarks/FoamBench_extended_openfoam13_reference_qois.json", - "membership": { - "expected_case_count": 100, - "case_id_style": "family_variant" - }, - "qoi": { - "extractor": "extended", - "required_fraction": 1.0 - }, - "numerical": { - "contract": "foambench.qoi.design", - "tolerances": "joint_physical_admissibility_and_reference_response_provisional", - "reference_statistics_path": "benchmarks/reference_statistics/extended.json" - } -} diff --git a/benchmarks/evaluation/qoi.py b/benchmarks/evaluation/qoi.py deleted file mode 100644 index 0c3c0fa4562a3dd8d35bef9a9b6aabcb6e854a2b..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/qoi.py +++ /dev/null @@ -1,79 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from .comparison import compare_case -from .extbench import extract_contract_case - -from .field_candidate import extract_field_candidate -from .models import BenchmarkProfile, CaseArtifact -from .schema import validate - - -def empty_candidate(case_id: str, status: str, reason: str) -> dict[str, Any]: - return { - "schema_version": "foambench.qoi.candidate", - "case_id": case_id, - "status": status, - "qois": {}, - "health": {"status": "not_assessed", "reason": reason}, - } - - -def evaluate_qoi( - artifact: CaseArtifact, - profile: BenchmarkProfile, - reference: dict[str, Any], - *, - execution_pass: bool, -) -> dict[str, Any]: - if not execution_pass or artifact.case_dir is None: - return { - "status": "not_evaluated_execution_failure", - "physics_grounded_qoi_pass": False, - "effective_pass_ratio": 0.0, - "candidate": empty_candidate( - artifact.case_id, "not_evaluated_execution_failure", "execution_not_passed" - ), - "comparison": None, - } - try: - if profile.extractor == "extended": - candidate = extract_contract_case(artifact.case_dir, artifact.case_id) - required = candidate.get("required_metrics", []) - elif profile.extractor == "field": - required = reference.get("principal_metrics") - if not isinstance(required, list): - required = list(reference.get("qois", {})) - requested = list(reference.get("qois", {})) - candidate = extract_field_candidate( - artifact.case_dir, - artifact.case_id, - requested, - required_metrics=required, - log_paths=list(artifact.solver_logs), - ) - else: - raise ValueError(f"unknown QoI extractor: {profile.extractor}") - validate(candidate, "foambench_qoi_candidate.schema.json") - comparison = compare_case(reference, candidate, profile.required_qoi_fraction) - validate(comparison, "foambench_qoi_comparison.schema.json") - health = candidate.get("health") - health_pass = not isinstance(health, dict) or health.get("status") in {None, "pass"} - physics_grounded_qoi = bool(comparison.get("physics_grounded_qoi_pass") and health_pass) - return { - "status": "pass" if physics_grounded_qoi else str(comparison.get("status", "fail")), - "physics_grounded_qoi_pass": physics_grounded_qoi, - "effective_pass_ratio": float(comparison.get("qoi_pass_ratio", 0.0)) if health_pass else 0.0, - "candidate": candidate, - "comparison": comparison, - } - except Exception as exc: - return { - "status": "evaluation_error", - "physics_grounded_qoi_pass": False, - "effective_pass_ratio": 0.0, - "candidate": empty_candidate(artifact.case_id, "error", str(exc)), - "comparison": None, - "error": str(exc), - } diff --git a/benchmarks/evaluation/qoi_glue.py b/benchmarks/evaluation/qoi_glue.py deleted file mode 100644 index 0fafc4a6df8865e62a56221bdbf50e5fc031810d..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/qoi_glue.py +++ /dev/null @@ -1,493 +0,0 @@ -#!/usr/bin/env python3 -"""Conservative LLM-assisted recovery for incomplete Extended QoI evidence. - -The model is an evidence router only. It selects an existing file/column and -an allow-listed deterministic operation; this module computes the observation -and validates the source locally. Reference QoI values are never included in -the model packet. -""" -from __future__ import annotations - -import copy -import csv -import hashlib -import json -import math -import os -import re -import subprocess -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[2] -GLUE_VERSION = "foambench.qoi_glue.v1" -PLAN_SCHEMA = ROOT / "schemas/qoi_recovery_plan.schema.json" -TABLE_SUFFIXES = {".csv", ".dat", ".raw", ".xy"} -TIME_COLUMN = "Time" -MASS_COLUMNS = { - "rhophi", - "massflow", - "massflux", - "sumphi", - "areaintegratephi", -} -EXPECTED_BRANCHES = {"Re_tau_180", "Re_tau_395", "Re_tau_590"} - - -def _enabled() -> bool: - return os.environ.get("EVOLUTION_QOI_GLUE", "off").strip().lower() in { - "1", "true", "on", "yes", - } - - -def _model() -> str: - return ( - os.environ.get("evolution_QOI_GLUE_MODEL") - or os.environ.get("evolution_EVALUATION_MODEL") - or "gpt-5.6-terra" - ) - - -def _reasoning() -> str | None: - return ( - os.environ.get("evolution_QOI_GLUE_REASONING_EFFORT") - or os.environ.get("evolution_EVALUATION_REASONING_EFFORT") - or os.environ.get("evolution_REASONING_EFFORT") - ) - - -def _timeout() -> float: - raw = os.environ.get("EVOLUTION_QOI_GLUE_TIMEOUT", "180") - try: - return max(5.0, float(raw)) - except ValueError: - return 180.0 - - -def _normalise(value: str) -> str: - return re.sub(r"[^a-z0-9]", "", value.lower().replace("+", "plus")) - - -def _finite(value: Any) -> float | None: - if isinstance(value, bool) or not isinstance(value, (int, float)): - return None - result = float(value) - return result if math.isfinite(result) else None - - -def _safe_source(case_dir: Path, raw: Any) -> Path: - if not isinstance(raw, str) or not raw or Path(raw).is_absolute(): - raise ValueError("source must be a relative case path") - source = (case_dir / raw).resolve(strict=True) - if not source.is_relative_to(case_dir.resolve(strict=True)): - raise ValueError("source escapes the case directory") - if not source.is_file(): - raise ValueError("source is not a file") - return source - - -def _evidence_path(case_dir: Path, source: Path) -> str: - return source.relative_to(case_dir.resolve(strict=True)).as_posix() - - -def _field_dimensions(case_dir: Path, field: str) -> str | None: - for path in sorted(case_dir.rglob(field), reverse=True): - if not path.is_file() or not path.parent.name.replace(".", "", 1).isdigit(): - continue - text = path.read_bytes()[:4096].decode("ascii", errors="ignore") - match = re.search(r"dimensions\s*\[([^]]+)\]", text) - if match: - return " ".join(match.group(1).split()) - return None - - -def _named_numeric_rows(path: Path) -> tuple[list[str], list[list[float]]]: - """Read a compatible numeric table without accepting arbitrary prose.""" - headers: list[list[str]] = [] - rows: list[list[float]] = [] - for line in path.read_text(encoding="utf-8", errors="ignore").splitlines(): - stripped = line.strip() - if not stripped: - continue - if stripped.startswith("#"): - names = stripped[1:].strip().replace(",", " ").replace("\t", " ").split() - if names: - headers.append(names) - continue - parts = stripped.replace("(", " ").replace(")", " ").replace(",", " ").split() - if parts and all(re.fullmatch(r"[-+0-9.eE]+", item) for item in parts): - rows.append([float(item) for item in parts]) - elif not rows and ("," in stripped or "\t" in stripped): - names = [item.strip() for item in stripped.split(",")] if "," in stripped else stripped.split("\t") - if names: - headers.append(names) - if not rows: - return [], [] - width = len(rows[0]) - header = next((names for names in reversed(headers) if len(names) == width), []) - return header, [row for row in rows if len(row) == width] - - -def _case_fingerprint(case_dir: Path) -> str: - digest = hashlib.sha256() - for path in sorted(item for item in case_dir.rglob("*") if item.is_file()): - relative = path.relative_to(case_dir).as_posix().encode("utf-8") - digest.update(len(relative).to_bytes(8, "big")) - digest.update(relative) - digest.update(path.stat().st_size.to_bytes(8, "big")) - with path.open("rb") as stream: - for block in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(block) - return digest.hexdigest() - - -def _inventory(case_dir: Path) -> list[dict[str, Any]]: - entries: list[dict[str, Any]] = [] - candidates = [item for item in case_dir.rglob("*") if item.is_file()] - candidates.sort(key=lambda item: (item.suffix.lower() not in TABLE_SUFFIXES, str(item))) - for path in candidates[:180]: - relative = path.relative_to(case_dir).as_posix() - item: dict[str, Any] = {"path": relative, "bytes": path.stat().st_size} - if path.suffix.lower() in TABLE_SUFFIXES and path.stat().st_size <= 512 * 1024: - sample = path.read_text(encoding="utf-8", errors="ignore")[:1600] - item["sample"] = sample - elif path.name in {"phi", "C", "U", "Vc", "p", "alpha.water"}: - sample = path.read_bytes()[:4096].decode("ascii", errors="ignore") - match = re.search(r"dimensions\s*\[([^]]+)\]", sample) - if match: - item["dimensions"] = " ".join(match.group(1).split()) - entries.append(item) - return entries - - -def build_packet( - case_dir: Path, - case_id: str, - candidate: dict[str, Any], - comparison: dict[str, Any], -) -> dict[str, Any]: - """Create the small, reference-free packet supplied to the model.""" - return { - "schema_version": GLUE_VERSION, - "case_id": case_id, - "family": case_id.split("/", 1)[0] if "/" in case_id else case_id, - "required_metrics": list(candidate.get("required_metrics", [])), - "missing_metrics": list(candidate.get("missing_metrics", [])), - "extraction_errors": list(candidate.get("extraction_errors", [])), - "comparison_status": comparison.get("status"), - "allowed_operations": { - "table_time_history": "Read an explicit Time plus one flux column; preserve signed values and phi dimensions.", - "branch_spalding_table": "Split one labelled table by branch and compute branch wall-law scalars only when yPlus and spaldingYPlus columns exist.", - }, - "files": _inventory(case_dir), - } - - -def _prompt(packet: dict[str, Any]) -> str: - return ( - "You are a conservative CFD measurement-evidence router.\n" - "Reference QoI values are unavailable and must not be requested or inferred.\n" - "Do not calculate or emit QoI numbers. Return only JSON matching the supplied schema.\n" - "Select an existing file and columns only when they are physically equivalent to a declared principal metric.\n" - "Use status=unrecoverable when evidence is absent, ambiguous, a proxy, or has the wrong physical quantity.\n" - "Allowed operations are exactly table_time_history and branch_spalding_table.\n\n" - "Evidence packet:\n" + json.dumps(packet, ensure_ascii=False, indent=2) - ) - - -def _cache_path(campaign_root: Path, case_dir: Path, case_id: str, missing: list[str], model: str) -> Path: - identity = { - "version": GLUE_VERSION, - "case_id": case_id, - "missing": sorted(missing), - "model": model, - "fingerprint": _case_fingerprint(case_dir), - } - key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode("utf-8")).hexdigest() - return campaign_root / "cache" / "qoi_glue" / f"{key}.json" - - -def _write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - temporary.replace(path) - - -def _load_cached(path: Path) -> dict[str, Any] | None: - if not path.is_file(): - return None - try: - value = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return None - return value if isinstance(value, dict) else None - - -def _run_model( - case_dir: Path, - packet: dict[str, Any], - artifact: Path, -) -> dict[str, Any]: - from scripts.evolution_adapter_common import codex_exec_command - - model = _model() - artifact.parent.mkdir(parents=True, exist_ok=True) - final_message = artifact.with_suffix(".last_message.json") - trajectory = artifact.with_suffix(".trajectory.jsonl") - command = codex_exec_command( - case_dir, - final_message, - model, - output_schema=PLAN_SCHEMA if PLAN_SCHEMA.is_file() else None, - reasoning_effort=_reasoning(), - sandbox="read-only", - ) - try: - completed = subprocess.run( - command, - input=_prompt(packet), - text=True, - encoding="utf-8", - errors="replace", - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - cwd=case_dir, - timeout=_timeout(), - check=False, - ) - except (OSError, subprocess.TimeoutExpired) as exc: - return { - "status": "unavailable", - "model": model, - "error": str(exc), - "command": command, - } - trajectory.write_text(completed.stdout, encoding="utf-8") - if completed.returncode != 0: - return { - "status": "unavailable", - "model": model, - "return_code": completed.returncode, - "stderr_tail": completed.stderr[-2000:], - "command": command, - } - try: - plan = json.loads(final_message.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: - return { - "status": "invalid_response", - "model": model, - "error": str(exc), - "stderr_tail": completed.stderr[-2000:], - } - if not isinstance(plan, dict): - return {"status": "invalid_response", "model": model, "error": "plan is not an object"} - return { - "status": "received", - "model": model, - "return_code": completed.returncode, - "plan": plan, - "stderr_tail": completed.stderr[-2000:], - } - - -def _validate_mapping(mapping: dict[str, Any], required: set[str]) -> None: - metric = mapping.get("metric") - if not isinstance(metric, str) or metric not in required: - raise ValueError("mapping metric is not a missing principal metric") - operation = mapping.get("operation") - if operation not in {"table_time_history", "branch_spalding_table"}: - raise ValueError("operation is not allow-listed") - if operation == "table_time_history": - column = mapping.get("column") - if not isinstance(column, str) or not column: - raise ValueError("table_time_history requires a column") - if operation == "branch_spalding_table": - if metric != "branchwise_wall_law_metrics": - raise ValueError("branch_spalding_table has one supported metric") - if mapping.get("branch_column") != "branch": - raise ValueError("branch_spalding_table requires a branch column") - - -def _execute_time_history(case_dir: Path, mapping: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: - source = _safe_source(case_dir, mapping.get("source")) - header, rows = _named_numeric_rows(source) - if TIME_COLUMN not in header: - raise ValueError("table has no Time column") - column = str(mapping["column"]) - if column not in header or _normalise(column) not in MASS_COLUMNS: - raise ValueError("column is not an allow-listed explicit flux column") - if "inlet" not in str(source).lower() and str(mapping.get("patch", "")).lower() not in {"inlet", "inlet1", "main"}: - raise ValueError("mass-flow source is not identified as an inlet") - dimensions = _field_dimensions(case_dir, "phi") - quantity = { - "1 0 -1 0 0 0 0": "explicit_mass_flow", - "0 3 -1 0 0 0 0": "explicit_volumetric_flow", - }.get(dimensions) - if quantity is None: - raise ValueError("phi dimensions are absent or unsupported") - time_index, value_index = header.index(TIME_COLUMN), header.index(column) - points = [ - {"time": row[time_index], "value": row[value_index]} - for row in rows - if math.isfinite(row[time_index]) and math.isfinite(row[value_index]) - ] - if not points: - raise ValueError("table has no finite history points") - branch = "root" - parent = source.relative_to(case_dir).parts - if "postProcessing" in parent: - branch = "/".join(parent[: parent.index("postProcessing")]) or "root" - history: dict[str, Any] = { - "kind": "time_history", - "quantity": quantity, - "field_dimensions": dimensions, - "points": sorted(points, key=lambda item: item["time"]), - } - if branch != "root": - history = { - "kind": "branched_time_histories", - "quantity": quantity, - "field_dimensions": dimensions, - "branches": {branch: history}, - } - return history, [_evidence_path(case_dir, source)] - - -def _csv_rows(path: Path) -> tuple[list[str], list[dict[str, str]]]: - with path.open(newline="", encoding="utf-8", errors="ignore") as stream: - reader = csv.DictReader(stream) - rows = [dict(row) for row in reader if row] - return list(reader.fieldnames or []), rows - - -def _execute_branch_spalding(case_dir: Path, mapping: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: - source = _safe_source(case_dir, mapping.get("source")) - columns, rows = _csv_rows(source) - normalised = {_normalise(column): column for column in columns} - branch_name = normalised.get("branch") - y_name = normalised.get("yplus") - predicted_name = normalised.get("spaldingyplus") - if not branch_name or not y_name or not predicted_name: - raise ValueError("branch table requires branch, yPlus, and spaldingYPlus columns") - branches: dict[str, Any] = {} - for branch in EXPECTED_BRANCHES: - selected = [row for row in rows if row.get(branch_name) == branch] - if not selected: - raise ValueError(f"branch table is missing {branch}") - errors: list[float] = [] - y_values: list[float] = [] - for row in selected: - yplus = _finite(float(row[y_name])) if row.get(y_name) else None - predicted = _finite(float(row[predicted_name])) if row.get(predicted_name) else None - if yplus is None or predicted is None or yplus < 0 or predicted < 0: - continue - y_values.append(yplus) - errors.append(math.log1p(yplus) - math.log1p(predicted)) - if not errors or not y_values: - raise ValueError(f"branch {branch} has no finite wall-law rows") - branches[branch] = { - "first_cell_yplus": min(y_values), - "spalding_log_rmse": math.sqrt(sum(item * item for item in errors) / len(errors)), - } - return {"kind": "branch_scalars", "branches": branches}, [_evidence_path(case_dir, source)] - - -def apply_plan( - case_dir: Path, - candidate: dict[str, Any], - plan: dict[str, Any], -) -> tuple[dict[str, Any], dict[str, Any]]: - """Apply a validated plan; any ambiguity leaves the candidate unchanged.""" - if plan.get("status") != "recoverable": - return copy.deepcopy(candidate), {"status": str(plan.get("status", "unrecoverable")), "reason": plan.get("reason")} - mappings = plan.get("mappings") - required = set(candidate.get("missing_metrics", [])) - if not isinstance(mappings, list) or not mappings: - return copy.deepcopy(candidate), {"status": "invalid_plan", "reason": "recoverable plan has no mappings"} - result = copy.deepcopy(candidate) - selected: dict[str, Any] = {} - try: - for mapping in mappings: - if not isinstance(mapping, dict): - raise ValueError("mapping is not an object") - _validate_mapping(mapping, required) - metric = str(mapping["metric"]) - if metric in selected: - raise ValueError(f"duplicate mapping for {metric}") - if mapping["operation"] == "table_time_history": - value, evidence = _execute_time_history(case_dir, mapping) - method = "qoi_glue.table_time_history.v1" - else: - value, evidence = _execute_branch_spalding(case_dir, mapping) - method = "qoi_glue.branch_spalding_table.v1" - selected[metric] = {"value": value, "evidence": evidence, "method": method} - except (OSError, ValueError, TypeError, KeyError) as exc: - return copy.deepcopy(candidate), {"status": "rejected", "reason": str(exc), "plan": plan} - qois = result.setdefault("qois", {}) - evidence = result.setdefault("evidence", {}) - methods = result.setdefault("metric_methods", {}) - resolver = result.setdefault("resolver_report", {}) - for metric, item in selected.items(): - qois[metric] = item["value"] - evidence[metric] = item["evidence"] - methods[metric] = item["method"] - resolver[metric] = { - "status": "selected", - "selected_evidence": item["evidence"], - "method": item["method"], - "physical_validation": "qoi_glue.allowlisted_operation.v1", - } - required_metrics = list(result.get("required_metrics", [])) - missing = sorted(set(required_metrics) - set(qois)) - result["missing_metrics"] = missing - extraction_errors = list(result.get("extraction_errors", [])) - result["status"] = "complete" if not missing and not extraction_errors else "incomplete" - health = result.setdefault("health", {}) - health["status"] = "pass" if not missing and not extraction_errors else "incomplete" - checks = health.setdefault("checks", {}) - checks["principal_qoi_complete"] = not missing - checks["principal_extraction_error_free"] = not extraction_errors - return result, { - "status": "recovered_complete" if not missing and not extraction_errors else "recovered_partial", - "metrics": sorted(selected), - "evidence": {metric: item["evidence"] for metric, item in selected.items()}, - "methods": {metric: item["method"] for metric, item in selected.items()}, - "plan": plan, - } - - -def recover_with_llm( - case_dir: Path, - case_id: str, - candidate: dict[str, Any], - comparison: dict[str, Any], - campaign_root: Path, -) -> tuple[dict[str, Any], dict[str, Any]]: - """Recover one incomplete candidate, with one cached model call at most.""" - if not _enabled(): - return copy.deepcopy(candidate), {"status": "disabled", "version": GLUE_VERSION} - missing = list(candidate.get("missing_metrics", [])) - if not missing: - return copy.deepcopy(candidate), {"status": "not_needed", "version": GLUE_VERSION} - model = _model() - artifact = _cache_path(campaign_root, case_dir, case_id, missing, model) - cached = _load_cached(artifact) - if cached is None: - packet = build_packet(case_dir, case_id, candidate, comparison) - cached = _run_model(case_dir, packet, artifact) - cached["version"] = GLUE_VERSION - cached["case_id"] = case_id - cached["missing_metrics"] = sorted(missing) - _write_json(artifact, cached) - plan = cached.get("plan") if isinstance(cached.get("plan"), dict) else {"status": cached.get("status", "unavailable")} - recovered, detail = apply_plan(case_dir, candidate, plan) - detail.update({ - "version": GLUE_VERSION, - "artifact": str(artifact), - "model": cached.get("model", model), - "execution_status": cached.get("status"), - }) - return recovered, detail diff --git a/benchmarks/evaluation/qoi_reference.py b/benchmarks/evaluation/qoi_reference.py deleted file mode 100644 index 15f0f704343cc5dcba71bc8cf6d74a0930dad32e..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/qoi_reference.py +++ /dev/null @@ -1,566 +0,0 @@ -#!/usr/bin/env python3 -"""Build canonical FoamBench QoI reference datasets from completed runs. - -The extractor uses family-level principal result groups, volume-weighted -generic diagnostics, and geometry-aware normalized probes. It never edits the -benchmark source JSON. -""" -from __future__ import annotations - -import argparse -import json -import math -import os -import re -import subprocess -import sys -from concurrent.futures import ThreadPoolExecutor, as_completed -from datetime import datetime, timezone -from pathlib import Path -from typing import Any, Callable - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.foam_io import field_path -from benchmarks.evaluation.schema import validate - -try: - from benchmarks.evaluation.field_extractor import ( - ExtractionError, FATAL_RE, extract_case_qois, latest_time_dir, magnitude, - parse_log_metrics, parse_scalar_field, parse_vector_field, read_text, - ) -except ImportError: # Direct script execution keeps the historical CLI working. - from field_extractor import ( - ExtractionError, FATAL_RE, extract_case_qois, latest_time_dir, magnitude, - parse_log_metrics, parse_scalar_field, parse_vector_field, read_text, - ) - - -SCHEMA_VERSION = "foambench.reference_qois.v2" -TOLERANCE_POLICY = "principal_relative_15pct_abs_floor_1e-8.v1" -COMMON_SCALAR_FIELDS = ( - "p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", - "nuTilda", "Qdot", "CH4", "O2", "CO2", "H2O", "N2", - "alpha.water", "h", "hTotal", -) -POSITIVE_FIELDS = {"T", "rho", "k", "epsilon", "omega", "nuTilda", "h", "hTotal"} -ADVANCED_TEMPLATE = { - "Cavity_LES": "Cavity", - "Cavity_SA": "Cavity", - "Cavity_geometry_1": "Cavity", - "Cylinder_LES": "Cylinder", - "Cylinder_SA": "Cylinder", - "Diamond_Obstacle_KOMEGASST": "Obstacle", - "Diamond_Obstacle_SA": "Obstacle", - "Double_Square_SA": "Obstacle", - "Rectangular_Obstacle_KOMEGASST": "Obstacle", - "Rectangular_Obstacle_SA": "Obstacle", - "counterFlowFlame2D_KE": "counterFlowFlame2D", - "counterFlowFlame2D_SA": "counterFlowFlame2D", - "nozzleFlow2D_SA": "Nozzle", - "obliqueShock_KE": "Shock", - "obliqueShock_LES": "Shock", - "wedge_SA": "Shock", -} - - -def utc_now() -> str: - return datetime.now(timezone.utc).isoformat() - - -def write_json(path: Path, value: Any) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") - temporary.replace(path) - - -def scalar_field(time_dir: Path, name: str) -> list[float]: - path = field_path(time_dir, name) - return parse_scalar_field(path) if path else [] - - -def vector_field(time_dir: Path, name: str) -> list[tuple[float, float, float]]: - path = field_path(time_dir, name) - return parse_vector_field(path) if path else [] - - -def align(values: list[Any], count: int) -> list[Any]: - if len(values) == count: - return values - if len(values) == 1 and count: - return values * count - return [] - - -def weighted_mean(values: list[float], weights: list[float]) -> float | None: - if not values or len(values) != len(weights): - return None - denominator = sum(weights) - return sum(value * weight for value, weight in zip(values, weights)) / denominator if denominator else None - - -def weighted_stats(values: list[float], weights: list[float]) -> dict[str, float]: - pairs = [(value, weight) for value, weight in zip(values, weights) if math.isfinite(value) and math.isfinite(weight)] - if not pairs: - return {} - clean_values = [value for value, _ in pairs] - clean_weights = [weight for _, weight in pairs] - mean = weighted_mean(clean_values, clean_weights) - return { - "min": min(clean_values), - "max": max(clean_values), - "volume_mean": float(mean), - } if mean is not None else {} - - -def bounds(centres: list[tuple[float, float, float]]) -> tuple[tuple[float, float, float], tuple[float, float, float]]: - return ( - tuple(min(point[axis] for point in centres) for axis in range(3)), - tuple(max(point[axis] for point in centres) for axis in range(3)), - ) - - -def normalized_point(centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> tuple[float, float, float]: - low, high = bounds(centres) - return tuple(low[axis] + fraction[axis] * (high[axis] - low[axis]) for axis in range(3)) - - -def nearest_index(centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> int: - target = normalized_point(centres, fraction) - low, high = bounds(centres) - scale = [max(high[axis] - low[axis], 1e-12) for axis in range(3)] - return min( - range(len(centres)), - key=lambda index: sum(((centres[index][axis] - target[axis]) / scale[axis]) ** 2 for axis in range(3)), - ) - - -def scalar_probe(values: list[float], centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> float | None: - return values[nearest_index(centres, fraction)] if len(values) == len(centres) else None - - -def speed_probe(velocities: list[tuple[float, float, float]], centres: list[tuple[float, float, float]], fraction: tuple[float, float, float]) -> float | None: - if len(velocities) != len(centres): - return None - x, y, z = velocities[nearest_index(centres, fraction)] - return math.sqrt(x * x + y * y + z * z) - - -def probe_drop(values: list[float], centres: list[tuple[float, float, float]]) -> float | None: - upstream = scalar_probe(values, centres, (0.2, 0.5, 0.5)) - downstream = scalar_probe(values, centres, (0.8, 0.5, 0.5)) - return upstream - downstream if upstream is not None and downstream is not None else None - - -def pressure_ratio(pressures: list[float]) -> float | None: - positive = [value for value in pressures if math.isfinite(value) and value > 1e-12] - return max(positive) / min(positive) if positive else None - - -def thermo_parameters(case_dir: Path) -> tuple[float, float]: - text = read_text(case_dir / "constant" / "physicalProperties") - mol_weight_match = re.search(r"(?m)^\s*molWeight\s+([-+0-9.eE]+)\s*;", text) - cp_match = re.search(r"(?m)^\s*Cp\s+([-+0-9.eE]+)\s*;", text) - if not mol_weight_match or not cp_match: - return 1.4, 0.7143 - mol_weight = float(mol_weight_match.group(1)) - cp = float(cp_match.group(1)) - gas_constant = 8314.46261815324 / mol_weight if mol_weight > 0 else 0.0 - gamma = cp / (cp - gas_constant) if cp > gas_constant else 1.4 - return gamma, gas_constant if gas_constant > 0 else 0.7143 - - -def mach_values( - velocities: list[tuple[float, float, float]], - temperatures: list[float], - gamma: float, - gas_constant: float, -) -> list[float]: - if len(temperatures) == 1 and velocities: - temperatures = temperatures * len(velocities) - if len(velocities) != len(temperatures): - return [] - return [ - speed / math.sqrt(gamma * gas_constant * temperature) - for speed, temperature in zip(magnitude(velocities), temperatures) - if temperature > 0 and math.isfinite(temperature) - ] - - -def shock_location(pressures: list[float], centres: list[tuple[float, float, float]]) -> float | None: - if len(pressures) != len(centres) or len(pressures) < 2: - return None - low, high = bounds(centres) - y_span = max(high[1] - low[1], 1e-12) - z_span = max(high[2] - low[2], 1e-12) - y_mid = 0.5 * (low[1] + high[1]) - z_mid = 0.5 * (low[2] + high[2]) - selected = [ - (point[0], value) - for point, value in zip(centres, pressures) - if abs(point[1] - y_mid) <= 0.08 * y_span and abs(point[2] - z_mid) <= 0.51 * z_span - ] - selected.sort() - if len(selected) < 2: - return None - best_x, best_gradient = None, -1.0 - for (x0, p0), (x1, p1) in zip(selected, selected[1:]): - dx = x1 - x0 - if dx <= 1e-12: - continue - gradient = abs(p1 - p0) / dx - if gradient > best_gradient: - best_x, best_gradient = 0.5 * (x0 + x1), gradient - return best_x - - -def phase_front(alpha: list[float], centres: list[tuple[float, float, float]]) -> float | None: - wet = [point[0] for value, point in zip(alpha, centres) if value >= 0.5] - return max(wet) if wet else None - - -def add_metric(target: dict[str, float], name: str, value: float | None) -> None: - if value is not None and math.isfinite(value): - target[name] = float(value) - - -def family_metrics( - case_dir: Path, - template: str, - scalars: dict[str, list[float]], - velocities: list[tuple[float, float, float]], - vorticity: list[tuple[float, float, float]], - centres: list[tuple[float, float, float]], - volumes: list[float], -) -> tuple[str, dict[str, float]]: - metrics: dict[str, float] = {} - speed = magnitude(velocities) - vort_mag = magnitude(vorticity) - pressures = scalars.get("p", []) - temperatures = scalars.get("T", []) - gamma, gas_constant = thermo_parameters(case_dir) - mach = mach_values(velocities, temperatures, gamma, gas_constant) - - if template == "BernardCells": - group = "thermal_state" - stats = weighted_stats(temperatures, volumes) - add_metric(metrics, "T_volume_mean", stats.get("volume_mean")) - add_metric(metrics, "T_max", stats.get("max")) - elif template == "Cavity": - group = "cavity_response" - add_metric(metrics, "U_center_probe", speed_probe(velocities, centres, (0.5, 0.5, 0.5))) - add_metric(metrics, "vorticity_volume_mean", weighted_mean(vort_mag, volumes)) - elif template == "Cylinder": - group = "wake_response" - add_metric(metrics, "U_wake_probe", speed_probe(velocities, centres, (0.75, 0.5, 0.5))) - add_metric(metrics, "vorticity_volume_mean", weighted_mean(vort_mag, volumes)) - elif template == "counterFlowFlame2D": - group = "flame_response" - add_metric(metrics, "T_max", max(temperatures) if temperatures else None) - add_metric(metrics, "CO2_volume_mean", weighted_mean(scalars.get("CO2", []), volumes)) - elif template == "damBreakWithObstacle": - group = "free_surface_response" - alpha = scalars.get("alpha.water", []) - add_metric(metrics, "front_position", phase_front(alpha, centres)) - add_metric(metrics, "water_volume", sum(value * volume for value, volume in zip(alpha, volumes))) - elif template == "forwardStep": - group = "shock_response" - add_metric(metrics, "shock_location", shock_location(pressures, centres)) - add_metric(metrics, "pressure_ratio", pressure_ratio(pressures)) - elif template in {"obliqueShock", "wedge", "Shock"}: - group = "shock_response" - add_metric(metrics, "pressure_ratio", pressure_ratio(pressures)) - add_metric(metrics, "Mach_volume_mean", weighted_mean(mach, volumes)) - elif template == "pitzDaily": - group = "separation_response" - add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres)) - add_metric(metrics, "U_downstream_probe", speed_probe(velocities, centres, (0.8, 0.5, 0.5))) - elif template == "shallowWaterWithSquareBump": - group = "surface_response" - heights = scalars.get("h", []) - fluxes = scalars.get("_hU_magnitude", []) - froude = [flux / abs(height) / math.sqrt(9.81 * height) if height > 0 else 0.0 for flux, height in zip(fluxes, heights)] - add_metric(metrics, "h_volume_mean", weighted_mean(heights, volumes)) - add_metric(metrics, "Froude_volume_mean", weighted_mean(froude, volumes)) - elif template == "squareBend": - group = "bend_response" - add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres)) - add_metric(metrics, "Mach_volume_mean", weighted_mean(mach, volumes)) - elif template == "Obstacle": - group = "obstacle_response" - add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres)) - add_metric(metrics, "U_wake_probe", speed_probe(velocities, centres, (0.8, 0.5, 0.5))) - elif template == "Nozzle": - group = "nozzle_response" - add_metric(metrics, "pressure_probe_drop", probe_drop(pressures, centres)) - add_metric(metrics, "U_outlet_probe", speed_probe(velocities, centres, (0.9, 0.5, 0.5))) - else: - raise ValueError(f"no QoI family template for {template}") - return group, metrics - - -def tolerance(value: float) -> dict[str, float]: - margin = max(abs(value) * 0.15, 1e-8) - return { - "reference_value": value, - "low": value - margin, - "high": value + margin, - "relative_tolerance": 0.15, - "absolute_floor": 1e-8, - } - - -def prepare_case(case_dir: Path) -> dict[str, Any]: - commands = ( - ("writeCellCentres",), - ("writeCellVolumes",), - ("vorticity",), - ) - records = [] - log_path = case_dir / "qoi_postprocess.log" - with log_path.open("w", encoding="utf-8") as log: - for function_name, in commands: - completed = subprocess.run( - ["foamPostProcess", "-case", str(case_dir), "-func", function_name, "-latestTime"], - stdout=log, - stderr=subprocess.STDOUT, - check=False, - text=True, - timeout=300, - ) - records.append({"function": function_name, "return_code": completed.returncode}) - control_path = case_dir / "system" / "controlDict" - control = read_text(control_path) - if re.search(r"(?m)^\s*writeFormat\s+binary\s*;", control): - set_ascii = subprocess.run( - ["foamDictionary", "-case", str(case_dir), "system/controlDict", "-entry", "writeFormat", "-set", "ascii"], - stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=60, - ) - converted = subprocess.run( - ["foamFormatConvert", "-case", str(case_dir), "-latestTime"], - stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=300, - ) - restored = subprocess.run( - ["foamDictionary", "-case", str(case_dir), "system/controlDict", "-entry", "writeFormat", "-set", "binary"], - stdout=log, stderr=subprocess.STDOUT, check=False, text=True, timeout=60, - ) - records.append({ - "function": "convertLatestTimeToAscii", - "return_code": converted.returncode, - "set_ascii_return_code": set_ascii.returncode, - "restore_binary_return_code": restored.returncode, - }) - return {"case_dir": str(case_dir), "commands": records} - - -def prepare_all(case_dirs: list[Path], jobs: int) -> list[dict[str, Any]]: - records = [] - with ThreadPoolExecutor(max_workers=jobs) as executor: - futures = {executor.submit(prepare_case, case_dir): case_dir for case_dir in case_dirs} - for future in as_completed(futures): - case_dir = futures[future] - try: - records.append(future.result()) - except Exception as exc: # keep the other reference cases extractable - records.append({"case_dir": str(case_dir), "error": str(exc)}) - return sorted(records, key=lambda record: record["case_dir"]) - - -def case_id_from_dir(track: str, case_dir: Path) -> str: - safe = case_dir.parent.name - return safe.replace("__", "/", 1) if track == "basic" else safe - - -def extract_case(track: str, case_dir: Path, execution: dict[tuple[str, str], dict[str, str]]) -> tuple[str, dict[str, Any]]: - case_id = case_id_from_dir(track, case_dir) - template = case_id.split("/", 1)[0] if track == "basic" else ADVANCED_TEMPLATE[case_id] - latest_time, latest = latest_time_dir(case_dir) - if latest is None: - raise ValueError(f"no numeric time directory: {case_dir}") - centres = vector_field(latest, "C") - volumes = scalar_field(latest, "Vc") - if not centres or not volumes: - raise ValueError(f"missing C/Vc post-processing fields: {case_dir}") - volumes = align(volumes, len(centres)) - if not volumes: - raise ValueError(f"C/Vc field length mismatch: {case_dir}") - - scalars: dict[str, list[float]] = {} - raw_nonfinite_fields: list[str] = [] - for name in COMMON_SCALAR_FIELDS: - path = field_path(latest, name) - if not path: - continue - raw = read_text(path) - if re.search(r"(?i)(? 1 + 1e-3: - positivity_failures.append("alpha.water_bounds") - full_log = read_text(case_dir / "full_run.log") - execution_record = execution.get((track, case_dir.parent.name), {}) - health_checks = { - "execution_exit_zero": execution_record.get("exit_code") == "0", - "no_fatal_marker": not fatal_logs and FATAL_RE.search(full_log) is None, - "required_geometry_fields_available": bool(centres and volumes), - "principal_qoi_complete": len(principal) == 2, - "all_parsed_fields_finite": not raw_nonfinite_fields, - "applicable_field_bounds_valid": not positivity_failures, - } - health_pass = all(health_checks.values()) - qois = {**principal, **diagnostics} - roles = {name: "principal" for name in principal} - roles.update({name: "diagnostic" for name in diagnostics}) - return case_id, { - "track": track, - "family": case_id.split("/", 1)[0] if track == "basic" else template, - "source_case_id": case_id, - "latest_time": latest_time, - "principal_qoi_group": principal_group, - "principal_metrics": sorted(principal), - "qois": dict(sorted(qois.items())), - "metric_roles": dict(sorted(roles.items())), - "tolerances": {name: tolerance(value) for name, value in sorted(principal.items())}, - "field_diagnostics": field_bounds, - "health": { - "status": "pass" if health_pass else "fail", - "checks": health_checks, - "nonfinite_fields": raw_nonfinite_fields, - "field_bound_failures": sorted(positivity_failures), - "fatal_logs": fatal_logs, - }, - "extraction": { - "geometry": "cellCentres-normalized probes", - "averaging": "cell-volume-weighted", - "reference_run": "anonymous-reference/basic_advanced", - }, - } - - -def load_execution_summary(path: Path) -> dict[tuple[str, str], dict[str, str]]: - lines = path.read_text(encoding="utf-8").splitlines() - header = lines[0].split("\t") - records = {} - for line in lines[1:]: - values = line.split("\t") - record = dict(zip(header, values)) - records[(record["track"], record["case_id"])] = record - return records - - -def dataset(cases: dict[str, Any], tracks: list[str], run_manifest: dict[str, Any]) -> dict[str, Any]: - selected = {case_id: record for case_id, record in cases.items() if record["track"] in tracks} - family_counts: dict[str, int] = {} - health_pass_count = 0 - for record in selected.values(): - family_counts[record["family"]] = family_counts.get(record["family"], 0) + 1 - health_pass_count += record["health"]["status"] == "pass" - result = { - "schema_version": SCHEMA_VERSION, - "generated_at": utc_now(), - "openfoam_version": "Foundation v13", - "producer": "benchmarks/evaluation/qoi_reference.py", - "design": "guide/foambench_basic_advanced_qoi_design.md", - "tolerance_policy": TOLERANCE_POLICY, - "source_run_manifest": run_manifest, - "summary": { - "tracks": tracks, - "case_count": len(selected), - "health_pass_count": health_pass_count, - "health_fail_count": len(selected) - health_pass_count, - "family_counts": dict(sorted(family_counts.items())), - }, - "notes": [ - "Reference values come from the completed fixed-final OpenFOAM Foundation v13 run.", - "Principal QoIs are family-defined; reference values and tolerances are case-specific.", - "Generic field and solver statistics are diagnostics and do not receive principal-QoI weight.", - "The 15% intervals are initial benchmark-consistency tolerances and should be refined with repeatability evidence.", - ], - "cases": dict(sorted(selected.items())), - } - validate(result, "foambench_qoi_reference.schema.json") - return result - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--run-root", type=Path, required=True) - parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--basic-output", type=Path) - parser.add_argument("--advanced-output", type=Path) - parser.add_argument("--prepare-fields", action="store_true") - parser.add_argument("--jobs", type=int, default=min(16, os.cpu_count() or 1)) - args = parser.parse_args() - - run_root = args.run_root.resolve(strict=True) - materialized = run_root / "materialized" - case_dirs = [ - path for track in ("basic", "advanced") - for path in sorted((materialized / track).glob("*/case")) - ] - if len(case_dirs) != 126: - raise ValueError(f"expected 126 materialized cases, found {len(case_dirs)}") - if args.prepare_fields: - preparation = prepare_all(case_dirs, max(1, args.jobs)) - write_json(run_root / "qoi_postprocess_summary.json", preparation) - - from benchmarks.evaluation.basic_advanced import build_references - - basic, advanced = build_references(run_root) - combined = { - **{key: value for key, value in basic.items() if key not in {"cases", "summary"}}, - "summary": { - "tracks": ["basic", "advanced"], - "case_count": len(basic["cases"]) + len(advanced["cases"]), - "health_pass_count": len(basic["cases"]) + len(advanced["cases"]), - "health_fail_count": 0, - }, - "cases": {**basic["cases"], **advanced["cases"]}, - } - validate(combined, "foambench_qoi_reference.schema.json") - write_json(args.output, combined) - if args.basic_output: - write_json(args.basic_output, basic) - if args.advanced_output: - write_json(args.advanced_output, advanced) - print(json.dumps(combined["summary"], ensure_ascii=False, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/evaluation/reference.py b/benchmarks/evaluation/reference.py deleted file mode 100644 index f1dd60f69e469c79a619006f4b6df969f61b8441..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/reference.py +++ /dev/null @@ -1,44 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -from .models import BenchmarkProfile - - -def reference_case_dir(profile: BenchmarkProfile, case_id: str) -> Path | None: - root = profile.reference_run_root - if root is None or not root.is_dir(): - return None - safe = case_id.replace("/", "__") - if profile.dataset in {"basic", "advanced"}: - candidate = root / profile.dataset / safe / "case" - return candidate if candidate.is_dir() else None - parent = root / safe - for name in ("full_run_case", "case"): - candidate = parent / name - if candidate.is_dir(): - return candidate - return None - - -def reference_log_paths(profile: BenchmarkProfile, case_id: str) -> tuple[Path, ...]: - case = reference_case_dir(profile, case_id) - return tuple(sorted(path for path in case.glob("log.*") if path.is_file())) if case else () - - -def reference_statistics(profile: BenchmarkProfile, case_id: str) -> dict | None: - """Load compact reference diagnostics without a historical simulation tree.""" - import json - from .numerical import DEFAULT_CONTRACT - name = profile.numerical_contract.get("reference_statistics_path") - if not name: - return None - path = Path(name) - if not path.is_absolute(): - path = profile.benchmark_path.parent.parent / path - data = json.loads(path.read_text(encoding="utf-8")) - if data.get("parser_contract") != DEFAULT_CONTRACT: - raise ValueError("Reference statistics parser contract differs from evaluator") - if case_id not in data["cases"]: - raise ValueError(f"Missing reference statistics for {case_id}") - return data["cases"][case_id] diff --git a/benchmarks/evaluation/reporting.py b/benchmarks/evaluation/reporting.py deleted file mode 100644 index c17f3c82eddfdb36abd5f7d2efed5ec7d940ca04..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/reporting.py +++ /dev/null @@ -1,89 +0,0 @@ -from __future__ import annotations - -import csv -from pathlib import Path -from typing import Any - - -CASE_COLUMNS = ( - "case_id", "dataset", "family", "variant", "replicate", - "execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass", - "qoi_status", "qoi_pass_ratio", "failure_categories", - "duration_seconds", "input_tokens", "output_tokens", -) - - -def _token(usage: dict[str, Any], *names: str) -> Any: - for name in names: - if isinstance(usage.get(name), (int, float)): - return usage[name] - return "" - - -def case_csv_row(result: dict[str, Any]) -> dict[str, Any]: - scores = result["scores"] - qoi = result["qoi"] - resources = result.get("resources", {}) - usage = resources.get("token_usage") if isinstance(resources.get("token_usage"), dict) else {} - return { - "case_id": result["case_id"], - "dataset": result["dataset"], - "family": result["family"], - "variant": result["variant"], - "replicate": result["replicate"], - "execution_pass": scores["execution_pass"], - "numerical_pass": scores["numerical_pass"], - "physics_grounded_qoi_pass": scores["physics_grounded_qoi_pass"], - "end_to_end_pass": scores["end_to_end_pass"], - "qoi_status": qoi.get("status", ""), - "qoi_pass_ratio": qoi.get("effective_pass_ratio", ""), - "failure_categories": ";".join(result.get("failure_categories", [])), - "duration_seconds": resources.get("duration_seconds") or "", - "input_tokens": _token(usage, "input_tokens", "prompt_tokens"), - "output_tokens": _token(usage, "output_tokens", "completion_tokens"), - } - - -def write_case_csv(path: Path, results: list[dict[str, Any]]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - with temporary.open("w", encoding="utf-8", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=CASE_COLUMNS) - writer.writeheader() - writer.writerows(case_csv_row(result) for result in results) - temporary.replace(path) - - -SUMMARY_COLUMNS = ( - "scope", "task_count", "execution_pass_count", "execution_pass_rate", - "numerical_pass_count", "numerical_pass_rate_all_tasks", - "physics_grounded_qoi_pass_count", "physics_grounded_qoi_pass_rate_all_tasks", - "end_to_end_pass_count", "end_to_end_pass_rate", -) - - -def write_summary_csv(path: Path, overall: dict[str, Any], families: dict[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name + ".tmp") - with temporary.open("w", encoding="utf-8", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=SUMMARY_COLUMNS) - writer.writeheader() - for scope, summary in [("overall", overall), *sorted(families.items())]: - writer.writerow({"scope": scope, **{key: summary.get(key) for key in SUMMARY_COLUMNS[1:]}}) - temporary.replace(path) - - -def summary_table(summary: dict[str, Any]) -> str: - total = int(summary["task_count"]) - rows = ( - ("Execution", "execution_pass_count", "execution_pass_rate"), - ("Numerical", "numerical_pass_count", "numerical_pass_rate_all_tasks"), - ("QoI", "physics_grounded_qoi_pass_count", "physics_grounded_qoi_pass_rate_all_tasks"), - ("End-to-end", "end_to_end_pass_count", "end_to_end_pass_rate"), - ) - lines = ["Metric Passed Rate", "----------- ----------- --------"] - for label, count_key, rate_key in rows: - rate = summary.get(rate_key) - rendered = "n/a" if rate is None else f"{float(rate) * 100:.2f}%" - lines.append(f"{label:<11} {int(summary[count_key]):>4}/{total:<6} {rendered:>8}") - return "\n".join(lines) diff --git a/benchmarks/evaluation/retained_fields.py b/benchmarks/evaluation/retained_fields.py deleted file mode 100644 index be854babbb8a61e42192b9a874cd915dfa23b97a..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/retained_fields.py +++ /dev/null @@ -1,304 +0,0 @@ -"""Reference-free measurements from retained OpenFOAM fields and static meshes. - -No subprocesses, field writes, fitted constants, or reference values. Unsupported -encodings/BCs/meshes fail closed instead of substituting a different observable. -""" -from __future__ import annotations - -import math -import re -import struct -from pathlib import Path - -import numpy as np - -from .foam_arrays import _bytes, _format, _arch, foam_path, read_label_list, read_vector_list, read_scalar_field - - -def _body(data: bytes) -> bytes: - marker = data.find(b"// * * *") - if marker < 0: - raise ValueError("mesh header separator absent") - return data[data.index(b"\n", marker) + 1:] - - -def _binary_list(data: bytes, code: str, endian: str) -> tuple[list, bytes]: - match = re.match(rb"\s*(\d+)\s*\(", data) - if not match: - raise ValueError("binary list header absent") - count = int(match[1]) - start = match.end() # Do not strip bytes: 0x0a/0x20 can be data. - end = start + count * struct.calcsize(endian + code) - tail = data[end:] - if not tail.startswith(b")"): - raise ValueError("truncated binary list or invalid terminator") - return list(struct.unpack(f"{endian}{count}{code}", data[start:end])), tail[1:] - - -def read_faces(path: Path) -> list[list[int]]: - data = _bytes(path) - body = _body(data) - if _format(data) == "binary": - if not re.search(rb"class\s+faceCompactList\s*;", data[:data.find(b"// * * *")]): - raise ValueError("only faceCompactList binary faces are supported") - endian, labels, _ = _arch(data) - code = "i" if labels == 32 else "q" - offsets, tail = _binary_list(body, code, endian) - indices, _ = _binary_list(tail, code, endian) - if not offsets or offsets[0] != 0 or offsets[-1] != len(indices): - raise ValueError("invalid compact face offsets") - if any(b - a < 3 for a, b in zip(offsets, offsets[1:])): - raise ValueError("invalid face size") - return [indices[a:b] for a, b in zip(offsets, offsets[1:])] - match = re.match(rb"\s*(\d+)\s*\(", body) - if not match: - raise ValueError("face list header absent") - faces = [] - position = match.end() - face_pattern = re.compile(rb"\s*(\d+)\s*\(([^()]*)\)") - for _ in range(int(match[1])): - row = face_pattern.match(body, position) - if not row: - raise ValueError("invalid ASCII face") - face = [int(x) for x in row[2].split()] - if len(face) != int(row[1]) or len(face) < 3: - raise ValueError("face length mismatch") - faces.append(face) - position = row.end() - if not body[position:].lstrip().startswith(b")"): - raise ValueError("face count mismatch") - return faces - - -def static_mesh(case: Path) -> bool: - if (case / "constant/dynamicMeshDict").exists(): - return False - # OpenFOAM 13 can configure motion/topology changes in constant/polyMesh. - if any((case / "constant/polyMesh" / name).exists() for name in ("mover", "topoChanger", "distributor")): - return False - return not any(path.is_dir() and (path / "polyMesh").exists() - for path in case.iterdir() if _is_time(path.name)) - - -def _is_time(value: str) -> bool: - try: - return math.isfinite(float(value)) - except ValueError: - return False - - -def mesh_arrays(case: Path): - mesh = case / "constant/polyMesh" - paths = [foam_path(mesh, name) for name in ("points", "faces", "owner", "neighbour")] - if any(path is None for path in paths): - raise ValueError("incomplete retained polyMesh") - points = np.asarray(read_vector_list(paths[0]), dtype=float) - faces = read_faces(paths[1]) - owner = np.asarray(read_label_list(paths[2]), dtype=int) - neighbour = np.asarray(read_label_list(paths[3]), dtype=int) - if len(owner) != len(faces) or len(neighbour) > len(owner) or not len(owner): - raise ValueError("mesh topology length mismatch") - if np.min(owner) < 0 or (len(neighbour) and (np.min(neighbour) < 0 or np.max(neighbour) > np.max(owner))): - raise ValueError("invalid cell indices") - if not np.isfinite(points).all() or any(min(face) < 0 or max(face) >= len(points) for face in faces): - raise ValueError("invalid mesh points/face indices") - return points, faces, owner, neighbour, paths - - -def planar_face_geometry(points, faces): - """Oriented area and volume moments, grouped by face size for bounded cost.""" - origin = points.mean(axis=0) - vectors = np.zeros((len(faces), 3)) - volumes = np.zeros(len(faces)) - moments = np.zeros((len(faces), 3)) - sizes = {} - for i, face in enumerate(faces): - sizes.setdefault(len(face), []).append(i) - for size, ids in sizes.items(): - vertices = points[np.asarray([faces[i] for i in ids])] - origin - center = vertices.mean(axis=1) - nxt = np.roll(vertices, -1, axis=1) - triangles = np.cross(vertices - center[:, None], nxt - center[:, None]) / 2 - area = triangles.sum(axis=1) - norms = np.linalg.norm(area, axis=1) - if np.any(norms <= 0): - raise ValueError("degenerate face") - distances = np.abs(np.einsum('fvi,fi->fv', vertices - center[:, None], area)) / norms[:, None] - scale = np.max(np.linalg.norm(vertices - center[:, None], axis=2), axis=1) - if np.any(distances > 1e-8 * scale[:, None]): - raise ValueError("nonplanar face: native geometry evidence required") - # Signed tetrahedra (origin, face center, edge endpoints). - tetra = np.einsum('fi,fvi->fv', center, np.cross(vertices, nxt)) / 6 - vectors[ids] = area - volumes[ids] = tetra.sum(axis=1) - moments[ids] = np.sum(tetra[:, :, None] * (center[:, None] + vertices + nxt) / 4, axis=1) - return origin, vectors, volumes, moments - - -def derive_cell_geometry(case: Path): - if not static_mesh(case): - raise ValueError("static geometry derivation disabled for changing meshes") - points, faces, owner, neighbour, paths = mesh_arrays(case) - origin, areas, face_volumes, face_moments = planar_face_geometry(points, faces) - count = int(owner.max()) + 1 - volumes = np.zeros(count) - moments = np.zeros((count, 3)) - closure = np.zeros((count, 3)) - surface = np.zeros(count) - for cells, sign, sl in ((owner, 1, slice(None)), (neighbour, -1, slice(0, len(neighbour)))): - np.add.at(volumes, cells, sign * face_volumes[sl]) - np.add.at(moments, cells, sign * face_moments[sl]) - np.add.at(closure, cells, sign * areas[sl]) - np.add.at(surface, cells, np.linalg.norm(areas[sl], axis=1)) - if np.any(volumes <= 0) or not np.isfinite(volumes).all(): - raise ValueError("nonpositive/nonfinite reconstructed cell volume") - if np.any(np.linalg.norm(closure, axis=1) > 1e-9 * surface): - raise ValueError("cell face surface does not close") - centers = moments / volumes[:, None] + origin - if not np.isfinite(centers).all(): - raise ValueError("nonfinite cell centers") - return volumes.tolist(), [tuple(row) for row in centers.tolist()], paths - - -def boundary_specs(case: Path) -> dict: - path = foam_path(case / "constant/polyMesh", "boundary") - if path is None: - raise ValueError("boundary file absent") - text = _body(_bytes(path)).decode('ascii') - result = {} - for name, block in re.findall(r'([\w]+)\s*\{([^{}]*)\}', text): - start = re.search(r'\bstartFace\s+(\d+)\s*;', block) - size = re.search(r'\bnFaces\s+(\d+)\s*;', block) - if start and size: - result[name] = (int(start[1]), int(size[1])) - return result - - -def scalar_boundary(path: Path, patch: str, owners: list[int]) -> tuple[list[float], str]: - data = _bytes(path) - # Locate boundaryField after the internal payload, never inside binary data. - internal = re.search(rb'internalField\s+nonuniform\s+List\s*', data) - if internal and _format(data) == 'binary': - endian, _, bits = _arch(data) - _, tail = _binary_list(data[internal.end():], 'f' if bits == 32 else 'd', endian) - else: - tail = data - anchor = re.search(rb'\bboundaryField\s*\{', tail) - if anchor is None: - raise ValueError('boundaryField absent') - tail = tail[anchor.end():] - # Replace length-delimited binary lists before parsing braces. Binary bytes - # may themselves contain braces, newlines or apparent dictionary keywords. - arrays = {} - if _format(data) == 'binary': - endian, _, bits = _arch(data) - parts = [] - while (match := re.search(rb'nonuniform\s+List\s*', tail)) is not None: - values, rest = _binary_list(tail[match.end():], 'f' if bits == 32 else 'd', endian) - key = f'__array_{len(arrays)}' - arrays[key] = values - parts.append(tail[:match.start()] + key.encode()) - tail = rest - tail = b''.join(parts) + tail - text = tail.decode('ascii') - blocks = dict(re.findall(r'([\w]+)\s*\{([^{}]*)\}', text)) - block = blocks.get(patch) - if block is None: - raise ValueError(f'patch {patch} has no explicit dictionary') - bc = re.search(r'\btype\s+(\w+)\s*;', block) - uniform = re.search(r'\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;', block) - stored = re.search(r'\bvalue\s+(__array_\d+)\s*;', block) - listed = re.search(r'\bvalue\s+nonuniform\s+List\s+(\d+)\s*\(([^()]*)\)\s*;', block) - if uniform: - values, method = [float(uniform[1])] * len(owners), 'stored_boundary_value' - elif stored: - values, method = arrays[stored[1]], 'stored_boundary_value' - elif listed: - values, method = [float(x) for x in listed[2].split()], 'stored_boundary_value' - if len(values) != int(listed[1]): - raise ValueError('boundary list length mismatch') - elif bc and bc[1] == 'zeroGradient' and path.name.removesuffix('.gz') == 'p': - internal_values = read_scalar_field(path) - if re.search(rb'internalField\s+uniform\s+', data): - values = internal_values * len(owners) - else: - values = [internal_values[i] for i in owners] - method = 'zeroGradient_exact_owner_value' - else: - raise ValueError(f'{patch}: unsupported boundary without stored values') - if len(values) != len(owners) or not all(math.isfinite(x) for x in values): - raise ValueError('boundary value count/nonfinite mismatch') - return values, method - - -def dimensions(path: Path) -> str | None: - match = re.search(rb'\bdimensions\s*\[([^]]+)\]', _bytes(path)[:4096]) - return ' '.join(match[1].decode('ascii').split()) if match else None - - -def pump_measurements(case: Path) -> tuple[dict, dict, list[str]]: - """All retained positive times, with signed inlet phi and boundary p. - - Only the unique inlet/outlet names (case insensitive) are recognized. No - reference times or values enter extraction; time alignment is comparator work. - """ - values, evidence, errors = {}, {}, [] - try: - if not static_mesh(case): - raise ValueError('pump retained-field fallback requires a static mesh') - points, faces, owner, _, paths = mesh_arrays(case) - _, vectors, _, _ = planar_face_geometry(points, faces) - areas = np.linalg.norm(vectors, axis=1) - specs = boundary_specs(case) - names = {} - for role in ('inlet', 'outlet'): - matches = [name for name in specs if name.lower() == role] - if len(matches) != 1: - raise ValueError(f'ambiguous or absent {role} patch') - names[role] = matches[0] - slices = {role: slice(specs[name][0], sum(specs[name])) for role, name in names.items()} - if any(sl.stop > len(owner) or sl.start == sl.stop for sl in slices.values()): - raise ValueError('invalid inlet/outlet face range') - except (OSError, ValueError, RuntimeError) as exc: - return {}, {}, [str(exc)] - histories = {'mass_flow_rate': [], 'pressure_rise': []} - phi_dimension: str | None = None - refs = {key: set() for key in histories} - boundary = foam_path(case / 'constant/polyMesh', 'boundary') - mesh_refs = [str(p.relative_to(case)) for p in [*paths, boundary] if p] - 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)): - for metric, field in (('mass_flow_rate', 'phi'), ('pressure_rise', 'p')): - path = foam_path(directory, field) - if path is None: - continue - try: - actual_dimensions = dimensions(path) - allowed_dimensions = ( - {'1 0 -1 0 0 0 0', '0 3 -1 0 0 0 0'} if field == 'phi' - else {'1 -1 -2 0 0 0 0', '0 2 -2 0 0 0 0'} - ) - if actual_dimensions not in allowed_dimensions: - raise ValueError('unsupported physical dimensions') - if field == 'phi': - phi_dimension = actual_dimensions - inlet, _ = scalar_boundary(path, names['inlet'], owner[slices['inlet']].tolist()) - if field == 'phi': - value = math.fsum(inlet) - else: - outlet, _ = scalar_boundary(path, names['outlet'], owner[slices['outlet']].tolist()) - value = float(np.average(outlet, weights=areas[slices['outlet']]) - np.average(inlet, weights=areas[slices['inlet']])) - histories[metric].append({'time': float(directory.name), 'value': value}) - refs[metric].add(str(path.relative_to(case))) - except (OSError, ValueError, RuntimeError, IndexError) as exc: - errors.append(f'{directory.name}/{field}: {exc}') - for metric, history in histories.items(): - if history: - values[metric] = {'kind': 'time_history', 'quantity': ( - 'explicit_mass_flow' if phi_dimension == '1 0 -1 0 0 0 0' else 'explicit_volumetric_flow' - ) if metric == 'mass_flow_rate' else 'pressure_rise', 'points': history} - if metric == 'mass_flow_rate': - values[metric]['field_dimensions'] = phi_dimension - else: - values[metric].update(definition='outlet_minus_inlet_patch_average', source_patches=names) - evidence[metric] = sorted(refs[metric] | set(mesh_refs)) - return values, evidence, errors diff --git a/benchmarks/evaluation/schema.py b/benchmarks/evaluation/schema.py deleted file mode 100644 index 8fd7035d15fb50154f23981226cab5eb79fc1ab9..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/schema.py +++ /dev/null @@ -1,21 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from typing import Any - -from jsonschema import Draft202012Validator, FormatChecker - -from .io import read_object - - -SCHEMA_ROOT = Path(__file__).resolve().parents[2] / "schemas" - - -def validate(value: Any, schema_name: str) -> None: - schema = read_object(SCHEMA_ROOT / schema_name) - validator = Draft202012Validator(schema, format_checker=FormatChecker()) - errors = sorted(validator.iter_errors(value), key=lambda error: list(error.absolute_path)) - if errors: - error = errors[0] - location = ".".join(str(item) for item in error.absolute_path) or "" - raise ValueError(f"{schema_name} validation failed at {location}: {error.message}") diff --git a/benchmarks/evaluation/stability.py b/benchmarks/evaluation/stability.py deleted file mode 100644 index f13cf722d02917b58a53b8e1d2369d7b57b62623..0000000000000000000000000000000000000000 --- a/benchmarks/evaluation/stability.py +++ /dev/null @@ -1,48 +0,0 @@ -from __future__ import annotations - -import math -import re -from pathlib import Path -from typing import Any - -from .foam_io import read_text - - -def numerical_scheme(case_dir: Path) -> str: - block = re.search(r"ddtSchemes\s*\{(?P.*?)\}", read_text(case_dir / "system/fvSchemes"), re.S) - default = re.search(r"\bdefault\s+([^;\s]+)", block.group("body")) if block else None - return default.group(1) if default else "unknown" - - -def steady_plateau( - qois: dict[str, Any], - baseline_spans: dict[str, float] | None = None, - *, - final_window_fraction: float = 0.2, - minimum_snapshots: int = 3, -) -> dict[str, Any]: - metrics = {} - passed = True - for name, value in sorted(qois.items()): - if not isinstance(value, dict) or value.get("kind") != "time_history": - continue - points = value.get("points", []) - samples = [float(point["value"]) for point in points if isinstance(point, dict) - and isinstance(point.get("value"), (int, float))] - if len(samples) < minimum_snapshots: - metrics[name] = {"status": "fail", "sample_count": len(samples), "expected_minimum": minimum_snapshots} - passed = False - continue - count = max(minimum_snapshots, math.ceil(len(samples) * final_window_fraction)) - selected = samples[-count:] - span = (max(selected) - min(selected)) / max(abs(selected[-1]), 1e-12) - limit = max(0.02, (baseline_spans or {}).get(name, 0.0) * 2.0) - ok = span <= limit - metrics[name] = {"status": "pass" if ok else "fail", "relative_span": span, - "limit": limit, "sample_count": count} - passed = passed and ok - return { - "status": "pass" if metrics and passed else "fail" if metrics else "not_applicable", - "applicable": bool(metrics), - "metrics": metrics, - } diff --git a/benchmarks/scripts/__init__.py b/benchmarks/scripts/__init__.py deleted file mode 100644 index 5b359f5f10e930be2cc01cbbbaa6edeb85ec4b77..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Reusable benchmark algorithms and their command-line compatibility entry points.""" diff --git a/benchmarks/scripts/build_extbench_reference.py b/benchmarks/scripts/build_extbench_reference.py deleted file mode 100644 index a12472dc0f804d495c347ae3b7d5acf8188bacb8..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/build_extbench_reference.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python3 -"""Build the executable Extended reference contract from an extraction audit.""" -from __future__ import annotations - -import argparse -import json -import math -from pathlib import Path -from typing import Any - - -STRICTLY_POSITIVE_SCALARS = {"first_cell_yplus", "rise_velocity", "equivalent_radius_final", "final_component_count"} -NONNEGATIVE_SCALARS = {"spalding_log_rmse", "Cd_rms", "interior_pressure_span"} -STRICTLY_POSITIVE_STRUCTURED = { - "branchwise_wall_law_metrics", "jet_to_mainstream_mass_flux_ratio", - "minimum_observed_equivalent_radius", "rise_velocity", -} - - -def physical_bounds(name: str, *, structured: bool = False) -> dict[str, Any]: - if name in STRICTLY_POSITIVE_SCALARS or (structured and name in STRICTLY_POSITIVE_STRUCTURED): - return {"physical_low": 1e-12, "physical_threshold_source": "task_implied_positive_response"} - if name in NONNEGATIVE_SCALARS: - return {"physical_low": 0.0, "physical_threshold_source": "definition_implied_nonnegative_response"} - return {} - - -def scalar_tolerance(name: str, value: float) -> dict[str, Any]: - # Component counts are discrete physical topology, not a continuously - # varying response. An exact interval prevents a one-component result - # from being accepted as a two-component result. - discrete = name == "final_component_count" - relative = 0.0 if discrete else (0.05 if name in {"Cd", "Cl", "Cm", "Cd_mean"} else 0.10) - floor = { - "Cd": 5e-4, "Cl": 1e-3, "Cm": 5e-4, "Cd_mean": 5e-4, - "Cd_rms": 5e-4, "spalding_log_rmse": 0.05, "first_cell_yplus": 0.05, - "interior_pressure_span": 1e-6, - }.get(name, max(abs(value) * 1e-6, 1e-12)) - width = 0.0 if discrete else max(abs(value) * relative, floor) - return { - "kind": "steady_scalar", - "low": value - width, - "high": value + width, - "relative_component": relative, - "absolute_floor": floor, - "criterion_role": "principal_response", - "reference_independent": False, - "threshold_source": "reference_anchored_repeatability_pending", - "provisional": True, - **physical_bounds(name), - } - - -def structured_tolerance(name: str, value: dict[str, Any]) -> dict[str, Any]: - kind = value.get("kind") - if kind in {"time_history", "component_trajectory", "branched_time_histories"}: - return {"kind": "trajectory", "normalized_rmse_max": 0.10, "normalized_linf_max": 0.25, - "minimum_time_coverage": 0.90, "normalization_floor": 1e-12, - "criterion_role": "principal_response_shape", "reference_independent": False, - "threshold_source": "reference_anchored_trajectory", "provisional": True} - if kind == "named_profiles": - return {"kind": "profile", "normalized_l1_max": 0.08, "normalized_linf_max": 0.20, - "normalization_floor": 1e-12, "criterion_role": "principal_response_shape", - "reference_independent": False, - "threshold_source": "reference_anchored_spatial_response_shape", "provisional": True} - if kind == "profile_feature_locations": - return {"kind": "event_location", "maximum_cell_offset": 2.0, - "physical_floor": 1e-12, "criterion_role": "principal_response_shape", - "reference_independent": False, - "threshold_source": "reference_anchored_feature_location", "provisional": True} - if kind in {"component_scalars", "branch_scalars", "scalar_ratio", "window_regression"}: - return { - "kind": kind, - "relative_max": 0.10, - "absolute_floor": 1e-12, - "criterion_role": "principal_response", - "reference_independent": False, - "threshold_source": "reference_anchored_structured_response", - "provisional": True, - **physical_bounds(name, structured=True), - } - raise ValueError(f"unsupported reference QoI kind: {kind!r}") - - -def build_reference(audit: dict[str, Any]) -> dict[str, Any]: - cases: dict[str, Any] = {} - for case_id, record in sorted(audit["cases"].items()): - if record.get("status") != "complete": - raise ValueError(f"cannot freeze incomplete reference case: {case_id}") - qois = record.get("qois", {}) - tolerances = {} - for name, value in qois.items(): - if isinstance(value, bool): - raise ValueError(f"invalid boolean QoI: {case_id}/{name}") - if isinstance(value, (int, float)): - if not math.isfinite(float(value)): - raise ValueError(f"non-finite QoI: {case_id}/{name}") - tolerances[name] = scalar_tolerance(name, float(value)) - elif isinstance(value, dict): - tolerances[name] = structured_tolerance(name, value) - else: - raise ValueError(f"unsupported QoI: {case_id}/{name}") - cases[case_id] = { - "case_id": case_id, - "family": record.get("family"), - "branch_id": record.get("branch_id"), - "principal_qoi_group": record.get("branch_id") or record.get("family") or "principal", - "principal_metrics": list(record.get("required_metrics", [])), - "metric_roles": {name: "principal" for name in qois}, - "qois": qois, - "conditional_metrics": list(record.get("conditional_metrics", [])), - "conditional_qois": dict(record.get("conditional_qois", {})), - "conditional_status": dict(record.get("conditional_status", {})), - "diagnostic_qois": dict(record.get("diagnostic_qois", {})), - "tolerances": tolerances, - "provenance": {"case_dir": record.get("case_dir"), "evidence": record.get("evidence"), - "metric_methods": record.get("metric_methods")}, - } - return { - "schema_version": "foambench.reference_qois", - "design": "foambench.qoi.design", - "tolerance_status": "joint_physical_admissibility_and_reference_response_provisional", - "notes": [ - "Principal reference bands test task-response agreement and are explicitly reference-anchored.", - "Definition-implied physical bounds are evaluated jointly when a sign or positivity rule is unambiguous.", - "Conditional QoIs remain unavailable rather than silently passing when their declared evidence is absent.", - ], - "case_count": len(cases), - "cases": cases, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--audit", required=True, type=Path) - parser.add_argument("--output", required=True, type=Path) - args = parser.parse_args() - audit = json.loads(args.audit.read_text(encoding="utf-8")) - output = build_reference(audit) - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n", encoding="utf-8") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/scripts/compare_foambench_qois.py b/benchmarks/scripts/compare_foambench_qois.py deleted file mode 100644 index e97a87392b8441a8877c38fde0bbff49f12eab00..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/compare_foambench_qois.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python3 -"""Compatibility CLI for the canonical FoamBench QoI comparator.""" -from __future__ import annotations - -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.comparison import * # noqa: F401,F403 -from benchmarks.evaluation.comparison import main - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/scripts/extract_extbench_qois.py b/benchmarks/scripts/extract_extbench_qois.py deleted file mode 100644 index c95bcd6aee4e2efd4651da7f84f29b5f62c1d2c5..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/extract_extbench_qois.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python3 -"""Compatibility CLI for the Extended FoamBench QoI audit extractor.""" -from __future__ import annotations - -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.extbench import * # noqa: F401,F403 -from benchmarks.evaluation.extbench import main - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/scripts/extract_foambench_candidate_qois.py b/benchmarks/scripts/extract_foambench_candidate_qois.py deleted file mode 100644 index 494db6fa2393315633cbbcd19eb5bec29851d3ae..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/extract_foambench_candidate_qois.py +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env python3 -"""Compatibility entry point for FoamBench candidate QoI extraction. - -Basic and advanced contracts use structured field histories and spatial -profiles. Those metrics are implemented by :mod:`basic_advanced`, whereas -the historical ``field_extractor`` only produces generic scalar diagnostics. -Keep the latter available for legacy callers, but route contract-backed -FoamBench cases to the structured implementation. -""" -from __future__ import annotations - -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.field_extractor import * # noqa: F401,F403 -from benchmarks.evaluation.field_extractor import ( - extract_case_qois as _legacy_extract_case_qois, - required_metrics as _legacy_required_metrics, -) -from benchmarks.evaluation.basic_advanced import ADVANCED_TEMPLATE, GROUPS, extract as _structured_extract - - -def _supports_structured_contract(case_id: str) -> bool: - """Return whether ``case_id`` belongs to Basic or Advanced FoamBench.""" - return case_id in ADVANCED_TEMPLATE or case_id.split("/", 1)[0] in GROUPS - - -def extract_case_qois(case_dir, case_id, reference_path=None, log_paths=None): - """Extract contract QoIs, preserving the legacy generic fallback. - - Evolution evaluation always provides ``reference_path``. Its metric set - is therefore the authoritative requested/required set for the structured - extractor. Legacy synthetic contracts retain their original behavior. - """ - if reference_path is not None and _supports_structured_contract(case_id): - required, _ = _legacy_required_metrics(reference_path, case_id) - return _structured_extract( - case_dir, - case_id, - requested_metrics=required, - required_metrics=required, - ) - return _legacy_extract_case_qois(case_dir, case_id, reference_path, log_paths) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/scripts/extract_foambench_qois.py b/benchmarks/scripts/extract_foambench_qois.py deleted file mode 100644 index 5c742492c19fedf088b04238bdd697f56040ab1f..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/extract_foambench_qois.py +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env python3 -"""Compatibility CLI for the canonical FoamBench reference extractor.""" -from __future__ import annotations - -import sys -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.qoi_reference import * # noqa: F401,F403 -from benchmarks.evaluation.qoi_reference import main - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/benchmarks/scripts/materialize_benchmark.py b/benchmarks/scripts/materialize_benchmark.py deleted file mode 100644 index bc743308963db7704a59153707737629e465a1ca..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/materialize_benchmark.py +++ /dev/null @@ -1,240 +0,0 @@ -#!/usr/bin/env python3 -"""Materialize OpenFOAM cases from a FoamBench JSON export. - -The Basic benchmark uses ``family/variant`` identifiers while Advanced uses -single-component identifiers. This script deliberately keeps either -representation lossless: it only creates the case tree and a manifest; it -does not edit controlDict files or shorten the requested simulation. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import shutil -import sys -from pathlib import Path -from typing import Any - - -CASE_KEY = re.compile(r"^[^/\\]+(?:/[^/\\]+)?$") -COMMAND_MARKERS = ( - "decomposePar", - "runParallel", - "reconstructPar", - "topoSet", - "setFields", - "checkMesh", - "createPatch", - "blockMesh", - "foamRun", - "foamPostProcess", -) - - -def sha256_bytes(data: bytes) -> str: - return hashlib.sha256(data).hexdigest() - - -def sha256_file(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def tree_sha256(root: Path) -> str: - """Hash relative paths and bytes, independent of directory iteration order.""" - digest = hashlib.sha256() - for path in sorted(p for p in root.rglob("*") if p.is_file()): - relative = path.relative_to(root).as_posix().encode("utf-8") - digest.update(len(relative).to_bytes(8, "big")) - digest.update(relative) - digest.update(bytes.fromhex(sha256_file(path))) - return digest.hexdigest() - - -def safe_relative_key(key: str) -> Path: - path = Path(key) - if path.is_absolute() or key.startswith(("/", "\\")): - raise ValueError(f"absolute case key is not allowed: {key!r}") - if any(part in ("", ".", "..") for part in path.parts): - raise ValueError(f"unsafe case key: {key!r}") - if len(path.parts) < 1: - raise ValueError(f"empty case key: {key!r}") - return path - - -def variant_sort_key(case_id: str) -> tuple[Any, ...]: - family, variant = case_id.split("/", 1) if "/" in case_id else (case_id, "default") - chunks = re.split(r"(\d+)", variant) - normalized: list[Any] = [] - for chunk in chunks: - normalized.append((0, int(chunk)) if chunk.isdigit() else (1, chunk)) - return (family, normalized) - - -def choose_case_ids(data: dict[str, Any], requested: list[str] | None, excluded: set[str] | None = None) -> list[str]: - excluded = excluded or set() - if requested: - unknown = sorted(set(requested) - set(data)) - if unknown: - raise ValueError("case id(s) not found: " + ", ".join(unknown)) - return requested - families: dict[str, list[str]] = {} - for case_id in data: - if not CASE_KEY.match(case_id): - raise ValueError(f"unsafe case id: {case_id!r}") - family = case_id.split("/", 1)[0] if "/" in case_id else case_id - families.setdefault(family, []).append(case_id) - return [sorted(ids, key=variant_sort_key)[0] for _, ids in sorted(families.items()) if ids and sorted(ids, key=variant_sort_key)[0] not in excluded] - - -def materialize_assets(case_id: str, spec: dict[str, Any], case_root: Path | None, - source: Path, asset_manifest: dict[str, Any] | None = None) -> list[dict[str, str]]: - """Verify declared geometry and optionally copy it, without reference case files.""" - records = [] - if spec.get("_external_assets"): - if asset_manifest is None: - raise ValueError(f"{case_id}: external assets declared but no asset manifest was found") - entries = asset_manifest.get("assets", {}) - for asset in spec["_external_assets"]: - if not isinstance(asset, dict) or not isinstance(asset.get("asset_id"), str) or not isinstance(asset.get("target"), str): - raise ValueError(f"{case_id}: malformed external asset declaration") - asset_id = asset["asset_id"] - record = entries.get(asset_id) - if not isinstance(record, dict): - raise ValueError(f"{case_id}: unknown asset_id {asset_id!r}") - asset_path = Path(record.get("path", "")) - if asset_path.is_absolute() or ".." in asset_path.parts: - raise ValueError(f"{case_id}: unsafe asset path for {asset_id!r}") - asset_file = source.parent.parent / asset_path - if not asset_file.is_file(): - raise ValueError(f"{case_id}: asset file does not exist: {asset_file}") - expected = record.get("sha256") - if not isinstance(expected, str) or sha256_file(asset_file) != expected: - raise ValueError(f"{case_id}: SHA-256 mismatch for asset {asset_id!r}") - relative = safe_relative_key(asset["target"]) - records.append({"asset_id": asset_id, "target": relative.as_posix(), "sha256": expected}) - if case_root is not None: - target = case_root / relative - if not target.resolve().is_relative_to(case_root.resolve()): - raise ValueError(f"{case_id}: asset target escapes case root") - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(asset_file, target) - return records - - -def materialize_case(case_id: str, spec: dict[str, Any], case_root: Path, source: Path, asset_manifest: dict[str, Any] | None = None) -> dict[str, Any]: - case_root.mkdir(parents=True, exist_ok=False) - allrun = spec.get("Allrun") - blocked = not isinstance(allrun, str) - if blocked: - allrun = "" - materialize_assets(case_id, spec, case_root, source, asset_manifest) - for key, content in spec.items(): - if key == "usr_requirement" or key.startswith("_") or key == "reference_subcases": - continue - relative = safe_relative_key(key) - if not isinstance(content, str): - raise ValueError(f"{case_id}: file content for {key!r} is not text") - target = case_root / relative - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(content, encoding="utf-8", newline="") - if key == "Allrun": - target.chmod(target.stat().st_mode | 0o111) - if blocked: - (case_root / "BLOCKED_REFERENCE.txt").write_text( - "This task has no runnable reference case. See the repair status report.\n" - + str(spec.get("usr_requirement", "")) + "\n", - encoding="utf-8", - ) - operations = [marker for marker in COMMAND_MARKERS if re.search(rf"\b{re.escape(marker)}\b", allrun)] - family, variant = case_id.split("/", 1) if "/" in case_id else (case_id, "default") - return { - "case_id": case_id, - "family": family, - "variant": variant, - "source_json": str(source.resolve()), - "source_json_sha256": sha256_file(source), - "usr_requirement": spec.get("usr_requirement", ""), - "allrun": allrun, - "workflow_operations": operations, - "case_sha256": tree_sha256(case_root), - "file_count": sum(1 for p in case_root.rglob("*") if p.is_file()), - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--benchmark", type=Path, required=True) - parser.add_argument("--output-root", type=Path, required=True) - parser.add_argument("--case-id", action="append", help="select a case; repeat to select several") - parser.add_argument("--status", type=Path, help="repair status JSON; blocked cases are excluded from default selection") - parser.add_argument("--asset-manifest", type=Path, help="asset manifest; defaults to benchmarks/assets/manifest.json next to the benchmark") - parser.add_argument("--allow-existing", action="store_true", help="allow an existing empty output root") - args = parser.parse_args() - - source = args.benchmark.resolve(strict=True) - output = args.output_root.resolve() - data = json.loads(source.read_text(encoding="utf-8")) - if not isinstance(data, dict): - raise ValueError("benchmark JSON root must be an object") - asset_manifest_path = args.asset_manifest.resolve() if args.asset_manifest else source.parent / "assets" / "manifest.json" - asset_manifest = None - if asset_manifest_path.exists(): - asset_manifest = json.loads(asset_manifest_path.read_text(encoding="utf-8")) - status_path = args.status - if status_path is None: - candidates = [ - source.with_name(source.name.replace("_repaired.json", "_repair_status.json")), - source.with_name(source.name.replace(".json", "_repair_status.json")), - ] - status_path = next((candidate for candidate in candidates if candidate.exists()), None) - excluded: set[str] = set() - if status_path and status_path.exists() and not args.case_id: - status_data = json.loads(status_path.read_text(encoding="utf-8")) - excluded = set(status_data.get("excluded_from_default_scientific_denominator", [])) - case_ids = choose_case_ids(data, args.case_id, excluded) - if output.exists(): - existing = list(output.iterdir()) - if existing and not args.allow_existing: - raise ValueError(f"output root is not empty: {output}; choose a new path or --allow-existing") - output.mkdir(parents=True, exist_ok=True) - track = output.name - cases: list[dict[str, Any]] = [] - for case_id in case_ids: - safe_name = case_id.replace("/", "__") - case_dir = output / safe_name / "case" - if case_dir.parent.exists(): - raise ValueError(f"case output already exists: {case_dir.parent}") - metadata = materialize_case(case_id, data[case_id], case_dir, source, asset_manifest) - metadata["track"] = track - metadata_path = case_dir.parent / "metadata.json" - metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - cases.append({"case_id": case_id, "relative_dir": safe_name, **metadata}) - manifest = { - "schema_version": "m0.materialized.v1", - "track": track, - "benchmark": str(source), - "benchmark_sha256": sha256_file(source), - "selection": "first_sorted_variant_per_family" if not args.case_id else "explicit_case_ids", - "case_count": len(cases), - "cases": cases, - } - (output / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(f"materialized {len(cases)} cases into {output}") - for item in cases: - print(f" {item['track']}: {item['case_id']} ({','.join(item['workflow_operations']) or 'no detected operations'})") - return 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, ValueError, json.JSONDecodeError) as exc: - print(f"materialize_benchmark.py: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/scripts/recover_extbench_qoi.py b/benchmarks/scripts/recover_extbench_qoi.py deleted file mode 100644 index 55059764f482f7a86687550d367492dabb860da7..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/recover_extbench_qoi.py +++ /dev/null @@ -1,293 +0,0 @@ -#!/usr/bin/env python3 -"""Recover incomplete QoI comparisons from frozen Extended FoamBench cases. - -The driver never invokes a solver and never edits a source run. It consumes -an existing ``campaign_evaluation.json`` and follows each record's explicit -``artifact.case_dir``. Only execution-pass cases whose original QoI status -contains ``incomplete`` are selected. -""" -from __future__ import annotations - -import argparse -import json -import sys -from collections import defaultdict -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from benchmarks.evaluation.aggregate import aggregate_results -from benchmarks.evaluation.extbench import extract_contract_case -from benchmarks.evaluation.frozen_recovery import ( - RECOVERY_VERSION, - document_checksum, - recover_case, - recovery_score_record, -) -from benchmarks.evaluation.comparison import compare_case -from benchmarks.evaluation.io import write_json - - -DEFAULT_REFERENCE = ROOT / "benchmarks/FoamBench_extended_openfoam13_reference_qois.json" -DEFAULT_DESIGN = ROOT / "benchmarks/FoamBench_extended_openfoam13_qoi_design.json" - - -def utc_now() -> str: - return datetime.now(timezone.utc).isoformat() - - -def load_json(path: Path) -> dict[str, Any]: - value = json.loads(path.read_text(encoding="utf-8")) - if not isinstance(value, dict): - raise ValueError(f"expected an object in {path}") - return value - - -def compact_failure_record( - source: dict[str, Any], - case_id: str, - reference: dict[str, Any], - design: dict[str, Any], - adapter: str, - error: Exception, -) -> dict[str, Any]: - """Keep one malformed case auditable without aborting other recoveries.""" - case_dir = Path(str(source.get("artifact", {}).get("case_dir", ""))) - candidate: dict[str, Any] - try: - candidate = extract_contract_case(case_dir, case_id, design) - comparison = compare_case(reference, candidate, 1.0) - except Exception as nested: - candidate = { - "schema_version": "foambench.qoi.candidate", - "case_id": case_id, - "required_metrics": list(reference.get("qois", {})), - "missing_metrics": sorted(reference.get("qois", {})), - "qois": {}, - "status": "incomplete", - "health": {"status": "incomplete", "reason": str(nested)}, - } - comparison = { - "schema_version": "foambench.qoi.case_comparison.v3", - "status": "incomplete", - "missing_metrics": sorted(reference.get("qois", {})), - "out_of_tolerance_metrics": [], - "invalid_contract_metrics": [], - "physics_grounded_qoi_pass": False, - "qoi_pass_ratio": 0.0, - } - return { - "case_id": case_id, - "family": case_id.split("/", 1)[0], - "variant": case_id.split("/", 1)[1], - "case_dir": str(case_dir), - "original": { - "reextract_status": comparison.get("status"), - "reextract_missing_metrics": comparison.get("missing_metrics", []), - "reextract_candidate_missing_metrics": candidate.get("missing_metrics", []), - }, - "recovery": { - "status": "irrecoverable_incomplete", - "version": RECOVERY_VERSION, - "methods": {}, - "source_evidence": {}, - "source_times": [], - "preflight": {"status": "error"}, - "reasons": [f"recovery driver exception: {error}"], - }, - "candidate": candidate, - "comparison": comparison, - } - - -def select_case_ids(campaign: dict[str, Any], requested: list[str] | None) -> list[str]: - cases = campaign.get("cases") - if not isinstance(cases, dict): - raise ValueError("campaign has no cases object") - selected = sorted(requested or cases) - unknown = sorted(set(selected) - set(cases)) - if unknown: - raise ValueError("unknown case IDs: " + ", ".join(unknown)) - filtered: list[str] = [] - for case_id in selected: - record = cases[case_id] - if not isinstance(record, dict): - continue - execution = record.get("execution", {}) - qoi = record.get("qoi", {}) - if execution.get("status") == "pass" and "incomplete" in str(qoi.get("status", "")): - filtered.append(case_id) - return filtered - - -def family_summary(rows: dict[str, dict[str, Any]]) -> dict[str, Any]: - grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) - for row in rows.values(): - grouped[str(row.get("family"))].append(row) - result: dict[str, Any] = {} - for family, family_rows in sorted(grouped.items()): - statuses = [row.get("recovery", {}).get("status") for row in family_rows] - result[family] = { - "selected_case_count": len(family_rows), - "recovered_complete_count": statuses.count("recovered_complete"), - "recovered_out_of_tolerance_count": statuses.count("recovered_out_of_tolerance"), - "irrecoverable_incomplete_count": statuses.count("irrecoverable_incomplete"), - "original_incomplete_count": len(family_rows), - "final_incomplete_count": sum("incomplete" in str(row.get("comparison", {}).get("status")) for row in family_rows), - "cases": sorted(row["case_id"] for row in family_rows), - } - return result - - -def run(args: argparse.Namespace) -> int: - campaign_path = args.campaign.resolve(strict=True) - reference_path = args.reference_qois.resolve(strict=True) - design_path = args.design.resolve(strict=True) - output = args.output.resolve() - campaign = load_json(campaign_path) - reference_doc = load_json(reference_path) - design = load_json(design_path) - references = reference_doc.get("cases") - if not isinstance(references, dict): - raise ValueError(f"reference document has no cases object: {reference_path}") - adapter = args.adapter or str(campaign.get("adapter", "")) - if adapter not in {"easyfoam", "foamagent"}: - raise ValueError("--adapter must be easyfoam or foamagent") - selected = select_case_ids(campaign, args.case_id) - if not selected: - raise ValueError("no execution-pass incomplete cases selected from campaign") - missing_reference = sorted(set(selected) - set(references)) - if missing_reference: - raise ValueError("reference document is missing selected cases: " + ", ".join(missing_reference)) - - recovered: dict[str, dict[str, Any]] = {} - scored_rows: dict[str, dict[str, Any]] = {} - for case_id in selected: - source = campaign["cases"][case_id] - raw_case_dir = source.get("artifact", {}).get("case_dir") - if not isinstance(raw_case_dir, str) or not raw_case_dir: - raise ValueError(f"{case_id}: campaign record has no artifact.case_dir") - case_dir = Path(raw_case_dir).resolve() - if not case_dir.is_dir(): - raise ValueError(f"{case_id}: artifact case directory does not exist: {case_dir}") - try: - item = recover_case(case_id, case_dir, references[case_id], adapter=adapter, design=design) - except Exception as exc: - item = compact_failure_record(source, case_id, references[case_id], design, adapter, exc) - source_qoi = source.get("qoi", {}) if isinstance(source.get("qoi"), dict) else {} - source_comparison = source_qoi.get("comparison", {}) if isinstance(source_qoi.get("comparison"), dict) else {} - source_candidate = source_qoi.get("candidate", {}) if isinstance(source_qoi.get("candidate"), dict) else {} - item.setdefault("original", {}).update({ - "campaign_status": source_qoi.get("status"), - "campaign_missing_metrics": source_comparison.get("missing_metrics", []), - "campaign_out_of_tolerance_metrics": source_comparison.get("out_of_tolerance_metrics", []), - "campaign_candidate_missing_metrics": source_candidate.get("missing_metrics", []), - }) - recovered[case_id] = item - scored_rows[case_id] = recovery_score_record(source, item) - - overall = aggregate_results(list(scored_rows.values())) - families: dict[str, dict[str, Any]] = {} - for family in sorted({row["family"] for row in scored_rows.values()}): - families[family] = aggregate_results([row for row in scored_rows.values() if row["family"] == family]) - recovery_statuses = [item["recovery"]["status"] for item in recovered.values()] - comparison_statuses = [item["comparison"].get("status") for item in recovered.values()] - summary = { - "schema_version": RECOVERY_VERSION, - "generated_at": utc_now(), - "source_campaign": str(campaign_path), - "adapter": adapter, - "selected_case_count": len(selected), - "original_incomplete_case_count": len(selected), - "final_incomplete_case_count": sum("incomplete" in str(status) for status in comparison_statuses), - "recovered_complete_count": recovery_statuses.count("recovered_complete"), - "recovered_out_of_tolerance_count": recovery_statuses.count("recovered_out_of_tolerance"), - "irrecoverable_incomplete_count": recovery_statuses.count("irrecoverable_incomplete"), - "comparison_status_counts": {status: comparison_statuses.count(status) for status in sorted(set(comparison_statuses))}, - "overall": overall, - "families": families, - "recovery_families": family_summary(recovered), - } - manifest = { - "schema_version": RECOVERY_VERSION, - "generated_at": summary["generated_at"], - "scope": "frozen execution-pass cases originally classified incomplete", - "solver_rerun": False, - "source_campaign": document_checksum(campaign_path), - "reference_contract": document_checksum(reference_path), - "design_contract": document_checksum(design_path), - "adapter": adapter, - "selected_case_ids": selected, - "selection_rule": "execution.status == pass and 'incomplete' in qoi.status", - "case_statuses": {case_id: item["recovery"] for case_id, item in recovered.items()}, - } - campaign_recovery = { - "schema_version": RECOVERY_VERSION, - "generated_at": summary["generated_at"], - "dataset": campaign.get("dataset", "extended"), - "adapter": adapter, - "run_root": campaign.get("run_root"), - "source_campaign": str(campaign_path), - "reference_qois": str(reference_path), - "design_contract": str(design_path), - "scope": "selected execution-pass incomplete cases only", - "overall": overall, - "families": families, - "summary": summary, - "cases": scored_rows, - } - candidate_document = { - "schema_version": "foambench.qoi.recovered_candidate.v1", - "generated_at": summary["generated_at"], - "source_campaign": str(campaign_path), - "reference_qois": str(reference_path), - "cases": {case_id: item["candidate"] for case_id, item in recovered.items()}, - } - comparison_document = { - "schema_version": "foambench.qoi.recovered_comparison.v1", - "generated_at": summary["generated_at"], - "source_campaign": str(campaign_path), - "reference_qois": str(reference_path), - "cases": {case_id: item["comparison"] for case_id, item in recovered.items()}, - } - output.mkdir(parents=True, exist_ok=True) - write_json(output / "campaign_evaluation.json", campaign_recovery) - write_json(output / "recovered_candidate_qois.json", candidate_document) - write_json(output / "recovered_comparisons.json", comparison_document) - write_json(output / "manifest.json", manifest) - write_json(output / "summary.json", summary) - for case_id, item in recovered.items(): - family, variant = case_id.split("/", 1) - write_json(output / "cases" / family / f"{variant}.json", item) - print( - f"frozen QoI recovery: {output} " - f"selected={len(selected)} final_incomplete={summary['final_incomplete_case_count']} " - f"recovered_complete={summary['recovered_complete_count']} " - f"recovered_out_of_tolerance={summary['recovered_out_of_tolerance_count']} " - f"irrecoverable={summary['irrecoverable_incomplete_count']}" - ) - return 0 - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--campaign", required=True, type=Path, help="existing campaign_evaluation.json") - parser.add_argument("--reference-qois", type=Path, default=DEFAULT_REFERENCE) - parser.add_argument("--design", type=Path, default=DEFAULT_DESIGN) - parser.add_argument("--adapter", choices=("easyfoam", "foamagent")) - parser.add_argument("--output", required=True, type=Path) - parser.add_argument("--case-id", action="append", help="optional repeated case selection") - args = parser.parse_args() - return run(args) - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, ValueError, json.JSONDecodeError) as exc: - print(f"recover_extbench_qoi.py: error: {exc}", file=sys.stderr) - raise SystemExit(2) diff --git a/benchmarks/scripts/validate_benchmark_assets.py b/benchmarks/scripts/validate_benchmark_assets.py deleted file mode 100644 index 4fa38add9a5e1437c7d0ede457d068ba76dc138a..0000000000000000000000000000000000000000 --- a/benchmarks/scripts/validate_benchmark_assets.py +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env python3 -"""Validate bundled FoamBench assets and benchmark references.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import re -from pathlib import Path -from typing import Any - - -LOCAL_PATH = re.compile(r"/(?:opt|data1|home)/") - - -def sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def iter_strings(value: Any): - if isinstance(value, dict): - for child in value.values(): - yield from iter_strings(child) - elif isinstance(value, list): - for child in value: - yield from iter_strings(child) - elif isinstance(value, str): - yield value - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--benchmark", type=Path, required=True) - parser.add_argument("--manifest", type=Path, required=True) - args = parser.parse_args() - - benchmark_path = args.benchmark.resolve(strict=True) - manifest_path = args.manifest.resolve(strict=True) - benchmark = json.loads(benchmark_path.read_text(encoding="utf-8")) - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - assets = manifest.get("assets") - if not isinstance(benchmark, dict) or not isinstance(assets, dict): - raise ValueError("benchmark and asset manifest roots must be objects") - - local_paths = [text for text in iter_strings(benchmark) if LOCAL_PATH.search(text)] - if local_paths: - raise ValueError(f"benchmark contains {len(local_paths)} machine-local absolute path(s)") - - repo_root = benchmark_path.parent.parent - referenced: set[str] = set() - case_count = 0 - reference_count = 0 - for case_id, case in benchmark.items(): - declarations = case.get("_external_assets", []) - if declarations: - case_count += 1 - for declaration in declarations: - asset_id = declaration.get("asset_id") - target = Path(declaration.get("target", "")) - if not isinstance(asset_id, str) or asset_id not in assets: - raise ValueError(f"{case_id}: unknown asset_id {asset_id!r}") - if target.is_absolute() or ".." in target.parts: - raise ValueError(f"{case_id}: unsafe asset target {str(target)!r}") - referenced.add(asset_id) - reference_count += 1 - - for asset_id, record in assets.items(): - relative = Path(record.get("path", "")) - if relative.is_absolute() or ".." in relative.parts: - raise ValueError(f"{asset_id}: unsafe manifest path") - path = repo_root / relative - if not path.is_file(): - raise ValueError(f"{asset_id}: missing file {path}") - expected = record.get("sha256") - if not isinstance(expected, str) or sha256(path) != expected: - raise ValueError(f"{asset_id}: SHA-256 mismatch") - - unreferenced = sorted(set(assets) - referenced) - if unreferenced: - raise ValueError("unreferenced manifest assets: " + ", ".join(unreferenced)) - print(f"validated {len(assets)} assets, {reference_count} references, and {case_count} cases") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/docs/DATA_FORMAT.md b/docs/DATA_FORMAT.md deleted file mode 100644 index 1797db5b4d6831a8bdc1c4be45d1c2735d3ce39c..0000000000000000000000000000000000000000 --- a/docs/DATA_FORMAT.md +++ /dev/null @@ -1,31 +0,0 @@ -# Data format and relationships - -The Hub table is a lossless projection of each source task's `usr_requirement`, with metadata added. It does not replace the original benchmark JSON documents. - -| Table field | Type | Meaning | -| --- | --- | --- | -| `task_id` | string | Unique across tracks: `:` | -| `track` | string | `extended`, `basic`, or `advanced` | -| `case_id` | string | Original source identifier; Advanced IDs need not contain `/` | -| `family` | string | Source ID prefix before `/`, or the complete unsuffixed ID | -| `task_origin` | string | Original ExtFoamBench task versus inherited/adapted FoamBench task | -| `usr_requirement` | string | Original natural-language requirement, unchanged | -| `external_asset_ids` | list of strings | Keys in `benchmarks/assets/manifest.json` | - -## Joining tasks to evaluation data - -Use `(track, case_id)` as the key. The evaluator profile at `benchmarks/evaluation/profiles/.json` points to the exact benchmark and reference-QoI JSON files. The original case documents are dictionaries keyed by `case_id`. The reference-QoI documents and numerical-statistics documents contain a `cases` dictionary keyed by that same identifier. - -Reference case records include file contents under keys such as `0/U`, `system/controlDict`, and `Allrun`. Extended records may also have `_external_assets` and `reference_subcases`. These are reference configurations and must not be exposed to the solving agent as task input. - -Reference-QoI records preserve `principal_metrics`, `qois`, `tolerances`, and additional track-specific metadata. Scalar, profile, history, event and branch structures stay in their original JSON representation; converting them into one flat scalar column would lose evaluation semantics. - -Extended measurement definitions are in the `cases` mapping of `FoamBench_extended_openfoam13_measurement_specs.json`. These contain measurement definitions rather than numerical reference answers. Family-level design is in the `families` list of `FoamBench_extended_openfoam13_qoi_design.json`. - -Numerical diagnostics are in `benchmarks/reference_statistics/.json`. An empty object denotes unavailable reference statistics. Do not equate it with zero residual, a passing check, or a missing reference-QoI record. Historical `log_paths` identify provenance; the named raw logs are not distributed. - -## Hugging Face configurations - -`extended` (default, 100 tasks), `basic` (110), `advanced` (16), and `all` (226) each expose one `test` split. These configurations distinguish task provenance and evaluation tracks. They are not training splits or the historical construction/validation/held-out split for skill evolution. - -The complete package retains legacy `FoamBench_extended_*` filenames for compatibility with the supplied scorer. On the dataset page, this track is named ExtFoamBench. diff --git a/docs/EVALUATION.md b/docs/EVALUATION.md deleted file mode 100644 index f8fadbb17c3ac523a4b1d5749ee5be37154003df..0000000000000000000000000000000000000000 --- a/docs/EVALUATION.md +++ /dev/null @@ -1,49 +0,0 @@ -# Evaluation protocol and executable scorer - -The EasyFoam authors developed the evaluation framework and generated the offline reference data for all three tracks. Basic and Advanced task definitions remain credited to upstream FoamBench. - -## Metrics and output fields - -| Concept | Report field under `overall` | Denominator | -| --- | --- | --- | -| ECR | `execution_pass_rate` | Complete assigned profile membership | -| Numerical acceptance | `numerical_pass_rate_all_tasks` | Complete assigned profile membership | -| Physical/QoI acceptance | `physics_grounded_qoi_pass_rate_all_tasks` | Complete assigned profile membership | -| TAR / joint acceptance | `end_to_end_pass_rate` | Complete assigned profile membership | - -Execution must pass before Numerical/QoI task acceptance is credited. All mandatory physical metrics must pass; a continuous quality score cannot override a failed mandatory metric. Missing rollouts remain in the denominator. Conditional-on-execution rates are separately reported. Full-profile evaluation of a one-task run counts the other tasks as missing; inspect the case-level result when testing one task. - -## Evaluate existing artifacts - -From the repository root, after installing `requirements.txt`: - -```bash -python -m benchmarks.evaluation evaluate --profile benchmarks/evaluation/profiles/extended.json --adapter easyfoam --run-root /path/to/existing/run --output outputs/evaluation -``` - -`/path/to/existing/run` is user-supplied data, not a bundled example. The adapters are `easyfoam`, `foamagent`, `chatcfd`, and `coding-agent`; they normalize different retained-run layouts. Adapter selection alone does not make an arbitrary folder compatible: consult `benchmarks/evaluation/adapters/` for required artifacts. No agent runtime or model call is performed by this command. - -Outputs include `campaign_evaluation.json`, `summary.json`, `summary.csv`, `cases.csv`, and per-case JSON reports. ECR and TAR are fractions from 0 to 1; multiply by 100 for percentages. - -## QoI and numerical evidence - -The supplied Extended design specifies principal versus diagnostic quantities and task branches. Measurement specs define the physical quantity, spatial support, and time semantics; the reference records supply comparison values and tolerances. Structured comparison preserves curves, events and branch-dependent responses, rather than replacing them with generic field extrema. - -Numerical checks use retained logs/fields and applicable reference statistics. Missing reference statistics are explicitly recorded. The evidence contract supports a validated manifest, retained-field derivation, semantic path discovery, and unresolved-evidence reporting. A filename match alone does not establish units, physical support, or time alignment. - -## Native tools and preparation - -Most offline checks use Python and retained outputs. Static planar-face meshes can supply cell centers/volumes directly. Some geometry or topology-changing histories require native OpenFOAM measurement tools. In particular, the supplied extractor may invoke `foamPostProcess` for missing time-local `C/Vc` fields; offline evaluation is not an unconditional read-only/no-OpenFOAM guarantee. - -Use copies of valuable retained runs when derived fields may be generated. `--prepare` explicitly prepares measurement fields and writes preparation logs. `--check-mesh` enables a fresh mesh audit when required. These options do not rerun the CFD agent. Actual OpenFOAM tool execution was not verified on Windows during dataset packaging. - -## Current implementation boundaries - -- Extended reference tolerances retain `joint_physical_admissibility_and_reference_response_provisional`. This release does not silently upgrade them to calibrated uncertainty bounds. -- The supplied Basic/Advanced scorer describes mandatory physical ranges/signatures, with structured profiles/histories/shock locations retained as reference-agreement diagnostics. The paper also describes profile acceptance criteria. Exact manuscript-to-implementation alignment must be checked before claiming identical historical scores. -- Spatial profile coverage counts profile-field combinations rather than individual reference sampling points. -- Early-convergence markers can satisfy the execution stop condition. -- Historical scalar-QoI and older numerical-contract results are not automatically comparable to this version. -- Historical agent outputs and paper result archives are absent. This release enables reuse of the supplied benchmark/evaluator and does not itself replay the manuscript tables. - -When comparing systems, freeze the same task membership, reference records, scorer version, and acceptance rules for every method. Changing these defines a different evaluation protocol. diff --git a/docs/PROVENANCE.md b/docs/PROVENANCE.md deleted file mode 100644 index 9baad0a99452971113e8ebf63913ee16a789c0e6..0000000000000000000000000000000000000000 --- a/docs/PROVENANCE.md +++ /dev/null @@ -1,29 +0,0 @@ -# Contribution attribution and provenance - -## Original EasyFoam contributions - -- **ExtFoamBench task design:** 100 tasks in ten families, with task variants covering physical settings and workflows. -- **Evaluation resources:** execution/numerical/physical acceptance framework, TAR reporting, task-specific QoI measurement and acceptance specifications, evidence contracts, and the supplied evaluation implementation. -- **Offline reference data:** reference simulations and derived QoI/numerical-statistics records generated by the EasyFoam authors for **Extended, Basic, and Advanced**. - -Original task design does not imply that every geometry, tutorial input, physical problem, or underlying simulation tool was created from scratch. - -## Inherited task definitions - -The **110 Basic and 16 Advanced tasks** originate from FoamBench / CFDLLMBench. They are redistributed here as OpenFOAM Foundation 13 adaptations to support the new evaluation and reference-data resources. They are not claimed as original EasyFoam tasks. - -Upstream: https://github.com/NLR-Theseus/cfdllmbench (the former NREL-Theseus URL redirects here). - -The upstream BSD-3-Clause notice is retained at `LICENSES/FoamBench-BSD-3-Clause.txt`. Cite the upstream work when using these tracks, in addition to EasyFoam when using its evaluator or offline reference data. - -## CFD sources and geometry - -The EasyFoam paper's Appendix A describes source cases including dyfluid tutorials, OpenFOAM tutorial geometries, and CFD-China material, with additional physical references. Consult the paper for family-level scientific attribution; this release does not invent more precise upstream revisions than the supplied source records establish. - -Seven OpenFOAM 13 geometry assets are accompanied by their original tutorial locations and SHA-256 digests in `benchmarks/assets/manifest.json`. The original asset README and GPL text are retained. Existing third-party notices within case text remain unchanged. DrivAer is an existing geometry, not an original EasyFoam geometry. - -## Snapshot and transformation - -`metadata/source_manifest.json` identifies the original files copied from the supplied research snapshot, with byte hashes. The HF release does not modify their contents, scoring code, reference values or tolerances. It adds task tables, documentation, inspection/verification utilities, and release metadata. Its evaluator README is tailored to this standalone distribution; agent campaign/evolution launchers are not bundled. - -The JSONL tables are deterministic projections of the original task requirements, with track/origin metadata and asset identifiers. `metadata/coverage.json` records reference-data availability. Raw simulation provenance cannot be reconstructed solely from compact reference summaries; raw logs and solution fields are not present in this package. diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md deleted file mode 100644 index f8b1b8ee13a4d283c307afca38eee81d388c7f8d..0000000000000000000000000000000000000000 --- a/docs/RELEASE_NOTES.md +++ /dev/null @@ -1,27 +0,0 @@ -# Release 1.0.0 - -Prepared on 2026-10-12 from the supplied EasyFoam research snapshot. - -## Included - -- 100 original ExtFoamBench tasks as the default Hub configuration. -- 110 inherited Basic and 16 inherited Advanced tasks, separately attributed. -- EasyFoam evaluation/reference resources for all 226 tasks. -- Unmodified source JSON, geometry assets, evaluation Python files, and required schemas. -- Hub-readable task tables, standalone documentation, inspection/verification commands, source hashes and coverage metadata. - -## Coverage and limits - -All tracks have matching task/reference-QoI case membership. Numerical reference statistics are empty for `nozzleCDV/4` and all ten `riemann2D` tasks (11 total). Conditional or diagnostic availability should be read from individual records, not inferred from case counts. - -Raw solution fields/logs, historical agent rollouts, Initial/Evolved checkpoints, historical evolution split manifests, and paper-result archives are outside this release. The reference-repeat/physical-negative-control and tolerance-sensitivity experiments described in the paper are not supplied here as independent raw result archives. - -Embedded protocol statuses, including provisional Extended tolerances, are preserved. The release version identifies a packaged snapshot; it is not a certification of exact historical manuscript reproduction. See `EVALUATION.md` for protocol boundaries. - -## Validation - -See `metadata/validation.json` for checks executed during packaging and `SHA256SUMS` for file integrity. These checks concern data consistency, loading and offline software behavior, not a new CFD reference rerun or a model benchmark campaign. - -## Updating - -If tasks, references, measurement definitions or scorer behavior change, publish a new version and describe the change. Keep a tag/revision identifying each evaluated release. Updating display text alone must not silently replace scientific data associated with a reported result. diff --git a/examples/inspect_task.py b/examples/inspect_task.py deleted file mode 100644 index a1672cc97e601402255bd68c776cad40dfa27976..0000000000000000000000000000000000000000 --- a/examples/inspect_task.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Inspect a task and evaluator-side reference summary without third-party dependencies.""" -import argparse -import json -from pathlib import Path -ROOT = Path(__file__).resolve().parents[1] -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--track', choices=('extended','basic','advanced'), default='extended') - parser.add_argument('--case-id', default='nozzleCDV/1') - args = parser.parse_args() - rows = [json.loads(line) for line in (ROOT/f'data/{args.track}.jsonl').read_text(encoding='utf-8').splitlines()] - row = next((x for x in rows if x['case_id']==args.case_id),None) - if row is None: parser.error(f'Unknown case {args.case_id!r} for {args.track}') - profile = json.loads((ROOT/f'benchmarks/evaluation/profiles/{args.track}.json').read_text(encoding='utf-8')) - refs = json.loads((ROOT/profile['reference_qois_path']).read_text(encoding='utf-8'))['cases'] - stats = json.loads((ROOT/f'benchmarks/reference_statistics/{args.track}.json').read_text(encoding='utf-8'))['cases'] - result = {'task':row,'reference_metric_names':refs[args.case_id].get('principal_metrics',[]),'reference_qoi_file':profile['reference_qois_path'],'reference_case_file':profile['benchmark_path'],'numerical_reference_statistics_available':bool(stats[args.case_id])} - if args.track=='extended': - specs=json.loads((ROOT/'benchmarks/FoamBench_extended_openfoam13_measurement_specs.json').read_text(encoding='utf-8')) - result['measurement_spec']=specs['cases'][args.case_id] - print(json.dumps(result,indent=2,ensure_ascii=True)) -if __name__=='__main__': main() diff --git a/metadata/families.json b/metadata/families.json deleted file mode 100644 index b4bb2725a57c307ac7d52f2408131d0c0762d064..0000000000000000000000000000000000000000 --- a/metadata/families.json +++ /dev/null @@ -1,187 +0,0 @@ -[ - { - "track": "extended", - "family": "ERCOFTA_pump", - "task_count": 10 - }, - { - "track": "extended", - "family": "MRF_stirredReactor", - "task_count": 10 - }, - { - "track": "extended", - "family": "aerofoilNACA0012", - "task_count": 10 - }, - { - "track": "extended", - "family": "compressibleBubbleCollapse", - "task_count": 10 - }, - { - "track": "extended", - "family": "drivaerFastback", - "task_count": 10 - }, - { - "track": "extended", - "family": "nozzleCDV", - "task_count": 10 - }, - { - "track": "extended", - "family": "riemann2D", - "task_count": 10 - }, - { - "track": "extended", - "family": "risingBubble", - "task_count": 10 - }, - { - "track": "extended", - "family": "supersonicCrossJet", - "task_count": 10 - }, - { - "track": "extended", - "family": "yPlusVerification", - "task_count": 10 - }, - { - "track": "basic", - "family": "BernardCells", - "task_count": 10 - }, - { - "track": "basic", - "family": "Cavity", - "task_count": 10 - }, - { - "track": "basic", - "family": "Cylinder", - "task_count": 10 - }, - { - "track": "basic", - "family": "counterFlowFlame2D", - "task_count": 10 - }, - { - "track": "basic", - "family": "damBreakWithObstacle", - "task_count": 10 - }, - { - "track": "basic", - "family": "forwardStep", - "task_count": 10 - }, - { - "track": "basic", - "family": "obliqueShock", - "task_count": 10 - }, - { - "track": "basic", - "family": "pitzDaily", - "task_count": 10 - }, - { - "track": "basic", - "family": "shallowWaterWithSquareBump", - "task_count": 10 - }, - { - "track": "basic", - "family": "squareBend", - "task_count": 10 - }, - { - "track": "basic", - "family": "wedge", - "task_count": 10 - }, - { - "track": "advanced", - "family": "Cavity_LES", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Cavity_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Cavity_geometry_1", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Cylinder_LES", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Cylinder_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Diamond_Obstacle_KOMEGASST", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Diamond_Obstacle_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Double_Square_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Rectangular_Obstacle_KOMEGASST", - "task_count": 1 - }, - { - "track": "advanced", - "family": "Rectangular_Obstacle_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "counterFlowFlame2D_KE", - "task_count": 1 - }, - { - "track": "advanced", - "family": "counterFlowFlame2D_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "nozzleFlow2D_SA", - "task_count": 1 - }, - { - "track": "advanced", - "family": "obliqueShock_KE", - "task_count": 1 - }, - { - "track": "advanced", - "family": "obliqueShock_LES", - "task_count": 1 - }, - { - "track": "advanced", - "family": "wedge_SA", - "task_count": 1 - } -] diff --git a/metadata/release.json b/metadata/release.json index e314f57ca437dfd14cee90d6fc6f7421efb22545..81f361b8c1304b923e0cabdaefafcf8c0368b3de 100644 --- a/metadata/release.json +++ b/metadata/release.json @@ -1,5 +1,5 @@ { - "release_version": "1.0.0", + "release_version": "1.1.0", "release_date": "2026-10-12", "dataset_name": "ExtFoamBench", "new_task_count": 100, @@ -14,5 +14,7 @@ "protocol_status": "Frozen supplied implementation; preserve embedded contract versions and provisional tolerance status", "historical_paper_result_reproduction_certified": false, "huggingface_repo_id": "Eurus132/ExtFoamBench", - "huggingface_url": "https://huggingface.co/datasets/Eurus132/ExtFoamBench" + "huggingface_url": "https://huggingface.co/datasets/Eurus132/ExtFoamBench", + "change_type": "Bilingual presentation and optional-tool packaging; scientific data and scoring implementation unchanged", + "evaluation_tools_archive": "tools/evaluation-tools.zip" } diff --git a/metadata/source_manifest.json b/metadata/source_manifest.json index 378f33d7409ed1995d720e48f49554523abadcb3..703bd4efc1e100aa0af029b2afe47518c3b25572 100644 --- a/metadata/source_manifest.json +++ b/metadata/source_manifest.json @@ -1,418 +1,476 @@ -{ - "schema_version": "extfoambench.source-manifest.v1", - "source_description": "User-supplied EasyFoam research source snapshot", - "copied_files_byte_identical": true, - "files": [ - { - "path": "benchmarks/__init__.py", - "sha256": "b5375698c34737e22fabdf9cea774287609ce6edc3fa8c73791c3749e89c3bca", - "bytes": 49 - }, - { - "path": "benchmarks/assets/manifest.json", - "sha256": "0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f", - "bytes": 2275 - }, - { - "path": "benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz", - "sha256": "0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe", - "bytes": 2839115 - }, - { - "path": "benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz", - "sha256": "f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7", - "bytes": 860951 - }, - { - "path": "benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz", - "sha256": "02f25f876414a9a4cbdb9cfb08da9916ac49f7851d4658067abc371447f882ce", - "bytes": 940038 - }, - { - "path": "benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz", - "sha256": "9fd098e03da6178852d4f9837bc06d2f24599065644f951b481907513d835d90", - "bytes": 112656 - }, - { - "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj", - "sha256": "612cb86bfa2c842444ba86f203af31c712da3e807ed537013fefff8ab40f42a2", - "bytes": 646 - }, - { - "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj", - "sha256": "d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117", - "bytes": 534 - }, - { - "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj", - "sha256": "d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b", - "bytes": 792 - }, - { - "path": "benchmarks/assets/README.md", - "sha256": "b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540", - "bytes": 780 - }, - { - "path": "benchmarks/evaluation/__init__.py", - "sha256": "6488b16a905c9e6ae7d33f06bd55fbf276c917df54f53984f4f4ba3504f1710d", - "bytes": 878 - }, - { - "path": "benchmarks/evaluation/__main__.py", - "sha256": "b965c21513f41de952a6f983700e961845746fd1b3df1c56ab1e7a612ca8be8f", - "bytes": 242 - }, - { - "path": "benchmarks/evaluation/adapters/__init__.py", - "sha256": "dc4d21e3f45bd036f5a0d23ef2e9bf4406f4e34a76437472e3b9bbb25ff5bd40", - "bytes": 631 - }, - { - "path": "benchmarks/evaluation/adapters/chatcfd.py", - "sha256": "b8933e85b63abc1c792fdad5ddd76dedb2e0344e38ce6d2e8991ee760e7419ce", - "bytes": 4175 - }, - { - "path": "benchmarks/evaluation/adapters/coding_agent.py", - "sha256": "cdf7354b586bc67898bc2f3b44292aacd7fc9d7a58f0544efa9c603ac69a8f11", - "bytes": 2193 - }, - { - "path": "benchmarks/evaluation/adapters/common.py", - "sha256": "260f1efc5943ef598fa02b3dae130101961fc0c2ce22080abec2b4836d850d63", - "bytes": 2764 - }, - { - "path": "benchmarks/evaluation/adapters/easyfoam.py", - "sha256": "5ffd5d35e2431ae568b3e78b647aa85d091d01c124bcdacedcb6e68d4474339b", - "bytes": 5282 - }, - { - "path": "benchmarks/evaluation/adapters/foamagent.py", - "sha256": "a33bcc116b3043c2b70a1342d0d3c71c30eac42f1ea286ca08b543f0e6496c40", - "bytes": 2829 - }, - { - "path": "benchmarks/evaluation/aggregate.py", - "sha256": "513e63ba562da617ef6f665c452bec8c2d308ca1e716629ac6ca360494724849", - "bytes": 5461 - }, - { - "path": "benchmarks/evaluation/basic_advanced.py", - "sha256": "1f8db418394f143b9ecb780eec4118ebde99885130cc30552f64735c5ea93307", - "bytes": 41291 - }, - { - "path": "benchmarks/evaluation/cli.py", - "sha256": "9d4a6bc429e0ef9a751384be2d777101f7f2d91dfee7edbdc6e3e0d771154ccd", - "bytes": 2994 - }, - { - "path": "benchmarks/evaluation/comparison.py", - "sha256": "eb44b8d8020e5f9c22f19880884ade107afd395246b0d9ad8f78b9a6a4d30280", - "bytes": 38842 - }, - { - "path": "benchmarks/evaluation/evidence_contract.py", - "sha256": "272bc7e44456c330fd7ac97685279538f8b0715d8aae3deb88366314fea1efc9", - "bytes": 5651 - }, - { - "path": "benchmarks/evaluation/execution.py", - "sha256": "cd2e1ff40d7dcb830b4230d86e143652d1d93a1b007019e3583384486a242604", - "bytes": 2772 - }, - { - "path": "benchmarks/evaluation/extbench.py", - "sha256": "78cd982892e8ede31ee7e951cec87c7c595813a975bf4b111ea0d980b37633b5", - "bytes": 81030 - }, - { - "path": "benchmarks/evaluation/field_candidate.py", - "sha256": "51d8bb69224ed37ae0de073700c5f9cfd403095f53fa16d633a3eb777e1a0b13", - "bytes": 500 - }, - { - "path": "benchmarks/evaluation/field_extractor.py", - "sha256": "95900ed3c04bc04846e2dd2dd6ae4f98c2fb0aba4b85978199c20b1a444f4c0e", - "bytes": 17099 - }, - { - "path": "benchmarks/evaluation/foam.py", - "sha256": "3c6a38077eecae484f264cd46478b21687b21ca33f543f4f041d954bdfa98205", - "bytes": 2950 - }, - { - "path": "benchmarks/evaluation/foam_arrays.py", - "sha256": "80bd6344a529cc574693053b97b14cccb209c40a099b01a942f8654ddf24c614", - "bytes": 5028 - }, - { - "path": "benchmarks/evaluation/foam_field.py", - "sha256": "ce3a16fb9e29587eaabd816bdfda832bcdc83e3744ac233e1365b3350146ddf9", - "bytes": 7085 - }, - { - "path": "benchmarks/evaluation/foam_io.py", - "sha256": "a043e6a9022c30aea8fa94b8f753f1608804c526644a1f851c23453b7482727a", - "bytes": 865 - }, - { - "path": "benchmarks/evaluation/frozen_recovery.py", - "sha256": "55bd6f2c61c4e3cef677e4cf428433ae9e3fb8b778efc10bb281e814fc2c5d05", - "bytes": 33511 - }, - { - "path": "benchmarks/evaluation/health.py", - "sha256": "1cf606f832b4410908faaddeb439d0ca768cf134f4832f87f901c113a17d25da", - "bytes": 2784 - }, - { - "path": "benchmarks/evaluation/io.py", - "sha256": "83c7166635578af9b5ed7eaeac96c06df7b65ab0936dc39a5310e5c42a6003e4", - "bytes": 1032 - }, - { - "path": "benchmarks/evaluation/measurement_specs.py", - "sha256": "eb16a2dbd37f6ddb112adb6a92f5b3c1b8aa6295592d8f5430d7d3a24f0ff334", - "bytes": 1846 - }, - { - "path": "benchmarks/evaluation/mesh.py", - "sha256": "7f35b96268d62aca315d70f2c14a6bdda602bb51b70666fb1fa7667bc88a0cbf", - "bytes": 2594 - }, - { - "path": "benchmarks/evaluation/models.py", - "sha256": "75cdb75a677e47c786769d541e019085eb84a3de73b0539647143d869115d8ef", - "bytes": 3077 - }, - { - "path": "benchmarks/evaluation/numerical.py", - "sha256": "f87a0946dc0d29c656e362d56e3aa0cc68c495d6daecf5d17f429a916e6468ff", - "bytes": 11958 - }, - { - "path": "benchmarks/evaluation/pipeline.py", - "sha256": "4921843f568f4ff06d4f02d270da87a8833d34dac2a448aae1a090caa68d2206", - "bytes": 6887 - }, - { - "path": "benchmarks/evaluation/preparation.py", - "sha256": "95d54ca4f2dea32c9223cc092db6ac1e93fd045ab3a47a965c10f035b6211bd3", - "bytes": 7412 - }, - { - "path": "benchmarks/evaluation/profiles/advanced.json", - "sha256": "5e8791bf4840c8ea18d1f5c70ca922b100e7694a07e75f2c7fb47a9b834137a2", - "bytes": 575 - }, - { - "path": "benchmarks/evaluation/profiles/basic.json", - "sha256": "a9976b3f6d2125a9ada142614052eb7d4cbc263ac8c1781f7b3fd4f0e567e2e4", - "bytes": 566 - }, - { - "path": "benchmarks/evaluation/profiles/extended.json", - "sha256": "8bbbc58e77b09da38eef2565e95b8d69c88b1db21ac696e9991b887e2394af85", - "bytes": 625 - }, - { - "path": "benchmarks/evaluation/profiles.py", - "sha256": "5cf9b70b1ec3ae040d2e3b478e61d5c4e1bf838106621e3d3f7c1827670841a5", - "bytes": 3329 - }, - { - "path": "benchmarks/evaluation/qoi.py", - "sha256": "305eba7114c1ae50521c05aa12ad95c9db35304af33665ea5e655bfd8f17c51b", - "bytes": 3096 - }, - { - "path": "benchmarks/evaluation/qoi_glue.py", - "sha256": "af47ba704a5edcd8490261a7ddba07fe9204473ae4d19d3b09a7e4f7fb9f548f", - "bytes": 20253 - }, - { - "path": "benchmarks/evaluation/qoi_reference.py", - "sha256": "99a6af4a1f422bbb4f808602b744b2fa3660b4a7740e39ab24f3f4fcad9bda6b", - "bytes": 24058 - }, - { - "path": "benchmarks/evaluation/reference.py", - "sha256": "627725f472e89d9b97ff8cedf23d2ac92097a53f27f23d648f7be0bf943d33b1", - "bytes": 1684 - }, - { - "path": "benchmarks/evaluation/reporting.py", - "sha256": "159655e9dadb4367a59a7ea1a804856c5280b3bc025c2892f06fd0535e265bae", - "bytes": 3765 - }, - { - "path": "benchmarks/evaluation/retained_fields.py", - "sha256": "0c54e9671b9f7353cbc28ecf9798d678db4bfacaa5f7c184bf4e45ebef9ec4a7", - "bytes": 14447 - }, - { - "path": "benchmarks/evaluation/schema.py", - "sha256": "477332e61a0f668ff51db9817ec874706051d37c2dedf65b5ca43b73435c9583", - "bytes": 731 - }, - { - "path": "benchmarks/evaluation/stability.py", - "sha256": "b9ba1b4c4583e9b393c699d47bab71a82aed159519408062b631147bd70d25a5", - "bytes": 1878 - }, - { - "path": "benchmarks/FoamBench_advanced_openfoam13_fixed_final.json", - "sha256": "74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027", - "bytes": 306717 - }, - { - "path": "benchmarks/FoamBench_advanced_openfoam13_reference_qois.json", - "sha256": "31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63", - "bytes": 357142 - }, - { - "path": "benchmarks/FoamBench_basic_openfoam13_fixed_final.json", - "sha256": "50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523", - "bytes": 2026359 - }, - { - "path": "benchmarks/FoamBench_basic_openfoam13_reference_qois.json", - "sha256": "6f91688f7c97b3ef6b8191256c14af7f8accb168e8d384aba763681e01c34724", - "bytes": 2031952 - }, - { - "path": "benchmarks/FoamBench_extended_openfoam13_evidence_contract.v1.json", - "sha256": "4f0eae169c7d575da991d7c23c313ce6e4971887fbbaffbbbf9bc65105c2b676", - "bytes": 2985 - }, - { - "path": "benchmarks/FoamBench_extended_openfoam13_fixed.json", - "sha256": "1e247ddfec51cc2a716ca5690661acb367a3f919ceb1a99fd2d40123cb1b4d5b", - "bytes": 2260175 - }, - { - "path": "benchmarks/FoamBench_extended_openfoam13_measurement_specs.json", - "sha256": "0bddaf5b3abc3569d105c89cbdeef8cf3c4cce381ba9f7a3d622cadadaf8a68b", - "bytes": 148565 - }, - { - "path": "benchmarks/FoamBench_extended_openfoam13_qoi_design.json", - "sha256": "fb1db5034a1d2688ad360c6b0810bab68c33d4c6dc1dc5bec29095e93b077393", - "bytes": 20291 - }, - { - "path": "benchmarks/FoamBench_extended_openfoam13_reference_qois.json", - "sha256": "65e5c2d9968d1dbc798d585c9398c6fba2646f7463909040ae0c039727c8a1f9", - "bytes": 7742495 - }, - { - "path": "benchmarks/reference_statistics/advanced.json", - "sha256": "6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b", - "bytes": 25631 - }, - { - "path": "benchmarks/reference_statistics/basic.json", - "sha256": "3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72", - "bytes": 148470 - }, - { - "path": "benchmarks/reference_statistics/extended.json", - "sha256": "637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9", - "bytes": 154741 - }, - { - "path": "benchmarks/scripts/__init__.py", - "sha256": "5c1f78137dc1c7032363bb0ebf96cf01f19c9f2ffb48abd7fef39cb8b54a9f82", - "bytes": 87 - }, - { - "path": "benchmarks/scripts/build_extbench_reference.py", - "sha256": "113840a36b914722ff422505b1ed128daf023ee20bf287ab8ebfcd1af938a786", - "bytes": 7060 - }, - { - "path": "benchmarks/scripts/compare_foambench_qois.py", - "sha256": "827836c6f2363f0104917b6573dc86935ffc58fd3b9dcdf0ca83cd5ce874f753", - "bytes": 446 - }, - { - "path": "benchmarks/scripts/extract_extbench_qois.py", - "sha256": "845727247e81e82d75abb0e05b62d1bd15f9a7d8512533b749b8a20e1631f6a5", - "bytes": 446 - }, - { - "path": "benchmarks/scripts/extract_foambench_candidate_qois.py", - "sha256": "1110f0962468820146307099c463c1be8a25cbc5c3729fd7abc116d7fe06d27a", - "bytes": 2020 - }, - { - "path": "benchmarks/scripts/extract_foambench_qois.py", - "sha256": "cf3c18a0329ac576fc05e35ba2f70f95f0c1d6668a86fe6a65d8402de41a1abe", - "bytes": 457 - }, - { - "path": "benchmarks/scripts/materialize_benchmark.py", - "sha256": "265ac1ec1fcc347c82e9351a86305d6f7bafaf3bd8ff69075904ebaf285ed2bc", - "bytes": 10921 - }, - { - "path": "benchmarks/scripts/recover_extbench_qoi.py", - "sha256": "fc1268f130f4b0800b5a75346198e97896bd5e74b07ea3face5d0e4afa0d6d2c", - "bytes": 13206 - }, - { - "path": "benchmarks/scripts/validate_benchmark_assets.py", - "sha256": "ca2f885342099b4a06f425d971bee5edc24b199b596000e9997f8940b23770b4", - "bytes": 3335 - }, - { - "path": "LICENSE", - "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", - "bytes": 11358 - }, - { - "path": "LICENSES/GPL-3.txt", - "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903", - "bytes": 35147 - }, - { - "path": "schemas/benchmark_evaluation.schema.json", - "sha256": "d49505bf35dffc763df91b13c8b5885e78b607af56d7aceba01e427c3fa19a6b", - "bytes": 4758 - }, - { - "path": "schemas/benchmark_profile.schema.json", - "sha256": "32a7f0865e9c851848fc775f9bde1125bd03749b4130d34fe95d5ffc62a700c0", - "bytes": 1478 - }, - { - "path": "schemas/foambench_qoi_candidate.schema.json", - "sha256": "88fb894b919323c0457f1cb4bf934f72320d644299185127c164579343606425", - "bytes": 944 - }, - { - "path": "schemas/foambench_qoi_comparison.schema.json", - "sha256": "9204923e5b93e333459ccfc43394137deaee1bf19d6f01beaf8ada664806d7e8", - "bytes": 1179 - }, - { - "path": "schemas/foambench_qoi_reference.schema.json", - "sha256": "2ef632eb4ed82ad78213de6ee4b18aa36558916a106cb258505493c95285ac68", - "bytes": 2327 - }, - { - "path": "schemas/qoi_recovery_plan.schema.json", - "sha256": "839a77fa504b7f13b2b6803c0ca2448df83418779cee2a2a5a5acdc18cd8760c", - "bytes": 881 - } - ], - "additional_upstream_notice": { - "path": "LICENSES/FoamBench-BSD-3-Clause.txt", - "source_url": "https://raw.githubusercontent.com/NLR-Theseus/cfdllmbench/main/LICENSE", - "retrieved_date": "2026-10-12", - "sha256": "7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22" - } -} +{ + "schema_version": "extfoambench.source-manifest.v1", + "source_description": "User-supplied EasyFoam research source snapshot", + "copied_files_byte_identical": true, + "files": [ + { + "path": "benchmarks/__init__.py", + "sha256": "b5375698c34737e22fabdf9cea774287609ce6edc3fa8c73791c3749e89c3bca", + "bytes": 49, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/assets/manifest.json", + "sha256": "0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f", + "bytes": 2275 + }, + { + "path": "benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz", + "sha256": "0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe", + "bytes": 2839115 + }, + { + "path": "benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz", + "sha256": "f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7", + "bytes": 860951 + }, + { + "path": "benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz", + "sha256": "02f25f876414a9a4cbdb9cfb08da9916ac49f7851d4658067abc371447f882ce", + "bytes": 940038 + }, + { + "path": "benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz", + "sha256": "9fd098e03da6178852d4f9837bc06d2f24599065644f951b481907513d835d90", + "bytes": 112656 + }, + { + "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj", + "sha256": "612cb86bfa2c842444ba86f203af31c712da3e807ed537013fefff8ab40f42a2", + "bytes": 646 + }, + { + "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj", + "sha256": "d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117", + "bytes": 534 + }, + { + "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj", + "sha256": "d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b", + "bytes": 792 + }, + { + "path": "benchmarks/assets/README.md", + "sha256": "b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540", + "bytes": 780 + }, + { + "path": "benchmarks/evaluation/__init__.py", + "sha256": "6488b16a905c9e6ae7d33f06bd55fbf276c917df54f53984f4f4ba3504f1710d", + "bytes": 878, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/__main__.py", + "sha256": "b965c21513f41de952a6f983700e961845746fd1b3df1c56ab1e7a612ca8be8f", + "bytes": 242, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/__init__.py", + "sha256": "dc4d21e3f45bd036f5a0d23ef2e9bf4406f4e34a76437472e3b9bbb25ff5bd40", + "bytes": 631, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/chatcfd.py", + "sha256": "b8933e85b63abc1c792fdad5ddd76dedb2e0344e38ce6d2e8991ee760e7419ce", + "bytes": 4175, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/coding_agent.py", + "sha256": "cdf7354b586bc67898bc2f3b44292aacd7fc9d7a58f0544efa9c603ac69a8f11", + "bytes": 2193, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/common.py", + "sha256": "260f1efc5943ef598fa02b3dae130101961fc0c2ce22080abec2b4836d850d63", + "bytes": 2764, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/easyfoam.py", + "sha256": "5ffd5d35e2431ae568b3e78b647aa85d091d01c124bcdacedcb6e68d4474339b", + "bytes": 5282, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/adapters/foamagent.py", + "sha256": "a33bcc116b3043c2b70a1342d0d3c71c30eac42f1ea286ca08b543f0e6496c40", + "bytes": 2829, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/aggregate.py", + "sha256": "513e63ba562da617ef6f665c452bec8c2d308ca1e716629ac6ca360494724849", + "bytes": 5461, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/basic_advanced.py", + "sha256": "1f8db418394f143b9ecb780eec4118ebde99885130cc30552f64735c5ea93307", + "bytes": 41291, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/cli.py", + "sha256": "9d4a6bc429e0ef9a751384be2d777101f7f2d91dfee7edbdc6e3e0d771154ccd", + "bytes": 2994, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/comparison.py", + "sha256": "eb44b8d8020e5f9c22f19880884ade107afd395246b0d9ad8f78b9a6a4d30280", + "bytes": 38842, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/evidence_contract.py", + "sha256": "272bc7e44456c330fd7ac97685279538f8b0715d8aae3deb88366314fea1efc9", + "bytes": 5651, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/execution.py", + "sha256": "cd2e1ff40d7dcb830b4230d86e143652d1d93a1b007019e3583384486a242604", + "bytes": 2772, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/extbench.py", + "sha256": "78cd982892e8ede31ee7e951cec87c7c595813a975bf4b111ea0d980b37633b5", + "bytes": 81030, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/field_candidate.py", + "sha256": "51d8bb69224ed37ae0de073700c5f9cfd403095f53fa16d633a3eb777e1a0b13", + "bytes": 500, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/field_extractor.py", + "sha256": "95900ed3c04bc04846e2dd2dd6ae4f98c2fb0aba4b85978199c20b1a444f4c0e", + "bytes": 17099, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/foam.py", + "sha256": "3c6a38077eecae484f264cd46478b21687b21ca33f543f4f041d954bdfa98205", + "bytes": 2950, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/foam_arrays.py", + "sha256": "80bd6344a529cc574693053b97b14cccb209c40a099b01a942f8654ddf24c614", + "bytes": 5028, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/foam_field.py", + "sha256": "ce3a16fb9e29587eaabd816bdfda832bcdc83e3744ac233e1365b3350146ddf9", + "bytes": 7085, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/foam_io.py", + "sha256": "a043e6a9022c30aea8fa94b8f753f1608804c526644a1f851c23453b7482727a", + "bytes": 865, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/frozen_recovery.py", + "sha256": "55bd6f2c61c4e3cef677e4cf428433ae9e3fb8b778efc10bb281e814fc2c5d05", + "bytes": 33511, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/health.py", + "sha256": "1cf606f832b4410908faaddeb439d0ca768cf134f4832f87f901c113a17d25da", + "bytes": 2784, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/io.py", + "sha256": "83c7166635578af9b5ed7eaeac96c06df7b65ab0936dc39a5310e5c42a6003e4", + "bytes": 1032, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/measurement_specs.py", + "sha256": "eb16a2dbd37f6ddb112adb6a92f5b3c1b8aa6295592d8f5430d7d3a24f0ff334", + "bytes": 1846, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/mesh.py", + "sha256": "7f35b96268d62aca315d70f2c14a6bdda602bb51b70666fb1fa7667bc88a0cbf", + "bytes": 2594, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/models.py", + "sha256": "75cdb75a677e47c786769d541e019085eb84a3de73b0539647143d869115d8ef", + "bytes": 3077, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/numerical.py", + "sha256": "f87a0946dc0d29c656e362d56e3aa0cc68c495d6daecf5d17f429a916e6468ff", + "bytes": 11958, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/pipeline.py", + "sha256": "4921843f568f4ff06d4f02d270da87a8833d34dac2a448aae1a090caa68d2206", + "bytes": 6887, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/preparation.py", + "sha256": "95d54ca4f2dea32c9223cc092db6ac1e93fd045ab3a47a965c10f035b6211bd3", + "bytes": 7412, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/profiles/advanced.json", + "sha256": "5e8791bf4840c8ea18d1f5c70ca922b100e7694a07e75f2c7fb47a9b834137a2", + "bytes": 575, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/profiles/basic.json", + "sha256": "a9976b3f6d2125a9ada142614052eb7d4cbc263ac8c1781f7b3fd4f0e567e2e4", + "bytes": 566, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/profiles/extended.json", + "sha256": "8bbbc58e77b09da38eef2565e95b8d69c88b1db21ac696e9991b887e2394af85", + "bytes": 625, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/profiles.py", + "sha256": "5cf9b70b1ec3ae040d2e3b478e61d5c4e1bf838106621e3d3f7c1827670841a5", + "bytes": 3329, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/qoi.py", + "sha256": "305eba7114c1ae50521c05aa12ad95c9db35304af33665ea5e655bfd8f17c51b", + "bytes": 3096, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/qoi_glue.py", + "sha256": "af47ba704a5edcd8490261a7ddba07fe9204473ae4d19d3b09a7e4f7fb9f548f", + "bytes": 20253, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/qoi_reference.py", + "sha256": "99a6af4a1f422bbb4f808602b744b2fa3660b4a7740e39ab24f3f4fcad9bda6b", + "bytes": 24058, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/reference.py", + "sha256": "627725f472e89d9b97ff8cedf23d2ac92097a53f27f23d648f7be0bf943d33b1", + "bytes": 1684, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/reporting.py", + "sha256": "159655e9dadb4367a59a7ea1a804856c5280b3bc025c2892f06fd0535e265bae", + "bytes": 3765, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/retained_fields.py", + "sha256": "0c54e9671b9f7353cbc28ecf9798d678db4bfacaa5f7c184bf4e45ebef9ec4a7", + "bytes": 14447, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/schema.py", + "sha256": "477332e61a0f668ff51db9817ec874706051d37c2dedf65b5ca43b73435c9583", + "bytes": 731, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/evaluation/stability.py", + "sha256": "b9ba1b4c4583e9b393c699d47bab71a82aed159519408062b631147bd70d25a5", + "bytes": 1878, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/FoamBench_advanced_openfoam13_fixed_final.json", + "sha256": "74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027", + "bytes": 306717 + }, + { + "path": "benchmarks/FoamBench_advanced_openfoam13_reference_qois.json", + "sha256": "31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63", + "bytes": 357142 + }, + { + "path": "benchmarks/FoamBench_basic_openfoam13_fixed_final.json", + "sha256": "50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523", + "bytes": 2026359 + }, + { + "path": "benchmarks/FoamBench_basic_openfoam13_reference_qois.json", + "sha256": "6f91688f7c97b3ef6b8191256c14af7f8accb168e8d384aba763681e01c34724", + "bytes": 2031952 + }, + { + "path": "benchmarks/FoamBench_extended_openfoam13_evidence_contract.v1.json", + "sha256": "4f0eae169c7d575da991d7c23c313ce6e4971887fbbaffbbbf9bc65105c2b676", + "bytes": 2985 + }, + { + "path": "benchmarks/FoamBench_extended_openfoam13_fixed.json", + "sha256": "1e247ddfec51cc2a716ca5690661acb367a3f919ceb1a99fd2d40123cb1b4d5b", + "bytes": 2260175 + }, + { + "path": "benchmarks/FoamBench_extended_openfoam13_measurement_specs.json", + "sha256": "0bddaf5b3abc3569d105c89cbdeef8cf3c4cce381ba9f7a3d622cadadaf8a68b", + "bytes": 148565 + }, + { + "path": "benchmarks/FoamBench_extended_openfoam13_qoi_design.json", + "sha256": "fb1db5034a1d2688ad360c6b0810bab68c33d4c6dc1dc5bec29095e93b077393", + "bytes": 20291 + }, + { + "path": "benchmarks/FoamBench_extended_openfoam13_reference_qois.json", + "sha256": "65e5c2d9968d1dbc798d585c9398c6fba2646f7463909040ae0c039727c8a1f9", + "bytes": 7742495 + }, + { + "path": "benchmarks/reference_statistics/advanced.json", + "sha256": "6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b", + "bytes": 25631 + }, + { + "path": "benchmarks/reference_statistics/basic.json", + "sha256": "3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72", + "bytes": 148470 + }, + { + "path": "benchmarks/reference_statistics/extended.json", + "sha256": "637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9", + "bytes": 154741 + }, + { + "path": "benchmarks/scripts/__init__.py", + "sha256": "5c1f78137dc1c7032363bb0ebf96cf01f19c9f2ffb48abd7fef39cb8b54a9f82", + "bytes": 87, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/build_extbench_reference.py", + "sha256": "113840a36b914722ff422505b1ed128daf023ee20bf287ab8ebfcd1af938a786", + "bytes": 7060, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/compare_foambench_qois.py", + "sha256": "827836c6f2363f0104917b6573dc86935ffc58fd3b9dcdf0ca83cd5ce874f753", + "bytes": 446, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/extract_extbench_qois.py", + "sha256": "845727247e81e82d75abb0e05b62d1bd15f9a7d8512533b749b8a20e1631f6a5", + "bytes": 446, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/extract_foambench_candidate_qois.py", + "sha256": "1110f0962468820146307099c463c1be8a25cbc5c3729fd7abc116d7fe06d27a", + "bytes": 2020, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/extract_foambench_qois.py", + "sha256": "cf3c18a0329ac576fc05e35ba2f70f95f0c1d6668a86fe6a65d8402de41a1abe", + "bytes": 457, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/materialize_benchmark.py", + "sha256": "265ac1ec1fcc347c82e9351a86305d6f7bafaf3bd8ff69075904ebaf285ed2bc", + "bytes": 10921, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/recover_extbench_qoi.py", + "sha256": "fc1268f130f4b0800b5a75346198e97896bd5e74b07ea3face5d0e4afa0d6d2c", + "bytes": 13206, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "benchmarks/scripts/validate_benchmark_assets.py", + "sha256": "ca2f885342099b4a06f425d971bee5edc24b199b596000e9997f8940b23770b4", + "bytes": 3335, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "LICENSE", + "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "bytes": 11358 + }, + { + "path": "LICENSES/GPL-3.txt", + "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903", + "bytes": 35147 + }, + { + "path": "schemas/benchmark_evaluation.schema.json", + "sha256": "d49505bf35dffc763df91b13c8b5885e78b607af56d7aceba01e427c3fa19a6b", + "bytes": 4758, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "schemas/benchmark_profile.schema.json", + "sha256": "32a7f0865e9c851848fc775f9bde1125bd03749b4130d34fe95d5ffc62a700c0", + "bytes": 1478, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "schemas/foambench_qoi_candidate.schema.json", + "sha256": "88fb894b919323c0457f1cb4bf934f72320d644299185127c164579343606425", + "bytes": 944, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "schemas/foambench_qoi_comparison.schema.json", + "sha256": "9204923e5b93e333459ccfc43394137deaee1bf19d6f01beaf8ada664806d7e8", + "bytes": 1179, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "schemas/foambench_qoi_reference.schema.json", + "sha256": "2ef632eb4ed82ad78213de6ee4b18aa36558916a106cb258505493c95285ac68", + "bytes": 2327, + "archive": "tools/evaluation-tools.zip" + }, + { + "path": "schemas/qoi_recovery_plan.schema.json", + "sha256": "839a77fa504b7f13b2b6803c0ca2448df83418779cee2a2a5a5acdc18cd8760c", + "bytes": 881, + "archive": "tools/evaluation-tools.zip" + } + ], + "additional_upstream_notice": { + "path": "LICENSES/FoamBench-BSD-3-Clause.txt", + "source_url": "https://raw.githubusercontent.com/NLR-Theseus/cfdllmbench/main/LICENSE", + "retrieved_date": "2026-10-12", + "sha256": "7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22" + } +} diff --git a/metadata/validation.json b/metadata/validation.json index e10449a77c455c3c91b30bce719f47ca760b5b56..344298b5ace3851d3a30cab2903d02d69b71cebd 100644 --- a/metadata/validation.json +++ b/metadata/validation.json @@ -1,167 +1,78 @@ { "status": "pass", + "version": "1.1.0", "date": "2026-10-12", - "environment": { - "python": "3.12.14", - "datasets": "5.1.0", - "huggingface_hub": "2.2.0", - "numpy": "2.5.4", - "jsonschema": "4.19.2" - }, "checks": [ { - "check": "hf_dataset_card_configs", + "check": "HF config extended", "status": "pass", - "detail": [ - "extended", - "basic", - "advanced", - "all" - ] + "detail": 100 }, { - "check": "hf_load_extended", + "check": "HF config basic", "status": "pass", - "detail": { - "rows": 100, - "columns": [ - "task_id", - "track", - "case_id", - "family", - "task_origin", - "usr_requirement", - "external_asset_ids" - ] - } + "detail": 110 }, { - "check": "hf_load_basic", + "check": "HF config advanced", "status": "pass", - "detail": { - "rows": 110, - "columns": [ - "task_id", - "track", - "case_id", - "family", - "task_origin", - "usr_requirement", - "external_asset_ids" - ] - } + "detail": 16 }, { - "check": "hf_load_advanced", + "check": "HF config all", "status": "pass", - "detail": { - "rows": 16, - "columns": [ - "task_id", - "track", - "case_id", - "family", - "task_origin", - "usr_requirement", - "external_asset_ids" - ] - } + "detail": 226 }, { - "check": "hf_load_all", - "status": "pass", - "detail": { - "rows": 226, - "columns": [ - "task_id", - "track", - "case_id", - "family", - "task_origin", - "usr_requirement", - "external_asset_ids" - ] - } - }, - { - "check": "profile_extended", - "status": "pass", - "detail": "exit 0" - }, - { - "check": "materialize_extended", - "status": "pass", - "detail": "exit 0" - }, - { - "check": "profile_basic", + "check": "extracted profile extended", "status": "pass", "detail": "exit 0" }, { - "check": "materialize_basic", + "check": "extracted profile basic", "status": "pass", "detail": "exit 0" }, { - "check": "profile_advanced", + "check": "extracted profile advanced", "status": "pass", "detail": "exit 0" }, { - "check": "materialize_advanced", + "check": "extracted geometry assets", "status": "pass", "detail": "exit 0" }, { - "check": "geometry", + "check": "extracted example", "status": "pass", "detail": "exit 0" }, { - "check": "inspect_example", + "check": "extracted materialization", "status": "pass", "detail": "exit 0" }, { - "check": "empty_run_evaluation", - "status": "pass", - "detail": "exit 0" - }, - { - "check": "missing_rollouts_denominator", - "status": "pass", - "detail": { - "assigned": 100, - "execution_pass_rate": 0, - "end_to_end_pass_rate": 0 - } - }, - { - "check": "python_syntax", + "check": "all documentation links", "status": "pass", - "detail": 51 + "detail": "resolve in base or extracted layout" }, { - "check": "local_markdown_links", + "check": "source scientific data and code unchanged", "status": "pass", - "detail": "all resolve" + "detail": 81 }, { - "check": "credential_pattern_scan", + "check": "task catalogs unchanged", "status": "pass", - "detail": "no matches for common token/private-key signatures; not an exhaustive security audit" + "detail": 226 } ], - "evaluator_environment": { - "python": "3.12.14", - "numpy": "1.26.4", - "jsonschema": "4.19.2" - }, + "prior_validation": "v1.0.0 validated all 226 reference input materializations and missing-rollout scoring; scientific data and code unchanged", "not_run": [ - "HF hosted dataset viewer (not uploaded)", - "CFD solver/reference reruns", - "model or agent inference", - "historical manuscript-table reproduction" + "new CFD simulations", + "model inference", + "historical manuscript reproduction" ] } diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index f65d8caa95c4b03d8aef03790310780ccbddcbcb..0000000000000000000000000000000000000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -numpy==1.26.4 -jsonschema==4.19.2 diff --git a/schemas/benchmark_evaluation.schema.json b/schemas/benchmark_evaluation.schema.json deleted file mode 100644 index 899ae724892171ea9addbfc6a93bbfe5b4d41e7d..0000000000000000000000000000000000000000 --- a/schemas/benchmark_evaluation.schema.json +++ /dev/null @@ -1,126 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "benchmark_evaluation.schema.json", - "title": "FoamBench Campaign and Case Evaluation", - "type": "object", - "additionalProperties": false, - "required": [ - "schema_version", - "generated_at", - "profile_id", - "dataset", - "adapter", - "run_root", - "reference_qois", - "definitions", - "overall", - "families", - "cases" - ], - "properties": { - "schema_version": {"const": "foambench.campaign_evaluation.v1"}, - "generated_at": {"type": "string", "format": "date-time"}, - "profile_id": {"type": "string", "minLength": 1}, - "dataset": {"type": "string", "minLength": 1}, - "adapter": {"enum": ["easyfoam", "foamagent", "chatcfd", "coding-agent"]}, - "run_root": {"type": "string", "minLength": 1}, - "reference_qois": {"type": "string", "minLength": 1}, - "definitions": {"type": "object"}, - "overall": {"$ref": "#/$defs/summary"}, - "families": {"type": "object", "additionalProperties": {"$ref": "#/$defs/summary"}}, - "cases": {"type": "object", "additionalProperties": {"$ref": "#/$defs/case"}} - }, - "$defs": { - "summary": { - "type": "object", - "required": [ - "task_count", - "execution_pass_count", - "execution_pass_rate", - "numerical_pass_count", - "numerical_pass_rate_all_tasks", - "physics_grounded_qoi_pass_count", - "physics_grounded_qoi_pass_rate_all_tasks", - "end_to_end_pass_count", - "end_to_end_pass_rate", - "failure_taxonomy" - ], - "properties": { - "task_count": {"type": "integer", "minimum": 0}, - "execution_pass_count": {"type": "integer", "minimum": 0}, - "execution_pass_rate": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, - "numerical_pass_count": {"type": "integer", "minimum": 0}, - "numerical_pass_rate_all_tasks": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, - "physics_grounded_qoi_pass_count": {"type": "integer", "minimum": 0}, - "physics_grounded_qoi_pass_rate_all_tasks": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, - "end_to_end_pass_count": {"type": "integer", "minimum": 0}, - "end_to_end_pass_rate": {"type": ["number", "null"], "minimum": 0, "maximum": 1}, - "failure_taxonomy": {"type": "object", "additionalProperties": {"type": "integer", "minimum": 0}} - } - }, - "case": { - "type": "object", - "additionalProperties": true, - "required": [ - "schema_version", - "case_id", - "dataset", - "family", - "variant", - "replicate", - "execution", - "numerical", - "qoi", - "scores", - "resources", - "artifact", - "failure_categories" - ], - "properties": { - "schema_version": {"const": "foambench.case_evaluation.v1"}, - "case_id": {"type": "string", "minLength": 1}, - "dataset": {"type": "string", "minLength": 1}, - "family": {"type": "string", "minLength": 1}, - "variant": {"type": "string", "minLength": 1}, - "replicate": {"type": "integer", "minimum": 1}, - "execution": {"$ref": "#/$defs/assessment"}, - "numerical": {"$ref": "#/$defs/assessment"}, - "qoi": { - "type": "object", - "required": ["status", "physics_grounded_qoi_pass", "effective_pass_ratio", "candidate"], - "properties": { - "status": {"type": "string"}, - "physics_grounded_qoi_pass": {"type": "boolean"}, - "effective_pass_ratio": {"type": "number", "minimum": 0, "maximum": 1}, - "candidate": {"type": "object"}, - "comparison": {"type": ["object", "null"]} - } - }, - "scores": { - "type": "object", - "additionalProperties": false, - "required": ["execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass"], - "properties": { - "execution_pass": {"type": "boolean"}, - "numerical_pass": {"type": "boolean"}, - "physics_grounded_qoi_pass": {"type": "boolean"}, - "end_to_end_pass": {"type": "boolean"} - } - }, - "resources": {"type": "object"}, - "artifact": {"type": "object"}, - "failure_categories": {"type": "array", "items": {"type": "string"}, "uniqueItems": true} - } - }, - "assessment": { - "type": "object", - "required": ["schema_version", "status", "checks", "failed_checks"], - "properties": { - "schema_version": {"type": "string"}, - "status": {"type": "string"}, - "checks": {"type": "object"}, - "failed_checks": {"type": "array", "items": {"type": "string"}} - } - } - } -} diff --git a/schemas/benchmark_profile.schema.json b/schemas/benchmark_profile.schema.json deleted file mode 100644 index 7438d9b4ed8a51fc969fc214171c15fd618964ed..0000000000000000000000000000000000000000 --- a/schemas/benchmark_profile.schema.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "benchmark_profile.schema.json", - "title": "FoamBench Evaluation Profile", - "type": "object", - "additionalProperties": false, - "required": [ - "profile_id", - "dataset", - "benchmark_path", - "reference_qois_path", - "membership", - "qoi", - "numerical" - ], - "properties": { - "profile_id": {"type": "string", "minLength": 1}, - "dataset": {"type": "string", "minLength": 1}, - "benchmark_path": {"type": "string", "minLength": 1}, - "reference_qois_path": {"type": "string", "minLength": 1}, - "reference_run_root": {"type": "string", "minLength": 1}, - "membership": { - "type": "object", - "additionalProperties": false, - "required": ["expected_case_count", "case_id_style"], - "properties": { - "expected_case_count": {"type": "integer", "minimum": 1}, - "case_id_style": {"enum": ["family_variant", "case_name"]} - } - }, - "qoi": { - "type": "object", - "additionalProperties": false, - "required": ["extractor", "required_fraction"], - "properties": { - "extractor": {"enum": ["field", "extended"]}, - "required_fraction": {"type": "number", "exclusiveMinimum": 0, "maximum": 1} - } - }, - "numerical": { - "type": "object", - "additionalProperties": true, - "required": ["contract"], - "properties": { - "contract": {"type": "string", "minLength": 1} - } - } - } -} diff --git a/schemas/foambench_qoi_candidate.schema.json b/schemas/foambench_qoi_candidate.schema.json deleted file mode 100644 index 640f5af574379073ea44632a74fbe022f53a0010..0000000000000000000000000000000000000000 --- a/schemas/foambench_qoi_candidate.schema.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "foambench_qoi_candidate.schema.json", - "title": "FoamBench QoI candidate observation", - "type": "object", - "required": ["schema_version", "case_id", "qois", "health"], - "properties": { - "schema_version": {"type": "string", "pattern": "^foambench\\.qoi\\.candidate(?:\\.v[0-9]+)?$"}, - "case_id": {"type": "string", "minLength": 1}, - "status": {"type": "string"}, - "qois": {"type": "object", "additionalProperties": {"oneOf": [{"type": "number"}, {"type": "object"}]}}, - "principal_metrics": {"type": "array", "items": {"type": "string"}}, - "required_metrics": {"type": "array", "items": {"type": "string"}}, - "missing_metrics": {"type": "array", "items": {"type": "string"}}, - "health": {"type": "object", "required": ["status"], "properties": {"status": {"type": "string"}}, "additionalProperties": true} - }, - "additionalProperties": true -} diff --git a/schemas/foambench_qoi_comparison.schema.json b/schemas/foambench_qoi_comparison.schema.json deleted file mode 100644 index 1923cf4b1e2d8c0e2c229da4289a473333078b7e..0000000000000000000000000000000000000000 --- a/schemas/foambench_qoi_comparison.schema.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "foambench_qoi_comparison.schema.json", - "title": "FoamBench QoI comparison", - "type": "object", - "required": ["schema_version", "status", "physics_grounded_qoi_pass", "qoi_pass_ratio", "qoi_quality", "qoi_coverage_fraction", "metrics"], - "properties": { - "schema_version": {"const": "foambench.qoi.case_comparison.v3"}, - "status": {"enum": ["pass", "incomplete", "out_of_tolerance", "incomplete_and_out_of_tolerance", "invalid_contract", "error"]}, - "physics_grounded_qoi_pass": {"type": "boolean"}, - "threshold_pass": {"type": "boolean"}, - "qoi_pass_ratio": {"type": "number", "minimum": 0, "maximum": 1}, - "qoi_quality": {"type": "number", "minimum": 0, "maximum": 1}, - "qoi_coverage_fraction": {"type": "number", "minimum": 0, "maximum": 1}, - "coverage_fraction": {"type": "number", "minimum": 0, "maximum": 1}, - "metrics": {"type": "object"}, - "group_scores": {"type": "object"}, - "missing_metrics": {"type": "array", "items": {"type": "string"}}, - "out_of_tolerance_metrics": {"type": "array", "items": {"type": "string"}} - }, - "additionalProperties": true -} diff --git a/schemas/foambench_qoi_reference.schema.json b/schemas/foambench_qoi_reference.schema.json deleted file mode 100644 index dc041b43b99c7eb5e2c3160789888f729316daa0..0000000000000000000000000000000000000000 --- a/schemas/foambench_qoi_reference.schema.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "foambench_qoi_reference.schema.json", - "title": "FoamBench QoI reference contract", - "type": "object", - "required": ["schema_version", "cases"], - "properties": { - "schema_version": {"type": "string", "pattern": "^foambench\\.reference_qois(?:\\.v[0-9]+)?$"}, - "cases": { - "type": "object", - "minProperties": 1, - "additionalProperties": {"$ref": "#/$defs/case"} - } - }, - "additionalProperties": true, - "$defs": { - "case": { - "type": "object", - "required": ["principal_qoi_group", "principal_metrics", "qois", "tolerances"], - "properties": { - "principal_qoi_group": {"type": "string", "minLength": 1}, - "principal_metrics": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"type": "string", "minLength": 1}}, - "qois": {"type": "object", "minProperties": 1, "additionalProperties": {"oneOf": [{"type": "number"}, {"type": "object"}]}}, - "tolerances": {"type": "object", "additionalProperties": {"$ref": "#/$defs/tolerance"}}, - "metric_roles": {"type": "object", "additionalProperties": {"enum": ["principal", "scored", "diagnostic", "redundant"]}} - }, - "additionalProperties": true - }, - "tolerance": { - "type": "object", - "properties": { - "low": {"type": "number"}, - "high": {"type": "number"}, - "reference_value": {"type": "number"}, - "relative_tolerance": {"type": "number", "minimum": 0}, - "absolute_floor": {"type": "number", "minimum": 0}, - "kind": {"type": "string"}, - "relative_max": {"type": "number", "minimum": 0}, - "normalized_rmse_max": {"type": "number", "minimum": 0}, - "normalized_linf_max": {"type": "number", "minimum": 0}, - "normalized_l1_max": {"type": "number", "minimum": 0}, - "minimum_time_coverage": {"type": "number", "minimum": 0, "maximum": 1}, - "normalization_floor": {"type": "number", "minimum": 0}, - "maximum_cell_offset": {"type": "number", "minimum": 0}, - "physical_floor": {"type": "number", "minimum": 0}, - "provisional": {"type": "boolean"} - }, - "anyOf": [ - {"required": ["low", "high"]}, - {"required": ["kind"]} - ], - "additionalProperties": true - } - } -} diff --git a/schemas/qoi_recovery_plan.schema.json b/schemas/qoi_recovery_plan.schema.json deleted file mode 100644 index faf792819dde15931e28ac95b9bc49e9e953f4a5..0000000000000000000000000000000000000000 --- a/schemas/qoi_recovery_plan.schema.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "qoi_recovery_plan.schema.json", - "title": "Conservative QoI recovery plan", - "type": "object", - "additionalProperties": false, - "required": ["status", "reason"], - "properties": { - "status": {"enum": ["recoverable", "unrecoverable", "uncertain"]}, - "reason": {"type": "string"}, - "mappings": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": false, - "required": ["metric", "source", "operation"], - "properties": { - "metric": {"type": "string"}, - "source": {"type": "string"}, - "operation": {"enum": ["table_time_history", "branch_spalding_table"]}, - "column": {"type": "string"}, - "patch": {"type": "string"}, - "branch_column": {"type": "string"} - } - } - } - } -} diff --git a/scripts/verify_release.py b/scripts/verify_release.py index 05d8bfe3b637ee12569fc52e8e4055cd36b24907..be23344b2a3615ae22cc2cecc37a24edb384d8f1 100644 --- a/scripts/verify_release.py +++ b/scripts/verify_release.py @@ -1,48 +1,56 @@ -"""Verify integrity, task projection, references and geometry; no solver runs.""" -import argparse -import hashlib -import json -from pathlib import Path -ROOT=Path(__file__).resolve().parents[1] -def read(p):return json.loads(p.read_text(encoding='utf-8')) -def require(ok,message): - if not ok:raise ValueError(message) -def verify(root): - paths=set() - for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines(): - digest,rel=line.split(' ',1);p=(root/rel).resolve() - require(p.is_relative_to(root.resolve()),f'Unsafe checksum path: {rel}') - require(p.is_file(),f'Missing file: {rel}') - require(hashlib.sha256(p.read_bytes()).hexdigest()==digest,f'Checksum mismatch: {rel}') - require(rel not in paths,f'Duplicate checksum path: {rel}');paths.add(rel) - source=read(root/'metadata/source_manifest.json') - for row in source['files']: - require(hashlib.sha256((root/row['path']).read_bytes()).hexdigest()==row['sha256'],f'Source drift: {row["path"]}') - coverage=read(root/'metadata/coverage.json');all_ids=set() - for track,expected in [('extended',100),('basic',110),('advanced',16)]: - profile=read(root/f'benchmarks/evaluation/profiles/{track}.json') - tasks=read(root/profile['benchmark_path']);refs=read(root/profile['reference_qois_path'])['cases'];stats=read(root/f'benchmarks/reference_statistics/{track}.json')['cases'] - rows=[json.loads(line) for line in (root/f'data/{track}.jsonl').read_text(encoding='utf-8').splitlines()] - require(len(rows)==len(tasks)==expected,f'Count mismatch: {track}') - require(set(tasks)==set(refs)==set(stats)=={r['case_id'] for r in rows},f'Membership mismatch: {track}') - for row in rows: - cid=row['case_id'];require(row['task_id']==f'{track}:{cid}' and row['task_id'] not in all_ids,'Task ID collision');all_ids.add(row['task_id']) - require(row['usr_requirement']==tasks[cid]['usr_requirement'],f'Prompt drift: {cid}') - require(row['track']==track and row['family']==cid.split('/')[0],f'Metadata mismatch: {cid}') - origin='ExtFoamBench (EasyFoam authors)' if track=='extended' else 'FoamBench (upstream; adapted for OpenFOAM 13)' - require(row['task_origin']==origin,f'Attribution mismatch: {cid}') - require(row['external_asset_ids']==[a['asset_id'] for a in tasks[cid].get('_external_assets',[])],f'Asset ID drift: {cid}') - for metric in refs[cid].get('principal_metrics',[]): - require(metric in refs[cid].get('qois',{}) and metric in refs[cid].get('tolerances',{}),f'Missing metric contract: {cid}/{metric}') - require(sorted(k for k,v in stats.items() if not v)==coverage[track]['missing_numerical_statistics_case_ids'],f'Coverage drift: {track}') - specs=read(root/'benchmarks/FoamBench_extended_openfoam13_measurement_specs.json') - require(set(specs['cases'])==set(read(root/'benchmarks/FoamBench_extended_openfoam13_fixed.json')),'Measurement membership drift') - assets=read(root/'benchmarks/assets/manifest.json')['assets'] - for asset_id,row in assets.items(): - require(hashlib.sha256((root/row['path']).read_bytes()).hexdigest()==row['sha256'],f'Geometry mismatch: {asset_id}') - return {'status':'pass','tasks':len(all_ids),'copied_source_files':len(source['files']),'checksum_files':len(paths),'geometry_assets':len(assets)} -def main(): - parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--root',type=Path,default=ROOT);args=parser.parse_args() - try:print(json.dumps(verify(args.root.resolve()),indent=2)) - except (OSError,ValueError,KeyError) as exc:parser.exit(1,f'Verification failed: {exc}\n') +"""Verify integrity, task projection, references and geometry; no solver runs.""" +import argparse +import hashlib +import json +import zipfile +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +def read(p):return json.loads(p.read_text(encoding='utf-8')) +def require(ok,message): + if not ok:raise ValueError(message) +def verify(root): + bundle=zipfile.ZipFile(root/'tools/evaluation-tools.zip') + require(bundle.testzip() is None, 'Corrupt optional tool archive') + def content(rel): + local=root/rel + return local.read_bytes() if local.is_file() else bundle.read(rel) + def document(rel): + return json.loads(content(rel).decode('utf-8-sig')) + paths=set() + for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines(): + digest,rel=line.split(' ',1);p=(root/rel).resolve() + require(p.is_relative_to(root.resolve()),f'Unsafe checksum path: {rel}') + require(p.is_file(),f'Missing file: {rel}') + require(hashlib.sha256(p.read_bytes()).hexdigest()==digest,f'Checksum mismatch: {rel}') + require(rel not in paths,f'Duplicate checksum path: {rel}');paths.add(rel) + source=read(root/'metadata/source_manifest.json') + for row in source['files']: + require(hashlib.sha256(content(row['path'])).hexdigest()==row['sha256'],f'Source drift: {row["path"]}') + coverage=read(root/'metadata/coverage.json');all_ids=set() + for track,expected in [('extended',100),('basic',110),('advanced',16)]: + profile=document(f'benchmarks/evaluation/profiles/{track}.json') + tasks=read(root/profile['benchmark_path']);refs=read(root/profile['reference_qois_path'])['cases'];stats=read(root/f'benchmarks/reference_statistics/{track}.json')['cases'] + rows=[json.loads(line) for line in (root/f'data/{track}.jsonl').read_text(encoding='utf-8').splitlines()] + require(len(rows)==len(tasks)==expected,f'Count mismatch: {track}') + require(set(tasks)==set(refs)==set(stats)=={r['case_id'] for r in rows},f'Membership mismatch: {track}') + for row in rows: + cid=row['case_id'];require(row['task_id']==f'{track}:{cid}' and row['task_id'] not in all_ids,'Task ID collision');all_ids.add(row['task_id']) + require(row['usr_requirement']==tasks[cid]['usr_requirement'],f'Prompt drift: {cid}') + require(row['track']==track and row['family']==cid.split('/')[0],f'Metadata mismatch: {cid}') + origin='ExtFoamBench (EasyFoam authors)' if track=='extended' else 'FoamBench (upstream; adapted for OpenFOAM 13)' + require(row['task_origin']==origin,f'Attribution mismatch: {cid}') + require(row['external_asset_ids']==[a['asset_id'] for a in tasks[cid].get('_external_assets',[])],f'Asset ID drift: {cid}') + for metric in refs[cid].get('principal_metrics',[]): + require(metric in refs[cid].get('qois',{}) and metric in refs[cid].get('tolerances',{}),f'Missing metric contract: {cid}/{metric}') + require(sorted(k for k,v in stats.items() if not v)==coverage[track]['missing_numerical_statistics_case_ids'],f'Coverage drift: {track}') + specs=read(root/'benchmarks/FoamBench_extended_openfoam13_measurement_specs.json') + require(set(specs['cases'])==set(read(root/'benchmarks/FoamBench_extended_openfoam13_fixed.json')),'Measurement membership drift') + assets=read(root/'benchmarks/assets/manifest.json')['assets'] + for asset_id,row in assets.items(): + require(hashlib.sha256(content(row['path'])).hexdigest()==row['sha256'],f'Geometry mismatch: {asset_id}') + return {'status':'pass','tasks':len(all_ids),'copied_source_files':len(source['files']),'checksum_files':len(paths),'geometry_assets':len(assets)} +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--root',type=Path,default=ROOT);args=parser.parse_args() + try:print(json.dumps(verify(args.root.resolve()),indent=2)) + except (OSError,ValueError,KeyError) as exc:parser.exit(1,f'Verification failed: {exc}\n') if __name__=='__main__':main() diff --git a/tools/evaluation-tools.zip b/tools/evaluation-tools.zip new file mode 100644 index 0000000000000000000000000000000000000000..f13a97b52dcf6dc0f1d460012559d73e4bf42fb3 --- /dev/null +++ b/tools/evaluation-tools.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bf6fd0963a10c4a42e7de6529b4e75ca144e81716fa000cde8ea26d5c45a021 +size 129452