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

Release ExtFoamBench v1.0.0

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +7 -0
  2. LICENSE +202 -0
  3. LICENSE.md +12 -0
  4. LICENSES/FoamBench-BSD-3-Clause.txt +28 -0
  5. LICENSES/GPL-3.txt +674 -0
  6. README.md +170 -0
  7. SHA256SUMS +102 -0
  8. VERSION +1 -0
  9. benchmarks/FoamBench_advanced_openfoam13_fixed_final.json +0 -0
  10. benchmarks/FoamBench_advanced_openfoam13_reference_qois.json +0 -0
  11. benchmarks/FoamBench_basic_openfoam13_fixed_final.json +0 -0
  12. benchmarks/FoamBench_basic_openfoam13_reference_qois.json +0 -0
  13. benchmarks/FoamBench_extended_openfoam13_evidence_contract.v1.json +59 -0
  14. benchmarks/FoamBench_extended_openfoam13_fixed.json +0 -0
  15. benchmarks/FoamBench_extended_openfoam13_measurement_specs.json +0 -0
  16. benchmarks/FoamBench_extended_openfoam13_qoi_design.json +266 -0
  17. benchmarks/FoamBench_extended_openfoam13_reference_qois.json +0 -0
  18. benchmarks/__init__.py +1 -0
  19. benchmarks/assets/README.md +15 -0
  20. benchmarks/assets/manifest.json +41 -0
  21. benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz +3 -0
  22. benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz +3 -0
  23. benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz +3 -0
  24. benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz +3 -0
  25. benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj +38 -0
  26. benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj +32 -0
  27. benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj +47 -0
  28. benchmarks/evaluation/README.md +12 -0
  29. benchmarks/evaluation/__init__.py +31 -0
  30. benchmarks/evaluation/__main__.py +10 -0
  31. benchmarks/evaluation/adapters/__init__.py +22 -0
  32. benchmarks/evaluation/adapters/chatcfd.py +85 -0
  33. benchmarks/evaluation/adapters/coding_agent.py +48 -0
  34. benchmarks/evaluation/adapters/common.py +71 -0
  35. benchmarks/evaluation/adapters/easyfoam.py +108 -0
  36. benchmarks/evaluation/adapters/foamagent.py +57 -0
  37. benchmarks/evaluation/aggregate.py +100 -0
  38. benchmarks/evaluation/basic_advanced.py +807 -0
  39. benchmarks/evaluation/cli.py +79 -0
  40. benchmarks/evaluation/comparison.py +750 -0
  41. benchmarks/evaluation/evidence_contract.py +119 -0
  42. benchmarks/evaluation/execution.py +62 -0
  43. benchmarks/evaluation/extbench.py +1572 -0
  44. benchmarks/evaluation/field_candidate.py +23 -0
  45. benchmarks/evaluation/field_extractor.py +421 -0
  46. benchmarks/evaluation/foam.py +84 -0
  47. benchmarks/evaluation/foam_arrays.py +129 -0
  48. benchmarks/evaluation/foam_field.py +155 -0
  49. benchmarks/evaluation/foam_io.py +29 -0
  50. benchmarks/evaluation/frozen_recovery.py +713 -0
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .cache/
5
+ outputs/
6
+ .env
7
+ .env.*
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
LICENSE.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Component licenses and attribution
2
+
3
+ This collection contains original and adapted material. The Hub uses `license: other` with this file as its license entry point because no single license label describes every component.
4
+
5
+ | Component | Retained terms / notice |
6
+ | --- | --- |
7
+ | EasyFoam project code and original project material | Existing project Apache-2.0 license in `LICENSE`, subject to third-party exceptions |
8
+ | Inherited FoamBench Basic/Advanced task content | Upstream BSD-3-Clause notice in `LICENSES/FoamBench-BSD-3-Clause.txt`; retain applicable OpenFOAM/other embedded notices |
9
+ | OpenFOAM tutorial-derived case content and geometry | Existing GPL-3.0-or-later notices and `LICENSES/GPL-3.txt`; see `benchmarks/assets/README.md` and `manifest.json` |
10
+ | Generated task catalogs | Projections of the corresponding task records; preserve their source attribution and applicable terms |
11
+
12
+ The packaging does not relicense upstream content or override embedded notices. Scientific authorship of the evaluation/reference data and original ExtFoamBench task design is distinguished from upstream ownership in `docs/PROVENANCE.md`. No new CC-BY, CC0 or other blanket grant is introduced by this release.
LICENSES/FoamBench-BSD-3-Clause.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Alliance for Sustainable Energy, LLC and Rensselaer Polytechnic Institute
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LICENSES/GPL-3.txt ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <http://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <http://www.gnu.org/philosophy/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: ExtFoamBench — CFD Tasks, Evaluation Protocols and Offline Reference Data
3
+ language:
4
+ - en
5
+ license: other
6
+ license_name: easyfoam-benchmarks-component-licenses
7
+ license_link: LICENSE.md
8
+ size_categories:
9
+ - n<1K
10
+ tags:
11
+ - benchmark
12
+ - computational-fluid-dynamics
13
+ - openfoam
14
+ - scientific-computing
15
+ - agents
16
+ - physics
17
+ - evaluation
18
+ - reference-data
19
+ configs:
20
+ - config_name: extended
21
+ default: true
22
+ data_files:
23
+ - split: test
24
+ path: data/extended.jsonl
25
+ - config_name: basic
26
+ data_files:
27
+ - split: test
28
+ path: data/basic.jsonl
29
+ - config_name: advanced
30
+ data_files:
31
+ - split: test
32
+ path: data/advanced.jsonl
33
+ - config_name: all
34
+ data_files:
35
+ - split: test
36
+ path:
37
+ - data/extended.jsonl
38
+ - data/basic.jsonl
39
+ - data/advanced.jsonl
40
+ ---
41
+
42
+ # ExtFoamBench
43
+
44
+ **100 new CFD tasks, task-specific QoI acceptance rules, and offline reference data for evaluating OpenFOAM agents.**
45
+
46
+ This release accompanies [EasyFoam: Skill-Oriented OpenFOAM Agents with Evidence-Driven Evolution](https://openreview.net/forum?id=GhQ5YmhU8B). It brings together three research contributions: the **ExtFoamBench task dataset**, the **execution / numerical / physical acceptance evaluation framework**, and **offline reference simulations summarized as QoIs and numerical diagnostics**.
47
+
48
+ The EasyFoam Skill library is available separately on [GitHub](https://github.com/CAS-CLab/EasyFoam). Installing that library does not require downloading this dataset. This dataset includes an offline evaluator; using it does not require installing the EasyFoam agent or providing a model API key.
49
+
50
+ ## Contributions and attribution
51
+
52
+ | Component | Task count | Task origin | Contribution in this release |
53
+ | --- | ---: | --- | --- |
54
+ | **ExtFoamBench / Extended** | **100** | New task suite developed by the EasyFoam authors, using attributed CFD source cases and geometry | New tasks, task-specific evaluation rules, and offline reference data |
55
+ | FoamBench Basic | 110 | Existing [FoamBench / CFDLLMBench](https://github.com/NLR-Theseus/cfdllmbench), adapted for OpenFOAM Foundation 13 | Evaluation rules and offline reference data developed/generated by the EasyFoam authors |
56
+ | FoamBench Advanced | 16 | Existing FoamBench / CFDLLMBench, adapted for OpenFOAM Foundation 13 | Evaluation rules and offline reference data developed/generated by the EasyFoam authors |
57
+
58
+ **The 126 Basic/Advanced tasks are not claimed as an original EasyFoam dataset.** They are included for compatibility with the evaluation suite. The EasyFoam authors' evaluation and offline-reference contributions cover all **226** tasks. Existing geometry, OpenFOAM tutorials, and upstream benchmark materials retain their provenance and licenses.
59
+
60
+ The default Hub configuration, `extended`, shows only the 100 ExtFoamBench tasks. `basic` and `advanced` expose inherited tasks separately. `all` combines the 226 evaluation tasks. The `test` split name means benchmark evaluation tasks; it does **not** describe the historical held-out split used in the EasyFoam skill-evolution experiments.
61
+
62
+ ## ExtFoamBench coverage
63
+
64
+ Each of the ten families contains ten tasks: a baseline and nine variants.
65
+
66
+ | Family | Physical setting |
67
+ | --- | --- |
68
+ | `yPlusVerification` | Near-wall resolution and wall-law verification |
69
+ | `risingBubble` | Buoyancy-driven two-phase bubble motion |
70
+ | `supersonicCrossJet` | Supersonic cross-flow / jet interaction |
71
+ | `nozzleCDV` | Compressible converging-diverging nozzle flow |
72
+ | `MRF_stirredReactor` | Rotating stirred-reactor flow |
73
+ | `ERCOFTA_pump` | Rotating-pump pressure and flow response |
74
+ | `compressibleBubbleCollapse` | Compressible bubble-collapse dynamics |
75
+ | `aerofoilNACA0012` | Airfoil aerodynamic response |
76
+ | `drivaerFastback` | Vehicle external aerodynamics |
77
+ | `riemann2D` | Two-dimensional compressible Riemann flow |
78
+
79
+ Variants cover operating conditions and boundary conditions, geometry and mesh, physics and closure models, solver/numerical settings, and study/workflow requirements. Some tasks require multiple runs, comparisons, parallel execution, or restart workflows.
80
+
81
+ ## What is downloaded?
82
+
83
+ | Location | Contents |
84
+ | --- | --- |
85
+ | `data/*.jsonl` | Hub-readable task catalog: identifiers, original requirements, origin, and permitted geometry identifiers |
86
+ | `benchmarks/FoamBench_*_fixed*.json` | Reference case input dictionaries, including OpenFOAM files and any reference subcases |
87
+ | `benchmarks/FoamBench_*_reference_qois.json` | Offline reference QoIs, principal metrics, and acceptance tolerances for each track |
88
+ | `benchmarks/FoamBench_extended_*measurement_specs.json` | Per-task measurement definitions for ExtFoamBench |
89
+ | `benchmarks/FoamBench_extended_*qoi_design.json` | Family/branch QoI design and principal-versus-diagnostic roles |
90
+ | `benchmarks/FoamBench_extended_*evidence_contract.v1.json` | Evidence format and discovery contract |
91
+ | `benchmarks/reference_statistics/` | Parsed reference residual, Courant, continuity, and related numerical diagnostics |
92
+ | `benchmarks/assets/` | Seven geometry assets, original source locations, and SHA-256 checksums |
93
+ | `benchmarks/evaluation/`, `schemas/` | Offline evaluation implementation and validation schemas |
94
+ | `benchmarks/scripts/` | Reference materialization, extraction, comparison, and asset checking utilities |
95
+ | `metadata/` | Version, family coverage, missing-data inventory, and source checksums |
96
+ | `docs/` | Data format, evaluation, provenance, and release notes |
97
+
98
+ Reference data are **simulation-derived computational references**, with the assumptions and limits of their configurations. Raw solution fields, raw reference logs, historical agent rollouts, and paper-result archives are not included in this release. No historical train/validation/test split is inferred or invented.
99
+
100
+ ## Quick start: inspect a task locally
101
+
102
+ From the downloaded repository root, using Python 3.11 or 3.12:
103
+
104
+ ```bash
105
+ python examples/inspect_task.py --track extended --case-id nozzleCDV/1
106
+ python scripts/verify_release.py
107
+ ```
108
+
109
+ Both commands use the Python standard library and do not run a model or a CFD solver. The inspection command shows the task plus the associated measurement and reference-metric summary. Its output is intended for a human or evaluator, not as an agent prompt.
110
+
111
+ For the Hub task catalog, install `datasets` in a separate environment from the pinned evaluator dependencies, and use:
112
+
113
+ ```python
114
+ from datasets import load_dataset
115
+
116
+ tasks = load_dataset("Eurus132/ExtFoamBench", "extended", split="test")
117
+ print(len(tasks)) # 100
118
+ print(tasks[0]["usr_requirement"])
119
+ ```
120
+
121
+ The task catalog excludes reference input files and reference values. Load/download the full repository if you need the evaluator and reference data; `load_dataset` loads only the selected task table. Pin the repository revision when reporting experiments.
122
+
123
+ ## Quick start: validate the evaluator inputs
124
+
125
+ ```bash
126
+ python -m pip install -r requirements.txt
127
+ python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json
128
+ python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/basic.json
129
+ python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/advanced.json
130
+ python benchmarks/scripts/validate_benchmark_assets.py --benchmark benchmarks/FoamBench_extended_openfoam13_fixed.json --manifest benchmarks/assets/manifest.json
131
+ ```
132
+
133
+ These checks require no OpenFOAM installation. Materialize one **reference input case** without solving it:
134
+
135
+ ```bash
136
+ python benchmarks/scripts/materialize_benchmark.py --benchmark benchmarks/FoamBench_basic_openfoam13_fixed_final.json --case-id Cavity/1 --output-root outputs/reference-input
137
+ ```
138
+
139
+ Actual CFD simulation requires **OpenFOAM Foundation 13** and the appropriate system tools. This release does not launch an agent. The offline evaluator consumes existing run artifacts; some derived measurements require native OpenFOAM tools. See [Evaluation](docs/EVALUATION.md) before enabling preparation or mesh auditing.
140
+
141
+ ## Evaluation: execution, numerics, and physics
142
+
143
+ The framework measures whether a task completes (**E**), satisfies applicable numerical checks (**N**), and satisfies every mandatory task-specific physical/QoI criterion (**Q**). It reports execution completion rate (**ECR**) and joint task acceptance rate (**TAR**):
144
+
145
+ ```text
146
+ ECR = count(E passes) / number of assigned tasks
147
+ TAR = count(E and N and Q all pass) / number of assigned tasks
148
+ ```
149
+
150
+ A high ECR alone does not establish physically acceptable task completion. Measurements can be scalars, spatial profiles, time histories, events, or branch-dependent responses. The supplied contracts fix extraction semantics, tolerances, missing-evidence behavior, and aggregation. Optional diagnostic scores and continuous quality values are not substitutes for mandatory acceptance checks or TAR.
151
+
152
+ See [Evaluation](docs/EVALUATION.md) for the implementation fields, [Data format](docs/DATA_FORMAT.md) for file relationships, and [release notes](docs/RELEASE_NOTES.md) for current protocol boundaries.
153
+
154
+ ## Reference visibility and intended use
155
+
156
+ This is a public research dataset and evaluation resource. Give a solving agent only the selected task requirements, allowed assets, and explicitly task-visible measurement instructions. Keep reference inputs, reference values, and evaluator files outside its accessible workspace. A working-directory setting alone is not read-access isolation.
157
+
158
+ The benchmark supports comparative research under its declared contracts. Passing it is not a general certification of physical validity or engineering suitability. Researchers should report software/data revisions, model and runtime settings, task membership, and any changed acceptance rules.
159
+
160
+ ## Data completeness and versioning
161
+
162
+ All 226 tasks have reference-QoI case entries. Parsed numerical reference statistics are nonempty for **215 of 226** tasks. They are unavailable for `nozzleCDV/4` and all ten `riemann2D` tasks in the Extended track; missing statistics are recorded explicitly in [coverage.json](metadata/coverage.json), not filled with synthetic values. Case-entry presence is not a claim that every optional diagnostic or conditional QoI is available.
163
+
164
+ Release `1.0.0` packages the supplied data and scorer without changing their numerical contents. Embedded schema versions and the Extended contract's `provisional` tolerance status are retained. This package is not a certification that all current defaults reproduce every historical table in the manuscript. Changes to tasks, reference values, extraction, or scoring require a new release. See [release notes](docs/RELEASE_NOTES.md).
165
+
166
+ ## Attribution and licenses
167
+
168
+ Use of ExtFoamBench tasks or the EasyFoam evaluation/reference resources should cite the [EasyFoam paper](https://openreview.net/forum?id=GhQ5YmhU8B). Use of Basic/Advanced should also credit the [upstream FoamBench work](https://github.com/NLR-Theseus/cfdllmbench). Dataset originality and reuse permissions are described separately in [Provenance](docs/PROVENANCE.md) and [component licenses](LICENSE.md).
169
+
170
+ This is a mixed-origin collection. The repository does not apply a new blanket license that overrides upstream terms. Apache-2.0 project terms, the FoamBench BSD-3-Clause notice, and OpenFOAM GPL notices are retained in `LICENSE` and `LICENSES/`.
SHA256SUMS ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fec9848fa0a1a2a2d7f78eebc2cac8239fe830c918d5776a684ed129beb203d9 .gitignore
2
+ b5375698c34737e22fabdf9cea774287609ce6edc3fa8c73791c3749e89c3bca benchmarks/__init__.py
3
+ 0d9fe71467b76d42e23ad97a6878ef6f981ebbb72438bb0a96ffed0d15609f8f benchmarks/assets/manifest.json
4
+ 0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz
5
+ f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7 benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz
6
+ 02f25f876414a9a4cbdb9cfb08da9916ac49f7851d4658067abc371447f882ce benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz
7
+ 9fd098e03da6178852d4f9837bc06d2f24599065644f951b481907513d835d90 benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz
8
+ 612cb86bfa2c842444ba86f203af31c712da3e807ed537013fefff8ab40f42a2 benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj
9
+ d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117 benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj
10
+ d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj
11
+ b29238a8d12572509f8aa805dd095023c9b9759dbbd4c85e1def66ab40d5d540 benchmarks/assets/README.md
12
+ 6488b16a905c9e6ae7d33f06bd55fbf276c917df54f53984f4f4ba3504f1710d benchmarks/evaluation/__init__.py
13
+ b965c21513f41de952a6f983700e961845746fd1b3df1c56ab1e7a612ca8be8f benchmarks/evaluation/__main__.py
14
+ dc4d21e3f45bd036f5a0d23ef2e9bf4406f4e34a76437472e3b9bbb25ff5bd40 benchmarks/evaluation/adapters/__init__.py
15
+ b8933e85b63abc1c792fdad5ddd76dedb2e0344e38ce6d2e8991ee760e7419ce benchmarks/evaluation/adapters/chatcfd.py
16
+ cdf7354b586bc67898bc2f3b44292aacd7fc9d7a58f0544efa9c603ac69a8f11 benchmarks/evaluation/adapters/coding_agent.py
17
+ 260f1efc5943ef598fa02b3dae130101961fc0c2ce22080abec2b4836d850d63 benchmarks/evaluation/adapters/common.py
18
+ 5ffd5d35e2431ae568b3e78b647aa85d091d01c124bcdacedcb6e68d4474339b benchmarks/evaluation/adapters/easyfoam.py
19
+ a33bcc116b3043c2b70a1342d0d3c71c30eac42f1ea286ca08b543f0e6496c40 benchmarks/evaluation/adapters/foamagent.py
20
+ 513e63ba562da617ef6f665c452bec8c2d308ca1e716629ac6ca360494724849 benchmarks/evaluation/aggregate.py
21
+ 1f8db418394f143b9ecb780eec4118ebde99885130cc30552f64735c5ea93307 benchmarks/evaluation/basic_advanced.py
22
+ 9d4a6bc429e0ef9a751384be2d777101f7f2d91dfee7edbdc6e3e0d771154ccd benchmarks/evaluation/cli.py
23
+ eb44b8d8020e5f9c22f19880884ade107afd395246b0d9ad8f78b9a6a4d30280 benchmarks/evaluation/comparison.py
24
+ 272bc7e44456c330fd7ac97685279538f8b0715d8aae3deb88366314fea1efc9 benchmarks/evaluation/evidence_contract.py
25
+ cd2e1ff40d7dcb830b4230d86e143652d1d93a1b007019e3583384486a242604 benchmarks/evaluation/execution.py
26
+ 78cd982892e8ede31ee7e951cec87c7c595813a975bf4b111ea0d980b37633b5 benchmarks/evaluation/extbench.py
27
+ 51d8bb69224ed37ae0de073700c5f9cfd403095f53fa16d633a3eb777e1a0b13 benchmarks/evaluation/field_candidate.py
28
+ 95900ed3c04bc04846e2dd2dd6ae4f98c2fb0aba4b85978199c20b1a444f4c0e benchmarks/evaluation/field_extractor.py
29
+ 3c6a38077eecae484f264cd46478b21687b21ca33f543f4f041d954bdfa98205 benchmarks/evaluation/foam.py
30
+ 80bd6344a529cc574693053b97b14cccb209c40a099b01a942f8654ddf24c614 benchmarks/evaluation/foam_arrays.py
31
+ ce3a16fb9e29587eaabd816bdfda832bcdc83e3744ac233e1365b3350146ddf9 benchmarks/evaluation/foam_field.py
32
+ a043e6a9022c30aea8fa94b8f753f1608804c526644a1f851c23453b7482727a benchmarks/evaluation/foam_io.py
33
+ 55bd6f2c61c4e3cef677e4cf428433ae9e3fb8b778efc10bb281e814fc2c5d05 benchmarks/evaluation/frozen_recovery.py
34
+ 1cf606f832b4410908faaddeb439d0ca768cf134f4832f87f901c113a17d25da benchmarks/evaluation/health.py
35
+ 83c7166635578af9b5ed7eaeac96c06df7b65ab0936dc39a5310e5c42a6003e4 benchmarks/evaluation/io.py
36
+ eb16a2dbd37f6ddb112adb6a92f5b3c1b8aa6295592d8f5430d7d3a24f0ff334 benchmarks/evaluation/measurement_specs.py
37
+ 7f35b96268d62aca315d70f2c14a6bdda602bb51b70666fb1fa7667bc88a0cbf benchmarks/evaluation/mesh.py
38
+ 75cdb75a677e47c786769d541e019085eb84a3de73b0539647143d869115d8ef benchmarks/evaluation/models.py
39
+ f87a0946dc0d29c656e362d56e3aa0cc68c495d6daecf5d17f429a916e6468ff benchmarks/evaluation/numerical.py
40
+ 4921843f568f4ff06d4f02d270da87a8833d34dac2a448aae1a090caa68d2206 benchmarks/evaluation/pipeline.py
41
+ 95d54ca4f2dea32c9223cc092db6ac1e93fd045ab3a47a965c10f035b6211bd3 benchmarks/evaluation/preparation.py
42
+ 5e8791bf4840c8ea18d1f5c70ca922b100e7694a07e75f2c7fb47a9b834137a2 benchmarks/evaluation/profiles/advanced.json
43
+ a9976b3f6d2125a9ada142614052eb7d4cbc263ac8c1781f7b3fd4f0e567e2e4 benchmarks/evaluation/profiles/basic.json
44
+ 8bbbc58e77b09da38eef2565e95b8d69c88b1db21ac696e9991b887e2394af85 benchmarks/evaluation/profiles/extended.json
45
+ 5cf9b70b1ec3ae040d2e3b478e61d5c4e1bf838106621e3d3f7c1827670841a5 benchmarks/evaluation/profiles.py
46
+ 305eba7114c1ae50521c05aa12ad95c9db35304af33665ea5e655bfd8f17c51b benchmarks/evaluation/qoi.py
47
+ af47ba704a5edcd8490261a7ddba07fe9204473ae4d19d3b09a7e4f7fb9f548f benchmarks/evaluation/qoi_glue.py
48
+ 99a6af4a1f422bbb4f808602b744b2fa3660b4a7740e39ab24f3f4fcad9bda6b benchmarks/evaluation/qoi_reference.py
49
+ e0b13a6223ffa692f1297ba76b6817db4156bb3c3c3d2abfa96afc095d41511f benchmarks/evaluation/README.md
50
+ 627725f472e89d9b97ff8cedf23d2ac92097a53f27f23d648f7be0bf943d33b1 benchmarks/evaluation/reference.py
51
+ 159655e9dadb4367a59a7ea1a804856c5280b3bc025c2892f06fd0535e265bae benchmarks/evaluation/reporting.py
52
+ 0c54e9671b9f7353cbc28ecf9798d678db4bfacaa5f7c184bf4e45ebef9ec4a7 benchmarks/evaluation/retained_fields.py
53
+ 477332e61a0f668ff51db9817ec874706051d37c2dedf65b5ca43b73435c9583 benchmarks/evaluation/schema.py
54
+ b9ba1b4c4583e9b393c699d47bab71a82aed159519408062b631147bd70d25a5 benchmarks/evaluation/stability.py
55
+ 74133664f968335b38cd17a0265d5003a4cce52230fc3f03846fcd3315599027 benchmarks/FoamBench_advanced_openfoam13_fixed_final.json
56
+ 31f46baabdbfb1482d8ef2573d25b82cd1c40f6859bf71cddae6f12e80fbba63 benchmarks/FoamBench_advanced_openfoam13_reference_qois.json
57
+ 50588c363869dd0a37befaa8e91bbc83c7bd8b14d8a23ff1eb2dc66fd77a0523 benchmarks/FoamBench_basic_openfoam13_fixed_final.json
58
+ 6f91688f7c97b3ef6b8191256c14af7f8accb168e8d384aba763681e01c34724 benchmarks/FoamBench_basic_openfoam13_reference_qois.json
59
+ 4f0eae169c7d575da991d7c23c313ce6e4971887fbbaffbbbf9bc65105c2b676 benchmarks/FoamBench_extended_openfoam13_evidence_contract.v1.json
60
+ 1e247ddfec51cc2a716ca5690661acb367a3f919ceb1a99fd2d40123cb1b4d5b benchmarks/FoamBench_extended_openfoam13_fixed.json
61
+ 0bddaf5b3abc3569d105c89cbdeef8cf3c4cce381ba9f7a3d622cadadaf8a68b benchmarks/FoamBench_extended_openfoam13_measurement_specs.json
62
+ fb1db5034a1d2688ad360c6b0810bab68c33d4c6dc1dc5bec29095e93b077393 benchmarks/FoamBench_extended_openfoam13_qoi_design.json
63
+ 65e5c2d9968d1dbc798d585c9398c6fba2646f7463909040ae0c039727c8a1f9 benchmarks/FoamBench_extended_openfoam13_reference_qois.json
64
+ 6c4a770c4b750ab0a8587cd18543517fd45cc93671014ced5fc81d668cd8a41b benchmarks/reference_statistics/advanced.json
65
+ 3f780d1cac318eb13e43eae062b6f713d8a549b149856adc3749b06b1c916f72 benchmarks/reference_statistics/basic.json
66
+ 637e8b34e515fb439976804970eea4aa0cb651ef8aeeff59dfaa44c67844a0e9 benchmarks/reference_statistics/extended.json
67
+ 5c1f78137dc1c7032363bb0ebf96cf01f19c9f2ffb48abd7fef39cb8b54a9f82 benchmarks/scripts/__init__.py
68
+ 113840a36b914722ff422505b1ed128daf023ee20bf287ab8ebfcd1af938a786 benchmarks/scripts/build_extbench_reference.py
69
+ 827836c6f2363f0104917b6573dc86935ffc58fd3b9dcdf0ca83cd5ce874f753 benchmarks/scripts/compare_foambench_qois.py
70
+ 845727247e81e82d75abb0e05b62d1bd15f9a7d8512533b749b8a20e1631f6a5 benchmarks/scripts/extract_extbench_qois.py
71
+ 1110f0962468820146307099c463c1be8a25cbc5c3729fd7abc116d7fe06d27a benchmarks/scripts/extract_foambench_candidate_qois.py
72
+ cf3c18a0329ac576fc05e35ba2f70f95f0c1d6668a86fe6a65d8402de41a1abe benchmarks/scripts/extract_foambench_qois.py
73
+ 265ac1ec1fcc347c82e9351a86305d6f7bafaf3bd8ff69075904ebaf285ed2bc benchmarks/scripts/materialize_benchmark.py
74
+ fc1268f130f4b0800b5a75346198e97896bd5e74b07ea3face5d0e4afa0d6d2c benchmarks/scripts/recover_extbench_qoi.py
75
+ ca2f885342099b4a06f425d971bee5edc24b199b596000e9997f8940b23770b4 benchmarks/scripts/validate_benchmark_assets.py
76
+ 488b6a139660cbcafd3de131c1e7e3c6758e71f609003e69cbfa1f9991afe95a data/advanced.jsonl
77
+ 50a62e6ab16faa998dd1c284db6ecb4e8ac78ee226c8be4e0fb6cce741e7581f data/basic.jsonl
78
+ edfd82f84456540c89844eae84143dc4897a93599b1b28f278a945de5826981e data/extended.jsonl
79
+ 07019bf3f590423b1b0804e6a8ac1dacf97677cb23a4842c4e5a0e601c155974 docs/DATA_FORMAT.md
80
+ f0c1d691c071253fa66517e68349d9c2ee6c6d73f963a967c10173180693342b docs/EVALUATION.md
81
+ 4f1353233c7d1d86da7f49d51a64f584805c435f8b052c37b37d30c84927530d docs/PROVENANCE.md
82
+ a3690d9a63846f36f58bd8e79e1ab974a4d46673a16943166e8ad0fd9b91faf1 docs/RELEASE_NOTES.md
83
+ c05b1930bed5658497b9ac9de230127c23a8541b274adfd270c995943773f4d5 examples/inspect_task.py
84
+ cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
85
+ 1c8f0e5ad4fe2f145137ef723f54d62e8891a2b1b3467c90bc33c4c6680c907f LICENSE.md
86
+ 7e0a18d9201969787f5fc32b977318576c7d2942f2828e19fa212bde19706a22 LICENSES/FoamBench-BSD-3-Clause.txt
87
+ 8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903 LICENSES/GPL-3.txt
88
+ 770397d605802346385b7c69ab27b919c1b734d653c6ed64b255349e5ffeaef2 metadata/coverage.json
89
+ a82a5872d4c62c7a0159ee23c684273e0eb61f4cd252f0db735e15e00364f95a metadata/families.json
90
+ ffc93609ac4a7d0f858696da211e1ec214409df51b8223d6833fd318b0d19f86 metadata/release.json
91
+ 74105bd146098de3bbe19c995eed3b3e5c63cad8b9480d08db34333292fec1d5 metadata/source_manifest.json
92
+ 9b912f908b65a553835273e3cfe3745b5d63f5d148ec1b719412db2471dbd0d7 metadata/validation.json
93
+ ba391bbb79dd26d51519409f44987afff3757513aa7bf9519b053795c2f156d8 README.md
94
+ df4bd25666834a74821035deda2154cd2922e3e0d2d00db0bd02f99ba4ad8caf requirements.txt
95
+ d49505bf35dffc763df91b13c8b5885e78b607af56d7aceba01e427c3fa19a6b schemas/benchmark_evaluation.schema.json
96
+ 32a7f0865e9c851848fc775f9bde1125bd03749b4130d34fe95d5ffc62a700c0 schemas/benchmark_profile.schema.json
97
+ 88fb894b919323c0457f1cb4bf934f72320d644299185127c164579343606425 schemas/foambench_qoi_candidate.schema.json
98
+ 9204923e5b93e333459ccfc43394137deaee1bf19d6f01beaf8ada664806d7e8 schemas/foambench_qoi_comparison.schema.json
99
+ 2ef632eb4ed82ad78213de6ee4b18aa36558916a106cb258505493c95285ac68 schemas/foambench_qoi_reference.schema.json
100
+ 839a77fa504b7f13b2b6803c0ca2448df83418779cee2a2a5a5acdc18cd8760c schemas/qoi_recovery_plan.schema.json
101
+ 73da798dd8c3ff74733a2a08a8d914d9e85c6d3184196dd0f2f8d0a45789a45a scripts/verify_release.py
102
+ 59854984853104df5c353e2f681a15fc7924742f9a2e468c29af248dce45ce03 VERSION
VERSION ADDED
@@ -0,0 +1 @@
 
 
1
+ 1.0.0
benchmarks/FoamBench_advanced_openfoam13_fixed_final.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_advanced_openfoam13_reference_qois.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_basic_openfoam13_fixed_final.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_basic_openfoam13_reference_qois.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_extended_openfoam13_evidence_contract.v1.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "foambench.evidence.contract.v1",
3
+ "purpose": "Agent-independent discovery and validation contract for physics-grounded QoI evidence",
4
+ "normalization": "lowercase ASCII alphanumeric for routing hints only",
5
+ "roots": [
6
+ "case/postProcessing",
7
+ "case/postprocessing",
8
+ "case/results",
9
+ "case/outputs",
10
+ "workspace/postProcessing",
11
+ "workspace/postprocessing",
12
+ "workspace/results",
13
+ "workspace/outputs",
14
+ "workspace/evidence",
15
+ "workspace/reports"
16
+ ],
17
+ "manifest": {
18
+ "path": "workspace/evidence/qoi_manifest.v1.json",
19
+ "required_fields": ["metric", "path", "kind", "columns", "time_semantics", "method_version"],
20
+ "path_policy": "path must resolve below a canonical evidence root",
21
+ "priority": ["validated_manifest", "deterministic_field_derivation", "semantic_discovery"]
22
+ },
23
+ "kinds": {
24
+ "force_coefficients": {
25
+ "aliases": ["forcecoeffs", "forcecoefficients", "forcecoefficient", "aerodynamicloads", "aeroloads", "loads"],
26
+ "required_columns": ["Time", "at_least_one_of:Cd,Cl,Cm"],
27
+ "physical_validation": "coefficient table with declared reference normalization"
28
+ },
29
+ "patch_flux": {
30
+ "aliases": ["patchflowrate", "patchflow", "massflow", "massflux", "rhophi", "fluxhistory"],
31
+ "required_columns": ["Time", "explicit_mass_or_volumetric_flux"],
32
+ "physical_validation": "patch identity and phi dimensions/unit declaration"
33
+ },
34
+ "patch_pressure": {
35
+ "aliases": ["patchaverage", "patchintegrate", "pressurerise", "pressuredifference", "patchpressure"],
36
+ "required_columns": ["Time", "pressure", "inlet_identity", "outlet_identity"],
37
+ "physical_validation": "static/total pressure convention and outlet-minus-inlet orientation"
38
+ },
39
+ "wall_law_profile": {
40
+ "aliases": ["spaldingcomparison", "uplusyplus", "walllawprofile", "velocityprofile", "wallprofile"],
41
+ "required_columns": ["y_plus_alias"],
42
+ "optional_columns": ["u_plus_alias", "spalding_prediction_alias"],
43
+ "physical_validation": "wall/region identity and final-saved-time or declared profile time"
44
+ },
45
+ "centerline_profile": {
46
+ "aliases": ["centerline", "centreline", "horizontal", "vertical", "px0", "py0", "rhox0", "rhoy0"],
47
+ "required_columns": ["coordinate", "at_least_one_of:p,rho,U"],
48
+ "physical_validation": "line orientation and sample time must be recoverable"
49
+ },
50
+ "bubble_geometry": {
51
+ "aliases": ["bubblegeometry", "bubblemetrics", "interfacegeometry"],
52
+ "required_columns": ["component_identity", "geometry_value"],
53
+ "physical_validation": "derived from alpha/interface fields; undefined topology is not incomplete evidence"
54
+ }
55
+ },
56
+ "proxy_policy": "A routing hint never promotes a file to evidence; metric-specific content, units, dimensions, identity, and time validation are mandatory.",
57
+ "unresolved_status": "unresolved_evidence",
58
+ "extractor_method_version": "physics_grounded_qoi.extractors.v3.1"
59
+ }
benchmarks/FoamBench_extended_openfoam13_fixed.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_extended_openfoam13_measurement_specs.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/FoamBench_extended_openfoam13_qoi_design.json ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "foambench.qoi.design",
3
+ "status": "executable_reference_contract",
4
+ "frozen_reference_unchanged": true,
5
+ "scope": "Extended FoamBench scientific QoI contract",
6
+ "global_policy": {
7
+ "principal_qoi_is": "the declared physical response of the task, not a generic field extreme or output-availability fallback",
8
+ "acceptance_model": "Every principal response must satisfy its reference-anchored task-response contract and any declared reference-independent physical bounds. Both are reported explicitly and must pass jointly.",
9
+ "fallback_policy": "A fallback proxy may be reported as diagnostic or coverage evidence, but never silently replaces a principal QoI.",
10
+ "conditional_policy": "A conditional QoI is mandatory only when its declared applicability evidence is retained. Missing applicability evidence is reported as unavailable and never counted as a passed physical criterion.",
11
+ "branch_policy": "Cases are aggregated only with cases sharing the same response definition and branch. Variant relations are scored separately from absolute reference agreement.",
12
+ "time_policy": "Every history QoI declares endpoint, event, steady-window, or transient-trajectory semantics. Full-history means are not a default.",
13
+ "tolerance_policy": {
14
+ "global_default_percent": null,
15
+ "steady_scalar": "max(3*sigma_repeat, discretization_envelope, measurement_floor)",
16
+ "profile": "normalized L1/L2/Linf error with a declared reference norm and spatial window",
17
+ "event_location": "max(3*sigma_event, 2*local_cell_size, physical_measurement_floor)",
18
+ "trajectory": "time-aligned normalized RMSE plus event-time error",
19
+ "provisional_rule": "If repeatability and discretization evidence are unavailable, the result is provisional and cannot be called strict scientific validation."
20
+ },
21
+ "required_provenance": [
22
+ "source_fields_or_postprocessing_file",
23
+ "patch_region_or_probe_definition",
24
+ "unit_and_normalization",
25
+ "time_window_or_event_rule",
26
+ "method_version",
27
+ "reference_uncertainty_or_provisional_flag"
28
+ ]
29
+ },
30
+ "families": [
31
+ {
32
+ "family": "ERCOFTA_pump",
33
+ "scientific_question": "Does the rotating pump surrogate produce the intended pressure/flow response under speed, pressure, mesh, model, and transient branches?",
34
+ "branches": [
35
+ {
36
+ "id": "steady_pressure_flow",
37
+ "cases": ["1", "2", "3", "4", "6", "7", "8", "10"],
38
+ "principal_qois": [
39
+ {"name": "pressure_rise", "definition": "outlet-minus-inlet area-averaged static-pressure difference on the explicitly named patches", "source": "inlet/outlet patchAverage(p) outputs", "aggregation": "time-aligned saved history"},
40
+ {"name": "mass_flow_rate", "definition": "signed mass or volumetric flow from the explicitly named inlet flux, preserving phi dimensions", "source": "inlet face flux", "aggregation": "saved history; inlet/outlet conservation remains diagnostic until both fluxes are retained"}
41
+ ],
42
+ "diagnostics": ["shaft_torque", "shaft_power", "mass_balance_residual", "rotor_zone_extent"],
43
+ "relations": ["speed-response branch", "outlet-pressure branch", "mesh/rotor-zone sensitivity"]
44
+ },
45
+ {
46
+ "id": "transient_pressure_flow",
47
+ "cases": ["5", "9"],
48
+ "principal_qois": [
49
+ {"name": "pressure_rise_history", "definition": "time-aligned pressure-rise history between declared inlet/outlet patches", "aggregation": "trajectory over declared transient window"}
50
+ ],
51
+ "diagnostics": ["shaft_torque_history", "mass_balance_residual"]
52
+ }
53
+ ],
54
+ "forbidden_principal_proxies": ["domain_pressure_span", "global_p_min_max", "unweighted_internal_pressure_range"]
55
+ },
56
+ {
57
+ "family": "MRF_stirredReactor",
58
+ "scientific_question": "How do impeller rotation, rheology, baffles, mesh, and rotating formulation change mixer power and phase/interface response?",
59
+ "branches": [
60
+ {
61
+ "id": "single_phase_mixing",
62
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
63
+ "principal_qois": [
64
+ {"name": "volume_average_speed_final", "definition": "cell-volume-weighted final-time average velocity magnitude", "source": "retained U and cell volumes; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"}
65
+ ],
66
+ "diagnostics": ["stirrer_power_history", "volume_average_speed_history", "circulation", "mass_balance_residual"],
67
+ "relations": ["speed scaling", "mesh convergence", "baffle/model/sliding-mesh paired comparison"]
68
+ },
69
+ {
70
+ "id": "two_phase_interface",
71
+ "cases": ["10"],
72
+ "principal_qois": [
73
+ {"name": "volume_average_speed_history", "definition": "cell-volume-weighted domain average of velocity magnitude over the saved reference time window", "source": "U and cell volumes", "aggregation": "time-aligned trajectory"},
74
+ {"name": "volume_speed_rms_history", "definition": "cell-volume-weighted RMS spatial fluctuation of velocity magnitude about its instantaneous domain mean", "source": "U and cell volumes", "aggregation": "time-aligned trajectory"}
75
+ ],
76
+ "diagnostics": ["phase_volume_conservation", "interface_centroid", "phase_fraction_by_region"]
77
+ }
78
+ ],
79
+ "forbidden_principal_proxies": ["alpha_minimum_history", "global_alpha_minimum", "unrelated_phase_extreme"]
80
+ },
81
+ {
82
+ "family": "aerofoilNACA0012",
83
+ "scientific_question": "How do Mach number, angle of attack, turbulence model, mesh, and transient treatment change aerodynamic loads?",
84
+ "branches": [
85
+ {
86
+ "id": "aerodynamic_loads",
87
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
88
+ "principal_qois": [
89
+ {"name": "Cd", "definition": "drag coefficient from the forceCoeffs header-addressed Cd column", "source": "declared aerofoil wall patches and drag direction", "aggregation": "steady-window mean, or transient mean plus RMS"},
90
+ {"name": "Cl", "definition": "lift coefficient from the header-addressed Cl column", "source": "declared wall patches and lift direction", "aggregation": "same window"},
91
+ {"name": "Cm", "definition": "moment coefficient about declared reference center and pitch axis", "source": "forceCoeffs output", "aggregation": "same window"}
92
+ ],
93
+ "diagnostics": ["surface_pressure_coefficient_profile", "separation_location", "residual_and_force_plateau"],
94
+ "relations": ["Mach response", "angle-of-attack load trend", "mesh convergence", "model comparison"]
95
+ }
96
+ ],
97
+ "extractor_requirements": ["parse forceCoeffs header by field name; never assume row index", "verify dragDir, liftDir, Aref, lRef, CofR", "do not compare a transient endpoint to a steady-window reference"]
98
+ },
99
+ {
100
+ "family": "compressibleBubbleCollapse",
101
+ "scientific_question": "How do pressure, bubble geometry, density ratio, wall distance, mesh, and compressibility change bubble-collapse dynamics?",
102
+ "branches": [
103
+ {
104
+ "id": "collapse_dynamics",
105
+ "cases": ["1", "3", "4", "5", "6", "7", "8", "9"],
106
+ "principal_qois": [
107
+ {"name": "equivalent_radius_final", "definition": "final radius from connected gas-phase volume, R=(3V/(4*pi))^(1/3) in 3D or the declared 2D area-equivalent convention", "source": "gas-phase alpha and cell volumes; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"},
108
+ {"name": "final_component_count", "definition": "number of retained connected gas components at the final saved field", "source": "gas-phase alpha and cell connectivity", "aggregation": "final saved field"}
109
+ ],
110
+ "diagnostics": ["bubble_centroid_history", "bubble_count", "interface_area", "minimum_pressure", "phase_volume_conservation"],
111
+ "relations": ["ambient-pressure trend", "wall-distance effect", "mesh/AMR convergence"]
112
+ },
113
+ {
114
+ "id": "materialized_single_bubble_response",
115
+ "cases": ["2"],
116
+ "principal_qois": [
117
+ {"name": "equivalent_radius_final", "definition": "final connected-gas equivalent radius for the single 50 um bubble actually materialized by setFieldsDict", "source": "gas-phase alpha and cell volumes; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"},
118
+ {"name": "final_component_count", "definition": "number of retained connected gas components at the final saved field", "source": "gas-phase alpha and cell connectivity", "aggregation": "final saved field"}
119
+ ],
120
+ "diagnostics": ["collapse_time_censored_diagnostic", "bubble_centroid_history", "phase_volume_conservation"],
121
+ "relations": []
122
+ },
123
+ {
124
+ "id": "axisymmetric_ring_interaction",
125
+ "cases": ["10"],
126
+ "principal_qois": [
127
+ {"name": "equivalent_radius_final", "definition": "final connected gas-region equivalent radius under the materialized axisymmetric wedge convention", "source": "gas-phase alpha and cell volumes with wedge volume factor; measurement-only C/Vc preparation is permitted", "aggregation": "component-preserving final field"},
128
+ {"name": "final_component_count", "definition": "number of retained connected gas components at the final saved field", "source": "gas-phase alpha and cell connectivity", "aggregation": "final saved field"}
129
+ ],
130
+ "diagnostics": ["component_count", "collapse_time_censored_diagnostic", "phase_volume_conservation"],
131
+ "relations": ["axisymmetric connected-region interaction"]
132
+ }
133
+ ],
134
+ "extractor_requirements": ["identify gas phase explicitly", "use connected components when multiple bubbles exist", "do not use global alpha minimum as a bubble-response substitute"]
135
+ },
136
+ {
137
+ "family": "drivaerFastback",
138
+ "scientific_question": "How do speed, mesh, wheel/ground treatment, turbulence model, and DDES treatment change vehicle aerodynamic loads?",
139
+ "branches": [
140
+ {
141
+ "id": "steady_aerodynamic_loads",
142
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
143
+ "principal_qois": [
144
+ {"name": "Cd", "definition": "header-addressed drag coefficient for body, wheels, and declared force patches", "source": "forceCoeffs", "aggregation": "last steady window"},
145
+ {"name": "Cl", "definition": "header-addressed lift coefficient", "source": "forceCoeffs", "aggregation": "last steady window"},
146
+ {"name": "Cm", "definition": "header-addressed moment coefficient about declared center", "source": "forceCoeffs", "aggregation": "last steady window"}
147
+ ],
148
+ "relations": ["speed scaling", "mesh convergence", "wheel/ground treatment comparison", "turbulence-model comparison"]
149
+ },
150
+ {
151
+ "id": "transient_ddes",
152
+ "cases": ["10"],
153
+ "principal_qois": [
154
+ {"name": "Cd_mean", "definition": "time mean over statistically stationary DDES window", "source": "forceCoeffs", "aggregation": "stationary-window mean"},
155
+ {"name": "Cd_rms", "definition": "RMS fluctuation over the same window", "source": "forceCoeffs", "aggregation": "stationary-window RMS"}
156
+ ],
157
+ "diagnostics": ["Cl_mean", "Cl_rms", "dominant_force_frequency", "stationarity_test"]
158
+ }
159
+ ],
160
+ "extractor_requirements": ["parse forceCoeffs headers and reference quantities", "do not compare DDES endpoint to steady reference", "report body/wheel patch coverage"]
161
+ },
162
+ {
163
+ "family": "nozzleCDV",
164
+ "scientific_question": "How do back pressure, mesh, discretisation, boundary specification, solver, turbulence, and dimension change nozzle flow structure and mass-flow response?",
165
+ "branches": [
166
+ {
167
+ "id": "shock_present",
168
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
169
+ "principal_qois": [
170
+ {"name": "mass_flow_rate", "definition": "signed mass flux through the declared inlet section, preserving operating-point branches and the OpenFOAM phi sign", "source": "section face flux with phi dimensions [1 0 -1 0 0 0 0]", "aggregation": "final saved time per operating-point branch"}
171
+ ],
172
+ "conditional_qois": [
173
+ {"name": "shock_location", "condition": "a retained named centerline or versioned shock-detector output resolves one discontinuity", "definition": "location of maximum pressure-gradient or density-gradient on the declared centerline", "missing_evidence_status": "unavailable_not_passed"},
174
+ {"name": "pressure_ratio", "condition": "named inlet/outlet thermodynamic evidence and its static-or-total convention are retained", "definition": "declared static or total pressure ratio", "missing_evidence_status": "unavailable_not_passed"}
175
+ ],
176
+ "relations": ["back-pressure shock movement", "mesh convergence", "solver/discretisation comparison", "axisymmetric-vs-planar geometry"]
177
+ }
178
+ ],
179
+ "forbidden_principal_proxies": ["global_pressure_span", "pressure_min_max_without_section_or_centerline_definition"]
180
+ },
181
+ {
182
+ "family": "riemann2D",
183
+ "scientific_question": "How do numerical choices alter a four-quadrant compressible interaction while preserving the known/reference solution structure?",
184
+ "branches": [
185
+ {
186
+ "id": "profile_and_event_error",
187
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
188
+ "principal_qois": [
189
+ {"name": "centerline_profiles", "definition": "named rho, p, T, and velocity profiles on fixed horizontal and vertical centerlines", "source": "named sample profiles", "aggregation": "declared final time or aligned time; L1 and Linf errors are computed by the comparison layer"},
190
+ {"name": "event_locations", "definition": "declared shock, contact, and rarefaction feature locations from the versioned feature detector", "source": "feature detector on centerline profiles", "aggregation": "same time; location error is computed by the comparison layer"}
191
+ ],
192
+ "diagnostics": ["rho_min", "p_min", "positivity_failures", "mass_momentum_energy_balance", "parallel_difference_norm"],
193
+ "relations": ["mesh convergence", "Courant sensitivity", "flux/limiter comparison", "domain-size sensitivity", "restart/decomposition invariance"]
194
+ }
195
+ ],
196
+ "extractor_requirements": ["the reference profile and variable columns must be explicit", "a sampled value or last column is never called error without candidate-reference subtraction", "feature detector and sampling coordinates are versioned"]
197
+ },
198
+ {
199
+ "family": "risingBubble",
200
+ "scientific_question": "How do mesh, interface treatment, density/viscosity, gravity, and solver choices change bubble rise and deformation?",
201
+ "branches": [
202
+ {
203
+ "id": "bubble_trajectory",
204
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
205
+ "principal_qois": [
206
+ {"name": "bubble_centroid_y_final", "definition": "final volume-weighted centroid of the connected gas region from alpha threshold", "source": "gas-phase alpha and cell volumes; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"},
207
+ {"name": "equivalent_radius_final", "definition": "final connected gas-region equivalent radius", "source": "gas-phase alpha and cell volumes; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"},
208
+ {"name": "shape_aspect_ratio_final", "definition": "final principal-axis aspect ratio of the connected gas region", "source": "gas-phase alpha geometry and cell centres; measurement-only C/Vc preparation is permitted", "aggregation": "final saved field"}
209
+ ],
210
+ "diagnostics": ["bubble_centroid_y_history", "rise_velocity", "shape_aspect_ratio_history", "equivalent_diameter", "phase_volume_conservation", "interface_area", "breakup_or_coalescence_events"],
211
+ "relations": ["mesh convergence", "surface-tension/gravity branch", "density/viscosity branch", "solver/interface-scheme comparison"]
212
+ }
213
+ ],
214
+ "extractor_requirements": ["identify gas phase and connected component explicitly", "do not use global alpha minimum", "preserve transient histories rather than averaging all times into one scalar"]
215
+ },
216
+ {
217
+ "family": "supersonicCrossJet",
218
+ "scientific_question": "How do Mach number, jet/mainflow pressure ratio, injection angle, mesh, schemes, and solver formulation change jet penetration and shock structure?",
219
+ "branches": [
220
+ {
221
+ "id": "jet_trajectory_and_shock",
222
+ "cases": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
223
+ "principal_qois": [
224
+ {"name": "jet_to_mainstream_mass_flux_ratio", "definition": "absolute ratio of the explicit phi mass flux through inlet2 to inlet1 at the final saved time", "source": "inlet1 and inlet2 patch fluxes; phi dimensions must be mass/time", "aggregation": "final saved time with branches kept separate"},
225
+ {"name": "interior_pressure_span", "definition": "max(p)-min(p) in the declared internal shock-search window -1<=x<=1 and 0.1<=y<=0.95", "source": "final retained p field and cell centres; uniform p fields are expanded over the retained cells", "aggregation": "final saved field; boundary cells outside the search window are excluded"}
226
+ ],
227
+ "diagnostics": ["jet_centerline_trajectory", "section_pressure_ratio", "shock_strength", "mass_balance_residual"],
228
+ "relations": ["Mach trend", "pressure-ratio trend", "injection-angle trend", "mesh/scheme/solver sensitivity"]
229
+ }
230
+ ],
231
+ "extractor_requirements": ["declare the jet-identifying field or momentum criterion", "declare section coordinates and interpolation", "do not use global pressure span as principal response"]
232
+ },
233
+ {
234
+ "family": "yPlusVerification",
235
+ "scientific_question": "Does the wall-normal velocity profile and first-cell wall resolution agree with the declared turbulent-wall-law or low-Reynolds-number verification target?",
236
+ "branches": [
237
+ {
238
+ "id": "wall_law_profile",
239
+ "cases": ["1", "2", "8", "9"],
240
+ "principal_qois": [
241
+ {"name": "first_cell_yplus", "definition": "wall-normal y+ of first cell center on the declared wall patch", "source": "wall distance and wall shear, or an explicitly named wall-normal profile with y+", "aggregation": "patch/profile endpoint"}
242
+ ],
243
+ "diagnostics": ["spalding_log_rmse", "achieved_Re_tau", "u_tau", "profile_residual_by_yplus_bin"],
244
+ "relations": ["mesh resolution", "turbulence-model comparison"]
245
+ },
246
+ {
247
+ "id": "low_re_profile",
248
+ "cases": ["3", "4", "5", "6", "7"],
249
+ "principal_qois": [
250
+ {"name": "first_cell_yplus", "definition": "first-cell wall resolution on the declared wall patch", "source": "wall distance and wall shear, or an explicitly named wall-normal profile with y+", "aggregation": "patch/profile endpoint"}
251
+ ],
252
+ "diagnostics": ["spalding_log_rmse", "achieved_Re_tau", "wall_shear_distribution", "boundedness"]
253
+ },
254
+ {
255
+ "id": "multi_reynolds_branch",
256
+ "cases": ["10"],
257
+ "principal_qois": [
258
+ {"name": "branchwise_wall_law_metrics", "definition": "Spalding log-RMSE and first-cell yPlus preserved separately for Re_tau_180, Re_tau_395, and Re_tau_590 viscosity branches", "source": "branch-labelled spalding_comparison.raw or explicitly named branch profiles", "aggregation": "no cross-branch averaging"}
259
+ ],
260
+ "diagnostics": ["branchwise_achieved_Re_tau", "branchwise_first_cell_yplus"]
261
+ }
262
+ ],
263
+ "extractor_requirements": ["use spalding_comparison.raw residual by name only as an intermediate evidence source", "recompute/verify u_tau, nu, y+, U+, and valid y+ range", "never let a U_z column or an all-zero placeholder define profile error"]
264
+ }
265
+ ]
266
+ }
benchmarks/FoamBench_extended_openfoam13_reference_qois.json ADDED
The diff for this file is too large to render. See raw diff
 
benchmarks/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """FoamBench assets and evaluation utilities."""
benchmarks/assets/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ExtBench Geometry Assets
2
+
3
+ These files are copied from the OpenFOAM 13 tutorial distribution used to
4
+ build the benchmark reference cases. The OpenFOAM 13 distribution states in
5
+ `README.org` and `COPYING` that the distributed files may be redistributed
6
+ under the GNU General Public License, version 3 or later.
7
+
8
+ The asset manifest records the original tutorial location and SHA-256 digest
9
+ for every file. Materialization verifies the digest before copying an asset
10
+ into a case. The assets are kept separate from the case JSON so the benchmark
11
+ data remains readable and cases do not depend on a machine-specific `/opt`
12
+ path.
13
+
14
+ If a downstream distribution has additional provenance or licensing notices
15
+ for the DrivAer geometry, add them here and to `manifest.json` before release.
benchmarks/assets/manifest.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "foambench.asset-manifest.v1",
3
+ "license": "GPL-3.0-or-later (OpenFOAM 13 tutorial-derived files)",
4
+ "assets": {
5
+ "simpleRushtonMRF/stirrer4": {
6
+ "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj",
7
+ "sha256": "d64e176d6aa872857bb5b01791cc0441aa15ff8456440be7235f7481f658a117",
8
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/simpleRushtonMRF/constant/geometry/stirrer4.obj"
9
+ },
10
+ "simpleRushtonMRF/stirrer6": {
11
+ "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj",
12
+ "sha256": "d0572aec19c41b2454ba0d7eecd1e07a7aae6aa98695f35ce781715e663ae40b",
13
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/simpleRushtonMRF/constant/geometry/stirrer6.obj"
14
+ },
15
+ "simpleRushtonMRF/baffles": {
16
+ "path": "benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj",
17
+ "sha256": "612cb86bfa2c842444ba86f203af31c712da3e807ed537013fefff8ab40f42a2",
18
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/simpleRushtonMRF/constant/geometry/baffles.obj"
19
+ },
20
+ "naca0012/NACA0012": {
21
+ "path": "benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz",
22
+ "sha256": "9fd098e03da6178852d4f9837bc06d2f24599065644f951b481907513d835d90",
23
+ "source": "OpenFOAM-13/tutorials/resources/geometry/NACA0012.obj.gz"
24
+ },
25
+ "drivaerFastback/body": {
26
+ "path": "benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz",
27
+ "sha256": "0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe",
28
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/drivaerFastback/constant/geometry/body.obj.gz"
29
+ },
30
+ "drivaerFastback/frontWheels": {
31
+ "path": "benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz",
32
+ "sha256": "f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7",
33
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/drivaerFastback/constant/geometry/frontWheels.obj.gz"
34
+ },
35
+ "drivaerFastback/rearWheels": {
36
+ "path": "benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz",
37
+ "sha256": "02f25f876414a9a4cbdb9cfb08da9916ac49f7851d4658067abc371447f882ce",
38
+ "source": "OpenFOAM-13/tutorials/incompressibleFluid/drivaerFastback/constant/geometry/rearWheels.obj.gz"
39
+ }
40
+ }
41
+ }
benchmarks/assets/openfoam13/drivaerFastback/body.obj.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0622638e6d9e2ef61d739ef2ae699ce4d5fb212abeaaa6f4583da54f3da24efe
3
+ size 2839115
benchmarks/assets/openfoam13/drivaerFastback/frontWheels.obj.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3e4f7f432c3e76d4f509fbba2429825acfc25ab696265df73f828504e6483b7
3
+ size 860951
benchmarks/assets/openfoam13/drivaerFastback/rearWheels.obj.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02f25f876414a9a4cbdb9cfb08da9916ac49f7851d4658067abc371447f882ce
3
+ size 940038
benchmarks/assets/openfoam13/naca0012/NACA0012.obj.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fd098e03da6178852d4f9837bc06d2f24599065644f951b481907513d835d90
3
+ size 112656
benchmarks/assets/openfoam13/simpleRushtonMRF/baffles.obj ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wavefront OBJ file written 2024-10-12T17:20:59
2
+ o baffles
3
+
4
+ # points : 16
5
+ # faces : 8
6
+ # zones : 1
7
+ # 0 patch0 (nFaces: 8)
8
+
9
+ # <points count="16">
10
+ v 0.353553 0.353553 0
11
+ v 0.33234 0.33234 0
12
+ v 0.353553 0.353553 1.2
13
+ v 0.33234 0.33234 1.2
14
+ v -0.33234 -0.33234 0
15
+ v -0.353553 -0.353553 0
16
+ v -0.33234 -0.33234 1.2
17
+ v -0.353553 -0.353553 1.2
18
+ v -0.353553 0.353553 0
19
+ v -0.33234 0.33234 0
20
+ v -0.353553 0.353553 1.2
21
+ v -0.33234 0.33234 1.2
22
+ v 0.33234 -0.33234 0
23
+ v 0.353553 -0.353553 0
24
+ v 0.33234 -0.33234 1.2
25
+ v 0.353553 -0.353553 1.2
26
+ # </points>
27
+
28
+ # <faces count="8">
29
+ g patch0
30
+ f 2 4 3
31
+ f 2 3 1
32
+ f 6 8 7
33
+ f 6 7 5
34
+ f 10 12 11
35
+ f 10 11 9
36
+ f 14 16 15
37
+ f 14 15 13
38
+ # </faces>
benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer4.obj ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wavefront OBJ file
2
+ # Regions:
3
+ # 0 patch0
4
+ #
5
+ # points : 16
6
+ # triangles : 8
7
+ #
8
+ v -1.37773e-17 -0.075 0.57
9
+ v -2.75546e-17 -0.15 0.57
10
+ v -1.37773e-17 -0.075 0.63
11
+ v -2.75546e-17 -0.15 0.63
12
+ v -0.075 9.18485e-18 0.57
13
+ v -0.15 1.83697e-17 0.57
14
+ v -0.075 9.18485e-18 0.63
15
+ v -0.15 1.83697e-17 0.63
16
+ v 4.59243e-18 0.075 0.57
17
+ v 9.18485e-18 0.15 0.57
18
+ v 4.59243e-18 0.075 0.63
19
+ v 9.18485e-18 0.15 0.63
20
+ v 0.075 0 0.57
21
+ v 0.15 0 0.57
22
+ v 0.075 0 0.63
23
+ v 0.15 0 0.63
24
+ g patch0
25
+ f 1 2 4
26
+ f 1 4 3
27
+ f 5 6 8
28
+ f 5 8 7
29
+ f 9 10 12
30
+ f 9 12 11
31
+ f 13 14 16
32
+ f 13 16 15
benchmarks/assets/openfoam13/simpleRushtonMRF/stirrer6.obj ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wavefront OBJ file
2
+ # Regions:
3
+ # 0 zone0
4
+ # 1 patch0
5
+ #
6
+ # points : 24
7
+ # triangles : 12
8
+ #
9
+ v 0.0375 -0.0649519 0.57
10
+ v 0.075 -0.129904 0.57
11
+ v 0.0375 -0.0649519 0.63
12
+ v 0.075 -0.129904 0.63
13
+ v -0.0375 -0.0649519 0.57
14
+ v -0.075 -0.129904 0.57
15
+ v -0.0375 -0.0649519 0.63
16
+ v -0.075 -0.129904 0.63
17
+ v -0.075 9.18485e-18 0.57
18
+ v -0.15 1.83697e-17 0.57
19
+ v -0.075 9.18485e-18 0.63
20
+ v -0.15 1.83697e-17 0.63
21
+ v -0.0375 0.0649519 0.57
22
+ v -0.075 0.129904 0.57
23
+ v -0.0375 0.0649519 0.63
24
+ v -0.075 0.129904 0.63
25
+ v 0.075 0 0.57
26
+ v 0.15 0 0.57
27
+ v 0.075 0 0.63
28
+ v 0.15 0 0.63
29
+ v 0.0375 0.0649519 0.57
30
+ v 0.075 0.129904 0.57
31
+ v 0.0375 0.0649519 0.63
32
+ v 0.075 0.129904 0.63
33
+ g zone0
34
+ f 1 2 4
35
+ f 1 4 3
36
+ f 5 6 8
37
+ f 5 8 7
38
+ f 9 10 12
39
+ f 9 12 11
40
+ f 13 14 16
41
+ f 13 16 15
42
+ g patch0
43
+ f 17 18 20
44
+ f 17 20 19
45
+ g zone0
46
+ f 21 22 24
47
+ f 21 24 23
benchmarks/evaluation/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Standalone EasyFoam benchmark evaluator
2
+
3
+ This directory contains the supplied evaluation implementation for Basic, Advanced and Extended tracks. See [Evaluation](../../docs/EVALUATION.md) for metric definitions, commands, dependencies, native-tool behavior and protocol boundaries, and the [dataset card](../../README.md) for contribution attribution.
4
+
5
+ From the repository root:
6
+
7
+ ```bash
8
+ python -m pip install -r requirements.txt
9
+ python -m benchmarks.evaluation validate-profile --profile benchmarks/evaluation/profiles/extended.json
10
+ ```
11
+
12
+ Agent campaign launchers and skill-evolution runtime code are distributed separately from this dataset. No model API key is needed to inspect the dataset or evaluate retained artifacts.
benchmarks/evaluation/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataset-independent FoamBench evaluation framework."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from .aggregate import aggregate_results
7
+ from .models import BenchmarkProfile, CaseArtifact
8
+
9
+
10
+ def evaluate_campaign(
11
+ profile: BenchmarkProfile,
12
+ *,
13
+ adapter_name: str,
14
+ run_root: Path,
15
+ output_dir: Path | None = None,
16
+ check_mesh: bool = False,
17
+ mesh_timeout: float = 120.0,
18
+ ) -> dict[str, Any]:
19
+ """Evaluate a campaign without importing the full pipeline at package import time."""
20
+ from .pipeline import evaluate_campaign as run_evaluation
21
+
22
+ return run_evaluation(
23
+ profile,
24
+ adapter_name=adapter_name,
25
+ run_root=run_root,
26
+ output_dir=output_dir,
27
+ check_mesh=check_mesh,
28
+ mesh_timeout=mesh_timeout,
29
+ )
30
+
31
+ __all__ = ["BenchmarkProfile", "CaseArtifact", "aggregate_results", "evaluate_campaign"]
benchmarks/evaluation/__main__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ try:
7
+ raise SystemExit(main())
8
+ except (OSError, ValueError, RuntimeError, json.JSONDecodeError) as exc:
9
+ print(f"foambench-evaluate: error: {exc}", file=sys.stderr)
10
+ raise SystemExit(2)
benchmarks/evaluation/adapters/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .easyfoam import EasyFoamAdapter
2
+ from .foamagent import FoamAgentAdapter
3
+ from .chatcfd import ChatCFDAdapter
4
+ from .coding_agent import CodingAgentAdapter
5
+
6
+ ADAPTERS = {
7
+ "easyfoam": EasyFoamAdapter,
8
+ "foamagent": FoamAgentAdapter,
9
+ "chatcfd": ChatCFDAdapter,
10
+ "coding-agent": CodingAgentAdapter,
11
+ }
12
+
13
+
14
+ def create_adapter(name: str, *args, **kwargs):
15
+ try:
16
+ adapter = ADAPTERS[name]
17
+ except KeyError as exc:
18
+ raise ValueError(f"unknown evaluation adapter: {name}") from exc
19
+ return adapter(*args, **kwargs)
20
+
21
+
22
+ __all__ = ["EasyFoamAdapter", "FoamAgentAdapter", "ChatCFDAdapter", "create_adapter"]
benchmarks/evaluation/adapters/chatcfd.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from ..io import read_object
6
+ from ..models import BenchmarkProfile, CaseArtifact
7
+ from .common import duration, token_usage
8
+
9
+
10
+ class ChatCFDAdapter:
11
+ """Normalize ChatCFD rollouts for the shared FoamBench scorer.
12
+
13
+ ChatCFD writes a case_run.log and keeps its model accounting in either a
14
+ rollout manifest or qa_logs.jsonl. The adapter deliberately does not
15
+ infer case identity from generated files: a manifest is the reproducible
16
+ source of truth for benchmark membership.
17
+ """
18
+
19
+ def __init__(self, run_root: Path, profile: BenchmarkProfile):
20
+ self.run_root = run_root.resolve(strict=True)
21
+ self.profile = profile
22
+
23
+ def discover(self) -> dict[str, CaseArtifact]:
24
+ artifacts: dict[str, CaseArtifact] = {}
25
+ for manifest_path in sorted(self.run_root.rglob("rollout_manifest.json")):
26
+ manifest = read_object(manifest_path)
27
+ case_id = manifest.get("case_id")
28
+ if not isinstance(case_id, str) or case_id in artifacts:
29
+ continue
30
+ rollout = manifest_path.parent
31
+ case_ref = manifest.get("case_path", "case")
32
+ case_dir = Path(case_ref)
33
+ if not case_dir.is_absolute():
34
+ case_dir = rollout / case_dir
35
+ case_dir = case_dir.resolve()
36
+ family, variant = self.profile.identity(case_id)
37
+ logs = [p.resolve() for p in case_dir.glob("log.*") if p.is_file()]
38
+ logs.extend(p.resolve() for p in (case_dir / "case_run.log", case_dir / "Allrun.out", case_dir / "Allrun.err") if p.is_file())
39
+ normalized = dict(manifest)
40
+ normalized["duration_seconds"] = duration(manifest)
41
+ normalized["token_usage"] = token_usage(manifest)
42
+ if manifest.get("resource_measurement") == "request-journal-v1":
43
+ # Shared CSV reporting uses input/output names. Preserve the
44
+ # raw journal totals and completeness flags alongside aliases.
45
+ usage = normalized["token_usage"]
46
+ usage["input_tokens"] = usage["prompt_tokens"]
47
+ usage["output_tokens"] = usage["response_tokens"]
48
+ # Task selection and generation/repair have separate logs.
49
+ qa_logs = {p.resolve() for p in (rollout / "qa_logs.jsonl", case_dir / "qa_logs.jsonl") if p.is_file()}
50
+ if not normalized["token_usage"] and qa_logs:
51
+ totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0}
52
+ for path in sorted(qa_logs):
53
+ for key, value in self._qa_usage(path).items():
54
+ totals[key] += value
55
+ normalized["token_usage"] = totals
56
+ artifacts[case_id] = CaseArtifact(
57
+ case_id=case_id,
58
+ dataset=self.profile.dataset,
59
+ family=str(manifest.get("family") or family),
60
+ variant=str(manifest.get("variant") or variant),
61
+ replicate=int(manifest.get("replicate", 1)),
62
+ rollout_dir=rollout,
63
+ # Like Foam-Agent, ChatCFD supplies generic solver evidence,
64
+ # not an EasyFoam workflow workspace with formal run records.
65
+ workspace_dir=None,
66
+ case_dir=case_dir if case_dir.is_dir() else None,
67
+ manifest=normalized,
68
+ solver_logs=tuple(sorted(set(logs))),
69
+ )
70
+ return artifacts
71
+
72
+ @staticmethod
73
+ def _qa_usage(path: Path) -> dict[str, int]:
74
+ import json
75
+ totals = {"calls": 0, "prompt_tokens": 0, "response_tokens": 0, "reasoning_tokens": 0}
76
+ for line in path.read_text(encoding="utf-8").splitlines():
77
+ try:
78
+ row = json.loads(line)
79
+ except json.JSONDecodeError:
80
+ continue
81
+ totals["calls"] += 1
82
+ totals["prompt_tokens"] += int(row.get("prompt_tokens", 0) or 0)
83
+ totals["response_tokens"] += int(row.get("response_tokens", 0) or 0)
84
+ totals["reasoning_tokens"] += int(row.get("reasoning_tokens", 0) or 0)
85
+ return totals
benchmarks/evaluation/adapters/coding_agent.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from ..io import read_object
6
+ from ..models import BenchmarkProfile, CaseArtifact
7
+
8
+
9
+ class CodingAgentAdapter:
10
+ """Use externally recorded output discovery; impose no agent-side file contract."""
11
+
12
+ def __init__(self, run_root: Path, profile: BenchmarkProfile):
13
+ self.run_root = run_root.resolve(strict=True)
14
+ self.profile = profile
15
+
16
+ def discover(self) -> dict[str, CaseArtifact]:
17
+ result = {}
18
+ for path in sorted(self.run_root.glob("*/*/replicate_001/rollout_manifest.json")):
19
+ manifest = read_object(path)
20
+ if manifest.get("experiment_kind") != "requirement_only_coding_agent.v1":
21
+ raise ValueError(f"Unexpected experiment manifest: {path}")
22
+ case_id = manifest["case_id"]
23
+ if case_id in result:
24
+ raise ValueError(f"Duplicate case: {case_id}")
25
+ rollout = path.parent
26
+ workspace = rollout / "workspace"
27
+ ref = manifest.get("output_discovery", {}).get("case_ref")
28
+ case_dir = None
29
+ if isinstance(ref, str):
30
+ candidate = (workspace / ref).resolve()
31
+ if not candidate.is_relative_to(workspace.resolve()):
32
+ raise ValueError(f"Case escapes workspace: {ref}")
33
+ case_dir = candidate
34
+ logs = []
35
+ for ref in manifest.get("solver_log_refs", []):
36
+ candidate = (rollout / ref).resolve()
37
+ if not candidate.is_relative_to(rollout.resolve()):
38
+ raise ValueError(f"Log escapes rollout: {ref}")
39
+ if candidate.is_file():
40
+ logs.append(candidate)
41
+ family, variant = self.profile.identity(case_id)
42
+ result[case_id] = CaseArtifact(
43
+ case_id=case_id, dataset=self.profile.dataset, family=family, variant=variant,
44
+ replicate=1, rollout_dir=rollout, workspace_dir=workspace, case_dir=case_dir,
45
+ manifest={**manifest, "agent_mode": "coding-only", "domain_assets_enabled": False},
46
+ solver_logs=tuple(logs),
47
+ )
48
+ return result
benchmarks/evaluation/adapters/common.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from ..io import read_object
7
+
8
+
9
+ def formal_records(workspace: Path) -> tuple[Path, ...]:
10
+ paths: list[Path] = []
11
+ workflow_path = workspace / "workflow.json"
12
+ if workflow_path.is_file():
13
+ workflow = read_object(workflow_path)
14
+ refs = workflow.get("artifacts", {}).get("run_records", [])
15
+ for ref in refs if isinstance(refs, list) else []:
16
+ if isinstance(ref, str):
17
+ paths.append(workspace / ref)
18
+ paths.extend(workspace.glob("runs/formal-*/run_record.json"))
19
+ unique = {path.resolve() for path in paths if path.is_file()}
20
+ return tuple(sorted(unique))
21
+
22
+
23
+ def successful_formal_records(paths: tuple[Path, ...]) -> tuple[Path, ...]:
24
+ successful = []
25
+ for path in paths:
26
+ record = read_object(path)
27
+ if record.get("mode") == "formal" and record.get("terminal_status") == "succeeded":
28
+ successful.append(path)
29
+ return tuple(successful)
30
+
31
+
32
+ def logs_from_records(workspace: Path, records: tuple[Path, ...]) -> tuple[Path, ...]:
33
+ logs: list[Path] = []
34
+ for path in records:
35
+ record = read_object(path)
36
+ for command in record.get("commands", []) if isinstance(record.get("commands"), list) else []:
37
+ if not isinstance(command, dict):
38
+ continue
39
+ for key in ("stdout_ref", "stderr_ref"):
40
+ ref = command.get(key)
41
+ if isinstance(ref, str):
42
+ candidate = workspace / ref
43
+ if candidate.is_file():
44
+ logs.append(candidate.resolve())
45
+ return tuple(dict.fromkeys(logs))
46
+
47
+
48
+ def token_usage(manifest: dict[str, Any]) -> dict[str, Any]:
49
+ usage = manifest.get("token_usage")
50
+ if isinstance(usage, dict):
51
+ return dict(usage)
52
+ attempts = manifest.get("attempts")
53
+ if isinstance(attempts, list) and attempts and isinstance(attempts[-1], dict):
54
+ usage = attempts[-1].get("token_usage")
55
+ return dict(usage) if isinstance(usage, dict) else {}
56
+
57
+
58
+ def duration(manifest: dict[str, Any]) -> float | None:
59
+ value = manifest.get("duration_seconds")
60
+ if isinstance(value, (int, float)):
61
+ return float(value)
62
+ process = manifest.get("process")
63
+ if isinstance(process, dict) and isinstance(process.get("duration_seconds"), (int, float)):
64
+ return float(process["duration_seconds"])
65
+ attempts = manifest.get("attempts")
66
+ values = [
67
+ float(item["duration_seconds"])
68
+ for item in attempts if isinstance(attempts, list) and isinstance(item, dict)
69
+ and isinstance(item.get("duration_seconds"), (int, float))
70
+ ] if isinstance(attempts, list) else []
71
+ return sum(values) if values else None
benchmarks/evaluation/adapters/easyfoam.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from ..foam import FATAL_RE, final_log_time, normal_end
6
+ from ..foam_io import read_text
7
+ from ..io import read_object
8
+ from ..models import BenchmarkProfile, CaseArtifact
9
+ from .common import duration, formal_records, logs_from_records, successful_formal_records, token_usage
10
+
11
+
12
+ class EasyFoamAdapter:
13
+ """Normalize supported EasyFoam rollout layouts."""
14
+
15
+ def __init__(self, run_root: Path, profile: BenchmarkProfile):
16
+ self.run_root = run_root.resolve(strict=True)
17
+ self.profile = profile
18
+
19
+ def discover(self) -> dict[str, CaseArtifact]:
20
+ artifacts: dict[str, CaseArtifact] = {}
21
+ legacy = sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json"))
22
+ current = sorted(self.run_root.rglob("run_manifest.json")) if not legacy else []
23
+ for path in [*legacy, *current]:
24
+ manifest = read_object(path)
25
+ case_id = manifest.get("case_id")
26
+ if not isinstance(case_id, str) or case_id in artifacts:
27
+ continue
28
+ rollout = path.parent
29
+ workspace = self._workspace(rollout, manifest)
30
+ family, variant = self.profile.identity(case_id)
31
+ coding_only = manifest.get("agent_mode") == "coding-only" or manifest.get("domain_assets_enabled") is False
32
+ case_dir = workspace / "case" if workspace else None
33
+ if coding_only and case_dir and case_dir.is_dir():
34
+ # Coding-only rollouts intentionally do not retain EasyFoam
35
+ # formal records. Avoid scanning their large workspaces for
36
+ # workflow/run-record artifacts before using generic logs.
37
+ records = ()
38
+ generic_logs = [item for item in case_dir.glob("log.*") if item.is_file()]
39
+ generic_logs.extend(
40
+ item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file()
41
+ )
42
+ logs = _successful_generic_logs(generic_logs)
43
+ else:
44
+ records = formal_records(workspace) if workspace and workspace.is_dir() else ()
45
+ logs = logs_from_records(workspace, successful_formal_records(records)) if workspace else ()
46
+ normalized = dict(manifest)
47
+ normalized["duration_seconds"] = duration(manifest)
48
+ normalized["token_usage"] = token_usage(manifest)
49
+ artifacts[case_id] = CaseArtifact(
50
+ case_id=case_id,
51
+ dataset=self.profile.dataset,
52
+ family=str(manifest.get("family") or family),
53
+ variant=str(manifest.get("variant") or variant),
54
+ replicate=int(manifest.get("replicate", 1)),
55
+ rollout_dir=rollout,
56
+ workspace_dir=workspace,
57
+ case_dir=case_dir,
58
+ manifest=normalized,
59
+ formal_run_records=records,
60
+ solver_logs=logs,
61
+ workflow_path=workspace / "workflow.json" if workspace else None,
62
+ evidence_summary_path=workspace / "evidence_summary.json" if workspace else None,
63
+ )
64
+ return artifacts
65
+
66
+ def _workspace(self, rollout: Path, manifest: dict) -> Path | None:
67
+ direct = rollout / "workspace"
68
+ if direct.is_dir():
69
+ return direct.resolve()
70
+ ref = manifest.get("workspace_ref")
71
+ if isinstance(ref, str):
72
+ candidate = Path(ref)
73
+ if not candidate.is_absolute():
74
+ candidate = self.run_root / candidate
75
+ return candidate.resolve()
76
+ return None
77
+
78
+
79
+ def _successful_generic_logs(paths: list[Path]) -> tuple[Path, ...]:
80
+ """Select final successful solver evidence without failed repair/postprocess logs."""
81
+ canonical_paths = tuple(sorted({item.resolve() for item in paths if item.name == "log.foamRun"}))
82
+ if canonical_paths:
83
+ # log.foamRun is the runner's canonical solver log. Do not read
84
+ # multi-hundred-MB repair logs during artifact discovery; execution
85
+ # and numerical gates perform the substantive log checks later.
86
+ return canonical_paths
87
+ if paths:
88
+ # Avoid eagerly loading every repair/post-processing log merely to
89
+ # choose evidence. Prefer the newest generic log; gate parsing will
90
+ # validate its contents when it is actually evaluated.
91
+ existing = [item.resolve() for item in paths if item.is_file()]
92
+ if existing:
93
+ return (max(existing, key=lambda item: item.stat().st_mtime),)
94
+ evidence = []
95
+ for path in sorted({item.resolve() for item in paths}):
96
+ text = read_text(path)
97
+ if FATAL_RE.search(text):
98
+ continue
99
+ evidence.append((path, text, final_log_time(text)))
100
+ canonical = [item for item in evidence if item[0].name == "log.foamRun"]
101
+ if canonical:
102
+ return tuple(item[0] for item in canonical)
103
+ timed = [item for item in evidence if item[2] is not None]
104
+ if timed:
105
+ latest = max(float(item[2]) for item in timed if item[2] is not None)
106
+ return tuple(item[0] for item in timed if item[2] == latest)
107
+ ended = [item for item in evidence if normal_end(item[1])]
108
+ return tuple(item[0] for item in (ended or evidence))
benchmarks/evaluation/adapters/foamagent.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from ..io import read_object
6
+ from ..models import BenchmarkProfile, CaseArtifact
7
+ from .common import duration, token_usage
8
+
9
+
10
+ class FoamAgentAdapter:
11
+ def __init__(self, run_root: Path, profile: BenchmarkProfile):
12
+ self.run_root = run_root.resolve(strict=True)
13
+ self.profile = profile
14
+
15
+ def discover(self) -> dict[str, CaseArtifact]:
16
+ artifacts: dict[str, CaseArtifact] = {}
17
+ for path in sorted(self.run_root.glob("*/*/replicate_*/rollout_manifest.json")):
18
+ manifest = read_object(path)
19
+ case_id = manifest.get("case_id")
20
+ if not isinstance(case_id, str) or case_id in artifacts:
21
+ continue
22
+ rollout = path.parent
23
+ case_dir = rollout / "case"
24
+ family, variant = self.profile.identity(case_id)
25
+ logs = [item for item in case_dir.glob("log.*") if item.is_file()]
26
+ logs.extend(item for item in (case_dir / "Allrun.out", case_dir / "Allrun.err") if item.is_file())
27
+ process = manifest.get("process") if isinstance(manifest.get("process"), dict) else {}
28
+ attempts = manifest.get("attempts") if isinstance(manifest.get("attempts"), list) else []
29
+ last_attempt = attempts[-1] if attempts and isinstance(attempts[-1], dict) else {}
30
+ normalized = dict(manifest)
31
+ normalized["return_code"] = process.get(
32
+ "return_code", last_attempt.get("return_code", manifest.get("return_code"))
33
+ )
34
+ normalized["timed_out"] = bool(process.get(
35
+ "timed_out", last_attempt.get("timed_out", manifest.get("timed_out", False))
36
+ ))
37
+ normalized["duration_seconds"] = duration(manifest)
38
+ normalized["token_usage"] = token_usage(manifest)
39
+ for metrics_path in (rollout / "llm_metrics.json", rollout / "attempt_001.llm_metrics.json"):
40
+ if metrics_path.is_file():
41
+ normalized["token_usage"] = token_usage({"token_usage": read_object(metrics_path)})
42
+ break
43
+ if isinstance(manifest.get("execution"), dict):
44
+ normalized["source_execution"] = manifest["execution"]
45
+ artifacts[case_id] = CaseArtifact(
46
+ case_id=case_id,
47
+ dataset=self.profile.dataset,
48
+ family=str(manifest.get("family") or family),
49
+ variant=str(manifest.get("variant") or variant),
50
+ replicate=int(manifest.get("replicate", 1)),
51
+ rollout_dir=rollout,
52
+ workspace_dir=None,
53
+ case_dir=case_dir,
54
+ manifest=normalized,
55
+ solver_logs=tuple(sorted({item.resolve() for item in logs})),
56
+ )
57
+ return artifacts
benchmarks/evaluation/aggregate.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import statistics
4
+ from collections import Counter
5
+ from typing import Any
6
+
7
+
8
+ def _rate(count: int, denominator: int) -> float | None:
9
+ return count / denominator if denominator else None
10
+
11
+
12
+ def aggregate_results(rows: list[dict[str, Any]]) -> dict[str, Any]:
13
+ total = len(rows)
14
+ execution = sum(bool(row.get("scores", {}).get("execution_pass")) for row in rows)
15
+ numerical = sum(bool(row.get("scores", {}).get("numerical_pass")) for row in rows)
16
+ qoi = sum(
17
+ bool(
18
+ row.get("scores", {}).get(
19
+ "physics_grounded_qoi_pass",
20
+ row.get("scores", {}).get("qoi_pass"),
21
+ )
22
+ )
23
+ for row in rows
24
+ )
25
+ end_to_end = sum(bool(row.get("scores", {}).get("end_to_end_pass")) for row in rows)
26
+ ratios = [float(row.get("qoi", {}).get("effective_pass_ratio", 0.0)) for row in rows]
27
+ coverage = [
28
+ float(comparison["qoi_coverage_fraction"])
29
+ for row in rows
30
+ for comparison in [row.get("qoi", {}).get("comparison")]
31
+ if isinstance(comparison, dict) and isinstance(comparison.get("qoi_coverage_fraction"), (int, float))
32
+ ]
33
+ failures = Counter(
34
+ failure
35
+ for row in rows
36
+ for failure in row.get("failure_categories", [])
37
+ )
38
+ return {
39
+ "task_count": total,
40
+ "execution_pass_count": execution,
41
+ "execution_pass_rate": _rate(execution, total),
42
+ "numerical_pass_count": numerical,
43
+ "numerical_pass_rate_all_tasks": _rate(numerical, total),
44
+ "numerical_pass_rate_execution_pass": _rate(numerical, execution),
45
+ "physics_grounded_qoi_pass_count": qoi,
46
+ "physics_grounded_qoi_pass_rate_all_tasks": _rate(qoi, total),
47
+ "physics_grounded_qoi_pass_rate_execution_pass": _rate(qoi, execution),
48
+ "end_to_end_pass_count": end_to_end,
49
+ "end_to_end_pass_rate": _rate(end_to_end, total),
50
+ "mean_qoi_pass_ratio_all_tasks": statistics.fmean(ratios) if ratios else None,
51
+ "mean_qoi_coverage_evaluated": statistics.fmean(coverage) if coverage else None,
52
+ "failure_taxonomy": dict(sorted(failures.items())),
53
+ }
54
+
55
+
56
+ def aggregate_evolution(groups: dict[str, list[dict[str, Any]]]) -> dict[str, Any]:
57
+ """Paired repeated-split reporting. Duplicate tasks remain group-qualified."""
58
+ metrics = ("execution_pass", "numerical_pass", "physics_grounded_qoi_pass", "end_to_end_pass")
59
+
60
+ def summarize(rows):
61
+ for row in rows:
62
+ for side in ("initial", "evolved"):
63
+ scores = row.get("reporting_scores", {}).get(side)
64
+ if not isinstance(scores, dict) or any(type(scores.get(key)) is not bool for key in metrics):
65
+ raise ValueError("independent reporting scores are missing; reward is not a pass metric")
66
+ if scores["end_to_end_pass"] != all(scores[key] for key in metrics[:3]):
67
+ raise ValueError("TAR is inconsistent with the three task-level checks")
68
+ return {metric: {
69
+ side: {"count": sum(row["reporting_scores"][side][metric] for row in rows),
70
+ "rate": statistics.fmean(row["reporting_scores"][side][metric] for row in rows)}
71
+ for side in ("initial", "evolved")
72
+ } | {
73
+ "gain": statistics.fmean(int(row["reporting_scores"]["evolved"][metric]) - int(row["reporting_scores"]["initial"][metric]) for row in rows),
74
+ "failed_to_passed": sum(not row["reporting_scores"]["initial"][metric] and row["reporting_scores"]["evolved"][metric] for row in rows),
75
+ "passed_to_failed": sum(row["reporting_scores"]["initial"][metric] and not row["reporting_scores"]["evolved"][metric] for row in rows),
76
+ } for metric in metrics}
77
+
78
+ per_group = {}
79
+ all_rows = []
80
+ for group_id, rows in groups.items():
81
+ keys = {(row["dataset"], row["case_id"]) for row in rows}
82
+ if not rows or len(keys) != len(rows):
83
+ raise ValueError(f"empty or duplicate test tasks in group {group_id}")
84
+ per_group[group_id] = {"task_count": len(rows), "metrics": summarize(rows)}
85
+ all_rows.extend(dict(row, group_id=group_id) for row in rows)
86
+ families = {family: summarize([row for row in all_rows if row["family"] == family])
87
+ for family in sorted({row["family"] for row in all_rows})}
88
+ means = {metric: {side: {
89
+ "mean": statistics.fmean(group["metrics"][metric][side]["rate"] for group in per_group.values()),
90
+ "min": min(group["metrics"][metric][side]["rate"] for group in per_group.values()),
91
+ "max": max(group["metrics"][metric][side]["rate"] for group in per_group.values()),
92
+ } for side in ("initial", "evolved")} for metric in metrics}
93
+ return {"groups": per_group, "group_rates": means, "families": families,
94
+ "family_equal_weight_rates": {metric: {side: statistics.fmean(family[metric][side]["rate"] for family in families.values())
95
+ for side in ("initial", "evolved")} for metric in metrics},
96
+ "test_records_per_condition": len(all_rows),
97
+ "unique_task_count": len({(row["dataset"], row["case_id"]) for row in all_rows}),
98
+ "test_frequency": dict(Counter(f"{row['dataset']}::{row['case_id']}" for row in all_rows)),
99
+ "interpretation": "Descriptive repeated splits; overlapping tasks and groups are not independent samples.",
100
+ "cases": all_rows}
benchmarks/evaluation/basic_advanced.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Structured QoIs shared by FoamBench Basic and Advanced references/candidates."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import math
8
+ import re
9
+ import subprocess
10
+ from pathlib import Path
11
+ from typing import Any, Callable
12
+
13
+ from .foam_arrays import FoamArrayError, foam_path, read_scalar_field, read_vector_field
14
+ from .foam_io import magnitude, read_text
15
+ from .io import utc_now, write_json
16
+ from .schema import validate
17
+
18
+
19
+ ADVANCED_TEMPLATE = {
20
+ "Cavity_LES": "Cavity", "Cavity_SA": "Cavity", "Cavity_geometry_1": "Cavity",
21
+ "Cylinder_LES": "Cylinder", "Cylinder_SA": "Cylinder",
22
+ "Diamond_Obstacle_KOMEGASST": "Obstacle", "Diamond_Obstacle_SA": "Obstacle",
23
+ "Double_Square_SA": "Obstacle", "Rectangular_Obstacle_KOMEGASST": "Obstacle",
24
+ "Rectangular_Obstacle_SA": "Obstacle", "counterFlowFlame2D_KE": "counterFlowFlame2D",
25
+ "counterFlowFlame2D_SA": "counterFlowFlame2D", "nozzleFlow2D_SA": "Nozzle",
26
+ "obliqueShock_KE": "Shock", "obliqueShock_LES": "Shock", "wedge_SA": "Shock",
27
+ }
28
+
29
+ GROUPS = {
30
+ "BernardCells": "thermal_state", "Cavity": "cavity_response", "Cylinder": "wake_response",
31
+ "counterFlowFlame2D": "flame_response", "damBreakWithObstacle": "free_surface_response",
32
+ "forwardStep": "shock_response", "obliqueShock": "shock_response", "wedge": "shock_response",
33
+ "Shock": "shock_response", "pitzDaily": "separation_response", "Obstacle": "obstacle_response",
34
+ "shallowWaterWithSquareBump": "surface_response", "squareBend": "bend_response",
35
+ "Nozzle": "nozzle_response",
36
+ }
37
+
38
+ PHYSICS_METRICS = {
39
+ "BernardCells": ("temperature_min", "temperature_max", "convection_mean_speed"),
40
+ "Cavity": ("response_speed_max", "reverse_flow_min_u"),
41
+ "Cylinder": ("wake_deficit_final",),
42
+ "counterFlowFlame2D": ("species_sum_max_error", "reaction_temperature_span"),
43
+ "damBreakWithObstacle": ("water_volume_relative_drift", "front_net_advance"),
44
+ "forwardStep": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
45
+ "obliqueShock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
46
+ "wedge": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
47
+ "Shock": ("supersonic_volume_fraction", "shock_pressure_jump_ratio"),
48
+ "pitzDaily": ("reverse_flow_volume_fraction", "streamwise_pressure_change_magnitude"),
49
+ "Obstacle": ("streamwise_pressure_change_magnitude",),
50
+ "shallowWaterWithSquareBump": ("mid_bump_height_relative_change",),
51
+ "squareBend": ("streamwise_pressure_change_magnitude",),
52
+ "Nozzle": ("flow_speed_max",),
53
+ }
54
+
55
+ # Each family already extracts one spatial response profile. Making that
56
+ # profile mandatory adds field-structure discrimination without introducing
57
+ # another observable or extractor. Scalar envelopes remain the
58
+ # reference-independent admissibility check; profiles are the deliberately
59
+ # stricter, reference-anchored response-shape check.
60
+ PRINCIPAL_RESPONSE_PROFILES = {
61
+ "BernardCells": ("thermal_vertical_profile",),
62
+ "Cavity": ("centerline_velocity_profiles",),
63
+ "Cylinder": ("wake_velocity_profiles",),
64
+ "counterFlowFlame2D": ("reaction_zone_profile",),
65
+ "damBreakWithObstacle": ("free_surface_profile",),
66
+ "forwardStep": ("pressure_mach_profiles",),
67
+ "obliqueShock": ("pressure_mach_profiles",),
68
+ "wedge": ("pressure_mach_profiles",),
69
+ "Shock": ("pressure_mach_profiles",),
70
+ "pitzDaily": ("separation_profiles",),
71
+ "Obstacle": ("separation_profiles",),
72
+ "shallowWaterWithSquareBump": ("surface_profile",),
73
+ "squareBend": ("bend_axial_profile",),
74
+ "Nozzle": ("nozzle_axial_profile",),
75
+ }
76
+
77
+
78
+ def principal_metrics(template: str) -> tuple[str, ...]:
79
+ return PHYSICS_METRICS[template] + PRINCIPAL_RESPONSE_PROFILES[template]
80
+
81
+
82
+ def numeric_times(case: Path) -> list[tuple[float, Path]]:
83
+ result = []
84
+ for child in case.iterdir():
85
+ if child.is_dir():
86
+ try:
87
+ result.append((float(child.name), child))
88
+ except ValueError:
89
+ pass
90
+ return sorted(result)
91
+
92
+
93
+ def align(values: list[Any], count: int) -> list[Any]:
94
+ if len(values) == count:
95
+ return values
96
+ if len(values) == 1 and count:
97
+ return values * count
98
+ return []
99
+
100
+
101
+ def scalars(directory: Path, name: str, count: int) -> list[float]:
102
+ path = foam_path(directory, name)
103
+ if path is None:
104
+ return []
105
+ try:
106
+ return align(read_scalar_field(path), count)
107
+ except (FoamArrayError, OSError, ValueError):
108
+ return []
109
+
110
+
111
+ def vectors(directory: Path, name: str, count: int) -> list[tuple[float, float, float]]:
112
+ path = foam_path(directory, name)
113
+ if path is None:
114
+ return []
115
+ try:
116
+ return align(read_vector_field(path), count)
117
+ except (FoamArrayError, OSError, ValueError):
118
+ match = re.search(
119
+ r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)",
120
+ read_text(path),
121
+ )
122
+ return [(float(match[1]), float(match[2]), float(match[3]))] * count if match else []
123
+
124
+
125
+ def geometry(case: Path) -> tuple[list[tuple[float, float, float]], list[float], float, Path]:
126
+ times = numeric_times(case)
127
+ for time, directory in reversed(times):
128
+ c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
129
+ if c_path and v_path:
130
+ centres = read_vector_field(c_path)
131
+ volumes = align(read_scalar_field(v_path), len(centres))
132
+ if centres and volumes:
133
+ return centres, volumes, time, directory
134
+ # C and Vc are measurement products, not required solver outputs. The
135
+ # independent evaluator also runs without prepare_campaign(), so recover
136
+ # the same geometric quantities directly from a retained static polyMesh.
137
+ # This uses no reference values and never writes into the frozen case.
138
+ if not times:
139
+ raise ValueError(f"no retained time directories for measurement: {case}")
140
+ from .retained_fields import derive_cell_geometry
141
+ try:
142
+ volumes, centres, _ = derive_cell_geometry(case)
143
+ except (ValueError, OSError) as exc:
144
+ raise ValueError(f"missing C/Vc and retained mesh geometry unavailable: {case}: {exc}") from exc
145
+ time, directory = times[-1]
146
+ count = raw_field_count(directory)
147
+ if count is not None and count != len(centres):
148
+ raise ValueError(f"retained field/mesh cell count mismatch: {case}")
149
+ return centres, volumes, time, directory
150
+
151
+
152
+ def raw_field_count(directory: Path) -> int | None:
153
+ for name, reader in (("alpha.water", read_scalar_field), ("h", read_scalar_field),
154
+ ("T", read_scalar_field), ("p", read_scalar_field), ("U", read_vector_field)):
155
+ path = foam_path(directory, name)
156
+ if path is None:
157
+ continue
158
+ try:
159
+ count = len(reader(path))
160
+ except (FoamArrayError, OSError, ValueError):
161
+ continue
162
+ if count > 1:
163
+ return count
164
+ return None
165
+
166
+
167
+ def geometry_for_time(
168
+ case: Path, directory: Path, fallback_centres: list[tuple[float, float, float]], fallback_volumes: list[float],
169
+ ) -> tuple[list[tuple[float, float, float]], list[float]]:
170
+ expected = raw_field_count(directory)
171
+ if expected in {None, len(fallback_centres)}:
172
+ return fallback_centres, fallback_volumes
173
+ c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
174
+ if not c_path or not v_path:
175
+ for function in ("writeCellCentres", "writeCellVolumes"):
176
+ completed = subprocess.run(
177
+ ["foamPostProcess", "-case", str(case), "-func", function, "-time", directory.name],
178
+ stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=False,
179
+ )
180
+ if completed.returncode != 0:
181
+ raise ValueError(f"{case}: {function} failed at time {directory.name}")
182
+ c_path, v_path = foam_path(directory, "C"), foam_path(directory, "Vc")
183
+ if not c_path or not v_path:
184
+ raise ValueError(f"{case}: no time-local C/Vc at {directory.name}")
185
+ centres = read_vector_field(c_path)
186
+ volumes = align(read_scalar_field(v_path), len(centres))
187
+ if len(centres) != expected or not volumes:
188
+ raise ValueError(f"{case}: time-local geometry mismatch at {directory.name}")
189
+ return centres, volumes
190
+
191
+
192
+ def bounds(centres: list[tuple[float, float, float]]) -> tuple[list[float], list[float]]:
193
+ return ([min(p[i] for p in centres) for i in range(3)], [max(p[i] for p in centres) for i in range(3)])
194
+
195
+
196
+ def primary_axis(spans: list[float]) -> int:
197
+ """Choose x/y/z deterministically when extents differ only by roundoff."""
198
+ largest = max(spans)
199
+ return next(i for i, span in enumerate(spans) if math.isclose(span, largest, rel_tol=1e-12, abs_tol=0.0))
200
+
201
+
202
+ def weighted(values: list[float], volumes: list[float]) -> float:
203
+ denominator = sum(volumes)
204
+ return sum(value * volume for value, volume in zip(values, volumes)) / denominator
205
+
206
+
207
+ def bins(
208
+ centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
209
+ fields: dict[str, list[float]], *, count: int = 41,
210
+ selector: Callable[[tuple[float, float, float]], bool] | None = None,
211
+ ) -> list[list[float]]:
212
+ low, high = bounds(centres)
213
+ span = high[axis] - low[axis]
214
+ groups: list[list[int]] = [[] for _ in range(count)]
215
+ for index, point in enumerate(centres):
216
+ if selector is not None and not selector(point):
217
+ continue
218
+ slot = min(count - 1, max(0, int((point[axis] - low[axis]) / max(span, 1e-30) * count)))
219
+ groups[slot].append(index)
220
+ rows = []
221
+ for indices in groups:
222
+ if not indices:
223
+ continue
224
+ weights = [volumes[i] for i in indices]
225
+ row = [weighted([centres[i][axis] for i in indices], weights)]
226
+ for values in fields.values():
227
+ row.append(weighted([values[i] for i in indices], weights))
228
+ rows.append(row)
229
+ return rows
230
+
231
+
232
+ def profile(profile_id: str, coordinate: str, rows: list[list[float]], fields: list[str]) -> dict[str, Any]:
233
+ return {"profile_id": profile_id, "columns": [coordinate, *fields], "rows": rows}
234
+
235
+
236
+ def named_profiles(items: list[dict[str, Any]]) -> dict[str, Any]:
237
+ return {"kind": "named_profiles", "profiles": items}
238
+
239
+
240
+ def history(points: list[dict[str, float]]) -> dict[str, Any]:
241
+ return {"kind": "time_history", "points": points}
242
+
243
+
244
+ def velocity_fields(directory: Path, count: int) -> tuple[list[tuple[float, float, float]], dict[str, list[float]]]:
245
+ velocity = vectors(directory, "U", count)
246
+ if not velocity:
247
+ return [], {}
248
+ return velocity, {
249
+ "u": [v[0] for v in velocity], "v": [v[1] for v in velocity],
250
+ "speed": magnitude(velocity),
251
+ }
252
+
253
+
254
+ def thermo(case: Path) -> tuple[float, float]:
255
+ text = read_text(case / "constant" / "physicalProperties")
256
+ mw = re.search(r"(?m)^\s*molWeight\s+([-+0-9.eE]+)\s*;", text)
257
+ cp = re.search(r"(?m)^\s*Cp\s+([-+0-9.eE]+)\s*;", text)
258
+ if not mw or not cp:
259
+ return 1.4, 287.0
260
+ gas = 8314.46261815324 / float(mw[1])
261
+ heat = float(cp[1])
262
+ return (heat / (heat - gas) if heat > gas else 1.4), gas
263
+
264
+
265
+ def state_fields(case: Path, directory: Path, count: int) -> dict[str, list[float]]:
266
+ _, fields = velocity_fields(directory, count)
267
+ for name in (
268
+ "p", "p_rgh", "rho", "T", "CH4", "O2", "CO2", "H2O", "N2", "Qdot",
269
+ "alpha.water", "alpha.fuel", "h",
270
+ ):
271
+ values = scalars(directory, name, count)
272
+ if values:
273
+ fields[name] = values
274
+ if fields.get("T") and fields.get("speed"):
275
+ gamma, gas = thermo(case)
276
+ fields["Mach"] = [u / math.sqrt(gamma * gas * t) if t > 0 else 0.0 for u, t in zip(fields["speed"], fields["T"])]
277
+ hu = vectors(directory, "hU", count)
278
+ if hu and fields.get("h"):
279
+ fields["Froude"] = [
280
+ q / h / math.sqrt(9.81 * h) if h > 1e-12 else 0.0
281
+ for q, h in zip(magnitude(hu), fields["h"])
282
+ ]
283
+ return fields
284
+
285
+
286
+ def line_profile(
287
+ profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float],
288
+ axis: int, fixed_axis: int, fraction: float, fields: dict[str, list[float]], names: list[str],
289
+ ) -> dict[str, Any]:
290
+ low, high = bounds(centres)
291
+ target = low[fixed_axis] + fraction * (high[fixed_axis] - low[fixed_axis])
292
+ target = min((point[fixed_axis] for point in centres), key=lambda value: abs(value - target))
293
+ bandwidth = max((high[fixed_axis] - low[fixed_axis]) / 41.0, 1e-12)
294
+ selected = lambda point: abs(point[fixed_axis] - target) <= bandwidth
295
+ usable = {name: fields[name] for name in names if name in fields}
296
+ return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable, selector=selected), list(usable))
297
+
298
+
299
+ def section_profile(
300
+ profile_id: str, centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
301
+ fields: dict[str, list[float]], names: list[str],
302
+ ) -> dict[str, Any]:
303
+ usable = {name: fields[name] for name in names if name in fields}
304
+ return profile(profile_id, "xyz"[axis], bins(centres, volumes, axis, usable), list(usable))
305
+
306
+
307
+ def histories(
308
+ case: Path, centres: list[tuple[float, float, float]], volumes: list[float],
309
+ measure: Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None],
310
+ ) -> dict[str, Any]:
311
+ points = []
312
+ for time, directory in numeric_times(case):
313
+ local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes)
314
+ fields = state_fields(case, directory, len(local_centres))
315
+ value = measure(fields, local_centres, local_volumes)
316
+ if value is not None and math.isfinite(value):
317
+ points.append({"time": time, "value": float(value)})
318
+ return history(points)
319
+
320
+
321
+ def shock_events(value: dict[str, Any]) -> dict[str, Any]:
322
+ events = []
323
+ for item in value.get("profiles", []):
324
+ columns, rows = item["columns"], item["rows"]
325
+ if "p" not in columns or len(rows) < 2:
326
+ continue
327
+ p_index = columns.index("p")
328
+ candidates = []
329
+ coordinate_min, coordinate_max = rows[0][0], rows[-1][0]
330
+ interior_low = coordinate_min + 0.05 * (coordinate_max - coordinate_min)
331
+ interior_high = coordinate_max - 0.05 * (coordinate_max - coordinate_min)
332
+ for left, right in zip(rows, rows[1:]):
333
+ dx = right[0] - left[0]
334
+ coordinate = 0.5 * (right[0] + left[0])
335
+ if dx > 0 and interior_low < coordinate < interior_high:
336
+ candidates.append((abs(right[p_index] - left[p_index]) / dx, coordinate, dx))
337
+ if candidates:
338
+ _, coordinate, cell = max(candidates)
339
+ events.append({"profile_id": item["profile_id"], "field": "p", "coordinate": coordinate, "local_cell_size": cell})
340
+ return {"kind": "profile_feature_locations", "events": events}
341
+
342
+
343
+ def relative_drift(values: list[float]) -> float | None:
344
+ finite_values = [float(value) for value in values if math.isfinite(value)]
345
+ if len(finite_values) < 2:
346
+ return None
347
+ scale = max(abs(finite_values[0]), sum(abs(value) for value in finite_values) / len(finite_values), 1e-12)
348
+ return (max(finite_values) - min(finite_values)) / scale
349
+
350
+
351
+ def pressure_change(
352
+ pressure: list[float], centres: list[tuple[float, float, float]], volumes: list[float], axis: int,
353
+ ) -> float | None:
354
+ if not pressure:
355
+ return None
356
+ cut = max(1, len(pressure) // 10)
357
+ ordered = sorted(zip(centres, pressure, volumes), key=lambda item: item[0][axis])
358
+ first, last = ordered[:cut], ordered[-cut:]
359
+ return weighted([p for _, p, _ in first], [w for _, _, w in first]) - weighted(
360
+ [p for _, p, _ in last], [w for _, _, w in last]
361
+ )
362
+
363
+
364
+ def inventory_series(case: Path, field_name: str) -> list[float]:
365
+ centres, volumes, _, _ = geometry(case)
366
+ values = []
367
+ for _, directory in numeric_times(case):
368
+ local_centres, local_volumes = geometry_for_time(case, directory, centres, volumes)
369
+ field = scalars(directory, field_name, len(local_centres))
370
+ if field:
371
+ values.append(sum(value * volume for value, volume in zip(field, local_volumes)))
372
+ return values
373
+
374
+
375
+ def shock_pressure_jump_ratio(profiles: dict[str, Any]) -> float | None:
376
+ ratios = []
377
+ for item in profiles.get("profiles", []):
378
+ columns, rows = item.get("columns", []), item.get("rows", [])
379
+ if "p" not in columns:
380
+ continue
381
+ index = columns.index("p")
382
+ for left, right in zip(rows, rows[1:]):
383
+ low, high = sorted((float(left[index]), float(right[index])))
384
+ if low > 0:
385
+ ratios.append(high / low)
386
+ return max(ratios) if ratios else None
387
+
388
+
389
+ def family_qois(case: Path, template: str) -> dict[str, Any]:
390
+ centres, volumes, _, latest = geometry(case)
391
+ low, high = bounds(centres)
392
+ spans = [high[i] - low[i] for i in range(3)]
393
+ primary = primary_axis(spans)
394
+ secondary = 1 if primary == 0 else 0
395
+ fields = state_fields(case, latest, len(centres))
396
+ if fields.get("p"):
397
+ pressure_mean = weighted(fields["p"], volumes)
398
+ fields["p_gauge"] = [value - pressure_mean for value in fields["p"]]
399
+ qois: dict[str, Any] = {}
400
+
401
+ def downstream_min_u(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
402
+ values = [u for point, u in zip(c, f.get("u", [])) if point[primary] >= low[primary] + 0.5 * spans[primary]]
403
+ return min(values) if values else None
404
+
405
+ def middle_section_mean(name: str, fraction: float = 0.5) -> Callable[[dict[str, list[float]], list[tuple[float, float, float]], list[float]], float | None]:
406
+ def measure(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
407
+ values = f.get(name, [])
408
+ if not values:
409
+ return None
410
+ local_low, local_high = bounds(c)
411
+ target = local_low[primary] + fraction * (local_high[primary] - local_low[primary])
412
+ target = min((point[primary] for point in c), key=lambda value: abs(value - target))
413
+ width = max((local_high[primary] - local_low[primary]) / 41.0, 1e-12)
414
+ selected = [(value, volume) for point, value, volume in zip(c, values, v) if abs(point[primary] - target) <= width]
415
+ return weighted([item[0] for item in selected], [item[1] for item in selected]) if selected else None
416
+ return measure
417
+
418
+ def wake_deficit(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
419
+ streamwise = f.get("u", [])
420
+ if not streamwise:
421
+ return None
422
+ local_low, local_high = bounds(c)
423
+ span = local_high[primary] - local_low[primary]
424
+ width = max(span / 41.0, 1e-12)
425
+ section_values = []
426
+ for fraction in (0.10, 0.65):
427
+ target = local_low[primary] + fraction * span
428
+ target = min((point[primary] for point in c), key=lambda value: abs(value - target))
429
+ selected = [(u, volume) for point, u, volume in zip(c, streamwise, v)
430
+ if abs(point[primary] - target) <= width]
431
+ if not selected:
432
+ return None
433
+ section_values.append(weighted([item[0] for item in selected], [item[1] for item in selected]))
434
+ upstream, wake = section_values
435
+ return (upstream - wake) / max(abs(upstream), 1e-12)
436
+
437
+ if template == "BernardCells":
438
+ qois["thermal_vertical_profile"] = named_profiles([
439
+ line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["T", "u", "v", "speed"])
440
+ ])
441
+ qois["circulation_strength_history"] = histories(case, centres, volumes, lambda f, c, v: weighted(f["speed"], v) if f.get("speed") else None)
442
+ if fields.get("T"):
443
+ qois["temperature_min"] = min(fields["T"])
444
+ qois["temperature_max"] = max(fields["T"])
445
+ if fields.get("speed"):
446
+ qois["convection_mean_speed"] = weighted(fields["speed"], volumes)
447
+ elif template == "Cavity":
448
+ qois["centerline_velocity_profiles"] = named_profiles([
449
+ line_profile("vertical_centerline", centres, volumes, 1, 0, 0.5, fields, ["u", "v", "speed"]),
450
+ line_profile("horizontal_centerline", centres, volumes, 0, 1, 0.5, fields, ["u", "v", "speed"]),
451
+ ])
452
+ qois["kinetic_energy_history"] = histories(case, centres, volumes, lambda f, c, w: 0.5 * weighted([v*v for v in f["speed"]], w) if f.get("speed") else None)
453
+ if fields.get("speed"):
454
+ qois["response_speed_max"] = max(fields["speed"])
455
+ if fields.get("u"):
456
+ qois["reverse_flow_min_u"] = min(fields["u"])
457
+ elif template == "Cylinder":
458
+ qois["wake_velocity_profiles"] = named_profiles([
459
+ line_profile(f"wake_x_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"])
460
+ for fraction in (0.65, 0.80)
461
+ ])
462
+ qois["wake_deficit_history"] = histories(case, centres, volumes, wake_deficit)
463
+ points = qois["wake_deficit_history"].get("points", [])
464
+ if points:
465
+ qois["wake_deficit_final"] = float(points[-1]["value"])
466
+ elif template == "counterFlowFlame2D":
467
+ names = ["T", "CO2"] + (["Qdot"] if fields.get("Qdot") else [])
468
+ qois["reaction_zone_profile"] = named_profiles([section_profile("reaction_axis", centres, volumes, primary, fields, names)])
469
+ if fields.get("Qdot"):
470
+ qois["heat_release_history"] = histories(case, centres, volumes, lambda f, c, w: sum(v*vol for v, vol in zip(f["Qdot"], w)) if f.get("Qdot") else None)
471
+ else:
472
+ qois["peak_temperature_history"] = histories(case, centres, volumes, lambda f, c, v: max(f["T"]) if f.get("T") else None)
473
+ species = [fields[name] for name in ("CH4", "O2", "CO2", "H2O", "N2") if fields.get(name)]
474
+ if len(species) == 5:
475
+ qois["species_sum_max_error"] = max(abs(sum(values) - 1.0) for values in zip(*species))
476
+ if fields.get("T"):
477
+ qois["reaction_temperature_span"] = max(fields["T"]) - min(fields["T"])
478
+ elif template == "damBreakWithObstacle":
479
+ qois["front_position_history"] = histories(case, centres, volumes, lambda f, c, v: max((p[0] for p, a in zip(c, f.get("alpha.water", [])) if a >= 0.5), default=None))
480
+ alpha = fields.get("alpha.water", [])
481
+ rows = []
482
+ for slot in bins(centres, volumes, 0, {"alpha": alpha}):
483
+ x = slot[0]
484
+ width = spans[0] / 41
485
+ wet_y = [p[1] for p, a in zip(centres, alpha) if abs(p[0] - x) <= width and a >= 0.5]
486
+ if wet_y:
487
+ rows.append([x, max(wet_y)])
488
+ qois["free_surface_profile"] = named_profiles([profile("alpha_0.5_surface", "x", rows, ["surface_y"])])
489
+ drift = relative_drift(inventory_series(case, "alpha.water"))
490
+ if drift is not None:
491
+ qois["water_volume_relative_drift"] = drift
492
+ front_points = qois["front_position_history"].get("points", [])
493
+ if len(front_points) >= 2:
494
+ qois["front_net_advance"] = float(front_points[-1]["value"]) - float(front_points[0]["value"])
495
+ elif template in {"forwardStep", "obliqueShock", "wedge", "Shock"}:
496
+ profiles = named_profiles([
497
+ line_profile(f"streamline_{fraction:.2f}", centres, volumes, primary, secondary, fraction, fields, ["p", "Mach", "u", "speed"])
498
+ for fraction in (0.25, 0.50, 0.75)
499
+ ])
500
+ qois["pressure_mach_profiles"] = profiles
501
+ qois["shock_feature_locations"] = shock_events(profiles)
502
+ if fields.get("Mach"):
503
+ qois["supersonic_volume_fraction"] = sum(
504
+ volume for mach, volume in zip(fields["Mach"], volumes) if mach > 1.0
505
+ ) / sum(volumes)
506
+ jump = shock_pressure_jump_ratio(profiles)
507
+ if jump is not None:
508
+ qois["shock_pressure_jump_ratio"] = jump
509
+ elif template in {"pitzDaily", "Obstacle"}:
510
+ qois["separation_profiles"] = named_profiles([
511
+ section_profile("streamwise_sections", centres, volumes, primary, fields, ["u", "v", "speed", "p_gauge"]),
512
+ *[line_profile(f"wake_{fraction:.2f}", centres, volumes, secondary, primary, fraction, fields, ["u", "v", "speed", "p_gauge"]) for fraction in (0.65, 0.80)],
513
+ ])
514
+ qois["recirculation_strength_history"] = histories(case, centres, volumes, downstream_min_u)
515
+ downstream = [
516
+ (u, volume) for point, u, volume in zip(centres, fields.get("u", []), volumes)
517
+ if point[primary] >= low[primary] + 0.5 * spans[primary]
518
+ ]
519
+ if downstream:
520
+ qois["reverse_flow_volume_fraction"] = sum(
521
+ volume for u, volume in downstream if u < 0.0
522
+ ) / sum(volume for _, volume in downstream)
523
+ change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary)
524
+ if change is not None:
525
+ qois["streamwise_pressure_change_magnitude"] = abs(change)
526
+ elif template == "shallowWaterWithSquareBump":
527
+ qois["surface_profile"] = named_profiles([section_profile("bump_axis", centres, volumes, primary, fields, ["h", "Froude"])])
528
+ qois["mid_bump_height_history"] = histories(case, centres, volumes, middle_section_mean("h"))
529
+ height_points = qois["mid_bump_height_history"].get("points", [])
530
+ if len(height_points) >= 2:
531
+ first, last = float(height_points[0]["value"]), float(height_points[-1]["value"])
532
+ qois["mid_bump_height_relative_change"] = abs(last - first) / max(abs(first), 1e-12)
533
+ elif template in {"squareBend", "Nozzle"}:
534
+ prefix = "bend" if template == "squareBend" else "nozzle"
535
+ qois[f"{prefix}_axial_profile"] = named_profiles([section_profile("axial_sections", centres, volumes, primary, fields, ["p", "p_rgh", "Mach", "u", "speed"])])
536
+ def pressure_drop(f: dict[str, list[float]], c: list[tuple[float, float, float]], v: list[float]) -> float | None:
537
+ return pressure_change(f.get("p") or f.get("p_rgh") or [], c, v, primary)
538
+ qois["pressure_drop_history"] = histories(case, centres, volumes, pressure_drop)
539
+ if template == "squareBend":
540
+ change = pressure_change(fields.get("p", []) or fields.get("p_rgh", []), centres, volumes, primary)
541
+ if change is not None:
542
+ qois["streamwise_pressure_change_magnitude"] = abs(change)
543
+ else:
544
+ drift = relative_drift(inventory_series(case, "alpha.fuel"))
545
+ if drift is not None:
546
+ qois["transported_phase_inventory_relative_drift"] = drift
547
+ if fields.get("speed"):
548
+ qois["flow_speed_max"] = max(fields["speed"])
549
+ else:
550
+ raise ValueError(f"no structured QoI family for {template}")
551
+ return qois
552
+
553
+
554
+ def structured_errors(name: str, value: Any) -> list[str]:
555
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
556
+ return [] if math.isfinite(float(value)) else [f"{name}: non-finite scalar"]
557
+ if not isinstance(value, dict):
558
+ return [f"{name}: not structured"]
559
+ if value.get("kind") == "time_history":
560
+ return [] if len(value.get("points", [])) >= 2 else [f"{name}: fewer than two history points"]
561
+ if value.get("kind") == "named_profiles":
562
+ profiles = value.get("profiles", [])
563
+ return [] if profiles and all(len(p.get("rows", [])) >= 2 and len(p.get("columns", [])) >= 2 for p in profiles) else [f"{name}: incomplete profiles"]
564
+ if value.get("kind") == "profile_feature_locations":
565
+ return [] if value.get("events") else [f"{name}: no feature events"]
566
+ return [f"{name}: unsupported kind"]
567
+
568
+
569
+ def extract(
570
+ case: Path,
571
+ case_id: str,
572
+ requested_metrics: list[str] | None = None,
573
+ *,
574
+ required_metrics: list[str] | None = None,
575
+ log_paths: list[Path] | None = None,
576
+ ) -> dict[str, Any]:
577
+ family = case_id.split("/", 1)[0]
578
+ template = ADVANCED_TEMPLATE.get(case_id, family)
579
+ values = family_qois(case, template)
580
+ requested = requested_metrics or sorted(values)
581
+ required = required_metrics or requested
582
+ selected = {name: values[name] for name in requested if name in values}
583
+ missing = sorted(set(required) - set(selected))
584
+ errors = [
585
+ error for name, value in selected.items() if name in required
586
+ for error in structured_errors(name, value)
587
+ ]
588
+ _, _, latest_time, _ = geometry(case)
589
+ complete = not missing and not errors
590
+ return {
591
+ "schema_version": "foambench.qoi.candidate", "case_id": case_id, "family": template,
592
+ "latest_time": latest_time, "status": "complete" if complete else "incomplete",
593
+ "principal_qoi_group": GROUPS[template],
594
+ "principal_metrics": sorted(name for name in required if name in selected),
595
+ "required_metrics": required, "missing_metrics": missing, "qois": selected,
596
+ "health": {"status": "pass" if complete else "fail", "checks": {
597
+ "principal_qoi_complete": not missing, "structured_qoi_valid": not errors,
598
+ "measurement_geometry_available": True, "no_proxy_fallback": True,
599
+ }, "validation_errors": errors},
600
+ }
601
+
602
+
603
+ FIELD_NORMALIZATION_FLOORS = {
604
+ "p": 1.0, "p_gauge": 1.0, "p_rgh": 1.0, "T": 0.1, "CO2": 1e-6, "Qdot": 1e-3,
605
+ "u": 1e-5, "v": 1e-5, "speed": 1e-5, "Mach": 1e-4,
606
+ "h": 1e-6, "Froude": 1e-4, "surface_y": 1e-6,
607
+ }
608
+ HISTORY_NORMALIZATION_FLOORS = {
609
+ "circulation_strength_history": 1e-6, "kinetic_energy_history": 1e-8,
610
+ "wake_deficit_history": 1e-4, "recirculation_strength_history": 1e-5,
611
+ "heat_release_history": 1e-3, "peak_temperature_history": 0.1,
612
+ "front_position_history": 1e-5, "mid_bump_height_history": 1e-6,
613
+ "pressure_drop_history": 1.0,
614
+ }
615
+
616
+
617
+ def tolerance(name: str, value: dict[str, Any], group: str) -> dict[str, Any]:
618
+ kind = value.get("kind")
619
+ if kind == "time_history":
620
+ return {"kind": kind, "normalized_rmse_max": 0.06 if group == "shock_response" else 0.08,
621
+ "normalized_linf_max": 0.15 if group == "shock_response" else 0.20,
622
+ "minimum_time_coverage": 1.0,
623
+ "normalization_floor": HISTORY_NORMALIZATION_FLOORS.get(name, 1e-8), "provisional": True}
624
+ if kind == "named_profiles":
625
+ columns = {column for item in value.get("profiles", []) for column in item.get("columns", [])[1:]}
626
+ return {"kind": kind, "normalized_l1_max": 0.05 if group == "shock_response" else 0.08,
627
+ "normalized_linf_max": 0.15 if group == "shock_response" else 0.20,
628
+ "normalization_floors": {column: FIELD_NORMALIZATION_FLOORS.get(column, 1e-8) for column in sorted(columns)},
629
+ "criterion_role": "principal_response_shape",
630
+ "reference_independent": False,
631
+ "threshold_source": "reference_anchored_spatial_response_shape",
632
+ "provisional": True}
633
+ if kind == "profile_feature_locations":
634
+ return {"kind": kind, "maximum_cell_offset": 2.0, "physical_floor": 1e-10, "provisional": True}
635
+ raise ValueError(f"unsupported structured tolerance for {kind}")
636
+
637
+
638
+ def uniform_scalars(path: Path) -> list[float]:
639
+ return [
640
+ float(match)
641
+ for match in re.findall(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", read_text(path))
642
+ ]
643
+
644
+
645
+ def uniform_vector_magnitudes(path: Path) -> list[float]:
646
+ return [
647
+ math.sqrt(sum(float(component) ** 2 for component in match))
648
+ for match in re.findall(
649
+ r"\bvalue\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)\s*;",
650
+ read_text(path),
651
+ )
652
+ ]
653
+
654
+
655
+ def physical_tolerance(template: str, name: str, case: Path) -> dict[str, Any]:
656
+ common: dict[str, Any] = {
657
+ "kind": "physics_range",
658
+ "criterion_role": "principal_physics",
659
+ "reference_independent": True,
660
+ }
661
+ if template == "BernardCells" and name in {"temperature_min", "temperature_max"}:
662
+ imposed = uniform_scalars(case / "0" / "T")
663
+ if len(imposed) < 2:
664
+ raise ValueError(f"{case}: cannot determine imposed temperature envelope")
665
+ low, high = min(imposed), max(imposed)
666
+ margin = max(1e-6, 0.02 * max(high - low, 1e-6))
667
+ bounds = (low - margin, high + margin)
668
+ return {**common, "low": bounds[0], "high": bounds[1],
669
+ "threshold_source": "imposed_temperature_boundary_envelope", "provisional": False}
670
+ if template == "BernardCells" and name == "convection_mean_speed":
671
+ return {**common, "low": 1e-12, "high": 1e6,
672
+ "threshold_source": "nontrivial_buoyant_response", "provisional": True}
673
+ if template == "Cavity":
674
+ imposed = uniform_vector_magnitudes(case / "0" / "U")
675
+ lid_speed = max(imposed, default=0.0)
676
+ if lid_speed <= 0:
677
+ raise ValueError(f"{case}: cannot determine moving-wall speed")
678
+ if name == "response_speed_max":
679
+ return {**common, "low": 0.10 * lid_speed, "high": 1.0 * lid_speed,
680
+ "threshold_source": "lid_speed_response_envelope_tightened", "provisional": True}
681
+ if name == "reverse_flow_min_u":
682
+ return {**common, "low": -1.0 * lid_speed, "high": -0.05 * lid_speed,
683
+ "threshold_source": "main_vortex_reverse_flow_envelope_tightened", "provisional": True}
684
+ if template == "shallowWaterWithSquareBump" and name == "mid_bump_height_relative_change":
685
+ initial_depths = uniform_scalars(case / "0" / "h")
686
+ initial_depth = sum(initial_depths) / len(initial_depths) if initial_depths else 0.0
687
+ # The shallow-water family changes regime with its prompt-specified
688
+ # initial depth. A single non-zero floor would accept a numerically
689
+ # stagnant response for the deeper cases.
690
+ low = 2e-4 if initial_depth <= 0.012 else 0.1
691
+ return {**common, "low": low, "high": 1.0,
692
+ "threshold_source": "initial_depth_conditioned_bump_response", "provisional": True}
693
+ fixed = {
694
+ # These are first-stage family envelopes: they reject merely non-zero
695
+ # signatures while retaining the checked-in reference regimes. They
696
+ # are intentionally absolute and reference-independent; later runs can
697
+ # replace them with law-based relations or repeatability envelopes.
698
+ ("Cylinder", "wake_deficit_final"): (0.03, 0.15, "bounded_dimensionless_wake_deficit"),
699
+ ("counterFlowFlame2D", "species_sum_max_error"): (0.0, 5e-5, "species_mass_fraction_closure_tightened"),
700
+ ("counterFlowFlame2D", "reaction_temperature_span"): (500.0, 3000.0, "bounded_thermal_reaction_zone"),
701
+ ("damBreakWithObstacle", "water_volume_relative_drift"): (0.0, 5e-3, "closed_phase_volume_conservation_tightened"),
702
+ ("damBreakWithObstacle", "front_net_advance"): (0.03, 0.25, "bounded_downstream_free_surface_advance"),
703
+ ("forwardStep", "supersonic_volume_fraction"): (0.40, 1.0, "supersonic_regime_coverage_tightened"),
704
+ ("obliqueShock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
705
+ ("wedge", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
706
+ ("Shock", "supersonic_volume_fraction"): (0.85, 1.0, "supersonic_regime_coverage_tightened"),
707
+ ("forwardStep", "shock_pressure_jump_ratio"): (1.50, 20.0, "bounded_compressive_pressure_feature"),
708
+ ("obliqueShock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"),
709
+ ("wedge", "shock_pressure_jump_ratio"): (2.00, 6.50, "bounded_compressive_pressure_feature"),
710
+ ("Shock", "shock_pressure_jump_ratio"): (1.10, 2.20, "bounded_compressive_pressure_feature"),
711
+ ("pitzDaily", "reverse_flow_volume_fraction"): (1e-3, 0.08, "bounded_separated_reverse_flow_signature"),
712
+ ("pitzDaily", "streamwise_pressure_change_magnitude"): (8.0, 140.0, "bounded_streamwise_pressure_response"),
713
+ ("Obstacle", "streamwise_pressure_change_magnitude"): (0.005, 10.0, "bounded_obstacle_pressure_response"),
714
+ ("squareBend", "streamwise_pressure_change_magnitude"): (3e4, 1.2e5, "bounded_bend_pressure_response"),
715
+ ("Nozzle", "flow_speed_max"): (100.0, 1000.0, "bounded_nozzle_flow_response"),
716
+ }
717
+ if (template, name) not in fixed:
718
+ raise ValueError(f"no physics tolerance for {template}/{name}")
719
+ low, high, source = fixed[(template, name)]
720
+ exact_sources = {"species_mass_fraction_closure", "closed_phase_volume_conservation"}
721
+ return {**common, "low": low, "high": high, "threshold_source": source,
722
+ "provisional": source not in exact_sources}
723
+
724
+
725
+ def diagnostic_scalar_tolerance(value: float) -> dict[str, Any]:
726
+ scale = max(abs(float(value)), 1e-12)
727
+ return {
728
+ "low": float(value) - 0.2 * scale,
729
+ "high": float(value) + 0.2 * scale,
730
+ "kind": "diagnostic_scalar_reference",
731
+ "provisional": True,
732
+ "threshold_source": "reference_diagnostic_relative_band",
733
+ }
734
+
735
+
736
+ def build_references(run_root: Path) -> tuple[dict[str, Any], dict[str, Any]]:
737
+ documents: dict[str, dict[str, Any]] = {}
738
+ for track in ("basic", "advanced"):
739
+ records = {}
740
+ for wrapper in sorted((run_root / "materialized" / track).iterdir()):
741
+ case = wrapper / "case"
742
+ if not case.is_dir():
743
+ continue
744
+ case_id = wrapper.name.replace("__", "/", 1) if track == "basic" else wrapper.name
745
+ candidate = extract(case, case_id)
746
+ if candidate["status"] != "complete":
747
+ raise ValueError(f"{case_id}: {candidate['health'].get('validation_errors') or candidate['missing_metrics']}")
748
+ group, qois = candidate["principal_qoi_group"], candidate["qois"]
749
+ principal = list(principal_metrics(candidate["family"]))
750
+ missing_principal = sorted(set(principal) - set(qois))
751
+ if missing_principal:
752
+ raise ValueError(f"{case_id}: missing physics metrics {missing_principal}")
753
+ roles = {name: "principal" if name in principal else "diagnostic" for name in qois}
754
+ tolerances = {
755
+ name: tolerance(name, value, group)
756
+ if isinstance(value, dict) and name in principal else (
757
+ physical_tolerance(candidate["family"], name, case)
758
+ if name in principal else (
759
+ diagnostic_scalar_tolerance(value)
760
+ if isinstance(value, (int, float)) and not isinstance(value, bool)
761
+ else tolerance(name, value, group)
762
+ )
763
+ )
764
+ for name, value in qois.items()
765
+ }
766
+ records[case_id] = {
767
+ "track": track, "family": candidate["family"], "source_case_id": case_id,
768
+ "latest_time": candidate["latest_time"], "principal_qoi_group": group,
769
+ "principal_metrics": sorted(principal), "qois": qois,
770
+ "metric_roles": roles, "tolerances": tolerances,
771
+ "health": candidate["health"], "extraction": {
772
+ "producer": "benchmarks/evaluation/basic_advanced.py",
773
+ "geometry": "field-derived physics metrics plus physical-coordinate reference diagnostics",
774
+ "reference_run": str(run_root),
775
+ },
776
+ }
777
+ documents[track] = {
778
+ "schema_version": "foambench.reference_qois.v2", "generated_at": utc_now(),
779
+ "openfoam_version": "Foundation v13", "producer": "benchmarks/evaluation/basic_advanced.py",
780
+ "design": "guide/foambench_basic_advanced_qoi_design.md",
781
+ "tolerance_policy": "physics_grounded_scalar_and_response_shape_joint_gate.v2",
782
+ "summary": {"tracks": [track], "case_count": len(records), "health_pass_count": len(records), "health_fail_count": 0},
783
+ "notes": ["Principal scalar QoIs are reference-independent family physics criteria extracted from retained fields.",
784
+ "One existing spatial response profile per family is also principal and must jointly pass its reference-anchored shape tolerance.",
785
+ "Other histories, profiles, and feature locations remain diagnostic and do not decide Physics-grounded pass.",
786
+ "Provisional physical-signature and response-shape limits require future valid-alternative calibration."],
787
+ "cases": records,
788
+ }
789
+ validate(documents[track], "foambench_qoi_reference.schema.json")
790
+ return documents["basic"], documents["advanced"]
791
+
792
+
793
+ def main() -> int:
794
+ parser = argparse.ArgumentParser(description=__doc__)
795
+ parser.add_argument("--run-root", required=True, type=Path)
796
+ parser.add_argument("--basic-output", required=True, type=Path)
797
+ parser.add_argument("--advanced-output", required=True, type=Path)
798
+ args = parser.parse_args()
799
+ basic, advanced = build_references(args.run_root.resolve(strict=True))
800
+ write_json(args.basic_output, basic)
801
+ write_json(args.advanced_output, advanced)
802
+ print(json.dumps({"basic": len(basic["cases"]), "advanced": len(advanced["cases"])}, indent=2))
803
+ return 0
804
+
805
+
806
+ if __name__ == "__main__":
807
+ raise SystemExit(main())
benchmarks/evaluation/cli.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .io import read_object
9
+ from .models import BenchmarkProfile
10
+ from .pipeline import evaluate_campaign
11
+ from .preparation import prepare_campaign
12
+ from .profiles import load_assets
13
+ from .reporting import summary_table
14
+ from .schema import validate
15
+
16
+
17
+ def build_parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(description="Evaluate FoamBench rollouts with a dataset-independent scorer.")
19
+ subparsers = parser.add_subparsers(dest="command", required=True)
20
+ validate = subparsers.add_parser("validate-profile", help="validate benchmark profile assets")
21
+ validate.add_argument("--profile", type=Path, required=True)
22
+ evaluate = subparsers.add_parser("evaluate", help="evaluate one rollout campaign")
23
+ evaluate.add_argument("--profile", type=Path, required=True)
24
+ evaluate.add_argument("--adapter", choices=("easyfoam", "foamagent", "chatcfd", "coding-agent"), required=True)
25
+ evaluate.add_argument("--run-root", type=Path, required=True)
26
+ evaluate.add_argument("--output", type=Path, required=True)
27
+ evaluate.add_argument(
28
+ "--prepare", action="store_true",
29
+ help="generate measurement-only C, Vc, and vorticity fields before evaluation",
30
+ )
31
+ evaluate.add_argument("--prepare-jobs", type=int, default=1)
32
+ evaluate.add_argument(
33
+ "--check-mesh", action="store_true",
34
+ help="run read-only checkMesh when no retained mesh log is available",
35
+ )
36
+ evaluate.add_argument("--mesh-timeout", type=float, default=120.0)
37
+ return parser
38
+
39
+
40
+ def main(argv: list[str] | None = None) -> int:
41
+ args = build_parser().parse_args(argv)
42
+ validate(read_object(args.profile), "benchmark_profile.schema.json")
43
+ profile = BenchmarkProfile.load(args.profile)
44
+ if args.command == "validate-profile":
45
+ benchmark, references = load_assets(profile)
46
+ print(json.dumps({
47
+ "profile_id": profile.profile_id,
48
+ "dataset": profile.dataset,
49
+ "benchmark_case_count": len(benchmark),
50
+ "reference_case_count": len(references),
51
+ "status": "pass",
52
+ }, indent=2, sort_keys=True))
53
+ return 0
54
+ if args.prepare:
55
+ prepare_campaign(
56
+ profile,
57
+ adapter_name=args.adapter,
58
+ run_root=args.run_root,
59
+ output_root=args.output.resolve() / "preparation",
60
+ jobs=args.prepare_jobs,
61
+ )
62
+ report = evaluate_campaign(
63
+ profile,
64
+ adapter_name=args.adapter,
65
+ run_root=args.run_root,
66
+ output_dir=args.output,
67
+ check_mesh=args.check_mesh,
68
+ mesh_timeout=args.mesh_timeout,
69
+ )
70
+ print(summary_table(report["overall"]))
71
+ return 0
72
+
73
+
74
+ if __name__ == "__main__":
75
+ try:
76
+ raise SystemExit(main())
77
+ except (OSError, ValueError, RuntimeError) as exc:
78
+ print(f"foambench-evaluate: error: {exc}", file=sys.stderr)
79
+ raise SystemExit(2)
benchmarks/evaluation/comparison.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Compare candidate FoamBench QoIs with checked-in reference contracts.
3
+
4
+ Coverage and numerical agreement are reported separately. Related field
5
+ statistics are scored as equal-weight QoI groups; ranges and runtime metrics
6
+ remain available as diagnostics but do not determine the group score. A
7
+ missing QoI means that the benchmark cannot assess that part of the result; it
8
+ is not relabelled as an out-of-tolerance value.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import math
15
+ import re
16
+ import sys
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+
22
+ def finite(value: Any) -> float | None:
23
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
24
+ return None
25
+ result = float(value)
26
+ return result if math.isfinite(result) else None
27
+
28
+
29
+ def scalar_observation(value: Any) -> float | None:
30
+ direct = finite(value)
31
+ if direct is not None:
32
+ return direct
33
+ if isinstance(value, dict) and value.get("kind") in {"scalar_ratio", "window_regression"}:
34
+ return finite(value.get("value"))
35
+ return None
36
+
37
+
38
+ def interpolate(points: list[dict[str, Any]], time: float) -> float | None:
39
+ rows = [(finite(item.get("time")), finite(item.get("value"))) for item in points if isinstance(item, dict)]
40
+ rows = sorted((t, v) for t, v in rows if t is not None and v is not None)
41
+ if not rows or time < rows[0][0] or time > rows[-1][0]:
42
+ return None
43
+ for index, (left_t, left_v) in enumerate(rows):
44
+ if abs(time - left_t) <= 1e-12 * max(1.0, abs(time)):
45
+ return left_v
46
+ if index + 1 < len(rows) and left_t < time < rows[index + 1][0]:
47
+ right_t, right_v = rows[index + 1]
48
+ weight = (time - left_t) / (right_t - left_t)
49
+ return left_v + weight * (right_v - left_v)
50
+ return None
51
+
52
+
53
+ def compare_history(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
54
+ reference_points = reference.get("points", [])
55
+ candidate_points = candidate.get("points", [])
56
+ pairs = []
57
+ for point in reference_points if isinstance(reference_points, list) else []:
58
+ time, reference_value = finite(point.get("time")), finite(point.get("value")) if isinstance(point, dict) else (None, None)
59
+ if time is None or reference_value is None:
60
+ continue
61
+ candidate_value = interpolate(candidate_points if isinstance(candidate_points, list) else [], time)
62
+ if candidate_value is not None:
63
+ pairs.append((reference_value, candidate_value))
64
+ required_coverage = finite(tolerance.get("minimum_time_coverage")) or 1.0
65
+ coverage = len(pairs) / len(reference_points) if reference_points else 0.0
66
+ if not pairs:
67
+ return {"status": "missing", "coverage_fraction": coverage}
68
+ floor = finite(tolerance.get("normalization_floor")) or 1e-12
69
+ norm = max(math.sqrt(sum(ref * ref for ref, _ in pairs) / len(pairs)), floor)
70
+ errors = [cand - ref for ref, cand in pairs]
71
+ nrmse = math.sqrt(sum(error * error for error in errors) / len(errors)) / norm
72
+ nlinf = max(abs(error) for error in errors) / norm
73
+ rmse_limit = finite(tolerance.get("normalized_rmse_max"))
74
+ linf_limit = finite(tolerance.get("normalized_linf_max"))
75
+ valid = rmse_limit is not None and linf_limit is not None
76
+ passed = valid and coverage >= required_coverage and nrmse <= rmse_limit and nlinf <= linf_limit
77
+ return {"status": "within_tolerance" if passed else "invalid_contract" if not valid else "out_of_tolerance",
78
+ "coverage_fraction": coverage, "aligned_point_count": len(pairs),
79
+ "normalized_rmse": nrmse, "normalized_linf": nlinf,
80
+ "normalized_rmse_max": rmse_limit, "normalized_linf_max": linf_limit}
81
+
82
+
83
+ def profile_key(profile: dict[str, Any]) -> str:
84
+ """Normalize centerline aliases by the coordinate direction they sample."""
85
+ name = Path(str(profile.get("profile_id", ""))).name.lower()
86
+ stem = Path(name).stem
87
+ if stem in {"centreline_y0", "centerline_y0", "centerliney", "horizontal", "horizontalcenterline", "horizontalcentreline"}:
88
+ return "horizontal.xy"
89
+ if stem in {"centreline_x0", "centerline_x0", "centerlinex", "vertical", "verticalcenterline", "verticalcentreline"}:
90
+ return "vertical.xy"
91
+ return name
92
+
93
+
94
+ def compare_profiles(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
95
+ references = {profile_key(item): item for item in reference.get("profiles", []) if isinstance(item, dict)}
96
+ candidates = {profile_key(item): item for item in candidate.get("profiles", []) if isinstance(item, dict)}
97
+ l1_limit, linf_limit = finite(tolerance.get("normalized_l1_max")), finite(tolerance.get("normalized_linf_max"))
98
+ if l1_limit is None or linf_limit is None:
99
+ return {"status": "invalid_contract"}
100
+ fields: list[dict[str, Any]] = []
101
+ expected_fields = sum(max(0, len(item.get("columns", [])) - 1) for item in references.values())
102
+ for key, ref_profile in references.items():
103
+ cand_profile = candidates.get(key)
104
+ if cand_profile is None:
105
+ continue
106
+ ref_columns, cand_columns = ref_profile.get("columns", []), cand_profile.get("columns", [])
107
+ ref_rows, cand_rows = ref_profile.get("rows", []), cand_profile.get("rows", [])
108
+ if len(ref_columns) < 2 or ref_columns[0] not in cand_columns:
109
+ continue
110
+ cand_x = cand_columns.index(ref_columns[0])
111
+ for field in ref_columns[1:]:
112
+ if field not in cand_columns:
113
+ continue
114
+ ref_i, cand_i = ref_columns.index(field), cand_columns.index(field)
115
+ cand_points = [{"time": row[cand_x], "value": row[cand_i]} for row in cand_rows]
116
+ pairs = [(row[ref_i], interpolate(cand_points, row[0])) for row in ref_rows]
117
+ pairs = [(ref, cand) for ref, cand in pairs if finite(ref) is not None and cand is not None]
118
+ if not pairs:
119
+ continue
120
+ declared_floors = tolerance.get("normalization_floors", {})
121
+ field_floor = finite(declared_floors.get(field)) if isinstance(declared_floors, dict) else None
122
+ norm = max(sum(abs(ref) for ref, _ in pairs) / len(pairs), field_floor or finite(tolerance.get("normalization_floor")) or 1e-12)
123
+ errors = [abs(cand - ref) for ref, cand in pairs]
124
+ fields.append({"profile": key, "field": field, "normalized_l1": sum(errors) / len(errors) / norm,
125
+ "normalized_linf": max(errors) / norm})
126
+ coverage = len(fields) / expected_fields if expected_fields else 0.0
127
+ passed = bool(fields) and coverage == 1.0 and all(item["normalized_l1"] <= l1_limit and item["normalized_linf"] <= linf_limit for item in fields)
128
+ return {"status": "within_tolerance" if passed else "missing" if not fields else "out_of_tolerance",
129
+ "coverage_fraction": coverage, "observed_field_count": len(fields),
130
+ "expected_field_count": expected_fields, "fields": fields,
131
+ "normalized_l1_max": l1_limit, "normalized_linf_max": linf_limit}
132
+
133
+
134
+ def compare_events(reference: dict[str, Any], candidate: dict[str, Any], tolerance: dict[str, Any]) -> dict[str, Any]:
135
+ def groups(value: dict[str, Any]) -> dict[tuple[str, str], list[dict[str, Any]]]:
136
+ result: dict[tuple[str, str], list[dict[str, Any]]] = {}
137
+ for event in value.get("events", []):
138
+ if isinstance(event, dict):
139
+ result.setdefault((profile_key({"profile_id": event.get("profile_id", "")}), str(event.get("field"))), []).append(event)
140
+ return result
141
+ refs, cands = groups(reference), groups(candidate)
142
+ cell_limit = finite(tolerance.get("maximum_cell_offset"))
143
+ if cell_limit is None:
144
+ return {"status": "invalid_contract"}
145
+ offsets = []
146
+ for key, ref_events in refs.items():
147
+ cand_events = cands.get(key, [])
148
+ available = list(cand_events)
149
+ for event in ref_events:
150
+ coordinate = finite(event.get("coordinate"))
151
+ if coordinate is None or not available:
152
+ continue
153
+ match = min(
154
+ available,
155
+ key=lambda item: abs(value - coordinate) if (value := finite(item.get("coordinate"))) is not None else math.inf,
156
+ )
157
+ available.remove(match)
158
+ matched_coordinate = finite(match.get("coordinate"))
159
+ if matched_coordinate is None:
160
+ continue
161
+ cell = max(finite(event.get("local_cell_size")) or 0.0, finite(match.get("local_cell_size")) or 0.0,
162
+ finite(tolerance.get("physical_floor")) or 1e-12)
163
+ offsets.append(abs(matched_coordinate - coordinate) / cell)
164
+ expected = sum(len(items) for items in refs.values())
165
+ coverage = len(offsets) / expected if expected else 0.0
166
+ passed = expected > 0 and coverage == 1.0 and max(offsets, default=math.inf) <= cell_limit
167
+ return {"status": "within_tolerance" if passed else "missing" if not offsets else "out_of_tolerance",
168
+ "coverage_fraction": coverage, "maximum_cell_offset": max(offsets, default=None), "allowed_cell_offset": cell_limit}
169
+
170
+
171
+ def compare_structured(reference: dict[str, Any], candidate: Any, tolerance: dict[str, Any]) -> dict[str, Any]:
172
+ if not isinstance(candidate, dict) or candidate.get("kind") != reference.get("kind"):
173
+ return {"status": "missing"}
174
+ kind = reference.get("kind")
175
+ if kind == "time_history":
176
+ return compare_history(reference, candidate, tolerance)
177
+ if kind == "branched_time_histories":
178
+ ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {})
179
+ results = {name: compare_history(value, cand_branches.get(name, {}), tolerance)
180
+ for name, value in ref_branches.items()}
181
+ passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values())
182
+ return {"status": "within_tolerance" if passed else "out_of_tolerance", "branches": results,
183
+ "coverage_fraction": sum(item.get("coverage_fraction", 0.0) for item in results.values()) / len(results) if results else 0.0}
184
+ if kind == "named_profiles":
185
+ return compare_profiles(reference, candidate, tolerance)
186
+ if kind == "profile_feature_locations":
187
+ return compare_events(reference, candidate, tolerance)
188
+ if kind == "component_trajectory":
189
+ refs = {str(item.get("component_id")): item for item in reference.get("series", [])}
190
+ cands = {str(item.get("component_id")): item for item in candidate.get("series", [])}
191
+ results = {key: compare_history({"points": item.get("points", [])}, {"points": cands.get(key, {}).get("points", [])}, tolerance)
192
+ for key, item in refs.items()}
193
+ passed = bool(results) and all(item["status"] == "within_tolerance" for item in results.values())
194
+ return {"status": "within_tolerance" if passed else "out_of_tolerance", "components": results}
195
+ if kind == "component_scalars":
196
+ refs = {str(item.get("component_id")): finite(item.get("value")) for item in reference.get("components", [])}
197
+ cands = {str(item.get("component_id")): finite(item.get("value")) for item in candidate.get("components", [])}
198
+ relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
199
+ if relative is None:
200
+ return {"status": "invalid_contract"}
201
+ errors = {key: abs(cands[key] - ref) / max(abs(ref), floor) for key, ref in refs.items() if ref is not None and cands.get(key) is not None}
202
+ physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
203
+ observed = [value for value in cands.values() if value is not None]
204
+ physically_valid = all(
205
+ (physical_low is None or value >= physical_low)
206
+ and (physical_high is None or value <= physical_high)
207
+ for value in observed
208
+ )
209
+ passed = len(errors) == len(refs) and physically_valid and all(error <= relative for error in errors.values())
210
+ return {"status": "within_tolerance" if passed else "missing" if not errors else "out_of_tolerance",
211
+ "relative_errors": errors, "physical_bounds_pass": physically_valid,
212
+ "physical_low": physical_low, "physical_high": physical_high}
213
+ if kind == "branch_scalars":
214
+ ref_branches, cand_branches = reference.get("branches", {}), candidate.get("branches", {})
215
+ relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
216
+ if relative is None:
217
+ return {"status": "invalid_contract"}
218
+ errors: dict[str, Any] = {}
219
+ for branch, ref_metrics in ref_branches.items():
220
+ cand_metrics = cand_branches.get(branch, {})
221
+ errors[branch] = {
222
+ name: abs(float(cand_metrics[name]) - float(ref)) / max(abs(float(ref)), floor)
223
+ for name, ref in ref_metrics.items()
224
+ if name in cand_metrics and finite(ref) is not None and finite(cand_metrics[name]) is not None
225
+ }
226
+ complete = set(errors) == set(ref_branches) and all(set(errors[b]) == set(ref_branches[b]) for b in ref_branches)
227
+ physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
228
+ observed = [value for branch in cand_branches.values() if isinstance(branch, dict) for value in branch.values()
229
+ if finite(value) is not None]
230
+ physically_valid = all(
231
+ (physical_low is None or float(value) >= physical_low)
232
+ and (physical_high is None or float(value) <= physical_high)
233
+ for value in observed
234
+ )
235
+ passed = complete and physically_valid and all(error <= relative for branch in errors.values() for error in branch.values())
236
+ return {"status": "within_tolerance" if passed else "missing" if not complete else "out_of_tolerance",
237
+ "relative_errors": errors, "relative_max": relative,
238
+ "physical_bounds_pass": physically_valid, "physical_low": physical_low,
239
+ "physical_high": physical_high}
240
+ scalar_ref, scalar_cand = scalar_observation(reference), scalar_observation(candidate)
241
+ if scalar_ref is not None and scalar_cand is not None:
242
+ relative, floor = finite(tolerance.get("relative_max")), finite(tolerance.get("absolute_floor")) or 1e-12
243
+ if relative is None:
244
+ return {"status": "invalid_contract"}
245
+ error = abs(scalar_cand - scalar_ref) / max(abs(scalar_ref), floor)
246
+ physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
247
+ physically_valid = (
248
+ (physical_low is None or scalar_cand >= physical_low)
249
+ and (physical_high is None or scalar_cand <= physical_high)
250
+ )
251
+ passed = error <= relative and physically_valid
252
+ return {"status": "within_tolerance" if passed else "out_of_tolerance",
253
+ "relative_error": error, "relative_max": relative, "physical_bounds_pass": physically_valid,
254
+ "physical_low": physical_low, "physical_high": physical_high}
255
+ return {"status": "invalid_contract", "reason": f"unsupported structured kind {kind!r}"}
256
+
257
+
258
+ def comparison_quality(result: dict[str, Any]) -> float:
259
+ """Map comparison distance to [0, 1] without changing strict status."""
260
+ status = result.get("status")
261
+ if status == "within_tolerance":
262
+ return 1.0
263
+ if status in {"missing", "invalid_contract"}:
264
+ return 0.0
265
+ distances: list[float] = []
266
+ for key in ("relative_error", "normalized_rmse", "normalized_l1", "maximum_cell_offset"):
267
+ value = finite(result.get(key))
268
+ limit = finite(result.get({
269
+ "relative_error": "relative_max",
270
+ "normalized_rmse": "normalized_rmse_max",
271
+ "normalized_l1": "normalized_l1_max",
272
+ "maximum_cell_offset": "allowed_cell_offset",
273
+ }[key]))
274
+ if value is not None and limit is not None and limit > 0:
275
+ distances.append(value / limit)
276
+ for value in result.get("fields", []) if isinstance(result.get("fields"), list) else []:
277
+ if isinstance(value, dict):
278
+ q = comparison_quality({
279
+ "status": "within_tolerance" if value.get("normalized_l1", math.inf) <= (result.get("normalized_l1_max") or 0.0) else "out_of_tolerance",
280
+ "normalized_l1": value.get("normalized_l1"),
281
+ "normalized_l1_max": result.get("normalized_l1_max"),
282
+ })
283
+ distances.append(1.0 - q)
284
+ for value in result.get("branches", {}).values() if isinstance(result.get("branches"), dict) else []:
285
+ if isinstance(value, dict):
286
+ distances.append(1.0 - comparison_quality(value))
287
+ ratio = sum(distances) / len(distances) if distances else 1.0
288
+ return max(0.0, min(1.0, 1.0 / (1.0 + ratio)))
289
+
290
+
291
+ def load_cases(path: Path) -> dict[str, Any]:
292
+ data = json.loads(path.read_text(encoding="utf-8"))
293
+ cases = data.get("cases") if isinstance(data, dict) else None
294
+ if not isinstance(cases, dict):
295
+ raise ValueError(f"JSON has no cases object: {path}")
296
+ return cases
297
+
298
+
299
+ def write_json(path: Path, value: Any) -> None:
300
+ path.parent.mkdir(parents=True, exist_ok=True)
301
+ temporary = path.with_name(path.name + ".tmp")
302
+ temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
303
+ temporary.replace(path)
304
+
305
+
306
+ STAT_SUFFIX_RE = re.compile(r"_(?:min|max|mean|range)$")
307
+ SCORING_POLICY = "grouped_qois"
308
+ EXPLICIT_SCORING_POLICY = "explicit_principal_qoi_group"
309
+
310
+
311
+ def case_scoring_policy(reference: dict[str, Any]) -> str:
312
+ return EXPLICIT_SCORING_POLICY if isinstance(reference.get("metric_roles"), dict) else SCORING_POLICY
313
+
314
+
315
+ def metric_role(name: str, explicit_roles: dict[str, Any] | None = None) -> str:
316
+ """Classify metrics without changing the extracted raw values.
317
+
318
+ Residual and Courant values remain useful diagnostics, while ``range`` is
319
+ a deterministic derivative of min/max. All other legacy measurements are
320
+ scored, but related statistics are aggregated as one QoI group below.
321
+ """
322
+ explicit = explicit_roles.get(name) if explicit_roles else None
323
+ if explicit in {"principal", "scored"}:
324
+ return "scored"
325
+ if explicit in {"diagnostic", "redundant"}:
326
+ return explicit
327
+ if "residual" in name or "courant" in name:
328
+ return "diagnostic"
329
+ if name.endswith("_range"):
330
+ return "redundant"
331
+ return "scored"
332
+
333
+
334
+ def metric_group(name: str, principal_group: str | None = None,
335
+ explicit_roles: dict[str, Any] | None = None) -> str:
336
+ if principal_group and explicit_roles and explicit_roles.get(name) in {"principal", "scored"}:
337
+ return principal_group
338
+ if name in {"center_u", "center_v", "center_w", "center_speed"}:
339
+ return "center_velocity"
340
+ return STAT_SUFFIX_RE.sub("", name)
341
+
342
+
343
+ def comparison_outcome(*, missing: list[str], out_of_tolerance: list[str],
344
+ invalid_contract: list[str], accepted: bool) -> str:
345
+ if invalid_contract:
346
+ return "invalid_contract"
347
+ if accepted:
348
+ return "pass"
349
+ if missing and out_of_tolerance:
350
+ return "incomplete_and_out_of_tolerance"
351
+ if missing:
352
+ return "incomplete"
353
+ return "out_of_tolerance"
354
+
355
+
356
+ def rollout_status(comparison: dict[str, Any]) -> str:
357
+ """Map a QoI result to a rollout status after execution has passed."""
358
+ return {
359
+ "pass": "scientifically_validated",
360
+ "incomplete": "execution_passed_qoi_incomplete",
361
+ "out_of_tolerance": "execution_passed_qoi_out_of_tolerance",
362
+ "incomplete_and_out_of_tolerance": "execution_passed_qoi_incomplete_and_out_of_tolerance",
363
+ "invalid_contract": "execution_passed_qoi_evaluation_error",
364
+ "error": "execution_passed_qoi_evaluation_error",
365
+ }.get(str(comparison.get("status")), "execution_passed_qoi_evaluation_error")
366
+
367
+
368
+ def compare_case(reference: dict[str, Any], candidate: dict[str, Any], required_fraction: float) -> dict[str, Any]:
369
+ references = reference.get("qois") if isinstance(reference.get("qois"), dict) else {}
370
+ tolerances = reference.get("tolerances") if isinstance(reference.get("tolerances"), dict) else {}
371
+ candidates = candidate.get("qois") if isinstance(candidate.get("qois"), dict) else {}
372
+ explicit_roles = reference.get("metric_roles") if isinstance(reference.get("metric_roles"), dict) else None
373
+ principal_group = reference.get("principal_qoi_group") if isinstance(reference.get("principal_qoi_group"), str) else None
374
+ role_for = lambda name: metric_role(name, explicit_roles)
375
+ metrics: dict[str, Any] = {}
376
+ passed = 0
377
+ out_of_tolerance: list[str] = []
378
+ missing: list[str] = []
379
+ invalid_contract: list[str] = []
380
+ diagnostic_out_of_tolerance: list[str] = []
381
+ diagnostic_missing: list[str] = []
382
+ redundant_metric_count = 0
383
+ groups: dict[str, dict[str, Any]] = {}
384
+ for name, reference_value in sorted(references.items()):
385
+ role = role_for(name)
386
+ group = metric_group(name, principal_group, explicit_roles)
387
+ if role == "redundant":
388
+ redundant_metric_count += 1
389
+ value = finite(candidates.get(name))
390
+ metrics[name] = {
391
+ "status": "available" if value is not None else "missing",
392
+ "role": role,
393
+ "group": group,
394
+ "reference_value": reference_value,
395
+ "candidate_value": value,
396
+ }
397
+ continue
398
+ group_record = groups.setdefault(group, {
399
+ "role": "scored" if role == "scored" else role,
400
+ "metrics": [],
401
+ "passed_metric_count": 0,
402
+ "observed_metric_count": 0,
403
+ "invalid_metric_count": 0,
404
+ "quality_sum": 0.0,
405
+ "coverage_fraction": 1.0,
406
+ })
407
+ group_record["metrics"].append(name)
408
+ tolerance = tolerances.get(name) if isinstance(tolerances.get(name), dict) else {}
409
+ if isinstance(reference_value, dict):
410
+ result = compare_structured(reference_value, candidates.get(name), tolerance)
411
+ result["quality"] = comparison_quality(result)
412
+ status = result.get("status")
413
+ is_missing = status == "missing"
414
+ is_invalid = status == "invalid_contract"
415
+ is_pass = status == "within_tolerance"
416
+ structured_coverage = finite(result.get("coverage_fraction"))
417
+ if structured_coverage is not None:
418
+ group_record["coverage_fraction"] = min(
419
+ group_record["coverage_fraction"], structured_coverage
420
+ )
421
+ elif is_missing:
422
+ group_record["coverage_fraction"] = 0.0
423
+ if is_missing:
424
+ missing.append(name)
425
+ if role == "diagnostic":
426
+ diagnostic_missing.append(name)
427
+ elif is_invalid and role == "scored":
428
+ invalid_contract.append(name)
429
+ group_record["invalid_metric_count"] += 1
430
+ else:
431
+ group_record["observed_metric_count"] += int(role == "scored")
432
+ if role == "scored":
433
+ passed += int(is_pass)
434
+ group_record["passed_metric_count"] += int(is_pass)
435
+ group_record["quality_sum"] += float(result["quality"])
436
+ if not is_pass:
437
+ out_of_tolerance.append(name)
438
+ elif role == "diagnostic" and not is_pass:
439
+ diagnostic_out_of_tolerance.append(name)
440
+ metrics[name] = {"role": role, "group": group, "reference_value": reference_value,
441
+ "candidate_value": candidates.get(name), **result}
442
+ continue
443
+ value = finite(candidates.get(name))
444
+ low, high = finite(tolerance.get("low")), finite(tolerance.get("high"))
445
+ if value is None:
446
+ missing.append(name)
447
+ group_record["coverage_fraction"] = 0.0
448
+ if role == "diagnostic":
449
+ diagnostic_missing.append(name)
450
+ metrics[name] = {
451
+ "status": "missing",
452
+ "role": role,
453
+ "group": group,
454
+ "reference_value": reference_value,
455
+ "quality": 0.0,
456
+ }
457
+ continue
458
+ if low is None or high is None:
459
+ group_record["coverage_fraction"] = 0.0
460
+ if role == "scored":
461
+ invalid_contract.append(name)
462
+ group_record["invalid_metric_count"] += 1
463
+ metrics[name] = {
464
+ "status": "invalid_contract" if role == "scored" else "available_without_tolerance",
465
+ "role": role,
466
+ "group": group,
467
+ "reference_value": reference_value,
468
+ "candidate_value": value,
469
+ "quality": 0.0,
470
+ }
471
+ continue
472
+ physical_low, physical_high = finite(tolerance.get("physical_low")), finite(tolerance.get("physical_high"))
473
+ physical_pass = (
474
+ (physical_low is None or value >= physical_low)
475
+ and (physical_high is None or value <= physical_high)
476
+ )
477
+ is_pass = low <= value <= high and physical_pass
478
+ tolerance_span = max(high - low, 1e-12)
479
+ distance = 0.0 if is_pass else min(abs(value - min(max(value, low), high)) / tolerance_span, 1.0)
480
+ quality = 1.0 if is_pass else max(0.0, 1.0 - distance)
481
+ if role == "scored":
482
+ passed += int(is_pass)
483
+ group_record["observed_metric_count"] += 1
484
+ group_record["passed_metric_count"] += int(is_pass)
485
+ group_record["quality_sum"] += quality
486
+ if not is_pass:
487
+ out_of_tolerance.append(name)
488
+ elif role == "diagnostic" and not is_pass:
489
+ diagnostic_out_of_tolerance.append(name)
490
+ metrics[name] = {
491
+ "status": "within_tolerance" if is_pass else "out_of_tolerance",
492
+ "role": role,
493
+ "group": group,
494
+ "reference_value": reference_value,
495
+ "candidate_value": value,
496
+ "low": low,
497
+ "high": high,
498
+ "absolute_error": abs(value - float(reference_value)),
499
+ "criterion_role": tolerance.get("criterion_role"),
500
+ "threshold_source": tolerance.get("threshold_source"),
501
+ "reference_independent": tolerance.get("reference_independent", False),
502
+ "provisional": tolerance.get("provisional"),
503
+ "physical_bounds_pass": physical_pass,
504
+ "physical_low": physical_low,
505
+ "physical_high": physical_high,
506
+ "physical_threshold_source": tolerance.get("physical_threshold_source"),
507
+ "quality": quality,
508
+ }
509
+ scored_groups = {
510
+ name: record for name, record in groups.items() if record["role"] == "scored"
511
+ }
512
+ scored_metrics = [name for name in references if role_for(name) == "scored"]
513
+ scored_missing = [name for name in missing if role_for(name) == "scored"]
514
+ scored_count = len(scored_metrics)
515
+ extracted_count = sum(record["observed_metric_count"] for record in scored_groups.values())
516
+ evaluated_count = extracted_count
517
+ coverage = extracted_count / scored_count if scored_count else 0.0
518
+ metric_value_pass_fraction = passed / evaluated_count if evaluated_count else None
519
+ metric_joint_pass_fraction = passed / scored_count if scored_count else 0.0
520
+ group_scores: dict[str, dict[str, Any]] = {}
521
+ for group_name, record in sorted(scored_groups.items()):
522
+ member_count = len(record["metrics"])
523
+ group_score = record["quality_sum"] / member_count if member_count else 0.0
524
+ group_coverage = (
525
+ min(record["observed_metric_count"] / member_count, record["coverage_fraction"])
526
+ if member_count else 0.0
527
+ )
528
+ group_scores[group_name] = {
529
+ "score": group_score,
530
+ "coverage_fraction": group_coverage,
531
+ "metric_count": member_count,
532
+ "observed_metric_count": record["observed_metric_count"],
533
+ "passed_metric_count": record["passed_metric_count"],
534
+ "metrics": record["metrics"],
535
+ }
536
+ qoi_pass_ratio = (
537
+ sum(item["score"] for item in group_scores.values()) / len(group_scores)
538
+ if group_scores else 0.0
539
+ )
540
+ qoi_coverage_fraction = (
541
+ sum(item["coverage_fraction"] for item in group_scores.values()) / len(group_scores)
542
+ if group_scores else 0.0
543
+ )
544
+ # Continuous quality is intentionally separate from the strict scientific
545
+ # acceptance bit. It exposes partial QoI agreement to Evolution without
546
+ # weakening the all-groups physics-grounded contract.
547
+ qoi_quality = qoi_pass_ratio * qoi_coverage_fraction
548
+ physics_grounded_accepted = bool(
549
+ scored_groups
550
+ and not scored_missing
551
+ and not invalid_contract
552
+ and not out_of_tolerance
553
+ and passed == scored_count
554
+ and all(
555
+ item["coverage_fraction"] == 1.0
556
+ for item in group_scores.values()
557
+ )
558
+ )
559
+ threshold_pass = bool(
560
+ scored_groups
561
+ and qoi_coverage_fraction == 1.0
562
+ and qoi_pass_ratio >= required_fraction
563
+ )
564
+ outcome = comparison_outcome(
565
+ missing=scored_missing,
566
+ out_of_tolerance=out_of_tolerance,
567
+ invalid_contract=invalid_contract,
568
+ accepted=physics_grounded_accepted,
569
+ )
570
+ diagnostic_names = [name for name in references if role_for(name) == "diagnostic"]
571
+ diagnostic_observed = [
572
+ name for name in diagnostic_names
573
+ if metrics.get(name, {}).get("status") not in {None, "missing", "invalid_contract"}
574
+ ]
575
+ diagnostic_passed = [
576
+ name for name in diagnostic_names if metrics.get(name, {}).get("status") == "within_tolerance"
577
+ ]
578
+ return {
579
+ "schema_version": "foambench.qoi.case_comparison.v3",
580
+ "scoring_policy": case_scoring_policy(reference),
581
+ "status": outcome,
582
+ "coverage_status": "complete" if scored_count and not scored_missing else "incomplete",
583
+ "value_status": (
584
+ "not_assessed" if not scored_count
585
+ else "within_tolerance" if metric_value_pass_fraction is not None and metric_value_pass_fraction >= required_fraction
586
+ else "out_of_tolerance"
587
+ ),
588
+ "required_metric_count": scored_count,
589
+ "extracted_metric_count": extracted_count,
590
+ "evaluated_metric_count": evaluated_count,
591
+ "passed_metric_count": passed,
592
+ "coverage_fraction": coverage,
593
+ "value_pass_fraction": metric_value_pass_fraction,
594
+ "joint_pass_fraction": metric_joint_pass_fraction,
595
+ "qoi_pass_ratio": qoi_pass_ratio,
596
+ "qoi_quality": qoi_quality,
597
+ "qoi_coverage_fraction": qoi_coverage_fraction,
598
+ "group_count": len(group_scores),
599
+ "group_scores": group_scores,
600
+ "physics_grounded_qoi_pass": physics_grounded_accepted,
601
+ "threshold_pass": threshold_pass,
602
+ "diagnostic_metric_count": sum(len(record["metrics"]) for record in groups.values() if record["role"] == "diagnostic"),
603
+ "diagnostic_observed_metric_count": len(diagnostic_observed),
604
+ "diagnostic_passed_metric_count": len(diagnostic_passed),
605
+ "diagnostic_reference_coverage_fraction": (
606
+ len(diagnostic_observed) / len(diagnostic_names) if diagnostic_names else None
607
+ ),
608
+ "diagnostic_reference_pass_fraction": (
609
+ len(diagnostic_passed) / len(diagnostic_observed) if diagnostic_observed else None
610
+ ),
611
+ "redundant_metric_count": redundant_metric_count,
612
+ # Raw metric fractions remain available above; the canonical case-level
613
+ # quality score is qoi_pass_ratio.
614
+ "pass_fraction": metric_joint_pass_fraction,
615
+ "required_fraction": required_fraction,
616
+ "missing_metrics": missing,
617
+ "scored_missing_metrics": scored_missing,
618
+ "diagnostic_missing_metrics": diagnostic_missing,
619
+ "out_of_tolerance_metrics": out_of_tolerance,
620
+ "diagnostic_out_of_tolerance_metrics": diagnostic_out_of_tolerance,
621
+ "invalid_contract_metrics": invalid_contract,
622
+ "metrics": metrics,
623
+ }
624
+
625
+
626
+ def main() -> int:
627
+ parser = argparse.ArgumentParser(description=__doc__)
628
+ parser.add_argument("--reference-qois", required=True, type=Path)
629
+ parser.add_argument("--candidate-qois", required=True, type=Path)
630
+ parser.add_argument("--case-id", action="append")
631
+ parser.add_argument(
632
+ "--required-fraction",
633
+ type=float,
634
+ default=1.0,
635
+ help="Optional observed-value/QoI-ratio threshold; physics_grounded_qoi_pass always requires every scored group.",
636
+ )
637
+ parser.add_argument("--output", type=Path)
638
+ parser.add_argument("--json", action="store_true")
639
+ args = parser.parse_args()
640
+ if not 0 < args.required_fraction <= 1:
641
+ parser.error("--required-fraction must be in (0, 1]")
642
+
643
+ references = load_cases(args.reference_qois.resolve(strict=True))
644
+ candidates = load_cases(args.candidate_qois.resolve(strict=True))
645
+ selected = args.case_id or sorted(references)
646
+ unknown = sorted(set(selected) - set(references))
647
+ if unknown:
648
+ raise ValueError("unknown reference case IDs: " + ", ".join(unknown))
649
+
650
+ results: dict[str, Any] = {}
651
+ missing_cases: list[str] = []
652
+ for case_id in selected:
653
+ candidate = candidates.get(case_id)
654
+ if not isinstance(candidate, dict):
655
+ missing_cases.append(case_id)
656
+ missing_metrics = sorted(references[case_id].get("qois", {}))
657
+ results[case_id] = {
658
+ "scoring_policy": case_scoring_policy(references[case_id]),
659
+ "status": "missing_candidate_case",
660
+ "coverage_status": "incomplete",
661
+ "value_status": "not_assessed",
662
+ "required_metric_count": len(missing_metrics),
663
+ "extracted_metric_count": 0,
664
+ "evaluated_metric_count": 0,
665
+ "passed_metric_count": 0,
666
+ "coverage_fraction": 0.0,
667
+ "value_pass_fraction": None,
668
+ "joint_pass_fraction": 0.0,
669
+ "qoi_pass_ratio": 0.0,
670
+ "qoi_coverage_fraction": 0.0,
671
+ "group_count": 0,
672
+ "pass_fraction": 0.0,
673
+ "missing_metrics": missing_metrics,
674
+ "out_of_tolerance_metrics": [],
675
+ "invalid_contract_metrics": [],
676
+ }
677
+ else:
678
+ results[case_id] = compare_case(references[case_id], candidate, args.required_fraction)
679
+
680
+ family_rows: dict[str, list[dict[str, Any]]] = {}
681
+ for case_id, result in results.items():
682
+ if "pass_fraction" in result:
683
+ reference_family = references.get(case_id, {}).get("family")
684
+ family = reference_family if isinstance(reference_family, str) and reference_family else case_id.split("/", 1)[0]
685
+ family_rows.setdefault(family, []).append(result)
686
+ def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
687
+ assessed = [row["value_pass_fraction"] for row in rows if row.get("value_pass_fraction") is not None]
688
+ qoi_ratios = [row["qoi_pass_ratio"] for row in rows if row.get("qoi_pass_ratio") is not None]
689
+ return {
690
+ "case_count": len(rows),
691
+ "passed_case_count": sum(row["status"] == "pass" for row in rows),
692
+ "incomplete_case_count": sum(bool(row.get("missing_metrics")) for row in rows),
693
+ "out_of_tolerance_case_count": sum(bool(row.get("out_of_tolerance_metrics")) for row in rows),
694
+ "macro_coverage_fraction": sum(row["coverage_fraction"] for row in rows) / len(rows),
695
+ "macro_value_pass_fraction": sum(assessed) / len(assessed) if assessed else None,
696
+ "macro_joint_pass_fraction": sum(row["joint_pass_fraction"] for row in rows) / len(rows),
697
+ "macro_qoi_pass_ratio": sum(qoi_ratios) / len(qoi_ratios) if qoi_ratios else 0.0,
698
+ "macro_qoi_coverage_fraction": sum(row.get("qoi_coverage_fraction", 0.0) for row in rows) / len(rows),
699
+ }
700
+
701
+ families = {family: summarize(rows) for family, rows in sorted(family_rows.items())}
702
+ passed_cases = sum(result.get("status") == "pass" for result in results.values())
703
+ aggregate = summarize(list(results.values())) if results else {
704
+ "incomplete_case_count": 0,
705
+ "out_of_tolerance_case_count": 0,
706
+ "macro_coverage_fraction": 0.0,
707
+ "macro_value_pass_fraction": None,
708
+ "macro_joint_pass_fraction": 0.0,
709
+ "macro_qoi_pass_ratio": 0.0,
710
+ "macro_qoi_coverage_fraction": 0.0,
711
+ }
712
+ policies = {result.get("scoring_policy", SCORING_POLICY) for result in results.values()}
713
+ report = {
714
+ "schema_version": "foambench.qoi.comparison.v3",
715
+ "scoring_policy": policies.pop() if len(policies) == 1 else "mixed",
716
+ "generated_at": datetime.now(timezone.utc).isoformat(),
717
+ "status": "pass" if passed_cases == len(selected) and not missing_cases else "fail",
718
+ "case_count": len(selected),
719
+ "passed_case_count": passed_cases,
720
+ "case_pass_fraction": passed_cases / len(selected) if selected else 0.0,
721
+ "incomplete_case_count": aggregate["incomplete_case_count"],
722
+ "out_of_tolerance_case_count": aggregate["out_of_tolerance_case_count"],
723
+ "macro_coverage_fraction": aggregate["macro_coverage_fraction"],
724
+ "macro_value_pass_fraction": aggregate["macro_value_pass_fraction"],
725
+ "macro_joint_pass_fraction": aggregate["macro_joint_pass_fraction"],
726
+ "macro_qoi_pass_ratio": aggregate["macro_qoi_pass_ratio"],
727
+ "macro_qoi_coverage_fraction": aggregate["macro_qoi_coverage_fraction"],
728
+ "missing_cases": missing_cases,
729
+ "families": families,
730
+ "cases": results,
731
+ }
732
+ if args.output:
733
+ write_json(args.output.resolve(), report)
734
+ if args.json or not args.output:
735
+ print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
736
+ else:
737
+ print(
738
+ f"comparison: {args.output.resolve()} "
739
+ f"(physics_grounded={passed_cases}/{len(selected)}, "
740
+ f"qoi_pass_ratio={report['macro_qoi_pass_ratio']:.4f})"
741
+ )
742
+ return 0 if report["status"] == "pass" else 1
743
+
744
+
745
+ if __name__ == "__main__":
746
+ try:
747
+ raise SystemExit(main())
748
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
749
+ print(f"compare_foambench_qois.py: error: {exc}", file=sys.stderr)
750
+ raise SystemExit(2)
benchmarks/evaluation/evidence_contract.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical evidence discovery for the Extended FoamBench contract.
2
+
3
+ The resolver deliberately separates *where/how an agent writes a file* from
4
+ the physical quantity represented by its contents. Callers still validate
5
+ headers, units, time semantics, and dimensions before using a file as QoI
6
+ evidence; this module only provides deterministic semantic routing.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+
16
+ CANONICAL_ALIASES: dict[str, tuple[str, ...]] = {
17
+ "force_coefficients": ("forcecoeffs", "forcecoefficients", "forcecoefficient", "aerodynamicloads", "aeroloads", "loads"),
18
+ "patch_flux": ("patchflowrate", "patchflow", "massflow", "massflux", "rhophi", "fluxhistory"),
19
+ "patch_pressure": ("patchaverage", "patchintegrate", "pressurerise", "pressuredifference", "patchpressure"),
20
+ "wall_law_profile": ("spaldingcomparison", "uplusyplus", "walllawprofile", "velocityprofile", "wallprofile"),
21
+ "centerline_profile": ("centerline", "centreline", "horizontal", "vertical", "px0", "py0", "rhox0", "rhoy0"),
22
+ "bubble_geometry": ("bubblegeometry", "bubblemetrics", "interfacegeometry"),
23
+ }
24
+
25
+ CONTRACT_VERSION = "foambench.evidence.contract.v1"
26
+ CONTRACT_FILE = Path(__file__).resolve().parents[1] / "FoamBench_extended_openfoam13_evidence_contract.v1.json"
27
+
28
+ # A manifest may use the QoI name instead of the routing kind. This mapping
29
+ # keeps that interface stable while allowing metric extractors to retain their
30
+ # own physical validation rules.
31
+ METRIC_KINDS = {
32
+ "Cd": "force_coefficients", "Cl": "force_coefficients", "Cm": "force_coefficients",
33
+ "Cd_mean": "force_coefficients", "Cd_rms": "force_coefficients",
34
+ "Cl_mean": "force_coefficients", "Cl_rms": "force_coefficients",
35
+ "first_cell_yplus": "wall_law_profile", "spalding_log_rmse": "wall_law_profile",
36
+ "centerline_profiles": "centerline_profile", "event_locations": "centerline_profile",
37
+ "mass_flow_rate": "patch_flux", "volumetric_flow_rate": "patch_flux",
38
+ "pressure_rise": "patch_pressure", "pressure_rise_history": "patch_pressure",
39
+ }
40
+
41
+
42
+ def compact_name(value: str) -> str:
43
+ return re.sub(r"[^a-z0-9]", "", value.lower())
44
+
45
+
46
+ def evidence_roots(case: Path) -> tuple[Path, ...]:
47
+ parent = case.parent
48
+ roots = (
49
+ case / "postProcessing", case / "postprocessing", case / "results", case / "outputs",
50
+ parent / "postProcessing", parent / "postprocessing", parent / "results", parent / "outputs",
51
+ parent / "evidence", parent / "reports",
52
+ )
53
+ return tuple(dict.fromkeys(root for root in roots if root.is_dir()))
54
+
55
+
56
+ def _manifest_paths(case: Path) -> tuple[Path, ...]:
57
+ """Locate the optional agent-emitted manifest without trusting its paths."""
58
+ return tuple(dict.fromkeys((case / "evidence/qoi_manifest.v1.json", case.parent / "evidence/qoi_manifest.v1.json")))
59
+
60
+
61
+ def declared_evidence(case: Path, kind: str) -> list[Path]:
62
+ """Return manifest-declared files for *kind* after path containment checks."""
63
+ paths: list[Path] = []
64
+ accepted_metrics = {kind, *[metric for metric, mapped in METRIC_KINDS.items() if mapped == kind]}
65
+ for manifest_path in _manifest_paths(case):
66
+ try:
67
+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))
68
+ except (OSError, ValueError, TypeError):
69
+ continue
70
+ entries = payload.get("entries", []) if isinstance(payload, dict) else []
71
+ if not isinstance(entries, list):
72
+ continue
73
+ for entry in entries:
74
+ if not isinstance(entry, dict) or entry.get("metric") not in accepted_metrics and entry.get("kind") != kind:
75
+ continue
76
+ raw = entry.get("path")
77
+ if not isinstance(raw, str) or not raw:
78
+ continue
79
+ candidate = (manifest_path.parent.parent / raw).resolve()
80
+ allowed = tuple(root.resolve() for root in evidence_roots(case))
81
+ if candidate.is_file() and any(candidate == root or root in candidate.parents for root in allowed):
82
+ paths.append(candidate)
83
+ return sorted(set(paths))
84
+
85
+
86
+ def resolve_evidence(case: Path, kind: str, *, suffixes: tuple[str, ...] = ()) -> list[Path]:
87
+ """Return files whose path semantically addresses canonical evidence kind.
88
+
89
+ This function never parses or promotes a file. The metric-specific
90
+ extractor remains responsible for schema/header/unit validation.
91
+ """
92
+ aliases = CANONICAL_ALIASES.get(kind, (kind,))
93
+ paths: set[Path] = set(declared_evidence(case, kind))
94
+ for root in evidence_roots(case):
95
+ for path in root.rglob("*"):
96
+ if not path.is_file():
97
+ continue
98
+ if suffixes and path.suffix.lower() not in suffixes:
99
+ continue
100
+ compact = compact_name(str(path))
101
+ if any(compact_name(alias) in compact for alias in aliases):
102
+ paths.add(path)
103
+ return sorted(paths)
104
+
105
+
106
+ def canonical_evidence_manifest() -> dict[str, object]:
107
+ """Machine-readable resolver contract for reports and future agents."""
108
+ fallback = {
109
+ "schema_version": CONTRACT_VERSION,
110
+ "normalization": "lowercase_ascii_alphanumeric_path_matching",
111
+ "kinds": {key: list(value) for key, value in CANONICAL_ALIASES.items()},
112
+ "content_validation": "required_by_metric_extractor",
113
+ "proxy_policy": "semantic routing never authorizes a proxy metric",
114
+ }
115
+ try:
116
+ payload = json.loads(CONTRACT_FILE.read_text(encoding="utf-8"))
117
+ except (OSError, ValueError, TypeError):
118
+ return fallback
119
+ return payload if isinstance(payload, dict) else fallback
benchmarks/evaluation/execution.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from .adapters.common import successful_formal_records
6
+ from .foam import FATAL_RE, converged_early, final_log_time, latest_time_dir, normal_end, read_logs
7
+ from .models import CaseArtifact
8
+
9
+
10
+ def evaluate_execution(artifact: CaseArtifact, expected_time: float | None) -> dict[str, Any]:
11
+ case_dir = artifact.case_dir
12
+ latest, _ = latest_time_dir(case_dir)
13
+ logs = artifact.solver_logs
14
+ text = read_logs(logs)
15
+ log_time = final_log_time(text)
16
+ successful = successful_formal_records(artifact.formal_run_records)
17
+ requires_formal_record = (
18
+ artifact.workspace_dir is not None
19
+ and artifact.manifest.get("agent_mode") != "coding-only"
20
+ and artifact.manifest.get("domain_assets_enabled") is not False
21
+ )
22
+ manifest_status = str(artifact.manifest.get("status", ""))
23
+ timed_out = bool(artifact.manifest.get("timed_out")) or manifest_status == "timed_out"
24
+ process_ok = artifact.manifest.get("return_code") in {None, 0}
25
+ observed_time = max(value for value in (latest, log_time) if value is not None) if any(
26
+ value is not None for value in (latest, log_time)
27
+ ) else None
28
+ reached = observed_time is not None and (
29
+ expected_time is None
30
+ or observed_time >= expected_time - max(1e-12, abs(expected_time) * 1e-9)
31
+ or converged_early(text)
32
+ )
33
+ checks = {
34
+ "case_directory_exists": bool(case_dir and case_dir.is_dir()),
35
+ "control_dict_exists": bool(case_dir and (case_dir / "system" / "controlDict").is_file()),
36
+ "agent_not_timed_out": not timed_out,
37
+ "agent_process_succeeded": process_ok,
38
+ "formal_run_succeeded": bool(successful) if requires_formal_record else True,
39
+ "solver_log_exists": bool(logs),
40
+ "no_fatal_log_marker": FATAL_RE.search(text) is None,
41
+ "latest_time_exists": latest is not None,
42
+ "stop_condition_reached": reached,
43
+ }
44
+ # Some retained run records omit the literal OpenFOAM "End" line from the
45
+ # selected stdout ref. Keep it as evidence rather than a hard requirement.
46
+ evidence = {
47
+ "normal_end_marker": normal_end(text),
48
+ "converged_early_marker": converged_early(text),
49
+ "formal_run_records": [str(path) for path in successful],
50
+ "solver_logs": [str(path) for path in logs],
51
+ }
52
+ failed = [name for name, passed in checks.items() if not passed]
53
+ return {
54
+ "schema_version": "foambench.execution.v2",
55
+ "status": "pass" if not failed else "fail",
56
+ "expected_latest_time": expected_time,
57
+ "candidate_latest_time": latest,
58
+ "candidate_final_log_time": log_time,
59
+ "checks": checks,
60
+ "failed_checks": failed,
61
+ "evidence": evidence,
62
+ }
benchmarks/evaluation/extbench.py ADDED
@@ -0,0 +1,1572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract and audit Extended FoamBench QoIs without fallback proxies."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import math
9
+ import re
10
+ import statistics
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from .evidence_contract import canonical_evidence_manifest, evidence_roots, resolve_evidence
15
+ from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_field, read_vector_list
16
+ from .io import utc_now, write_json
17
+ from .retained_fields import derive_cell_geometry, pump_measurements, static_mesh
18
+ from .measurement_specs import load_measurement_spec
19
+
20
+ ROOT = Path(__file__).resolve().parents[2]
21
+ DEFAULT_DESIGN = ROOT / "benchmarks/FoamBench_extended_openfoam13_qoi_design.json"
22
+ NUMERIC = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")
23
+
24
+
25
+ def named_numeric_rows(path: Path) -> tuple[list[str], list[list[float]]]:
26
+ """Read a whitespace/CSV table using the last compatible header."""
27
+ headers: list[list[str]] = []
28
+ rows: list[list[float]] = []
29
+ try:
30
+ for line in path.read_text(errors="ignore").splitlines():
31
+ stripped = line.strip()
32
+ if not stripped:
33
+ continue
34
+ if stripped.startswith("#"):
35
+ names = stripped[1:].strip().replace(",", " ").split()
36
+ if names:
37
+ headers.append(names)
38
+ continue
39
+ parts = stripped.replace("(", " ").replace(")", " ").replace(",", " ").split()
40
+ if parts and all(NUMERIC.match(value) for value in parts):
41
+ rows.append([float(value) for value in parts])
42
+ elif (not rows and ("," in stripped or "\t" in stripped)
43
+ and any(re.search(r"[A-Za-z_]", value) and not NUMERIC.fullmatch(value) for value in parts)):
44
+ names = [item.strip() for item in stripped.split(",")] if "," in stripped else stripped.split("\t")
45
+ if names:
46
+ headers.append(names)
47
+ except OSError:
48
+ return [], []
49
+ if not rows:
50
+ return [], []
51
+ width = len(rows[0])
52
+ header = next((names for names in reversed(headers) if len(names) == width), [])
53
+ return header, [row for row in rows if len(row) == width]
54
+
55
+
56
+ def matching_files(case: Path, needles: tuple[str, ...], suffixes: tuple[str, ...] = ()) -> list[Path]:
57
+ """Find explicit post-processing evidence in the case or its workspace."""
58
+ parent = case.parent
59
+ roots = [case / "postProcessing", case / "results", parent / "postProcessing", parent / "postprocessing", parent / "results"]
60
+ paths: list[Path] = []
61
+ for root in roots:
62
+ if not root.is_dir():
63
+ continue
64
+ paths.extend(path for path in root.rglob("*") if path.is_file()
65
+ and (not suffixes or path.suffix.lower() in suffixes)
66
+ and any(needle.lower() in str(path).lower() for needle in needles))
67
+ return sorted(set(paths))
68
+
69
+
70
+ def evidence_path(case: Path, path: Path) -> str:
71
+ """Serialize evidence paths for both native case and sibling workspace outputs."""
72
+ try:
73
+ return str(path.relative_to(case))
74
+ except ValueError:
75
+ return "../" + str(path.relative_to(case.parent))
76
+
77
+
78
+ def design_case_contract(case_id: str, design: dict[str, Any]) -> tuple[str | None, list[str]]:
79
+ """Return the branch and principal metrics for one family/variant."""
80
+ if "/" not in case_id:
81
+ raise ValueError(f"case id must be family/variant: {case_id}")
82
+ family_name, variant = case_id.split("/", 1)
83
+ family = next((item for item in design.get("families", []) if item.get("family") == family_name), None)
84
+ if family is None:
85
+ raise ValueError(f"design has no family for {case_id}")
86
+ return required_metrics(family, variant)
87
+
88
+
89
+ def design_case_conditionals(case_id: str, design: dict[str, Any]) -> list[str]:
90
+ if "/" not in case_id:
91
+ raise ValueError(f"case id must be family/variant: {case_id}")
92
+ family_name, variant = case_id.split("/", 1)
93
+ family = next((item for item in design.get("families", []) if item.get("family") == family_name), None)
94
+ if family is None:
95
+ raise ValueError(f"design has no family for {case_id}")
96
+ for branch in family.get("branches", []):
97
+ if variant in branch.get("cases", []):
98
+ return [item["name"] for item in branch.get("conditional_qois", [])]
99
+ return []
100
+
101
+
102
+ def extract_contract_case(case: Path, case_id: str, design: dict[str, Any] | None = None) -> dict[str, Any]:
103
+ """Extract one candidate using only the design contract."""
104
+ selected_design = design or json.loads(DEFAULT_DESIGN.read_text(encoding="utf-8"))
105
+ branch_id, metrics = design_case_contract(case_id, selected_design)
106
+ measurement_spec = load_measurement_spec(case_id)
107
+ if measurement_spec is not None:
108
+ declared = [item.get("metric") for item in measurement_spec.get("principal_measurements", [])]
109
+ if declared != metrics:
110
+ raise ValueError(f"measurement contract drift for {case_id}: {declared!r} != {metrics!r}")
111
+ conditionals = design_case_conditionals(case_id, selected_design)
112
+ result = extract_case(
113
+ case, case_id.split("/", 1)[0], case_id.split("/", 1)[1], metrics,
114
+ conditional_metrics=conditionals,
115
+ )
116
+ result["branch_id"] = branch_id
117
+ result["conditional_metrics"] = conditionals
118
+ result["contract_version"] = selected_design.get("schema_version")
119
+ if measurement_spec is not None:
120
+ result["measurement_contract"] = measurement_spec
121
+ return result
122
+
123
+
124
+ def locate_case(run_root: Path, family: str, variant: str) -> Path | None:
125
+ candidates = (
126
+ run_root / f"{family}__{variant}" / "full_run_case",
127
+ run_root / f"{family}__{variant}" / "case",
128
+ run_root / family / variant / "full_run_case",
129
+ run_root / family / variant / "case",
130
+ run_root / family / variant,
131
+ )
132
+ return next((path for path in candidates if path.is_dir()), None)
133
+
134
+
135
+ def required_metrics(family: dict[str, Any], variant: str) -> tuple[str | None, list[str]]:
136
+ for branch in family.get("branches", []):
137
+ if variant in branch.get("cases", []):
138
+ metrics = [item["name"] for item in branch.get("principal_qois", [])]
139
+ return branch.get("id"), metrics
140
+ return None, []
141
+
142
+
143
+ def final_fraction(values: list[float], fraction: float = 0.2, minimum: int = 5) -> list[float]:
144
+ if not values:
145
+ return []
146
+ count = min(len(values), max(minimum, math.ceil(len(values) * fraction)))
147
+ return values[-count:]
148
+
149
+
150
+ def force_coefficients(case: Path) -> tuple[dict[str, list[float]], list[str]]:
151
+ files = matching_files(case, ("forcecoeffs.dat",), (".dat", ".csv", ".raw"))
152
+ files.extend(resolve_evidence(case, "force_coefficients", suffixes=(".dat", ".csv", ".raw")))
153
+ # Content-addressed fallback: a different agent may call this table
154
+ # loads.csv or aero_coefficients.dat. The header is the physical contract.
155
+ candidates = [path for root in evidence_roots(case) for path in root.rglob("*")
156
+ if path.is_file() and path.suffix.lower() in {".dat", ".csv", ".raw"}]
157
+ for path in candidates:
158
+ if path in files:
159
+ continue
160
+ header, _ = named_numeric_rows(path)
161
+ if "Time" in header and any(name in header for name in ("Cd", "Cl", "Cm")):
162
+ files.append(path)
163
+ files = sorted(set(files))
164
+ columns: dict[str, list[float]] = {}
165
+ evidence: list[str] = []
166
+ for path in files:
167
+ header, rows = named_numeric_rows(path)
168
+ if not header or "Time" not in header:
169
+ continue
170
+ for name in ("Cd", "Cl", "Cm"):
171
+ if name not in header:
172
+ continue
173
+ index = header.index(name)
174
+ columns.setdefault(name, []).extend(
175
+ row[index] for row in rows if math.isfinite(row[index])
176
+ )
177
+ evidence.append(evidence_path(case, path))
178
+ return columns, evidence
179
+
180
+
181
+ def extract_force_metric(case: Path, metric: str) -> tuple[float | None, list[str], str]:
182
+ columns, evidence = force_coefficients(case)
183
+ base = metric.removesuffix("_mean").removesuffix("_rms")
184
+ values = final_fraction(columns.get(base, []))
185
+ if not values:
186
+ return None, [], "header_addressed_force_coefficients.v1"
187
+ if metric.endswith("_rms"):
188
+ mean = statistics.fmean(values)
189
+ value = math.sqrt(statistics.fmean((item - mean) ** 2 for item in values))
190
+ else:
191
+ value = statistics.fmean(values)
192
+ return value, evidence, "header_addressed_force_coefficients.v1"
193
+
194
+
195
+ def spalding_metrics_from_files(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]:
196
+ log_errors: list[float] = []
197
+ first_yplus: list[float] = []
198
+ evidence: list[str] = []
199
+ for path in files:
200
+ header, rows = named_numeric_rows(path)
201
+ normalized = {
202
+ re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): index
203
+ for index, name in enumerate(header)
204
+ }
205
+ y_index = next(
206
+ (normalized[name] for name in ("yplus", "firstcellyplus", "yplusmin", "firstcellyplusmin") if name in normalized),
207
+ None,
208
+ )
209
+ predicted_index = next(
210
+ (normalized[name] for name in ("spaldingyplus", "yplusspaldingup", "yplusspaldinguplus", "yplusspalding") if name in normalized),
211
+ None,
212
+ )
213
+ if y_index is None:
214
+ continue
215
+ # Zero is a valid observed wall resolution. Missing evidence is an
216
+ # absent row, not a non-positive value.
217
+ y_values = [row[y_index] for row in rows if len(row) > y_index and math.isfinite(row[y_index]) and row[y_index] >= 0]
218
+ if y_values:
219
+ first_yplus.append(min(y_values))
220
+ if predicted_index is None:
221
+ # A first-cell summary is valid endpoint evidence, but it cannot
222
+ # be relabelled as a profile residual.
223
+ evidence.append(evidence_path(relative_to, path))
224
+ continue
225
+ valid = [
226
+ (row[y_index], row[predicted_index]) for row in rows
227
+ if len(row) > max(y_index, predicted_index)
228
+ and math.isfinite(row[y_index]) and math.isfinite(row[predicted_index])
229
+ and row[y_index] >= 0 and row[predicted_index] >= 0
230
+ ]
231
+ if not valid:
232
+ continue
233
+ log_errors.extend(
234
+ math.log1p(yplus) - math.log1p(predicted)
235
+ for yplus, predicted in valid
236
+ )
237
+ evidence.append(evidence_path(relative_to, path))
238
+ result: dict[str, float] = {}
239
+ if log_errors:
240
+ result["spalding_log_rmse"] = math.sqrt(statistics.fmean(value * value for value in log_errors))
241
+ if first_yplus:
242
+ result["first_cell_yplus"] = statistics.fmean(first_yplus)
243
+ return result, evidence
244
+
245
+
246
+ def standard_yplus_metrics(files: list[Path], relative_to: Path) -> tuple[dict[str, float], list[str]]:
247
+ """Read OpenFOAM's standard ``yPlus.dat`` patch summary.
248
+
249
+ The standard table has the schema ``Time patch min max average``. It is
250
+ therefore intentionally parsed separately from ``named_numeric_rows``,
251
+ which rejects the non-numeric patch column. A zero average remains a
252
+ valid observation.
253
+ """
254
+ rows: list[tuple[float, str, float, float, float]] = []
255
+ evidence: list[str] = []
256
+ for path in files:
257
+ if path.name.lower() != "yplus.dat":
258
+ continue
259
+ try:
260
+ for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
261
+ parts = line.split()
262
+ if len(parts) < 5 or parts[0].startswith("#"):
263
+ continue
264
+ try:
265
+ time = float(parts[0])
266
+ minimum, maximum, average = float(parts[2]), float(parts[3]), float(parts[4])
267
+ except ValueError:
268
+ continue
269
+ if all(math.isfinite(value) for value in (time, minimum, maximum, average)):
270
+ rows.append((time, parts[1], minimum, maximum, average))
271
+ except OSError:
272
+ continue
273
+ if rows:
274
+ evidence.append(evidence_path(relative_to, path))
275
+ if not rows:
276
+ return {}, []
277
+ final_time = max(row[0] for row in rows)
278
+ final_rows = [row for row in rows if abs(row[0] - final_time) <= 1e-12 * max(1.0, abs(final_time))]
279
+ # Symmetric wall patches are one declared response; average their final
280
+ # values while retaining the source file as auditable evidence.
281
+ return {"first_cell_yplus": statistics.fmean(row[4] for row in final_rows)}, sorted(set(evidence))
282
+
283
+
284
+ def spalding_metrics(case: Path) -> tuple[dict[str, float], list[str]]:
285
+ files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv"))
286
+ # OpenFOAM's standard yPlus function object writes ``yPlus.dat`` with a
287
+ # non-numeric patch-name column (``Time patch min max average``). It is
288
+ # intentionally handled by ``standard_yplus_metrics`` below, so discover
289
+ # it by basename instead of sending it through ``named_numeric_rows``.
290
+ for root in evidence_roots(case):
291
+ files.extend(
292
+ path for path in root.rglob("*")
293
+ if path.is_file() and path.name.lower() == "yplus.dat"
294
+ )
295
+ # The rollout measurement writer emits an explicit wall table instead of
296
+ # a Spalding profile. yPlus_min is valid endpoint evidence; it is not
297
+ # treated as a profile residual.
298
+ files.extend(matching_files(case, ("yplus_wall.csv",), (".csv",)))
299
+ # Accept semantically equivalent wall tables even when the file name is
300
+ # agent-specific, provided the table contains a y+ column.
301
+ for root in evidence_roots(case):
302
+ for path in root.rglob("*"):
303
+ if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}:
304
+ continue
305
+ header, _ = named_numeric_rows(path)
306
+ normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")) for name in header}
307
+ if "yplus" in normalized or "firstcellyplus" in normalized:
308
+ files.append(path)
309
+ files = sorted(set(files))
310
+ standard_values, standard_evidence = standard_yplus_metrics(files, case)
311
+ wall_files = [path for path in files if path.name.lower() == "yplus_wall.csv"]
312
+ wall_values: list[float] = []
313
+ wall_evidence: list[str] = []
314
+ for path in wall_files:
315
+ try:
316
+ with path.open(newline="", encoding="utf-8", errors="ignore") as handle:
317
+ for row in csv.DictReader(handle):
318
+ raw = row.get("yPlus_min") or row.get("yplus_min") or row.get("first_cell_yplus")
319
+ if raw is not None:
320
+ value = float(raw)
321
+ if math.isfinite(value) and value >= 0:
322
+ wall_values.append(value)
323
+ if wall_values:
324
+ wall_evidence.append(evidence_path(case, path))
325
+ except (OSError, ValueError):
326
+ continue
327
+ # Branch-labelled evidence is handled separately for the multi-Re case.
328
+ files = [path for path in files if "branches" not in tuple(evidence_path(case, path).split("/"))]
329
+ values, evidence = spalding_metrics_from_files([path for path in files if path not in wall_files], case)
330
+ if "first_cell_yplus" not in values:
331
+ # CSV profile variants use a header with a literal ``y+`` token or a
332
+ # yplus column and do not necessarily contain a yPlus_min summary.
333
+ for path in files:
334
+ if path in wall_files:
335
+ continue
336
+ header, rows = named_numeric_rows(path)
337
+ normalized = {re.sub(r"[^a-z0-9]", "", name.lower().replace("+", "plus")): i for i, name in enumerate(header)}
338
+ index = next((normalized[name] for name in ("yplus", "firstcellyplus") if name in normalized), None)
339
+ if index is not None:
340
+ vals = [row[index] for row in rows if len(row) > index and math.isfinite(row[index]) and row[index] >= 0]
341
+ if vals:
342
+ values["first_cell_yplus"] = vals[0]
343
+ evidence.append(evidence_path(case, path))
344
+ break
345
+ if wall_values:
346
+ # The final row is the retained endpoint; using the mean would mix
347
+ # initialization transients with the declared final wall resolution.
348
+ values["first_cell_yplus"] = wall_values[-1]
349
+ evidence.extend(wall_evidence)
350
+ if "first_cell_yplus" not in values and standard_values:
351
+ values.update(standard_values)
352
+ evidence.extend(standard_evidence)
353
+ return values, sorted(set(evidence))
354
+
355
+
356
+ def branchwise_spalding_metrics(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
357
+ branches: dict[str, Any] = {}
358
+ evidence: list[str] = []
359
+ files = matching_files(case, ("spalding_comparison", "uplus_yplus", "wall_law_profile"), (".raw", ".xy", ".dat", ".csv"))
360
+ by_branch: dict[str, list[Path]] = {}
361
+ for path in files:
362
+ match = re.search(r"Re_tau_(180|395|590)", str(path))
363
+ if match:
364
+ by_branch.setdefault(f"Re_tau_{match.group(1)}", []).append(path)
365
+ for branch, branch_files in sorted(by_branch.items()):
366
+ values, refs = spalding_metrics_from_files(sorted(branch_files), case)
367
+ if {"spalding_log_rmse", "first_cell_yplus"} <= set(values):
368
+ branches[branch] = values
369
+ evidence.extend(refs)
370
+ expected = {"Re_tau_180", "Re_tau_395", "Re_tau_590"}
371
+ if set(branches) != expected:
372
+ return None, sorted(set(evidence))
373
+ return {"kind": "branch_scalars", "branches": branches}, sorted(set(evidence))
374
+
375
+
376
+ def stirrer_power_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
377
+ files = matching_files(case, ("surfaceFieldValue.dat",), (".dat",))
378
+ points: list[dict[str, float]] = []
379
+ evidence: list[str] = []
380
+ for path in files:
381
+ header, rows = named_numeric_rows(path)
382
+ fields = [name for name in header if name != "Time" and "stressUSf" in name]
383
+ if "Time" not in header or not fields:
384
+ continue
385
+ time_index, power_index = header.index("Time"), header.index(fields[0])
386
+ points.extend({"time": row[time_index], "value": row[power_index]} for row in rows if math.isfinite(row[power_index]))
387
+ evidence.append(evidence_path(case, path))
388
+ if not points:
389
+ return None, []
390
+ points.sort(key=lambda item: item["time"])
391
+ return {"kind": "time_history", "quantity": "surface_integrated_stressUSf_power", "points": points}, evidence
392
+
393
+
394
+ def named_sample_profiles(case: Path, names: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]:
395
+ profiles: list[dict[str, Any]] = []
396
+ evidence: list[str] = []
397
+ roots = [case, *evidence_roots(case)]
398
+ candidates: list[Path] = []
399
+ for root in roots:
400
+ candidates.extend(item for item in root.rglob("*") if item.is_file() and (
401
+ item.name in names or (item.suffix.lower() == ".csv" and item.parent.name.lower() == "profiles")
402
+ ))
403
+ for path in sorted(set(candidates)):
404
+ header, rows = named_numeric_rows(path)
405
+ if len(header) < 2 or not rows or not profile_has_physical_columns(header):
406
+ continue
407
+ profiles.append({
408
+ "profile_id": evidence_path(case, path),
409
+ "columns": header,
410
+ "rows": rows,
411
+ })
412
+ evidence.append(evidence_path(case, path))
413
+ if not profiles:
414
+ return None, []
415
+ return {"kind": "named_profiles", "profiles": profiles}, evidence
416
+
417
+
418
+ def result_profile_tables(case: Path, tokens: tuple[str, ...]) -> tuple[dict[str, Any] | None, list[str]]:
419
+ """Read explicit profile tables from workspace/results when named output
420
+ files use a family-specific filename instead of horizontal.xy/vertical.xy.
421
+ """
422
+ profiles: list[dict[str, Any]] = []
423
+ evidence: list[str] = []
424
+ roots = list(evidence_roots(case))
425
+ resolved = resolve_evidence(case, "centerline_profile", suffixes=(".csv", ".dat", ".raw", ".xy"))
426
+ for root in roots:
427
+ if not root.is_dir():
428
+ continue
429
+ for path in sorted(root.rglob("*")):
430
+ if not path.is_file() or path.suffix.lower() not in {".csv", ".dat", ".raw", ".xy"}:
431
+ continue
432
+ if path not in resolved and not any(token.lower() in path.name.lower() for token in tokens):
433
+ continue
434
+ header, rows = named_numeric_rows(path)
435
+ if len(header) < 2 or not rows or not profile_has_physical_columns(header):
436
+ continue
437
+ profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows})
438
+ evidence.append(evidence_path(case, path))
439
+ if not profiles:
440
+ return None, []
441
+ return {"kind": "named_profiles", "profiles": profiles}, sorted(set(evidence))
442
+
443
+
444
+ def profile_has_physical_columns(header: list[str]) -> bool:
445
+ """Require a coordinate and at least one sampled physical field."""
446
+ normalized = [re.sub(r"[^a-z0-9]", "", name.lower()) for name in header]
447
+ has_coordinate = any(name in {"x", "y", "z", "coordinate", "position", "arc"} or name.startswith(("x", "y", "z")) for name in normalized)
448
+ has_field = any(
449
+ name in {"p", "rho", "u", "ux", "uy", "uz"}
450
+ or name.startswith(("px", "py", "pz", "rhox", "rhoy", "rhoz"))
451
+ for name in normalized
452
+ )
453
+ return has_coordinate and has_field
454
+
455
+
456
+ def named_profiles_containing(case: Path, tokens: tuple[str, ...], required_columns: tuple[str, ...] = ()) -> tuple[dict[str, Any] | None, list[str]]:
457
+ """Read explicitly named sample tables; never infer a physical metric from field extrema."""
458
+ profiles: list[dict[str, Any]] = []
459
+ evidence: list[str] = []
460
+ for root in (case, *evidence_roots(case)):
461
+ for path in sorted(item for item in root.rglob("*") if item.is_file() and path_like_sample(item, tokens)):
462
+ header, rows = named_numeric_rows(path)
463
+ if len(header) < 2 or not rows or any(column not in header for column in required_columns):
464
+ continue
465
+ profiles.append({"profile_id": evidence_path(case, path), "columns": header, "rows": rows})
466
+ evidence.append(evidence_path(case, path))
467
+ return ({"kind": "named_profiles", "profiles": profiles}, evidence) if profiles else (None, [])
468
+
469
+
470
+ def path_like_sample(path: Path, tokens: tuple[str, ...]) -> bool:
471
+ name = path.name.lower()
472
+ return path.suffix.lower() in {".xy", ".raw", ".dat", ".csv"} and any(token.lower() in name for token in tokens)
473
+
474
+
475
+ def field_dimensions(case: Path, field: str) -> str | None:
476
+ for path in sorted(case.rglob(field), reverse=True):
477
+ if not path.is_file() or not path.parent.name.replace(".", "", 1).isdigit():
478
+ continue
479
+ header = path.read_bytes()[:4096].decode("ascii", errors="ignore")
480
+ match = re.search(r"dimensions\s*\[([^]]+)\]", header)
481
+ if match:
482
+ return " ".join(match.group(1).split())
483
+ return None
484
+
485
+
486
+ def evidence_branch(case: Path, path: Path) -> str:
487
+ try:
488
+ parts = path.relative_to(case).parts
489
+ except ValueError:
490
+ parts = path.relative_to(case.parent).parts
491
+ try:
492
+ index = parts.index("postProcessing")
493
+ except ValueError:
494
+ return "root"
495
+ return "/".join(parts[:index]) or "root"
496
+
497
+
498
+ def explicit_mass_flow_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
499
+ branch_points: dict[str, list[dict[str, float]]] = {}
500
+ evidence: list[str] = []
501
+ candidates = matching_files(case, ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi"), (".dat", ".raw", ".csv"))
502
+ # Some benchmark variants materialize several nested operating-point cases;
503
+ # accept their postProcessing evidence without flattening those branches.
504
+ if not candidates:
505
+ candidates = sorted(path for path in case.rglob("*") if path.is_file()
506
+ and path.suffix.lower() in {".dat", ".raw", ".csv"}
507
+ and any(token.lower() in str(path).lower()
508
+ for token in ("surfaceFieldValue", "massFlow", "massFlux", "rhoPhi")))
509
+ for path in candidates:
510
+ patch_match = re.search(r"patch=([^)/]+)", str(path))
511
+ if patch_match is not None and patch_match.group(1).lower() not in {"inlet", "inlet1", "main", "mainstream"}:
512
+ # The principal pump/nozzle response is the declared inlet flow;
513
+ # do not concatenate inlet and outlet fluxes into one history.
514
+ continue
515
+ header, rows = named_numeric_rows(path)
516
+ mass_columns = [column for column in header if any(token in column.lower() for token in ("rhophi", "massflow", "massflux", "sum(phi)"))]
517
+ if "Time" not in header or not mass_columns:
518
+ continue
519
+ t_index, value_index = header.index("Time"), header.index(mass_columns[0])
520
+ branch = evidence_branch(case, path)
521
+ branch_points.setdefault(branch, []).extend(
522
+ {"time": row[t_index], "value": row[value_index]}
523
+ for row in rows if math.isfinite(row[value_index])
524
+ )
525
+ evidence.append(evidence_path(case, path))
526
+ if not branch_points:
527
+ return None, []
528
+ dimensions = field_dimensions(case, "phi")
529
+ quantity = {
530
+ "1 0 -1 0 0 0 0": "explicit_mass_flow",
531
+ "0 3 -1 0 0 0 0": "explicit_volumetric_flow",
532
+ }.get(dimensions, "explicit_flux_unknown_dimensions")
533
+ branches = {
534
+ branch: {"kind": "time_history", "quantity": quantity,
535
+ "points": sorted(points, key=lambda item: item["time"])}
536
+ for branch, points in sorted(branch_points.items())
537
+ }
538
+ if set(branches) == {"root"}:
539
+ result = branches["root"]
540
+ else:
541
+ result = {"kind": "branched_time_histories", "quantity": quantity, "branches": branches}
542
+ result["field_dimensions"] = dimensions
543
+ return result, sorted(set(evidence))
544
+
545
+
546
+ def explicit_patch_pressure(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
547
+ histories: dict[str, list[dict[str, float]]] = {}
548
+ evidence: list[str] = []
549
+ for path in matching_files(case, ("patchAverage", "patchIntegrate", "pressureRise", "pressure_rise"), (".dat", ".raw", ".csv")):
550
+ header, rows = named_numeric_rows(path)
551
+ pressure_columns = [column for column in header if column != "Time" and any(token in column.lower() for token in ("p", "pressure"))]
552
+ match = re.search(r"patch=([^)/]+)", str(path))
553
+ if "Time" not in header or not pressure_columns or not match:
554
+ continue
555
+ patch_name = match.group(1)
556
+ t_index, value_index = header.index("Time"), header.index(pressure_columns[0])
557
+ histories.setdefault(patch_name, []).extend({"time": row[t_index], "value": row[value_index]} for row in rows if math.isfinite(row[value_index]))
558
+ evidence.append(evidence_path(case, path))
559
+ inlet_name = next((name for name in histories if "inlet" in name.lower()), None)
560
+ outlet_name = next((name for name in histories if "outlet" in name.lower()), None)
561
+ if inlet_name is None or outlet_name is None:
562
+ return None, []
563
+ inlet = {round(point["time"], 12): point["value"] for point in histories[inlet_name]}
564
+ outlet = {round(point["time"], 12): point["value"] for point in histories[outlet_name]}
565
+ points = [
566
+ {"time": time, "value": outlet[time] - inlet[time]}
567
+ for time in sorted(set(inlet) & set(outlet))
568
+ ]
569
+ if not points:
570
+ return None, []
571
+ return {
572
+ "kind": "time_history",
573
+ "quantity": "pressure_rise",
574
+ "definition": "outlet_minus_inlet_patch_average",
575
+ "source_patches": {"inlet": inlet_name, "outlet": outlet_name},
576
+ "points": points,
577
+ }, sorted(set(evidence))
578
+
579
+
580
+ def crossjet_inlet_mass_flux_ratio(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
581
+ fluxes: dict[str, list[tuple[float, float]]] = {}
582
+ evidence: list[str] = []
583
+ for path in resolve_evidence(case, "patch_flux", suffixes=(".dat", ".raw", ".csv")):
584
+ match = re.search(r"patch=([^)/]+)", str(path))
585
+ if match is None:
586
+ match = re.search(r"(?m)^\s*#\s*Selection\s*:\s*patch\(([^)]+)\)", path.read_text(errors="ignore"))
587
+ if match is None:
588
+ continue
589
+ patch = match.group(1).lower()
590
+ canonical = (
591
+ "inlet1" if patch in {"inlet1", "inlet", "main", "mainstream", "maininlet", "mainflowinlet"}
592
+ else "inlet2" if patch in {"inlet2", "jet", "injection", "jetinlet"}
593
+ else None
594
+ )
595
+ if canonical is None:
596
+ continue
597
+ header, rows = named_numeric_rows(path)
598
+ columns = [column for column in header if column != "Time" and "sum(phi)" in column]
599
+ if "Time" not in header or not columns:
600
+ continue
601
+ ti, vi = header.index("Time"), header.index(columns[0])
602
+ fluxes.setdefault(canonical, []).extend((row[ti], row[vi]) for row in rows)
603
+ evidence.append(evidence_path(case, path))
604
+ if not all(fluxes.get(patch) for patch in ("inlet1", "inlet2")):
605
+ return None, []
606
+ main = sorted(fluxes["inlet1"])[-1]
607
+ jet = sorted(fluxes["inlet2"])[-1]
608
+ if main[1] == 0:
609
+ return None, []
610
+ return {
611
+ "kind": "scalar_ratio",
612
+ "quantity": "jet_to_mainstream_mass_flux_ratio",
613
+ "value": abs(jet[1] / main[1]),
614
+ "mainstream_flux": main[1],
615
+ "jet_flux": jet[1],
616
+ "time": min(main[0], jet[0]),
617
+ "patch_aliases": {"mainstream": "inlet1", "jet": "inlet2"},
618
+ }, sorted(set(evidence))
619
+
620
+
621
+ def phase_volume_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
622
+ points: list[dict[str, float]] = []
623
+ evidence: list[str] = []
624
+ for time, directory in numeric_time_dirs(case):
625
+ alpha_path = foam_path(directory, "alpha.water")
626
+ volume_path = foam_path(directory, "Vc")
627
+ if alpha_path is None or volume_path is None:
628
+ continue
629
+ try:
630
+ alpha = read_scalar_field(alpha_path)
631
+ volumes = read_scalar_field(volume_path)
632
+ except (OSError, ValueError, RuntimeError):
633
+ continue
634
+ if len(alpha) != len(volumes) or not volumes:
635
+ continue
636
+ total = sum(volumes)
637
+ if total <= 0:
638
+ continue
639
+ points.append({"time": time, "value": sum(a * v for a, v in zip(alpha, volumes)) / total})
640
+ evidence.extend((evidence_path(case, alpha_path), evidence_path(case, volume_path)))
641
+ if not points:
642
+ return None, []
643
+ return {"kind": "time_history", "quantity": "volume_weighted_alpha_water", "points": points}, sorted(set(evidence))
644
+
645
+
646
+ def volume_average_speed_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
647
+ points: list[dict[str, float]] = []
648
+ evidence: list[str] = []
649
+ for time, directory in numeric_time_dirs(case):
650
+ velocity_path = foam_path(directory, "U")
651
+ volume_path = foam_path(directory, "Vc")
652
+ if velocity_path is None or volume_path is None:
653
+ continue
654
+ try:
655
+ velocity = read_vector_field(velocity_path)
656
+ volumes = read_scalar_field(volume_path)
657
+ except (OSError, ValueError, RuntimeError):
658
+ continue
659
+ if len(velocity) != len(volumes) or not volumes:
660
+ continue
661
+ total = sum(volumes)
662
+ if total <= 0:
663
+ continue
664
+ value = sum(math.sqrt(u * u + v * v + w * w) * volume
665
+ for (u, v, w), volume in zip(velocity, volumes)) / total
666
+ if not math.isfinite(value):
667
+ continue
668
+ points.append({"time": time, "value": value})
669
+ evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path)))
670
+ if not points:
671
+ return None, []
672
+ return {"kind": "time_history", "quantity": "volume_average_speed", "points": points}, sorted(set(evidence))
673
+
674
+
675
+ def volume_speed_rms_history(case: Path) -> tuple[dict[str, Any] | None, list[str]]:
676
+ points: list[dict[str, float]] = []
677
+ evidence: list[str] = []
678
+ for time, directory in numeric_time_dirs(case):
679
+ velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc")
680
+ if velocity_path is None or volume_path is None:
681
+ continue
682
+ try:
683
+ velocity, volumes = read_vector_field(velocity_path), read_scalar_field(volume_path)
684
+ except (OSError, ValueError, RuntimeError):
685
+ continue
686
+ if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0:
687
+ continue
688
+ speeds = [math.sqrt(u * u + v * v + w * w) for u, v, w in velocity]
689
+ total = sum(volumes)
690
+ mean = sum(speed * volume for speed, volume in zip(speeds, volumes)) / total
691
+ rms = math.sqrt(sum((speed - mean) ** 2 * volume for speed, volume in zip(speeds, volumes)) / total)
692
+ if math.isfinite(rms):
693
+ points.append({"time": time, "value": rms})
694
+ evidence.extend((evidence_path(case, velocity_path), evidence_path(case, volume_path)))
695
+ if not points:
696
+ return None, []
697
+ return {"kind": "time_history", "quantity": "volume_speed_spatial_rms", "points": points}, sorted(set(evidence))
698
+
699
+
700
+ def volume_average_speed_final(case: Path) -> tuple[float | None, list[str]]:
701
+ """Extract a final-state mixing response from retained U and cell volumes."""
702
+ for _, directory in reversed(numeric_time_dirs(case)):
703
+ velocity_path, volume_path = foam_path(directory, "U"), foam_path(directory, "Vc")
704
+ if velocity_path is None:
705
+ continue
706
+ try:
707
+ # Retained agent fields can contain a uniform internal U while Vc
708
+ # still has one volume per cell. Decode the concrete array first
709
+ # so the uniform vector is expanded using an observed cell count.
710
+ if volume_path is not None:
711
+ volumes = read_scalar_field(volume_path)
712
+ geometry_evidence = [volume_path]
713
+ else:
714
+ from .retained_fields import derive_cell_geometry
715
+ volumes, _, geometry_evidence = derive_cell_geometry(case)
716
+ try:
717
+ velocity = read_vector_field(velocity_path)
718
+ except (ValueError, RuntimeError):
719
+ velocity = read_vector_field_allow_uniform(velocity_path, len(volumes))
720
+ if volume_path is not None and len(volumes) == 1 and len(velocity) > 1:
721
+ volumes = volumes * len(velocity)
722
+ except (OSError, ValueError, RuntimeError):
723
+ continue
724
+ if len(velocity) != len(volumes) or not volumes or sum(volumes) <= 0:
725
+ continue
726
+ total = sum(volumes)
727
+ value = sum(math.sqrt(u * u + v * v + w * w) * volume
728
+ for (u, v, w), volume in zip(velocity, volumes)) / total
729
+ if math.isfinite(value):
730
+ return value, [evidence_path(case, path) for path in [velocity_path, *geometry_evidence]]
731
+ return None, []
732
+
733
+
734
+ def read_vector_field_allow_uniform(path: Path, count: int) -> list[tuple[float, float, float]]:
735
+ try:
736
+ return read_vector_field(path)
737
+ except (ValueError, RuntimeError):
738
+ text = path.read_text(encoding="ascii", errors="ignore")
739
+ match = re.search(r"internalField\s+uniform\s+\(([^)]+)\)", text)
740
+ if match is None:
741
+ raise
742
+ values = [float(item) for item in match.group(1).split()]
743
+ if len(values) != 3:
744
+ raise ValueError(f"invalid uniform vector field: {path}")
745
+ return [(values[0], values[1], values[2])] * count
746
+
747
+
748
+ def read_scalar_field_allow_uniform(path: Path, count: int) -> list[float]:
749
+ """Read a scalar field while preserving the semantics of a uniform field."""
750
+ try:
751
+ values = read_scalar_field(path)
752
+ except (ValueError, RuntimeError):
753
+ text = path.read_text(encoding="ascii", errors="ignore")
754
+ match = re.search(r"internalField\s+uniform\s+([^;]+);", text)
755
+ if match is None:
756
+ raise
757
+ return [float(match.group(1).strip())] * count
758
+ if len(values) == 1 and count > 1:
759
+ # OpenFOAM permits a uniform field to be serialized as one value.
760
+ return values * count
761
+ return values
762
+
763
+
764
+ def crossjet_interior_pressure_span(case: Path) -> tuple[float | None, list[str]]:
765
+ """Return the pressure response in the declared internal CrossJet window.
766
+
767
+ The span is deliberately computed from the retained pressure field rather
768
+ than from ``grad(p)``. This remains extractable for references that store
769
+ ``p`` as a uniform field and avoids treating a missing/zero post-processing
770
+ gradient as a shock observable.
771
+ """
772
+ for _, directory in reversed(numeric_time_dirs(case)):
773
+ centre_path, pressure_path = foam_path(directory, "C"), foam_path(directory, "p")
774
+ if pressure_path is None:
775
+ continue
776
+ try:
777
+ if centre_path is not None:
778
+ centres = read_vector_field(centre_path)
779
+ geometry_evidence = [centre_path]
780
+ else:
781
+ from .retained_fields import derive_cell_geometry
782
+ _, centres, geometry_evidence = derive_cell_geometry(case)
783
+ pressure = read_scalar_field_allow_uniform(pressure_path, len(centres))
784
+ except (OSError, ValueError, RuntimeError):
785
+ continue
786
+ if len(pressure) != len(centres):
787
+ continue
788
+ values = [value for (x, y, _), value in zip(centres, pressure)
789
+ if -1.0 <= x <= 1.0 and 0.1 <= y <= 0.95]
790
+ if values:
791
+ return max(values) - min(values), [evidence_path(case, path) for path in [*geometry_evidence, pressure_path]]
792
+ return None, []
793
+
794
+
795
+ def crossjet_interior_pressure_gradient_max(case: Path) -> tuple[float | None, list[str]]:
796
+ """Return the maximum interior pressure span."""
797
+ return crossjet_interior_pressure_span(case)
798
+
799
+
800
+ def profile_event_locations(profiles: dict[str, Any]) -> dict[str, Any] | None:
801
+ events: list[dict[str, Any]] = []
802
+ for profile in profiles.get("profiles", []):
803
+ columns = profile.get("columns", [])
804
+ rows = profile.get("rows", [])
805
+ if len(columns) < 2 or len(rows) < 5:
806
+ continue
807
+ coordinate_index = 0
808
+ for field in ("p", "rho"):
809
+ field_index = next((index for index, name in enumerate(columns)
810
+ if name.lower() == field or name.lower().startswith(field + "_")), None)
811
+ if field_index is None:
812
+ continue
813
+ gradients: list[tuple[int, float, float]] = []
814
+ for index in range(len(rows) - 1):
815
+ spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index])
816
+ if spacing <= 0:
817
+ continue
818
+ gradient = abs(rows[index + 1][field_index] - rows[index][field_index]) / spacing
819
+ coordinate = (rows[index + 1][coordinate_index] + rows[index][coordinate_index]) / 2
820
+ gradients.append((index, coordinate, gradient))
821
+ if not gradients:
822
+ continue
823
+ peak = max(value for _, _, value in gradients)
824
+ threshold = 0.05 * peak
825
+ candidates = [
826
+ item for position, item in enumerate(gradients)
827
+ if item[2] >= threshold
828
+ and (position == 0 or item[2] >= gradients[position - 1][2])
829
+ and (position == len(gradients) - 1 or item[2] > gradients[position + 1][2])
830
+ ]
831
+ selected: list[tuple[int, float, float]] = []
832
+ for candidate in sorted(candidates, key=lambda item: item[2], reverse=True):
833
+ if all(abs(candidate[0] - item[0]) >= 4 for item in selected):
834
+ selected.append(candidate)
835
+ if len(selected) == 12:
836
+ break
837
+ for index, coordinate, magnitude in sorted(selected, key=lambda item: item[1]):
838
+ local_spacing = abs(rows[index + 1][coordinate_index] - rows[index][coordinate_index])
839
+ events.append({
840
+ "profile_id": profile["profile_id"],
841
+ "field": field,
842
+ "coordinate": coordinate,
843
+ "gradient_magnitude": magnitude,
844
+ "local_cell_size": local_spacing,
845
+ })
846
+ if not events:
847
+ return None
848
+ return {
849
+ "kind": "profile_feature_locations",
850
+ "detector": "local_abs_gradient_peaks.v1",
851
+ "relative_prominence": 0.05,
852
+ "minimum_separation_samples": 4,
853
+ "maximum_features_per_field_profile": 12,
854
+ "events": events,
855
+ }
856
+
857
+
858
+ def final_riemann_profiles(profiles: dict[str, Any]) -> dict[str, Any]:
859
+ """Select each centerline's latest saved time and use its physical axis.
860
+
861
+ OpenFOAM raw sets may prefix x/y/z with arc distance. Preserve the sampled
862
+ values, but put x (horizontal) or y (vertical) first for event detection.
863
+ """
864
+ from .comparison import profile_key
865
+ selected: dict[str, tuple[float, dict[str, Any]]] = {}
866
+ for profile in profiles.get("profiles", []):
867
+ key = profile_key(profile)
868
+ axis = {"horizontal.xy": "x", "vertical.xy": "y"}.get(key)
869
+ columns = profile.get("columns", [])
870
+ if axis is None or axis not in columns:
871
+ continue
872
+ try:
873
+ time = float(Path(profile["profile_id"]).parent.name)
874
+ except ValueError:
875
+ time = -math.inf
876
+ if key in selected and time < selected[key][0]:
877
+ continue
878
+ order = [columns.index(axis)] + [i for i, name in enumerate(columns) if name != axis]
879
+ normalized = {**profile, "columns": [columns[i] for i in order],
880
+ "rows": [[row[i] for i in order] for row in profile["rows"]]}
881
+ selected[key] = (time, normalized)
882
+ return {"kind": "named_profiles", "profiles": [item[1] for item in selected.values()]}
883
+
884
+
885
+ def numeric_time_dirs(case: Path) -> list[tuple[float, Path]]:
886
+ result: list[tuple[float, Path]] = []
887
+ for path in case.iterdir():
888
+ if not path.is_dir():
889
+ continue
890
+ try:
891
+ result.append((float(path.name), path))
892
+ except ValueError:
893
+ pass
894
+ return sorted(result)
895
+
896
+
897
+ def mesh_dir(case: Path, time_dir: Path) -> Path:
898
+ local = time_dir / "polyMesh"
899
+ return local if local.is_dir() else case / "constant/polyMesh"
900
+
901
+
902
+ def connected_components(active: set[int], owner: list[int], neighbour: list[int]) -> list[list[int]]:
903
+ adjacency: dict[int, list[int]] = {cell: [] for cell in active}
904
+ for left, right in zip(owner, neighbour):
905
+ if left in active and right in active:
906
+ adjacency[left].append(right)
907
+ adjacency[right].append(left)
908
+ components: list[list[int]] = []
909
+ unseen = set(active)
910
+ while unseen:
911
+ seed = unseen.pop()
912
+ stack = [seed]
913
+ component = [seed]
914
+ while stack:
915
+ for cell in adjacency[stack.pop()]:
916
+ if cell in unseen:
917
+ unseen.remove(cell)
918
+ stack.append(cell)
919
+ component.append(cell)
920
+ components.append(component)
921
+ return components
922
+
923
+
924
+ def component_geometry(
925
+ cells: list[int], gas: list[float], volumes: list[float], centres: list[tuple[float, float, float]], volume_factor: float
926
+ ) -> dict[str, float]:
927
+ weights = [max(0.0, min(1.0, gas[cell])) * volumes[cell] for cell in cells]
928
+ volume = sum(weights)
929
+ if volume <= 0:
930
+ return {}
931
+ centroid = [sum(weight * centres[cell][axis] for weight, cell in zip(weights, cells)) / volume for axis in range(3)]
932
+ xx = sum(weight * (centres[cell][0] - centroid[0]) ** 2 for weight, cell in zip(weights, cells)) / volume
933
+ yy = sum(weight * (centres[cell][1] - centroid[1]) ** 2 for weight, cell in zip(weights, cells)) / volume
934
+ xy = sum(weight * (centres[cell][0] - centroid[0]) * (centres[cell][1] - centroid[1]) for weight, cell in zip(weights, cells)) / volume
935
+ root = math.sqrt(max(0.0, (xx - yy) ** 2 + 4 * xy * xy))
936
+ major = max(0.0, (xx + yy + root) / 2)
937
+ minor = max(0.0, (xx + yy - root) / 2)
938
+ aspect = math.sqrt(major / minor) if minor > 0 else None
939
+ return {
940
+ "volume": volume,
941
+ "centroid_x": centroid[0],
942
+ "centroid_y": centroid[1],
943
+ "centroid_z": centroid[2],
944
+ "aspect_ratio": aspect,
945
+ "equivalent_radius_3d": (3 * volume * volume_factor / (4 * math.pi)) ** (1 / 3),
946
+ }
947
+
948
+
949
+ def axisymmetric_volume_factor(case: Path) -> float:
950
+ boundary = case / "constant/polyMesh/boundary"
951
+ if not boundary.is_file() or "wedge" not in boundary.read_text(encoding="utf-8", errors="ignore"):
952
+ return 1.0
953
+ points_path = foam_path(case / "constant/polyMesh", "points")
954
+ if points_path is None:
955
+ return 1.0
956
+ angles = [math.atan2(y, x) for x, y, _ in read_vector_list(points_path) if x > 0]
957
+ if not angles:
958
+ return 1.0
959
+ wedge_angle = max(angles) - min(angles)
960
+ return 2 * math.pi / wedge_angle if wedge_angle > 0 else 1.0
961
+
962
+
963
+ def bubble_history(case: Path) -> tuple[list[dict[str, Any]], list[str], list[str]]:
964
+ history: list[dict[str, Any]] = []
965
+ evidence: list[str] = []
966
+ errors: list[str] = []
967
+ dynamic = not static_mesh(case)
968
+ volume_factor = axisymmetric_volume_factor(case)
969
+ cached_geometry: tuple[list[float], list[tuple[float, float, float]]] | None = None
970
+ cached_topology: tuple[list[int], list[int]] | None = None
971
+ time_dirs = numeric_time_dirs(case)
972
+ if not dynamic:
973
+ for _, directory in reversed(time_dirs):
974
+ volume_path = foam_path(directory, "Vc")
975
+ centre_path = foam_path(directory, "C")
976
+ if volume_path and centre_path:
977
+ cached_geometry = (read_scalar_field(volume_path), read_vector_field(centre_path))
978
+ break
979
+ topology_dir = case / "constant/polyMesh"
980
+ owner_path = foam_path(topology_dir, "owner")
981
+ neighbour_path = foam_path(topology_dir, "neighbour")
982
+ if owner_path and neighbour_path:
983
+ cached_topology = (read_label_list(owner_path), read_label_list(neighbour_path))
984
+ if cached_geometry is None:
985
+ try:
986
+ volumes, centres, mesh_paths = derive_cell_geometry(case)
987
+ cached_geometry = (volumes, centres)
988
+ evidence.extend(evidence_path(case, path) for path in mesh_paths)
989
+ boundary_path = foam_path(topology_dir, "boundary")
990
+ if boundary_path:
991
+ evidence.append(evidence_path(case, boundary_path))
992
+ except (OSError, ValueError, RuntimeError) as exc:
993
+ errors.append(f"retained mesh geometry: {exc}")
994
+ previous_tracks: dict[int, tuple[float, float, float]] = {}
995
+ next_track = 1
996
+ for time, directory in time_dirs:
997
+ alpha_path = foam_path(directory, "alpha.water")
998
+ if alpha_path is None:
999
+ continue
1000
+ volume_path = foam_path(directory, "Vc")
1001
+ centre_path = foam_path(directory, "C")
1002
+ try:
1003
+ if cached_geometry is not None and not dynamic:
1004
+ geometry = cached_geometry
1005
+ elif volume_path and centre_path:
1006
+ geometry = (read_scalar_field(volume_path), read_vector_field(centre_path))
1007
+ if not dynamic:
1008
+ cached_geometry = geometry
1009
+ else:
1010
+ errors.append(f"{directory.name}: missing C/Vc measurement fields")
1011
+ continue
1012
+ topology_dir = mesh_dir(case, directory)
1013
+ owner_path = foam_path(topology_dir, "owner")
1014
+ neighbour_path = foam_path(topology_dir, "neighbour")
1015
+ if (owner_path is None or neighbour_path is None) and dynamic:
1016
+ # Dynamic solvers may not retain a polyMesh in every output
1017
+ # directory. Reuse the immutable mesh topology only when it
1018
+ # is present and the field length remains compatible.
1019
+ owner_path = foam_path(case / "constant/polyMesh", "owner")
1020
+ neighbour_path = foam_path(case / "constant/polyMesh", "neighbour")
1021
+ if cached_topology is not None and not dynamic:
1022
+ topology = cached_topology
1023
+ elif owner_path and neighbour_path:
1024
+ topology = (read_label_list(owner_path), read_label_list(neighbour_path))
1025
+ if not dynamic:
1026
+ cached_topology = topology
1027
+ else:
1028
+ errors.append(f"{directory.name}: missing owner/neighbour topology")
1029
+ continue
1030
+ volumes, centres = geometry
1031
+ alpha = read_scalar_field_allow_uniform(alpha_path, len(volumes))
1032
+ if not (len(alpha) == len(volumes) == len(centres)):
1033
+ errors.append(f"{directory.name}: alpha/C/Vc length mismatch")
1034
+ continue
1035
+ gas = [1.0 - value for value in alpha]
1036
+ active = {index for index, value in enumerate(gas) if value >= 0.5}
1037
+ components = connected_components(active, *topology)
1038
+ geometries = [component_geometry(item, gas, volumes, centres, volume_factor) for item in components]
1039
+ geometries = sorted((item for item in geometries if item), key=lambda item: item["volume"], reverse=True)
1040
+ if geometries:
1041
+ cutoff = geometries[0]["volume"] * 1e-4
1042
+ geometries = [item for item in geometries if item["volume"] >= cutoff]
1043
+ available = set(previous_tracks)
1044
+ for item in geometries:
1045
+ point = (item["centroid_x"], item["centroid_y"], item["centroid_z"])
1046
+ if available:
1047
+ track = min(available, key=lambda key: sum((a - b) ** 2 for a, b in zip(point, previous_tracks[key])))
1048
+ available.remove(track)
1049
+ else:
1050
+ track = next_track
1051
+ next_track += 1
1052
+ item["track_id"] = track
1053
+ previous_tracks = {
1054
+ item["track_id"]: (item["centroid_x"], item["centroid_y"], item["centroid_z"])
1055
+ for item in geometries
1056
+ }
1057
+ history.append({"time": time, "components": geometries})
1058
+ evidence.extend(evidence_path(case, path) for path in (alpha_path, volume_path, centre_path) if path)
1059
+ except (OSError, ValueError, RuntimeError) as exc:
1060
+ errors.append(f"{directory.name}: {exc}")
1061
+ # A dynamic case may intentionally retain geometry/topology only at the
1062
+ # endpoint. Earlier missing derived fields make the optional trajectory
1063
+ # incomplete, but must not invalidate endpoint principal QoIs when the
1064
+ # final saved state was successfully measured.
1065
+ if history and history[-1].get("time") == (time_dirs[-1][0] if time_dirs else None):
1066
+ errors = []
1067
+ return history, sorted(set(evidence)), errors
1068
+
1069
+
1070
+ def component_trajectory(history: list[dict[str, Any]], field: str, all_components: bool = False) -> dict[str, Any] | None:
1071
+ rows = [item for item in history if item["components"]]
1072
+ if not rows:
1073
+ return None
1074
+ tracks = sorted({component["track_id"] for item in rows for component in item["components"]}) if all_components else [rows[0]["components"][0]["track_id"]]
1075
+ series = []
1076
+ for track in tracks:
1077
+ points = []
1078
+ omitted_invalid = 0
1079
+ for item in rows:
1080
+ component = next((part for part in item["components"] if part["track_id"] == track), None)
1081
+ if component is not None:
1082
+ value = component[field]
1083
+ if value is None:
1084
+ omitted_invalid += 1
1085
+ continue
1086
+ points.append({"time": item["time"], "value": value})
1087
+ series.append({
1088
+ "component_id": track,
1089
+ "points": points,
1090
+ "omitted_invalid_sample_count": omitted_invalid,
1091
+ "quality_note": "degenerate_component_geometry_samples_omitted" if omitted_invalid else None,
1092
+ })
1093
+ return {"kind": "component_trajectory", "component_identity": "nearest_centroid_continuation", "series": series}
1094
+
1095
+
1096
+ def collapse_events(radius: dict[str, Any]) -> dict[str, Any]:
1097
+ events = []
1098
+ for series in radius["series"]:
1099
+ points = series["points"]
1100
+ index = next((i for i in range(1, len(points) - 1) if points[i]["value"] <= points[i - 1]["value"] and points[i]["value"] < points[i + 1]["value"]), None)
1101
+ censored = index is None
1102
+ if points:
1103
+ index = min(range(len(points)), key=lambda i: points[i]["value"]) if index is None else index
1104
+ events.append({"component_id": series["component_id"], "time": points[index]["time"], "radius": points[index]["value"], "censored_at_time_boundary": censored})
1105
+ status = "complete" if events and all(not event["censored_at_time_boundary"] for event in events) else "censored"
1106
+ return {"kind": "component_events", "status": status, "detector": "first_strict_rebound_minimum_else_global_minimum", "events": events}
1107
+
1108
+
1109
+ def rise_velocity(centroid: dict[str, Any]) -> dict[str, Any] | None:
1110
+ points = centroid["series"][0]["points"]
1111
+ if len(points) < 3:
1112
+ return None
1113
+ end = points[-1]["time"]
1114
+ selected = [point for point in points if 0.3 * end <= point["time"] <= 0.7 * end]
1115
+ if len(selected) < 2:
1116
+ return None
1117
+ times = [point["time"] for point in selected]
1118
+ values = [point["value"] for point in selected]
1119
+ mt, my = statistics.fmean(times), statistics.fmean(values)
1120
+ denominator = sum((time - mt) ** 2 for time in times)
1121
+ if denominator == 0:
1122
+ return None
1123
+ slope = sum((time - mt) * (value - my) for time, value in zip(times, values)) / denominator
1124
+ return {"kind": "window_regression", "value": slope, "window": [times[0], times[-1]], "normalized_window": [0.3, 0.7], "sample_count": len(times)}
1125
+
1126
+
1127
+ def bubble_metrics(case: Path, family: str) -> tuple[dict[str, Any], list[str], list[str]]:
1128
+ history, evidence, errors = bubble_history(case)
1129
+ if family == "risingBubble":
1130
+ centroid = component_trajectory(history, "centroid_y")
1131
+ aspect = component_trajectory(history, "aspect_ratio")
1132
+ values: dict[str, Any] = {}
1133
+ if centroid:
1134
+ values["bubble_centroid_y_history"] = centroid
1135
+ values["bubble_centroid_y_final"] = final_component_scalar(centroid, "bubble_centroid_y_final")
1136
+ velocity = rise_velocity(centroid)
1137
+ if velocity:
1138
+ values["rise_velocity"] = velocity
1139
+ if aspect:
1140
+ values["shape_aspect_ratio_history"] = aspect
1141
+ values["shape_aspect_ratio_final"] = final_component_scalar(aspect, "shape_aspect_ratio_final")
1142
+ radius = component_trajectory(history, "equivalent_radius_3d")
1143
+ if radius:
1144
+ values["equivalent_radius_final"] = final_component_scalar(radius, "equivalent_radius_final")
1145
+ return values, evidence, errors
1146
+ radius = component_trajectory(history, "equivalent_radius_3d", all_components=True)
1147
+ if not radius:
1148
+ return {}, evidence, errors
1149
+ event = collapse_events(radius)
1150
+ values = {
1151
+ "equivalent_radius_history": radius,
1152
+ "equivalent_radius_final": final_component_scalar(radius, "equivalent_radius_final", all_components=True),
1153
+ "final_component_count": len(radius.get("series", [])),
1154
+ "collapse_time_censored_diagnostic": event,
1155
+ }
1156
+ minima = []
1157
+ for series in radius.get("series", []):
1158
+ observed = [point for point in series.get("points", [])
1159
+ if isinstance(point.get("value"), (int, float)) and math.isfinite(point["value"])]
1160
+ if observed:
1161
+ point = min(observed, key=lambda item: item["value"])
1162
+ minima.append({"component_id": series.get("component_id"), "time": point["time"], "value": point["value"]})
1163
+ if minima:
1164
+ values["minimum_observed_equivalent_radius"] = {
1165
+ "kind": "component_scalars", "quantity": "minimum_observed_equivalent_radius", "components": minima
1166
+ }
1167
+ if event["status"] == "complete":
1168
+ values["collapse_time"] = event
1169
+ return values, evidence, errors
1170
+
1171
+
1172
+ def final_component_scalar(
1173
+ trajectory: dict[str, Any], quantity: str, *, all_components: bool = False
1174
+ ) -> dict[str, Any]:
1175
+ """Return the last valid connected-component observation.
1176
+
1177
+ The full trajectory remains available as a diagnostic, while this endpoint
1178
+ response can be recovered when only the final field was retained.
1179
+ """
1180
+ series = trajectory.get("series", []) if isinstance(trajectory, dict) else []
1181
+ components = []
1182
+ selected = series if all_components else series[:1]
1183
+ for item in selected:
1184
+ points = [point for point in item.get("points", [])
1185
+ if isinstance(point, dict) and isinstance(point.get("value"), (int, float))
1186
+ and math.isfinite(float(point["value"]))]
1187
+ if points:
1188
+ point = points[-1]
1189
+ components.append({"component_id": item.get("component_id"), "time": point["time"], "value": point["value"]})
1190
+ return {"kind": "component_scalars", "quantity": quantity, "components": components}
1191
+
1192
+
1193
+ def structured_qoi_errors(name: str, value: Any) -> list[str]:
1194
+ errors: list[str] = []
1195
+ if isinstance(value, (int, float)):
1196
+ return [] if not isinstance(value, bool) and math.isfinite(float(value)) else [f"{name}: non-finite scalar"]
1197
+ if not isinstance(value, dict):
1198
+ return [f"{name}: unsupported QoI value"]
1199
+ kind = value.get("kind")
1200
+ if kind in {"time_history", "window_regression", "scalar_ratio"}:
1201
+ if kind == "time_history":
1202
+ points = value.get("points")
1203
+ if not isinstance(points, list) or not points:
1204
+ return [f"{name}: empty time history"]
1205
+ for point in points:
1206
+ if not isinstance(point, dict) or not all(
1207
+ isinstance(point.get(key), (int, float)) and math.isfinite(float(point[key]))
1208
+ for key in ("time", "value")
1209
+ ):
1210
+ errors.append(f"{name}: invalid time-history point")
1211
+ break
1212
+ elif not isinstance(value.get("value"), (int, float)) or not math.isfinite(float(value["value"])):
1213
+ errors.append(f"{name}: invalid scalar object")
1214
+ elif kind == "branched_time_histories":
1215
+ branches = value.get("branches")
1216
+ if not isinstance(branches, dict) or not branches:
1217
+ errors.append(f"{name}: no branches")
1218
+ else:
1219
+ for branch, history in branches.items():
1220
+ errors.extend(structured_qoi_errors(f"{name}/{branch}", history))
1221
+ elif kind == "branch_scalars":
1222
+ branches = value.get("branches")
1223
+ if not isinstance(branches, dict) or not branches:
1224
+ errors.append(f"{name}: no scalar branches")
1225
+ else:
1226
+ for branch, metrics in branches.items():
1227
+ if not isinstance(metrics, dict) or not metrics or any(
1228
+ not isinstance(item, (int, float)) or isinstance(item, bool) or not math.isfinite(float(item))
1229
+ for item in metrics.values()
1230
+ ):
1231
+ errors.append(f"{name}/{branch}: invalid branch scalar")
1232
+ elif kind == "component_scalars":
1233
+ components = value.get("components")
1234
+ if not isinstance(components, list) or not components:
1235
+ errors.append(f"{name}: no component scalars")
1236
+ elif any(not isinstance(item.get("value"), (int, float)) or not math.isfinite(float(item["value"]))
1237
+ for item in components if isinstance(item, dict)):
1238
+ errors.append(f"{name}: invalid component scalar")
1239
+ elif kind == "component_trajectory":
1240
+ series = value.get("series")
1241
+ if not isinstance(series, list) or not series:
1242
+ errors.append(f"{name}: no component trajectories")
1243
+ else:
1244
+ for item in series:
1245
+ points = item.get("points", []) if isinstance(item, dict) else []
1246
+ valid = [point for point in points if isinstance(point, dict)
1247
+ and isinstance(point.get("value"), (int, float))
1248
+ and math.isfinite(float(point["value"]))]
1249
+ if len(valid) < 2:
1250
+ errors.append(f"{name}: component has fewer than two valid points")
1251
+ elif kind == "named_profiles":
1252
+ profiles = value.get("profiles")
1253
+ if not isinstance(profiles, list) or not profiles:
1254
+ errors.append(f"{name}: no named profiles")
1255
+ elif any(not profile.get("rows") or len(profile.get("columns", [])) < 2 for profile in profiles):
1256
+ errors.append(f"{name}: empty or unlabelled profile")
1257
+ elif kind in {"profile_events", "profile_feature_locations"}:
1258
+ if not isinstance(value.get("events"), list):
1259
+ errors.append(f"{name}: invalid event collection")
1260
+ else:
1261
+ errors.append(f"{name}: unknown structured kind {kind!r}")
1262
+ return errors
1263
+
1264
+
1265
+ def extract_case(
1266
+ case: Path,
1267
+ family: str,
1268
+ variant: str,
1269
+ metrics: list[str],
1270
+ *,
1271
+ conditional_metrics: list[str] | None = None,
1272
+ ) -> dict[str, Any]:
1273
+ values: dict[str, Any] = {}
1274
+ evidence: dict[str, list[str]] = {}
1275
+ methods: dict[str, str] = {}
1276
+ spalding, spalding_evidence = spalding_metrics(case) if family == "yPlusVerification" else ({}, [])
1277
+ branchwise_spalding, branchwise_spalding_evidence = branchwise_spalding_metrics(case) if family == "yPlusVerification" else (None, [])
1278
+ bubbles, bubble_evidence, bubble_errors = bubble_metrics(case, family) if family in {"risingBubble", "compressibleBubbleCollapse"} else ({}, [], [])
1279
+ stirrer_power, stirrer_evidence = stirrer_power_history(case) if family == "MRF_stirredReactor" else (None, [])
1280
+ riemann_profiles, riemann_evidence = named_sample_profiles(case, ("horizontal.xy", "vertical.xy")) if family == "riemann2D" else (None, [])
1281
+ if family == "riemann2D" and riemann_profiles is None:
1282
+ riemann_profiles, riemann_evidence = result_profile_tables(case, ("centreline", "centerline", "p_x", "p_y", "rho_x", "rho_y"))
1283
+ if riemann_profiles is not None:
1284
+ riemann_profiles = final_riemann_profiles(riemann_profiles)
1285
+ riemann_events = profile_event_locations(riemann_profiles) if riemann_profiles is not None else None
1286
+ nozzle_profiles, nozzle_evidence = named_profiles_containing(case, ("centerline",), ("p",)) if family == "nozzleCDV" else (None, [])
1287
+ crossjet_profiles, crossjet_evidence = named_profiles_containing(case, ("trajectory", "centerline", "section"), ()) if family == "supersonicCrossJet" else (None, [])
1288
+ mass_flow, mass_flow_evidence = explicit_mass_flow_history(case) if family in {"ERCOFTA_pump", "nozzleCDV"} else (None, [])
1289
+ patch_pressure, patch_pressure_evidence = explicit_patch_pressure(case) if family == "ERCOFTA_pump" else (None, [])
1290
+ retained_values, retained_evidence, retained_errors = {}, {}, []
1291
+ if family == "ERCOFTA_pump":
1292
+ retained_values, retained_evidence, retained_errors = pump_measurements(case)
1293
+ crossjet_flux_ratio, crossjet_flux_evidence = crossjet_inlet_mass_flux_ratio(case) if family == "supersonicCrossJet" else (None, [])
1294
+ phase_volume, phase_volume_evidence = phase_volume_history(case) if family == "MRF_stirredReactor" else (None, [])
1295
+ average_speed, average_speed_evidence = volume_average_speed_history(case) if family == "MRF_stirredReactor" else (None, [])
1296
+ speed_rms, speed_rms_evidence = volume_speed_rms_history(case) if family == "MRF_stirredReactor" else (None, [])
1297
+ speed_final, speed_final_evidence = volume_average_speed_final(case) if family == "MRF_stirredReactor" else (None, [])
1298
+ pressure_span, pressure_span_evidence = crossjet_interior_pressure_span(case) if family == "supersonicCrossJet" else (None, [])
1299
+ conditional_metrics = conditional_metrics or []
1300
+ requested_metrics = list(dict.fromkeys([*metrics, *conditional_metrics]))
1301
+ for metric in requested_metrics:
1302
+ if metric in {"Cd", "Cl", "Cm", "Cd_mean", "Cd_rms", "Cl_mean", "Cl_rms"}:
1303
+ value, refs, method = extract_force_metric(case, metric)
1304
+ elif metric in spalding:
1305
+ value, refs, method = spalding[metric], spalding_evidence, "spalding_named_profile_or_endpoint.v1"
1306
+ elif metric == "branchwise_wall_law_metrics" and branchwise_spalding is not None:
1307
+ value, refs, method = branchwise_spalding, branchwise_spalding_evidence, "branchwise_spalding_metrics.v1"
1308
+ elif metric in bubbles:
1309
+ value, refs, method = bubbles[metric], bubble_evidence, "connected_gas_component_history.v1"
1310
+ elif metric == "stirrer_power_history" and stirrer_power is not None:
1311
+ value, refs, method = stirrer_power, stirrer_evidence, "named_stirrer_power_history.v1"
1312
+ elif metric == "phase_volume_fraction_history" and phase_volume is not None:
1313
+ value, refs, method = phase_volume, phase_volume_evidence, "volume_weighted_phase_fraction.v1"
1314
+ elif metric == "volume_average_speed_history" and average_speed is not None:
1315
+ value, refs, method = average_speed, average_speed_evidence, "volume_weighted_speed.v1"
1316
+ elif metric == "volume_speed_rms_history" and speed_rms is not None:
1317
+ value, refs, method = speed_rms, speed_rms_evidence, "volume_weighted_speed_rms.v1"
1318
+ elif metric == "volume_average_speed_final" and speed_final is not None:
1319
+ value, refs, method = speed_final, speed_final_evidence, "volume_weighted_final_speed.v1"
1320
+ elif metric == "centerline_profiles" and riemann_profiles is not None:
1321
+ value, refs, method = riemann_profiles, riemann_evidence, "named_centerline_profiles.v1"
1322
+ elif metric == "event_locations" and riemann_events is not None:
1323
+ value, refs, method = riemann_events, riemann_evidence, "local_abs_gradient_peaks.v1"
1324
+ elif metric == "centerline_pressure_profile" and nozzle_profiles is not None:
1325
+ value, refs, method = nozzle_profiles, nozzle_evidence, "named_centerline_pressure_profile.v1"
1326
+ elif metric in retained_values:
1327
+ # The retained-field measurement is the canonical path. Agent
1328
+ # emitted tables remain useful evidence, but a one-point table or
1329
+ # a table with a different time grid must not mask a complete
1330
+ # history available in the original fields.
1331
+ value, refs, method = retained_values[metric], retained_evidence[metric], "retained_boundary_field_measurement.v1"
1332
+ elif metric == "mass_flow_rate" and mass_flow is not None:
1333
+ value, refs, method = mass_flow, mass_flow_evidence, "explicit_mass_flux_history.v1"
1334
+ elif metric == "volumetric_flow_rate" and mass_flow is not None:
1335
+ value, refs, method = mass_flow, mass_flow_evidence, "explicit_volumetric_flux_history.v1"
1336
+ elif metric == "pressure_rise" and patch_pressure is not None:
1337
+ value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1"
1338
+ elif metric == "pressure_rise_history" and patch_pressure is not None:
1339
+ value, refs, method = patch_pressure, patch_pressure_evidence, "named_patch_pressure_history.v1"
1340
+ elif metric == "jet_centerline_trajectory" and crossjet_profiles is not None:
1341
+ value, refs, method = crossjet_profiles, crossjet_evidence, "declared_jet_trajectory_profile.v1"
1342
+ elif metric == "jet_to_mainstream_mass_flux_ratio" and crossjet_flux_ratio is not None:
1343
+ value, refs, method = crossjet_flux_ratio, crossjet_flux_evidence, "named_inlet_mass_flux_ratio.v1"
1344
+ elif metric == "interior_pressure_span" and pressure_span is not None:
1345
+ value, refs, method = pressure_span, pressure_span_evidence, "internal_pressure_span_from_p_field.v1"
1346
+ else:
1347
+ value, refs, method = None, [], "not_implemented_without_declared_v3_evidence"
1348
+ if value is not None and (not isinstance(value, float) or math.isfinite(value)):
1349
+ values[metric] = value
1350
+ evidence[metric] = refs
1351
+ methods[metric] = method
1352
+ extraction_errors = list(bubble_errors)
1353
+ if "stirrer_power_history" in metrics and stirrer_power is None:
1354
+ extraction_errors.append("stirrer_power_history: no named stirrer power evidence")
1355
+ missing = sorted(set(metrics) - set(values))
1356
+ principal_values = {name: values[name] for name in metrics if name in values}
1357
+ conditional_values = {name: values[name] for name in conditional_metrics if name in values}
1358
+ validation_errors = [
1359
+ error for name, value in principal_values.items()
1360
+ for error in structured_qoi_errors(name, value)
1361
+ ]
1362
+ diagnostic_qois = {name: value for name, value in bubbles.items() if name not in metrics}
1363
+ if family == "yPlusVerification":
1364
+ for name, value in spalding.items():
1365
+ if name not in metrics:
1366
+ diagnostic_qois[name] = value
1367
+ if branchwise_spalding is not None and "branchwise_wall_law_metrics" not in metrics:
1368
+ diagnostic_qois["branchwise_wall_law_metrics"] = branchwise_spalding
1369
+ if stirrer_power is not None and "stirrer_power_history" not in metrics:
1370
+ diagnostic_qois["stirrer_power_history"] = stirrer_power
1371
+ if phase_volume is not None and "phase_volume_fraction_history" not in metrics:
1372
+ diagnostic_qois["phase_volume_fraction_history"] = phase_volume
1373
+ if nozzle_profiles is not None and "centerline_pressure_profile" not in metrics:
1374
+ diagnostic_qois["centerline_pressure_profile"] = nozzle_profiles
1375
+ if crossjet_profiles is not None and "jet_centerline_trajectory" not in metrics:
1376
+ diagnostic_qois["jet_centerline_trajectory"] = crossjet_profiles
1377
+ complete = not missing and not validation_errors and not extraction_errors
1378
+ resolver = {
1379
+ metric: {
1380
+ "status": "selected" if metric in evidence else "unresolved",
1381
+ "selected_evidence": sorted(set(evidence.get(metric, []))),
1382
+ "method": methods.get(metric),
1383
+ "physical_validation": "metric_extractor_contract.v1",
1384
+ }
1385
+ for metric in requested_metrics
1386
+ }
1387
+ return {
1388
+ "schema_version": "foambench.qoi.candidate",
1389
+ "case_id": f"{family}/{variant}",
1390
+ "family": family,
1391
+ "required_metrics": metrics,
1392
+ "missing_metrics": missing,
1393
+ "qois": principal_values,
1394
+ "conditional_qois": conditional_values,
1395
+ "conditional_status": {
1396
+ name: "available" if name in conditional_values else "not_assessed_missing_evidence"
1397
+ for name in conditional_metrics
1398
+ },
1399
+ "diagnostic_qois": diagnostic_qois,
1400
+ "evidence": evidence,
1401
+ "metric_methods": methods,
1402
+ "evidence_contract": canonical_evidence_manifest(),
1403
+ "resolver_report": resolver,
1404
+ "extraction_errors": extraction_errors,
1405
+ "retained_field_diagnostics": retained_errors,
1406
+ "status": "complete" if complete else "incomplete",
1407
+ "health": {
1408
+ "status": "pass" if complete else "incomplete",
1409
+ "checks": {
1410
+ "principal_qoi_complete": not missing,
1411
+ "structured_qoi_valid": not validation_errors,
1412
+ "principal_extraction_error_free": not extraction_errors,
1413
+ "no_proxy_fallback": True,
1414
+ },
1415
+ "validation_errors": [*validation_errors, *extraction_errors],
1416
+ },
1417
+ }
1418
+
1419
+
1420
+ def metric_anomalies(cases: dict[str, dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
1421
+ grouped: dict[tuple[str, str, str], list[tuple[str, float]]] = {}
1422
+ anomalies: list[dict[str, Any]] = []
1423
+ review: list[dict[str, Any]] = []
1424
+ for case_id, record in cases.items():
1425
+ for metric, value in record.get("qois", {}).items():
1426
+ if isinstance(value, (int, float)):
1427
+ grouped.setdefault((record["family"], str(record.get("branch_id")), metric), []).append((case_id, float(value)))
1428
+ elif isinstance(value, dict) and value.get("kind") == "component_trajectory":
1429
+ expected_components = 2 if case_id == "compressibleBubbleCollapse/10" else 1
1430
+ if len(value.get("series", [])) != expected_components:
1431
+ review.append({
1432
+ "type": "unexpected_component_count",
1433
+ "case_id": case_id,
1434
+ "family": record["family"],
1435
+ "metric": metric,
1436
+ "expected": expected_components,
1437
+ "observed": len(value.get("series", [])),
1438
+ "interpretation": "review physical breakup versus threshold or mesh-induced disconnection",
1439
+ })
1440
+ for series in value.get("series", []):
1441
+ for point in series.get("points", []):
1442
+ sample = point.get("value")
1443
+ if not isinstance(sample, (int, float)) or not math.isfinite(sample):
1444
+ anomalies.append({
1445
+ "type": "invalid_trajectory_point",
1446
+ "case_id": case_id,
1447
+ "family": record["family"],
1448
+ "branch_id": record.get("branch_id"),
1449
+ "metric": metric,
1450
+ "component_id": series.get("component_id"),
1451
+ "time": point.get("time"),
1452
+ "value": sample,
1453
+ "quality_flag": point.get("quality_flag"),
1454
+ })
1455
+ for (family, branch, metric), rows in sorted(grouped.items()):
1456
+ values = [value for _, value in rows]
1457
+ if any(not math.isfinite(value) for value in values):
1458
+ anomalies.append({"type": "nonfinite", "family": family, "branch_id": branch, "metric": metric})
1459
+ continue
1460
+ if values and all(value == 0 for value in values):
1461
+ anomalies.append({"type": "all_zero", "family": family, "branch_id": branch, "metric": metric, "case_count": len(values)})
1462
+ if len(values) >= 2 and max(values) == min(values):
1463
+ anomalies.append({"type": "constant_metric", "family": family, "branch_id": branch, "metric": metric, "value": values[0]})
1464
+ nonzero = [abs(value) for value in values if value != 0]
1465
+ if len(nonzero) >= 2 and max(nonzero) / min(nonzero) > 1e6:
1466
+ review.append({"type": "dynamic_range_gt_1e6", "family": family, "branch_id": branch, "metric": metric, "minimum_abs": min(nonzero), "maximum_abs": max(nonzero), "interpretation": "review against declared variant relation; not automatically invalid"})
1467
+ if len(values) >= 5:
1468
+ median = statistics.median(values)
1469
+ deviations = [abs(value - median) for value in values]
1470
+ mad = statistics.median(deviations)
1471
+ if mad > 0:
1472
+ for case_id, value in rows:
1473
+ score = abs(value - median) / mad
1474
+ if score > 8:
1475
+ review.append({"type": "robust_outlier", "family": family, "branch_id": branch, "metric": metric, "case_id": case_id, "value": value, "median": median, "mad_score": score, "interpretation": "review against declared variant relation; not automatically invalid"})
1476
+ elif any(value != median for value in values):
1477
+ for case_id, value in rows:
1478
+ if value != median:
1479
+ review.append({"type": "robust_outlier", "family": family, "branch_id": branch, "metric": metric, "case_id": case_id, "value": value, "median": median, "mad_score": None, "interpretation": "review against declared variant relation; not automatically invalid"})
1480
+ return anomalies, review
1481
+
1482
+
1483
+ def extract_campaign(run_roots: Path | list[Path], design: dict[str, Any]) -> dict[str, Any]:
1484
+ roots = [run_roots] if isinstance(run_roots, Path) else list(run_roots)
1485
+ cases: dict[str, dict[str, Any]] = {}
1486
+ missing_case_dirs: list[str] = []
1487
+ for family in design.get("families", []):
1488
+ family_name = family["family"]
1489
+ variants = sorted({variant for branch in family.get("branches", []) for variant in branch.get("cases", [])}, key=int)
1490
+ for variant in variants:
1491
+ branch, metrics = required_metrics(family, variant)
1492
+ conditionals = [
1493
+ item["name"] for item in next(
1494
+ item for item in family.get("branches", []) if variant in item.get("cases", [])
1495
+ ).get("conditional_qois", [])
1496
+ ]
1497
+ case_id = f"{family_name}/{variant}"
1498
+ case_dir = None
1499
+ for root in roots:
1500
+ case_dir = locate_case(root, family_name, variant)
1501
+ if case_dir is not None:
1502
+ break
1503
+ if case_dir is None:
1504
+ missing_case_dirs.append(case_id)
1505
+ continue
1506
+ record = extract_case(
1507
+ case_dir, family_name, variant, metrics, conditional_metrics=conditionals
1508
+ )
1509
+ record["branch_id"] = branch
1510
+ record["case_dir"] = str(case_dir)
1511
+ cases[case_id] = record
1512
+ complete = sum(record["status"] == "complete" for record in cases.values())
1513
+ anomalies, review = metric_anomalies(cases)
1514
+ design_findings = [
1515
+ {
1516
+ "type": "reference_configuration_mismatch",
1517
+ "case_id": "compressibleBubbleCollapse/2",
1518
+ "severity": "resolved_by_contract_scope",
1519
+ "finding": "The materialized reference contains a single 50 um sphere. The QoI branch is restricted to that observed single-bubble response and makes no unsupported radius-scaling claim.",
1520
+ "evidence": "compressibleBubbleCollapse__2/full_run_case/system/setFieldsDict",
1521
+ "action": "Retain the materialized_single_bubble_response branch unless separate radius subcases are generated.",
1522
+ },
1523
+ {
1524
+ "type": "axisymmetric_geometry_mismatch",
1525
+ "case_id": "compressibleBubbleCollapse/10",
1526
+ "severity": "resolved_by_contract_scope",
1527
+ "finding": "The off-axis gas region in the 5 degree wedge is evaluated under an explicit axisymmetric connected-region convention, not described as an ordinary second 3D sphere.",
1528
+ "evidence": "compressibleBubbleCollapse__10/full_run_case/system/setFieldsDict and constant/polyMesh/boundary",
1529
+ "action": "Retain the axisymmetric_ring_interaction branch unless a genuinely 3D two-bubble case is materialized.",
1530
+ },
1531
+ {
1532
+ "type": "reference_coverage_gap",
1533
+ "severity": "blocking",
1534
+ "finding": "The 90-case main materialized run has no riemann2D directories. A separate riemann2d_parallel run exists, but it has not yet been merged into the unified reference audit and its diagnostics are not yet mapped to the profile/event contract.",
1535
+ "evidence": "anonymous-reference/extended/riemann2D",
1536
+ "action": "validate and import the ten separate Riemann runs into the unified current audit; do not synthesize profiles",
1537
+ },
1538
+ ]
1539
+ if any(root.name == "materialized" and root.parent.name.startswith("riemann2d_parallel") for root in roots):
1540
+ design_findings[-1]["severity"] = "resolved_for_current_audit"
1541
+ design_findings[-1]["finding"] = "The separate ten-case Riemann run is included in this audit; profile and feature evidence is now extracted, while reference uncertainty remains a comparison-layer concern."
1542
+ return {
1543
+ "schema_version": "foambench.qoi_extraction_audit.v1",
1544
+ "generated_at": utc_now(),
1545
+ "run_roots": [str(root) for root in roots],
1546
+ "case_count": len(cases),
1547
+ "complete_case_count": complete,
1548
+ "coverage_fraction": complete / len(cases) if cases else 0.0,
1549
+ "missing_case_dirs": missing_case_dirs,
1550
+ "structural_anomalies": anomalies,
1551
+ "review_candidates": review,
1552
+ "design_findings": design_findings,
1553
+ "cases": cases,
1554
+ }
1555
+
1556
+
1557
+ def main() -> int:
1558
+ parser = argparse.ArgumentParser(description=__doc__)
1559
+ parser.add_argument("--run-root", type=Path, action="append", required=True, help="reference run root; repeat to merge independent materialized campaigns")
1560
+ parser.add_argument("--design", type=Path, default=DEFAULT_DESIGN)
1561
+ parser.add_argument("--output", type=Path, required=True)
1562
+ args = parser.parse_args()
1563
+ design = json.loads(args.design.read_text(encoding="utf-8"))
1564
+ roots = [root.resolve(strict=True) for root in args.run_root]
1565
+ report = extract_campaign(roots, design)
1566
+ write_json(args.output.resolve(), report)
1567
+ print(json.dumps({key: report[key] for key in ("case_count", "complete_case_count", "coverage_fraction", "missing_case_dirs", "structural_anomalies", "review_candidates")}, indent=2))
1568
+ return 0
1569
+
1570
+
1571
+ if __name__ == "__main__":
1572
+ raise SystemExit(main())
benchmarks/evaluation/field_candidate.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from .basic_advanced import extract
7
+
8
+
9
+ def extract_field_candidate(
10
+ case_dir: Path,
11
+ case_id: str,
12
+ requested_metrics: list[str],
13
+ *,
14
+ required_metrics: list[str] | None = None,
15
+ log_paths: list[Path] | None = None,
16
+ ) -> dict[str, Any]:
17
+ return extract(
18
+ case_dir,
19
+ case_id,
20
+ requested_metrics,
21
+ required_metrics=required_metrics,
22
+ log_paths=log_paths,
23
+ )
benchmarks/evaluation/field_extractor.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract the numeric signatures used by the FoamBench v13 QoI contracts.
3
+
4
+ The definitions in this module intentionally preserve the extractor that
5
+ produced the checked-in reference JSON files. Candidate runs must use this
6
+ same implementation so reference and candidate values have identical field,
7
+ ordering, and proxy definitions.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import math
14
+ import re
15
+ import sys
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ ROOT = Path(__file__).resolve().parents[2]
21
+ if str(ROOT) not in sys.path:
22
+ sys.path.insert(0, str(ROOT))
23
+
24
+ from benchmarks.evaluation.foam_io import field_path, magnitude, read_text
25
+
26
+
27
+ NUMBER_RE = re.compile(r"[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?")
28
+ VECTOR_RE = re.compile(r"\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)")
29
+ RESIDUAL_RE = re.compile(
30
+ r"Solving for (?P<field>[^,]+), Initial residual = (?P<initial>[-+0-9.eE]+), "
31
+ r"Final residual = (?P<final>[-+0-9.eE]+), No Iterations (?P<iterations>\d+)"
32
+ )
33
+ COURANT_RE = re.compile(r"Courant Number mean:\s*(?P<mean>[-+0-9.eE]+)\s+max:\s*(?P<max>[-+0-9.eE]+)")
34
+ FATAL_RE = re.compile(
35
+ r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))",
36
+ re.I,
37
+ )
38
+
39
+ FAMILY_PROBLEM_TYPES = {
40
+ "BernardCells": "buoyant_thermal_convection",
41
+ "Cavity": "lid_driven_cavity",
42
+ "Cylinder": "cylinder_wake",
43
+ "counterFlowFlame2D": "counterflow_flame",
44
+ "damBreakWithObstacle": "free_surface_vof",
45
+ "forwardStep": "compressible_shock",
46
+ "obliqueShock": "compressible_shock",
47
+ "pitzDaily": "separated_internal_flow",
48
+ "shallowWaterWithSquareBump": "shallow_water_bump",
49
+ "squareBend": "compressible_bend",
50
+ "wedge": "compressible_shock",
51
+ }
52
+ FAMILY_ALIASES = {name.lower(): name for name in FAMILY_PROBLEM_TYPES}
53
+
54
+
55
+ class ExtractionError(RuntimeError):
56
+ """Raised when a field exists but cannot be interpreted safely."""
57
+
58
+
59
+ def utc_now() -> str:
60
+ return datetime.now(timezone.utc).isoformat()
61
+
62
+
63
+ def write_json(path: Path, data: Any) -> None:
64
+ path.parent.mkdir(parents=True, exist_ok=True)
65
+ temporary = path.with_name(path.name + ".tmp")
66
+ temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
67
+ temporary.replace(path)
68
+
69
+
70
+ def strip_comments(text: str) -> str:
71
+ return re.sub(r"//.*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S))
72
+
73
+
74
+ def foam_entry(text: str, key: str) -> str | None:
75
+ match = re.search(rf"^\s*{re.escape(key)}\s+([^;\s]+)\s*;", strip_comments(text), re.M)
76
+ return match.group(1) if match else None
77
+
78
+
79
+ def latest_time_dir(case_dir: Path) -> tuple[float | None, Path | None]:
80
+ choices: list[tuple[float, Path]] = []
81
+ if not case_dir.is_dir():
82
+ return None, None
83
+ for child in case_dir.iterdir():
84
+ if not child.is_dir():
85
+ continue
86
+ try:
87
+ choices.append((float(child.name), child))
88
+ except ValueError:
89
+ continue
90
+ return max(choices, key=lambda item: item[0]) if choices else (None, None)
91
+
92
+
93
+ def clean_internal_field_text(text: str) -> str:
94
+ marker = text.find("internalField")
95
+ if marker < 0:
96
+ return ""
97
+ text = text[marker:]
98
+ boundary = text.find("boundaryField")
99
+ return text[:boundary] if boundary >= 0 else text
100
+
101
+
102
+ def ensure_ascii_field(path: Path, text: str) -> None:
103
+ header = text[: min(len(text), 4096)]
104
+ if re.search(r"\bformat\s+binary\s*;", header):
105
+ raise ExtractionError(
106
+ f"binary OpenFOAM field is not supported directly: {path}; "
107
+ "convert the latest time to ASCII with foamFormatConvert before evaluation"
108
+ )
109
+
110
+
111
+ def parse_scalar_field(path: Path) -> list[float]:
112
+ raw = read_text(path)
113
+ ensure_ascii_field(path, raw)
114
+ text = clean_internal_field_text(raw)
115
+ if not text:
116
+ return []
117
+ uniform = re.search(r"internalField\s+uniform\s+([-+0-9.eE]+)", text)
118
+ if uniform:
119
+ return [float(uniform.group(1))]
120
+ start, end = text.find("("), text.rfind(")")
121
+ body = text[start + 1 : end] if start >= 0 and end > start else text
122
+ return [float(token) for token in NUMBER_RE.findall(body)]
123
+
124
+
125
+ def parse_vector_field(path: Path) -> list[tuple[float, float, float]]:
126
+ raw = read_text(path)
127
+ ensure_ascii_field(path, raw)
128
+ text = clean_internal_field_text(raw)
129
+ if not text:
130
+ return []
131
+ uniform = re.search(
132
+ r"internalField\s+uniform\s+\(([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\)", text
133
+ )
134
+ if uniform:
135
+ return [(float(uniform.group(1)), float(uniform.group(2)), float(uniform.group(3)))]
136
+ return [(float(m.group(1)), float(m.group(2)), float(m.group(3))) for m in VECTOR_RE.finditer(text)]
137
+
138
+
139
+ def scalar(latest: Path | None, name: str) -> list[float]:
140
+ path = field_path(latest, name)
141
+ return parse_scalar_field(path) if path else []
142
+
143
+
144
+ def vector(latest: Path | None, name: str) -> list[tuple[float, float, float]]:
145
+ path = field_path(latest, name)
146
+ return parse_vector_field(path) if path else []
147
+
148
+
149
+ def finite_values(values: list[float]) -> list[float]:
150
+ return [value for value in values if math.isfinite(value)]
151
+
152
+
153
+ def stats(values: list[float]) -> dict[str, float]:
154
+ values = finite_values(values)
155
+ if not values:
156
+ return {}
157
+ low, high = min(values), max(values)
158
+ return {"min": low, "max": high, "mean": sum(values) / len(values), "range": high - low}
159
+
160
+
161
+ def add_stats(qois: dict[str, float], prefix: str, values: list[float]) -> None:
162
+ qois.update({f"{prefix}_{suffix}": value for suffix, value in stats(values).items()})
163
+
164
+
165
+ def add_common_field_qois(qois: dict[str, float], latest: Path | None) -> None:
166
+ velocities = vector(latest, "U")
167
+ if velocities:
168
+ add_stats(qois, "velocity_magnitude", magnitude(velocities))
169
+ x, y, z = velocities[len(velocities) // 2]
170
+ qois.update({"center_u": x, "center_v": y, "center_w": z, "center_speed": math.sqrt(x*x + y*y + z*z)})
171
+ for name in ("p", "p_rgh", "T", "rho", "nut", "k", "epsilon", "omega", "nuTilda"):
172
+ values = scalar(latest, name)
173
+ if values:
174
+ add_stats(qois, name.replace(".", "_"), values)
175
+ vorticity = vector(latest, "vorticity")
176
+ if vorticity:
177
+ add_stats(qois, "vorticity_magnitude", magnitude(vorticity))
178
+
179
+
180
+ def add_compressible_qois(qois: dict[str, float], latest: Path | None) -> None:
181
+ temperatures = scalar(latest, "T")
182
+ speeds = magnitude(vector(latest, "U"))
183
+ if temperatures and speeds:
184
+ mach = [
185
+ speed / math.sqrt(1.4 * 0.7143 * temperature)
186
+ for speed, temperature in zip(speeds, temperatures)
187
+ if temperature > 0
188
+ ]
189
+ add_stats(qois, "mach", mach)
190
+ pressures = scalar(latest, "p")
191
+ if pressures:
192
+ summary = stats(pressures)
193
+ mean, low, high = summary.get("mean"), summary.get("min"), summary.get("max")
194
+ if mean is not None and low is not None and high is not None and abs(mean) > 1e-12:
195
+ qois["pressure_ratio_max_over_mean"] = high / mean
196
+ qois["pressure_ratio_max_over_min"] = high / max(abs(low), 1e-12)
197
+ if len(pressures) > 1:
198
+ qois["shock_strength_proxy_max_dp_index"] = max(abs(b - a) for a, b in zip(pressures, pressures[1:]))
199
+
200
+
201
+ def add_flame_qois(qois: dict[str, float], latest: Path | None) -> None:
202
+ qdot = scalar(latest, "Qdot")
203
+ if qdot:
204
+ add_stats(qois, "Qdot", qdot)
205
+ qois["integrated_Qdot_proxy"] = sum(finite_values(qdot))
206
+ for species in ("CH4", "O2", "CO2", "H2O", "N2", "Ydefault"):
207
+ values = scalar(latest, species)
208
+ if values:
209
+ add_stats(qois, species, values)
210
+
211
+
212
+ def add_vof_qois(qois: dict[str, float], latest: Path | None) -> None:
213
+ alpha = scalar(latest, "alpha.water")
214
+ if not alpha:
215
+ return
216
+ clipped = [min(1.0, max(0.0, value)) for value in alpha if math.isfinite(value)]
217
+ add_stats(qois, "alpha_water", clipped)
218
+ if clipped:
219
+ qois["alpha_water_volume_proxy"] = sum(clipped)
220
+ qois["alpha_water_wet_fraction"] = sum(value > 0.5 for value in clipped) / len(clipped)
221
+ last_wet = max((index for index, value in enumerate(clipped) if value > 0.5), default=0)
222
+ qois["alpha_water_front_index_fraction"] = last_wet / max(len(clipped) - 1, 1)
223
+
224
+
225
+ def add_shallow_water_qois(qois: dict[str, float], latest: Path | None) -> None:
226
+ heights, total_heights, fluxes = scalar(latest, "h"), scalar(latest, "hTotal"), vector(latest, "hU")
227
+ if heights:
228
+ add_stats(qois, "h", heights)
229
+ if total_heights:
230
+ add_stats(qois, "hTotal", total_heights)
231
+ velocities: list[float] = []
232
+ froude: list[float] = []
233
+ for height, flux in zip(heights, fluxes):
234
+ if abs(height) <= 1e-12:
235
+ continue
236
+ speed = math.sqrt(sum(component * component for component in flux)) / abs(height)
237
+ velocities.append(speed)
238
+ if height > 0:
239
+ froude.append(speed / math.sqrt(9.81 * height))
240
+ add_stats(qois, "shallow_velocity", velocities)
241
+ add_stats(qois, "froude", froude)
242
+
243
+
244
+ def infer_family(case_id: str) -> str:
245
+ first = case_id.split("/", 1)[0]
246
+ return FAMILY_ALIASES.get(first.lower(), first)
247
+
248
+
249
+ def infer_problem_type(family: str, latest: Path | None) -> str:
250
+ if family in FAMILY_PROBLEM_TYPES:
251
+ return FAMILY_PROBLEM_TYPES[family]
252
+ names = {path.name.removesuffix(".gz") for path in latest.iterdir() if path.is_file()} if latest else set()
253
+ if "alpha.water" in names:
254
+ return "free_surface_vof"
255
+ if {"h", "hU"} & names:
256
+ return "shallow_water_bump"
257
+ if "Qdot" in names or {"CH4", "O2"} & names:
258
+ return "counterflow_flame"
259
+ if {"p", "T", "U"} <= names:
260
+ return "compressible_flow"
261
+ return "generic_cfd"
262
+
263
+
264
+ def parse_log_metrics(case_dir: Path, log_paths: list[Path] | None = None) -> tuple[dict[str, float], list[str]]:
265
+ """Extract residual/Courant metrics from case logs and optional run logs.
266
+
267
+ FoamAgent writes solver output into ``case/log.*``. EasyFoam keeps the
268
+ same output under ``workspace/runs/formal-*/`` and records the paths in
269
+ ``run_record.json``. ``log_paths`` lets an offline evaluator consume that
270
+ evidence without copying or modifying the generated case.
271
+ """
272
+ candidates = sorted(
273
+ {path for pattern in ("log.foamRun*", "log.*") for path in case_dir.glob(pattern) if path.is_file()},
274
+ key=lambda path: (path.name != "log.foamRun", path.name),
275
+ )
276
+ if log_paths:
277
+ candidates.extend(path for path in log_paths if path.is_file() and path not in candidates)
278
+ texts = [(path, read_text(path)) for path in candidates]
279
+ residuals: list[float] = []
280
+ courants: list[float] = []
281
+ fatal_logs: list[str] = []
282
+ for path, text in texts:
283
+ if FATAL_RE.search(text):
284
+ fatal_logs.append(path.name)
285
+ residuals.extend(float(match.group("final")) for match in RESIDUAL_RE.finditer(text))
286
+ courants.extend(float(match.group("max")) for match in COURANT_RE.finditer(text))
287
+ qois: dict[str, float] = {}
288
+ if residuals:
289
+ qois.update({"max_final_residual": max(residuals), "last_final_residual": residuals[-1]})
290
+ if courants:
291
+ qois.update({"max_courant": max(courants), "last_courant": courants[-1]})
292
+ return qois, fatal_logs
293
+
294
+
295
+ def required_metrics(reference_path: Path | None, case_id: str) -> tuple[list[str] | None, dict[str, Any] | None]:
296
+ if reference_path is None:
297
+ return None, None
298
+ data = json.loads(reference_path.read_text(encoding="utf-8"))
299
+ cases = data.get("cases") if isinstance(data, dict) else None
300
+ if not isinstance(cases, dict) or not isinstance(cases.get(case_id), dict):
301
+ raise ValueError(f"case {case_id!r} is absent from reference contract {reference_path}")
302
+ record = cases[case_id]
303
+ qois = record.get("qois")
304
+ if not isinstance(qois, dict):
305
+ raise ValueError(f"case {case_id!r} has no qois object in {reference_path}")
306
+ return sorted(qois), record
307
+
308
+
309
+ def extract_case_qois(
310
+ case_dir: Path,
311
+ case_id: str,
312
+ reference_path: Path | None = None,
313
+ log_paths: list[Path] | None = None,
314
+ ) -> dict[str, Any]:
315
+ case_dir = case_dir.resolve(strict=True)
316
+ latest_time, latest = latest_time_dir(case_dir)
317
+ family = infer_family(case_id)
318
+ problem_type = infer_problem_type(family, latest)
319
+ required, reference = required_metrics(reference_path, case_id)
320
+ if reference and isinstance(reference.get("problem_type"), str):
321
+ problem_type = reference["problem_type"]
322
+
323
+ qois, fatal_logs = parse_log_metrics(case_dir, log_paths=log_paths)
324
+ add_common_field_qois(qois, latest)
325
+ if problem_type in {"compressible_shock", "compressible_flow", "compressible_bend"}:
326
+ add_compressible_qois(qois, latest)
327
+ if problem_type == "counterflow_flame":
328
+ add_flame_qois(qois, latest)
329
+ if problem_type == "free_surface_vof":
330
+ add_vof_qois(qois, latest)
331
+ if problem_type == "shallow_water_bump":
332
+ add_shallow_water_qois(qois, latest)
333
+ qois = {name: value for name, value in sorted(qois.items()) if math.isfinite(float(value))}
334
+ missing = sorted(set(required or []) - set(qois))
335
+ unexpected = sorted(set(qois) - set(required or [])) if required is not None else []
336
+ control = read_text(case_dir / "system" / "controlDict")
337
+ return {
338
+ "schema_version": "foambench.qoi.candidate.v1",
339
+ "generated_at": utc_now(),
340
+ "producer": "benchmarks/evaluation/qoi_reference.py",
341
+ "case_id": case_id,
342
+ "family": family,
343
+ "problem_type": problem_type,
344
+ "application": foam_entry(control, "application"),
345
+ "solver": foam_entry(control, "solver"),
346
+ "latest_time": latest_time,
347
+ "qois": qois,
348
+ "coverage": {
349
+ "required_count": len(required) if required is not None else None,
350
+ "extracted_required_count": len(required) - len(missing) if required is not None else None,
351
+ "fraction": (len(required) - len(missing)) / len(required) if required else None,
352
+ "missing_metrics": missing,
353
+ "unexpected_metrics": unexpected,
354
+ },
355
+ "fatal_logs": fatal_logs,
356
+ "status": "complete" if latest and not missing and not fatal_logs else "incomplete",
357
+ }
358
+
359
+
360
+ def find_case_dirs(root: Path) -> list[Path]:
361
+ return sorted({control.parents[1] for control in root.rglob("system/controlDict")})
362
+
363
+
364
+ def infer_case_id(case_dir: Path, root: Path) -> str:
365
+ relative = case_dir.resolve().relative_to(root.resolve())
366
+ parts = list(relative.parts)
367
+ if parts and parts[-1] in {"case", "workspace"}:
368
+ parts.pop()
369
+ if len(parts) >= 2 and parts[-1].startswith("replicate_"):
370
+ parts.pop()
371
+ return "/".join(parts[-2:]) if len(parts) >= 2 else (parts[0] if parts else case_dir.name)
372
+
373
+
374
+ def main() -> int:
375
+ parser = argparse.ArgumentParser(description=__doc__)
376
+ parser.add_argument("--case", type=Path, action="append", default=[])
377
+ parser.add_argument("--case-id", action="append", default=[])
378
+ parser.add_argument("--root", type=Path)
379
+ parser.add_argument("--reference-qois", type=Path)
380
+ parser.add_argument("--output", type=Path)
381
+ parser.add_argument("--require-complete", action="store_true")
382
+ parser.add_argument("--json", action="store_true")
383
+ args = parser.parse_args()
384
+
385
+ explicit_cases = [path.resolve(strict=True) for path in args.case]
386
+ if args.case_id and len(args.case_id) != len(explicit_cases):
387
+ parser.error("--case-id count must match --case count")
388
+ selected = [(path, args.case_id[index]) for index, path in enumerate(explicit_cases)]
389
+ if args.root:
390
+ root = args.root.resolve(strict=True)
391
+ selected.extend((path, infer_case_id(path, root)) for path in find_case_dirs(root) if path not in explicit_cases)
392
+ if not selected:
393
+ parser.error("provide --case or --root")
394
+
395
+ records: dict[str, Any] = {}
396
+ for case_dir, case_id in selected:
397
+ records[case_id] = extract_case_qois(case_dir, case_id, args.reference_qois)
398
+ incomplete = sorted(case_id for case_id, record in records.items() if record["status"] != "complete")
399
+ report = {
400
+ "schema_version": "foambench.qoi.candidates.v1",
401
+ "generated_at": utc_now(),
402
+ "case_count": len(records),
403
+ "complete_count": len(records) - len(incomplete),
404
+ "incomplete_cases": incomplete,
405
+ "cases": records,
406
+ }
407
+ if args.output:
408
+ write_json(args.output.resolve(), report)
409
+ if args.json or not args.output:
410
+ print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
411
+ else:
412
+ print(f"qoi_report: {args.output.resolve()} ({report['complete_count']}/{len(records)} complete)")
413
+ return 1 if args.require_complete and incomplete else 0
414
+
415
+
416
+ if __name__ == "__main__":
417
+ try:
418
+ raise SystemExit(main())
419
+ except (OSError, ValueError, ExtractionError, json.JSONDecodeError) as exc:
420
+ print(f"extract_foambench_qois.py: error: {exc}", file=sys.stderr)
421
+ raise SystemExit(2)
benchmarks/evaluation/foam.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from pathlib import Path
5
+
6
+ from .foam_io import read_text
7
+
8
+ NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
9
+ TIME_RE = re.compile(rf"(?m)^\s*Time\s*=\s*({NUMBER})\s*s?\s*$")
10
+ FATAL_RE = re.compile(
11
+ r"FOAM FATAL (?:ERROR|IO ERROR)|(?m:^\s*(?:Floating point exception|Segmentation fault)(?:\s|$))",
12
+ re.I,
13
+ )
14
+ NONFINITE_RE = re.compile(r"(?<![A-Za-z])[-+]?(?:nan|inf(?:inity)?)(?![A-Za-z])", re.I)
15
+
16
+
17
+ def final_time_dirs(case_dir: Path | None) -> tuple[float | None, list[Path], str]:
18
+ if case_dir is None or not case_dir.is_dir():
19
+ return None, [], "missing"
20
+ values: list[tuple[float, Path]] = []
21
+ for path in case_dir.iterdir():
22
+ if not path.is_dir():
23
+ continue
24
+ try:
25
+ value = float(path.name)
26
+ except ValueError:
27
+ continue
28
+ if value > 0:
29
+ values.append((value, path))
30
+ if values:
31
+ latest = max(value for value, _ in values)
32
+ return latest, [path for value, path in values if value == latest], "reconstructed"
33
+ processors = sorted(
34
+ (path for path in case_dir.iterdir() if path.is_dir() and re.fullmatch(r"processor\d+", path.name)),
35
+ key=lambda path: int(path.name[9:]),
36
+ )
37
+ processor_times = []
38
+ for processor in processors:
39
+ found = []
40
+ for path in processor.iterdir():
41
+ if not path.is_dir():
42
+ continue
43
+ try:
44
+ value = float(path.name)
45
+ except ValueError:
46
+ continue
47
+ if value > 0:
48
+ found.append((value, path))
49
+ processor_times.append(sorted(found))
50
+ if processors and all(processor_times):
51
+ common = set(value for value, _ in processor_times[0])
52
+ for values in processor_times[1:]:
53
+ common.intersection_update(value for value, _ in values)
54
+ if not common:
55
+ return None, [], "missing"
56
+ latest = max(common)
57
+ selected = [
58
+ next(path for value, path in values if value == latest)
59
+ for values in processor_times
60
+ ]
61
+ return latest, selected, "decomposed"
62
+ return None, [], "missing"
63
+
64
+
65
+ def latest_time_dir(case_dir: Path | None) -> tuple[float | None, Path | None]:
66
+ latest, directories, _ = final_time_dirs(case_dir)
67
+ return latest, directories[0] if directories else None
68
+
69
+
70
+ def read_logs(paths: tuple[Path, ...] | list[Path]) -> str:
71
+ return "\n".join(read_text(path) for path in paths if path.is_file())
72
+
73
+
74
+ def normal_end(log_text: str) -> bool:
75
+ return re.search(r"(?m)^\s*End\s*$", log_text) is not None
76
+
77
+
78
+ def converged_early(log_text: str) -> bool:
79
+ return re.search(r"solution converged|convergence criterion satisfied", log_text, re.I) is not None
80
+
81
+
82
+ def final_log_time(log_text: str) -> float | None:
83
+ values = [float(match.group(1)) for match in TIME_RE.finditer(log_text)]
84
+ return values[-1] if values else None
benchmarks/evaluation/foam_arrays.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Read complete OpenFOAM primitive arrays for v3 scientific QoIs."""
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import re
7
+ import struct
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+
12
+ NUMBER = rb"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?"
13
+
14
+
15
+ class FoamArrayError(RuntimeError):
16
+ """Raised when a primitive array cannot be decoded unambiguously."""
17
+
18
+
19
+ def _bytes(path: Path) -> bytes:
20
+ return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
21
+
22
+
23
+ def _header(data: bytes) -> bytes:
24
+ end = data.find(b"// * * *")
25
+ return data[: end if end >= 0 else min(len(data), 4096)]
26
+
27
+
28
+ def _format(data: bytes) -> Literal["ascii", "binary"]:
29
+ match = re.search(rb"\bformat\s+(ascii|binary)\s*;", _header(data))
30
+ if not match:
31
+ raise FoamArrayError("OpenFOAM header has no format entry")
32
+ return match.group(1).decode("ascii") # type: ignore[return-value]
33
+
34
+
35
+ def _arch(data: bytes) -> tuple[str, int, int]:
36
+ match = re.search(rb'\barch\s+"([^\"]+)"\s*;', _header(data))
37
+ arch = match.group(1).decode("ascii") if match else "LSB;label=32;scalar=64"
38
+ endian = ">" if arch.startswith("MSB") else "<"
39
+ label = int(re.search(r"label=(32|64)", arch).group(1)) if "label=" in arch else 32
40
+ scalar = int(re.search(r"scalar=(32|64)", arch).group(1)) if "scalar=" in arch else 64
41
+ return endian, label, scalar
42
+
43
+
44
+ def _list_payload(data: bytes, marker: bytes | None = None) -> tuple[int, bytes]:
45
+ if marker is None:
46
+ header_end = data.find(b"// * * *")
47
+ search = data[header_end if header_end >= 0 else 0 :]
48
+ match = re.search(rb"\b(\d+)\s*\(", search)
49
+ offset = (header_end if header_end >= 0 else 0) + (match.end() if match else 0)
50
+ else:
51
+ match = re.search(marker + rb"\s+(\d+)\s*\(", data)
52
+ offset = match.end() if match else 0
53
+ if not match:
54
+ raise FoamArrayError("OpenFOAM nonuniform list header was not found")
55
+ while offset < len(data) and data[offset : offset + 1] in (b"\n", b"\r"):
56
+ offset += 1
57
+ return int(match.group(1)), data[offset:]
58
+
59
+
60
+ def _ascii_body(payload: bytes) -> bytes:
61
+ end = payload.rfind(b")")
62
+ return payload[:end] if end >= 0 else payload
63
+
64
+
65
+ def read_scalar_field(path: Path) -> list[float]:
66
+ data = _bytes(path)
67
+ uniform = re.search(rb"internalField\s+uniform\s+(" + NUMBER + rb")", data)
68
+ if uniform:
69
+ return [float(uniform.group(1))]
70
+ count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List<scalar>")
71
+ if _format(data) == "ascii":
72
+ values = [float(token) for token in re.findall(NUMBER, _ascii_body(payload))[:count]]
73
+ else:
74
+ endian, _, scalar_bits = _arch(data)
75
+ code = "f" if scalar_bits == 32 else "d"
76
+ size = scalar_bits // 8
77
+ values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size]))
78
+ if len(values) != count:
79
+ raise FoamArrayError(f"{path}: declared {count} scalars but decoded {len(values)}")
80
+ return values
81
+
82
+
83
+ def read_vector_field(path: Path) -> list[tuple[float, float, float]]:
84
+ data = _bytes(path)
85
+ count, payload = _list_payload(data, rb"internalField\s+nonuniform\s+List<vector>")
86
+ return _decode_vectors(path, data, count, payload)
87
+
88
+
89
+ def read_vector_list(path: Path) -> list[tuple[float, float, float]]:
90
+ data = _bytes(path)
91
+ count, payload = _list_payload(data)
92
+ return _decode_vectors(path, data, count, payload)
93
+
94
+
95
+ def _decode_vectors(path: Path, data: bytes, count: int, payload: bytes) -> list[tuple[float, float, float]]:
96
+ if _format(data) == "ascii":
97
+ rows = re.findall(rb"\(\s*(" + NUMBER + rb")\s+(" + NUMBER + rb")\s+(" + NUMBER + rb")\s*\)", _ascii_body(payload))
98
+ values = [(float(x), float(y), float(z)) for x, y, z in rows[:count]]
99
+ else:
100
+ endian, _, scalar_bits = _arch(data)
101
+ code = "f" if scalar_bits == 32 else "d"
102
+ size = scalar_bits // 8
103
+ flat = struct.unpack(f"{endian}{count * 3}{code}", payload[: count * 3 * size])
104
+ values = list(zip(flat[0::3], flat[1::3], flat[2::3]))
105
+ if len(values) != count:
106
+ raise FoamArrayError(f"{path}: declared {count} vectors but decoded {len(values)}")
107
+ return values
108
+
109
+
110
+ def read_label_list(path: Path) -> list[int]:
111
+ data = _bytes(path)
112
+ count, payload = _list_payload(data)
113
+ if _format(data) == "ascii":
114
+ values = [int(token) for token in re.findall(rb"[-+]?\d+", _ascii_body(payload))[:count]]
115
+ else:
116
+ endian, label_bits, _ = _arch(data)
117
+ code = "i" if label_bits == 32 else "q"
118
+ size = label_bits // 8
119
+ values = list(struct.unpack(f"{endian}{count}{code}", payload[: count * size]))
120
+ if len(values) != count:
121
+ raise FoamArrayError(f"{path}: declared {count} labels but decoded {len(values)}")
122
+ return values
123
+
124
+
125
+ def foam_path(directory: Path, name: str) -> Path | None:
126
+ for candidate in (directory / name, directory / f"{name}.gz"):
127
+ if candidate.is_file():
128
+ return candidate
129
+ return None
benchmarks/evaluation/foam_field.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import gzip
4
+ import math
5
+ import mmap
6
+ import re
7
+ import struct
8
+ from pathlib import Path
9
+ from typing import Any, Iterable
10
+
11
+ NUMBER = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?"
12
+ NONFINITE_RE = re.compile(r"(?<![A-Za-z])[-+]?(?:nan|inf(?:inity)?)(?![A-Za-z])", re.I)
13
+ FIELD_CLASS_RE = re.compile(
14
+ r"\bclass\s+(?P<class>(?:vol|surface|point)(?:Scalar|Vector|SphericalTensor|SymmTensor|Tensor)Field)\s*;"
15
+ )
16
+ FORMAT_RE = re.compile(r"\bformat\s+(?P<format>ascii|binary)\s*;")
17
+ OBJECT_RE = re.compile(r"\bobject\s+(?P<object>[^;\s]+)\s*;")
18
+ LIST_RE = re.compile(
19
+ rb"nonuniform\s+(?:List<)?(?P<type>scalar|vector|sphericalTensor|symmTensor|tensor|label)>?"
20
+ rb"\s+(?P<count>\d+)\s*\("
21
+ )
22
+ COMPONENTS = {"scalar": 1, "vector": 3, "sphericalTensor": 1, "symmTensor": 6, "tensor": 9, "label": 1}
23
+
24
+
25
+ def _stats(values: Iterable[float]) -> dict[str, Any]:
26
+ low, high, count, nonfinite = math.inf, -math.inf, 0, 0
27
+ for value in values:
28
+ count += 1
29
+ if math.isfinite(value):
30
+ low, high = min(low, value), max(high, value)
31
+ else:
32
+ nonfinite += 1
33
+ return {
34
+ "count": count,
35
+ "finite": nonfinite == 0,
36
+ "nonfinite_count": nonfinite,
37
+ "min": None if low == math.inf else low,
38
+ "max": None if high == -math.inf else high,
39
+ }
40
+
41
+
42
+ def _binary_list_stats(
43
+ data: bytes | mmap.mmap,
44
+ match: re.Match[bytes],
45
+ width: int,
46
+ byte_order: str,
47
+ ) -> dict[str, Any]:
48
+ kind = match.group("type").decode("ascii")
49
+ count = int(match.group("count"))
50
+ item_count = count * COMPONENTS[kind]
51
+ start, end = match.end(), match.end() + item_count * width
52
+ if end > len(data) or not bytes(data[end : min(len(data), end + 16)]).lstrip().startswith(b")"):
53
+ raise ValueError("binary field list does not match its declaration")
54
+ unpacked = struct.iter_unpack(byte_order + ("d" if width == 8 else "f"), memoryview(data)[start:end])
55
+ result = _stats(item[0] for item in unpacked)
56
+ result.update({"value_type": kind, "element_count": count, "components": COMPONENTS[kind]})
57
+ return result
58
+
59
+
60
+ def _binary_internal_data(
61
+ data: bytes | mmap.mmap,
62
+ header: str,
63
+ ) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
64
+ width_match = re.search(r"scalar=(32|64)", header)
65
+ preferred = int(width_match.group(1)) // 8 if width_match else 8
66
+ byte_order = ">" if "MSB" in header else "<"
67
+ records = []
68
+ for match in LIST_RE.finditer(data):
69
+ for width in (preferred, 4 if preferred == 8 else 8):
70
+ try:
71
+ record = _binary_list_stats(data, match, width, byte_order)
72
+ record["offset"] = match.start()
73
+ records.append(record)
74
+ break
75
+ except ValueError:
76
+ continue
77
+ internal_marker, boundary_marker = data.find(b"internalField"), data.find(b"boundaryField")
78
+ internal = next(
79
+ (record for record in records if record["offset"] > internal_marker and (boundary_marker < 0 or record["offset"] < boundary_marker)),
80
+ None,
81
+ )
82
+ if internal is None and internal_marker >= 0:
83
+ stop = boundary_marker if boundary_marker > internal_marker else min(len(data), internal_marker + 1024)
84
+ section = bytes(data[internal_marker:stop]).decode("ascii", errors="ignore")
85
+ uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section)
86
+ if uniform:
87
+ internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1)))
88
+ return records, internal
89
+
90
+
91
+ def _binary_internal(path: Path, header: str) -> tuple[list[dict[str, Any]], dict[str, Any] | None]:
92
+ if path.suffix == ".gz":
93
+ with gzip.open(path, "rb") as stream:
94
+ return _binary_internal_data(stream.read(), header)
95
+ with path.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data:
96
+ return _binary_internal_data(data, header)
97
+
98
+
99
+ def _ascii_internal(raw: bytes) -> tuple[list[dict[str, Any]], dict[str, Any] | None, bool]:
100
+ text = raw.decode("utf-8", errors="replace")
101
+ marker = text.find("internalField")
102
+ boundary = text.find("boundaryField", marker + 1) if marker >= 0 else -1
103
+ section = text[marker : boundary if boundary >= 0 else len(text)] if marker >= 0 else ""
104
+ uniform = re.search(rf"internalField\s+uniform\s+(\([^;]+\)|{NUMBER})\s*;", section)
105
+ if uniform:
106
+ internal = _stats(float(token) for token in re.findall(NUMBER, uniform.group(1)))
107
+ return [internal], internal, NONFINITE_RE.search(section) is not None
108
+ listed = re.search(
109
+ rf"internalField\s+nonuniform\s+(?:List<)?(?P<type>scalar|vector|sphericalTensor|symmTensor|tensor)>?"
110
+ rf"\s+(?P<count>\d+)\s*\((?P<body>.*?)\)\s*;",
111
+ section,
112
+ re.S,
113
+ )
114
+ if not listed:
115
+ return [], None, NONFINITE_RE.search(section) is not None
116
+ values = [float(token) for token in re.findall(NUMBER, listed.group("body"))]
117
+ internal = _stats(values)
118
+ kind, count = listed.group("type"), int(listed.group("count"))
119
+ internal["count_matches_declaration"] = len(values) == count * COMPONENTS[kind]
120
+ return [internal], internal, NONFINITE_RE.search(section) is not None
121
+
122
+
123
+ def scan_field(path: Path, base: Path | None = None) -> dict[str, Any]:
124
+ base = base or path.parent
125
+ try:
126
+ if path.suffix == ".gz":
127
+ with gzip.open(path, "rb") as stream:
128
+ header_bytes = stream.read(4096)
129
+ else:
130
+ header_bytes = path.read_bytes()[:4096]
131
+ header = header_bytes.decode("ascii", errors="ignore")
132
+ field_class, field_format = FIELD_CLASS_RE.search(header), FORMAT_RE.search(header)
133
+ if not field_class or not field_format:
134
+ return {"status": "skip", "reason": "not_a_supported_field", "parse_ok": False}
135
+ if field_format.group("format") == "binary":
136
+ records, internal = _binary_internal(path, header)
137
+ nonfinite = any(not record["finite"] for record in records)
138
+ else:
139
+ raw = gzip.open(path, "rb").read() if path.suffix == ".gz" else path.read_bytes()
140
+ records, internal, marker = _ascii_internal(raw)
141
+ nonfinite = marker or any(not record["finite"] for record in records)
142
+ parse_ok = internal is not None and all(record.get("count_matches_declaration", True) for record in records)
143
+ object_match = OBJECT_RE.search(header)
144
+ return {
145
+ "path": str(path.relative_to(base)) if path.is_relative_to(base) else str(path),
146
+ "status": "pass" if parse_ok and not nonfinite else "fail",
147
+ "class": field_class.group("class"),
148
+ "format": field_format.group("format"),
149
+ "field": object_match.group("object") if object_match else path.name.removesuffix(".gz"),
150
+ "internal": internal,
151
+ "finite": not nonfinite,
152
+ "parse_ok": parse_ok,
153
+ }
154
+ except (OSError, ValueError, struct.error) as exc:
155
+ return {"status": "fail", "finite": False, "parse_ok": False, "error": str(exc)}
benchmarks/evaluation/foam_io.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small shared OpenFOAM file helpers used by evaluators and CLI extractors."""
2
+ from __future__ import annotations
3
+
4
+ import gzip
5
+ import math
6
+ from pathlib import Path
7
+
8
+
9
+ def read_text(path: Path) -> str:
10
+ try:
11
+ if path.suffix == ".gz":
12
+ with gzip.open(path, "rt", encoding="utf-8", errors="ignore") as stream:
13
+ return stream.read()
14
+ return path.read_text(encoding="utf-8", errors="replace")
15
+ except OSError:
16
+ return ""
17
+
18
+
19
+ def field_path(time_dir: Path | None, name: str) -> Path | None:
20
+ if time_dir is None:
21
+ return None
22
+ for candidate in (time_dir / name, time_dir / f"{name}.gz"):
23
+ if candidate.is_file():
24
+ return candidate
25
+ return None
26
+
27
+
28
+ def magnitude(values: list[tuple[float, float, float]]) -> list[float]:
29
+ return [math.sqrt(x * x + y * y + z * z) for x, y, z in values]
benchmarks/evaluation/frozen_recovery.py ADDED
@@ -0,0 +1,713 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Deterministic QoI recovery for already-finished Extended FoamBench runs.
3
+
4
+ This module deliberately has no solver or OpenFOAM command dependency. It
5
+ reads only the retained case files named by an existing campaign artifact and
6
+ returns a new candidate document in memory. The command-line driver writes
7
+ the audit products to a separate directory; neither the frozen run nor its
8
+ original QoI document is modified.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+ import gzip
14
+ import hashlib
15
+ import json
16
+ import math
17
+ import re
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any, Iterable
21
+
22
+ from .comparison import compare_case
23
+ from .extbench import (
24
+ extract_contract_case,
25
+ evidence_path,
26
+ field_dimensions,
27
+ numeric_time_dirs,
28
+ profile_event_locations,
29
+ read_scalar_field_allow_uniform,
30
+ read_vector_field_allow_uniform,
31
+ structured_qoi_errors,
32
+ )
33
+ from .foam_arrays import foam_path, read_label_list, read_scalar_field, read_vector_list
34
+
35
+
36
+ RECOVERY_VERSION = "foambench.frozen_qoi_recovery.v1"
37
+
38
+
39
+ @dataclass
40
+ class RecoveryEvidence:
41
+ """Values and audit information produced by one recovery branch."""
42
+
43
+ values: dict[str, Any] = field(default_factory=dict)
44
+ evidence: dict[str, list[str]] = field(default_factory=dict)
45
+ methods: dict[str, str] = field(default_factory=dict)
46
+ source_times: list[float] = field(default_factory=list)
47
+ preflight: dict[str, Any] = field(default_factory=dict)
48
+ reasons: list[str] = field(default_factory=list)
49
+
50
+
51
+ def sha256_file(path: Path) -> str:
52
+ digest = hashlib.sha256()
53
+ with path.open("rb") as stream:
54
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
55
+ digest.update(block)
56
+ return digest.hexdigest()
57
+
58
+
59
+ def _raw_bytes(path: Path) -> bytes:
60
+ return gzip.decompress(path.read_bytes()) if path.suffix == ".gz" else path.read_bytes()
61
+
62
+
63
+ def _text(path: Path) -> str:
64
+ return _raw_bytes(path).decode("utf-8", errors="ignore")
65
+
66
+
67
+ def _named_block(text: str, name: str, start: int = 0) -> str | None:
68
+ match = re.search(r"(?m)^\s*" + re.escape(name) + r"\s*\{", text[start:])
69
+ if match is None:
70
+ return None
71
+ left = start + match.end()
72
+ depth, index = 1, left
73
+ while index < len(text) and depth:
74
+ char = text[index]
75
+ if char == "{":
76
+ depth += 1
77
+ elif char == "}":
78
+ depth -= 1
79
+ index += 1
80
+ return text[left : index - 1] if depth == 0 else None
81
+
82
+
83
+ def _boundary_block(case: Path, patch: str) -> str | None:
84
+ path = foam_path(case / "constant/polyMesh", "boundary")
85
+ if path is None:
86
+ return None
87
+ text = _text(path)
88
+ anchor = text.find("object boundary")
89
+ return _named_block(text, patch, max(anchor, 0))
90
+
91
+
92
+ def _boundary_specs(case: Path) -> dict[str, dict[str, Any]]:
93
+ path = foam_path(case / "constant/polyMesh", "boundary")
94
+ if path is None:
95
+ return {}
96
+ text = _text(path)
97
+ anchor = max(text.find("object boundary"), 0)
98
+ result: dict[str, dict[str, Any]] = {}
99
+ names = re.finditer(r"(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\s*\{", text[anchor:])
100
+ for match in names:
101
+ name = match.group(1)
102
+ block = _named_block(text, name, anchor + match.start())
103
+ if block is None:
104
+ continue
105
+ start_match = re.search(r"\bstartFace\s+([0-9]+)\s*;", block)
106
+ count_match = re.search(r"\bnFaces\s+([0-9]+)\s*;", block)
107
+ if start_match and count_match:
108
+ result[name] = {
109
+ "start_face": int(start_match.group(1)),
110
+ "n_faces": int(count_match.group(1)),
111
+ "type": (re.search(r"\btype\s+([^;\s]+)\s*;", block) or [None, ""])[1],
112
+ }
113
+ return result
114
+
115
+
116
+ def _face_list(case: Path) -> list[list[int]]:
117
+ path = foam_path(case / "constant/polyMesh", "faces")
118
+ if path is None:
119
+ return []
120
+ text = _text(path)
121
+ marker = re.search(r"\bobject\s+faces\s*;.*?\n\s*[0-9]+\s*\(\s*\n", text, re.S)
122
+ if marker is None:
123
+ return []
124
+ body = text[marker.end() :]
125
+ return [
126
+ [int(value) for value in match.group(1).split()]
127
+ for match in re.finditer(r"[0-9]+\(\s*([0-9\s]+)\)", body)
128
+ ]
129
+
130
+
131
+ def _polygon_area(points: list[tuple[float, float, float]], indices: list[int]) -> float:
132
+ if len(indices) < 3:
133
+ return 0.0
134
+ origin = points[indices[0]]
135
+ area = 0.0
136
+ for left, right in zip(indices[1:-1], indices[2:]):
137
+ a = tuple(points[left][axis] - origin[axis] for axis in range(3))
138
+ b = tuple(points[right][axis] - origin[axis] for axis in range(3))
139
+ cross = (
140
+ a[1] * b[2] - a[2] * b[1],
141
+ a[2] * b[0] - a[0] * b[2],
142
+ a[0] * b[1] - a[1] * b[0],
143
+ )
144
+ area += 0.5 * math.sqrt(sum(value * value for value in cross))
145
+ return area
146
+
147
+
148
+ def _patch_geometry(case: Path, patch: str) -> tuple[list[float], list[int]]:
149
+ specs = _boundary_specs(case)
150
+ spec = specs.get(patch)
151
+ mesh = case / "constant/polyMesh"
152
+ points_path = foam_path(mesh, "points")
153
+ owner_path = foam_path(mesh, "owner")
154
+ if spec is None or points_path is None or owner_path is None:
155
+ return [], []
156
+ faces = _face_list(case)
157
+ points = read_vector_list(points_path)
158
+ owners = read_label_list(owner_path)
159
+ start, count = spec["start_face"], spec["n_faces"]
160
+ if start + count > len(faces) or start + count > len(owners):
161
+ return [], []
162
+ areas = [_polygon_area(points, faces[index]) for index in range(start, start + count)]
163
+ return areas, owners[start : start + count]
164
+
165
+
166
+ def _scalar_boundary_values(path: Path, patch: str) -> list[float] | None:
167
+ """Read one scalar patch's ``value`` entry without trusting field names."""
168
+ text = _text(path)
169
+ anchor = text.find("boundaryField")
170
+ block = _named_block(text, patch, max(anchor, 0))
171
+ if block is None:
172
+ return None
173
+ uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block)
174
+ if uniform:
175
+ spec = _boundary_specs(path.parents[2] if len(path.parents) > 2 else path.parent)
176
+ count = spec.get(patch, {}).get("n_faces", 1)
177
+ return [float(uniform.group(1))] * int(count or 1)
178
+ listed = re.search(
179
+ r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;",
180
+ block,
181
+ re.S,
182
+ )
183
+ if listed is None:
184
+ return None
185
+ count = int(listed.group(1))
186
+ values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))]
187
+ return values[:count] if len(values) >= count else None
188
+
189
+
190
+ def _field_boundary_scalar(path: Path, patch: str, face_count: int) -> list[float] | None:
191
+ """Boundary scalar reader with an explicit face count from the mesh."""
192
+ text = _text(path)
193
+ anchor = text.find("boundaryField")
194
+ block = _named_block(text, patch, max(anchor, 0))
195
+ if block is None:
196
+ return None
197
+ uniform = re.search(r"\bvalue\s+uniform\s+([-+0-9.eE]+)\s*;", block)
198
+ if uniform:
199
+ return [float(uniform.group(1))] * face_count
200
+ listed = re.search(
201
+ r"\bvalue\s+nonuniform\s+(?:List<)?scalar>?\s+([0-9]+)\s*\((.*?)\)\s*;",
202
+ block,
203
+ re.S,
204
+ )
205
+ if listed is None:
206
+ return None
207
+ count = int(listed.group(1))
208
+ values = [float(item) for item in re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", listed.group(2))]
209
+ return values[:count] if len(values) >= count else None
210
+
211
+
212
+ def _patch_sum_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]:
213
+ specs = _boundary_specs(case)
214
+ face_count = int(specs.get(patch, {}).get("n_faces", 0))
215
+ if face_count <= 0:
216
+ return [], [], [], "patch is absent from boundary contract"
217
+ target_values = sorted({float(value) for value in targets})
218
+ dirs = numeric_time_dirs(case)
219
+ points: list[dict[str, float]] = []
220
+ evidence: list[str] = []
221
+ source_times: list[float] = []
222
+ for target in target_values:
223
+ nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None)
224
+ if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)):
225
+ continue
226
+ actual_time, directory = nearest
227
+ path = foam_path(directory, field)
228
+ if path is None:
229
+ continue
230
+ values = _field_boundary_scalar(path, patch, face_count)
231
+ if not values or any(not math.isfinite(value) for value in values):
232
+ continue
233
+ points.append({"time": actual_time, "value": float(sum(values))})
234
+ evidence.append(evidence_path(case, path))
235
+ source_times.append(actual_time)
236
+ return points, sorted(set(evidence)), sorted(set(source_times)), None
237
+
238
+
239
+ def _patch_average_history(case: Path, field: str, patch: str, targets: Iterable[float]) -> tuple[list[dict[str, float]], list[str], list[float], str | None]:
240
+ areas, owners = _patch_geometry(case, patch)
241
+ if not areas or not owners or sum(areas) <= 0:
242
+ return [], [], [], "patch geometry could not be reconstructed"
243
+ target_values = sorted({float(value) for value in targets})
244
+ dirs = numeric_time_dirs(case)
245
+ points: list[dict[str, float]] = []
246
+ evidence: list[str] = []
247
+ source_times: list[float] = []
248
+ for target in target_values:
249
+ nearest = min(dirs, key=lambda item: abs(item[0] - target), default=None)
250
+ if nearest is None or abs(nearest[0] - target) > 1e-8 * max(1.0, abs(target)):
251
+ continue
252
+ actual_time, directory = nearest
253
+ path = foam_path(directory, field)
254
+ if path is None:
255
+ continue
256
+ try:
257
+ values = read_scalar_field_allow_uniform(path, max(owners) + 1)
258
+ except (OSError, ValueError, RuntimeError):
259
+ continue
260
+ if len(values) <= max(owners):
261
+ continue
262
+ total_area = sum(areas)
263
+ average = sum(area * values[owner] for area, owner in zip(areas, owners)) / total_area
264
+ if not math.isfinite(average):
265
+ continue
266
+ points.append({"time": actual_time, "value": float(average)})
267
+ evidence.append(evidence_path(case, path))
268
+ source_times.append(actual_time)
269
+ return points, sorted(set(evidence)), sorted(set(source_times)), None
270
+
271
+
272
+ def _reference_times(reference: dict[str, Any], metric_names: Iterable[str]) -> list[float]:
273
+ times: set[float] = set()
274
+ for metric in metric_names:
275
+ value = reference.get("qois", {}).get(metric)
276
+ if not isinstance(value, dict):
277
+ continue
278
+ if value.get("kind") == "time_history":
279
+ for point in value.get("points", []):
280
+ if isinstance(point, dict) and isinstance(point.get("time"), (int, float)):
281
+ times.add(float(point["time"]))
282
+ elif value.get("kind") == "branched_time_histories":
283
+ for branch in value.get("branches", {}).values():
284
+ if isinstance(branch, dict):
285
+ for point in branch.get("points", []):
286
+ if isinstance(point, dict) and isinstance(point.get("time"), (int, float)):
287
+ times.add(float(point["time"]))
288
+ return sorted(times)
289
+
290
+
291
+ def _history(quantity: str, points: list[dict[str, float]], dimensions: str | None = None) -> dict[str, Any]:
292
+ value: dict[str, Any] = {"kind": "time_history", "quantity": quantity, "points": sorted(points, key=lambda item: item["time"])}
293
+ if dimensions:
294
+ value["field_dimensions"] = dimensions
295
+ return value
296
+
297
+
298
+ def recover_ercofta(case: Path, reference: dict[str, Any], variant: str) -> RecoveryEvidence:
299
+ result = RecoveryEvidence()
300
+ reference_times = _reference_times(reference, ("mass_flow_rate", "pressure_rise"))
301
+ available_times = [time for time, _ in numeric_time_dirs(case)]
302
+ expected_latest = max(reference_times, default=None)
303
+ observed_latest = max(available_times, default=None)
304
+ result.preflight.update({
305
+ "reference_latest_time": expected_latest,
306
+ "retained_latest_time": observed_latest,
307
+ "time_semantics": "numeric_directory_name_exact_match",
308
+ })
309
+ if variant != "1" and expected_latest is not None and (observed_latest is None or observed_latest < expected_latest - 1e-10 * max(1.0, expected_latest)):
310
+ result.reasons.append(
311
+ f"retained result ends at {observed_latest!r}, before reference time {expected_latest!r}; no time rescaling is permitted"
312
+ )
313
+ result.preflight["status"] = "fail"
314
+ return result
315
+ mass_points, mass_refs, mass_times, mass_error = _patch_sum_history(case, "phi", "inlet", reference_times)
316
+ pressure_points_in, pressure_refs_in, pressure_times_in, pressure_error_in = _patch_average_history(case, "p", "inlet", reference_times)
317
+ pressure_points_out, pressure_refs_out, pressure_times_out, pressure_error_out = _patch_average_history(case, "p", "outlet", reference_times)
318
+ result.preflight.update({
319
+ "status": "pass" if mass_points or pressure_points_in else "fail",
320
+ "mass_point_count": len(mass_points),
321
+ "pressure_inlet_point_count": len(pressure_points_in),
322
+ "pressure_outlet_point_count": len(pressure_points_out),
323
+ })
324
+ if mass_points:
325
+ result.values["mass_flow_rate"] = _history("explicit_mass_flow", mass_points, field_dimensions(case, "phi"))
326
+ result.evidence["mass_flow_rate"] = mass_refs
327
+ result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1"
328
+ result.source_times.extend(mass_times)
329
+ if pressure_points_in and pressure_points_out:
330
+ inlet = {round(point["time"], 12): point["value"] for point in pressure_points_in}
331
+ outlet = {round(point["time"], 12): point["value"] for point in pressure_points_out}
332
+ points = [{"time": time, "value": outlet[time] - inlet[time]} for time in sorted(set(inlet) & set(outlet))]
333
+ if points:
334
+ result.values["pressure_rise"] = {
335
+ "kind": "time_history",
336
+ "quantity": "pressure_rise",
337
+ "definition": "outlet_minus_inlet_patch_owner_cell_area_average",
338
+ "source_patches": {"inlet": "inlet", "outlet": "outlet"},
339
+ "points": points,
340
+ }
341
+ result.evidence["pressure_rise"] = sorted(set(pressure_refs_in + pressure_refs_out))
342
+ result.methods["pressure_rise"] = "retained_p_owner_cell_patch_area_average.v1"
343
+ result.source_times.extend(pressure_times_in + pressure_times_out)
344
+ for error in (mass_error, pressure_error_in, pressure_error_out):
345
+ if error:
346
+ result.reasons.append(error)
347
+ if expected_latest is not None and not mass_points and not pressure_points_in:
348
+ result.reasons.append(
349
+ "no retained time directory matches the reference time grid; time units or scale are not inferred"
350
+ )
351
+ result.source_times = sorted(set(result.source_times))
352
+ return result
353
+
354
+
355
+ def _case_branch_dirs(case: Path) -> dict[str, Path]:
356
+ parent = case.parent
357
+ result = {"pBack_101325": case}
358
+ for path in parent.glob("case_pBack_*"):
359
+ match = re.fullmatch(r"case_pBack_([0-9]+)", path.name)
360
+ if match and path.is_dir():
361
+ result[f"pBack_{match.group(1)}"] = path
362
+ return result
363
+
364
+
365
+ def recover_nozzle(case: Path, reference: dict[str, Any], adapter: str, variant: str) -> RecoveryEvidence:
366
+ result = RecoveryEvidence()
367
+ reference_value = reference.get("qois", {}).get("mass_flow_rate", {})
368
+ if variant == "4" and adapter == "easyfoam" and reference_value.get("kind") == "branched_time_histories":
369
+ branches: dict[str, Any] = {}
370
+ evidence: list[str] = []
371
+ sources: dict[str, float] = {}
372
+ for branch, history in reference_value.get("branches", {}).items():
373
+ branch_case = _case_branch_dirs(case).get(branch)
374
+ points = history.get("points", []) if isinstance(history, dict) else []
375
+ target = [point.get("time") for point in points if isinstance(point, dict) and isinstance(point.get("time"), (int, float))]
376
+ if branch_case is None or not target:
377
+ result.reasons.append(f"missing retained branch directory or target time for {branch}")
378
+ continue
379
+ branch_points, refs, times, error = _patch_sum_history(branch_case, "phi", "inlet", target)
380
+ if branch_points:
381
+ branches[branch] = _history("explicit_mass_flow", branch_points, field_dimensions(branch_case, "phi"))
382
+ # ``evidence_path`` is relative to each branch case. Add the
383
+ # sibling directory explicitly so three otherwise identical
384
+ # ``0.005/phi`` paths cannot be confused in the manifest.
385
+ if branch_case != case:
386
+ evidence.extend(f"../{branch_case.name}/{ref}" for ref in refs)
387
+ else:
388
+ evidence.extend(refs)
389
+ if times:
390
+ sources[branch] = max(times)
391
+ elif error:
392
+ result.reasons.append(f"{branch}: {error}")
393
+ if branches:
394
+ result.values["mass_flow_rate"] = {
395
+ "kind": "branched_time_histories",
396
+ "quantity": "explicit_mass_flow",
397
+ "field_dimensions": field_dimensions(case, "phi"),
398
+ "branches": branches,
399
+ }
400
+ result.evidence["mass_flow_rate"] = sorted(set(evidence))
401
+ result.methods["mass_flow_rate"] = "retained_branch_phi_boundary_sum.v1"
402
+ result.preflight.update({"status": "pass", "branches": sorted(branches), "source_times": sources})
403
+ result.source_times.extend(sources.values())
404
+ else:
405
+ result.preflight["status"] = "fail"
406
+ return result
407
+ if variant == "2" and adapter == "foamagent" and reference_value.get("kind") == "time_history":
408
+ targets = [point.get("time") for point in reference_value.get("points", []) if isinstance(point, dict) and isinstance(point.get("time"), (int, float))]
409
+ points, refs, times, error = _patch_sum_history(case, "phi", "inlet", targets)
410
+ if points:
411
+ result.values["mass_flow_rate"] = _history("explicit_mass_flow", points, field_dimensions(case, "phi"))
412
+ result.evidence["mass_flow_rate"] = refs
413
+ result.methods["mass_flow_rate"] = "retained_phi_boundary_sum.v1"
414
+ result.source_times.extend(times)
415
+ result.preflight.update({"status": "pass", "point_count": len(points), "source_times": times})
416
+ else:
417
+ result.preflight["status"] = "fail"
418
+ if error:
419
+ result.reasons.append(error)
420
+ return result
421
+ result.preflight["status"] = "not_applicable"
422
+ return result
423
+
424
+
425
+ def _final_fields(case: Path) -> tuple[float, Path] | None:
426
+ for time, directory in reversed(numeric_time_dirs(case)):
427
+ if all(foam_path(directory, name) is not None for name in ("C", "U", "rho", "p", "T")):
428
+ return time, directory
429
+ return None
430
+
431
+
432
+ def recover_riemann(case: Path) -> RecoveryEvidence:
433
+ result = RecoveryEvidence()
434
+ final = _final_fields(case)
435
+ if final is None:
436
+ result.preflight = {"status": "fail", "reason": "final C/U/rho/p/T fields are not all retained"}
437
+ return result
438
+ time, directory = final
439
+ try:
440
+ centres = read_vector_list(foam_path(directory, "C")) # type: ignore[arg-type]
441
+ velocity = read_vector_field_allow_uniform(foam_path(directory, "U"), len(centres)) # type: ignore[arg-type]
442
+ rho = read_scalar_field_allow_uniform(foam_path(directory, "rho"), len(centres)) # type: ignore[arg-type]
443
+ pressure = read_scalar_field_allow_uniform(foam_path(directory, "p"), len(centres)) # type: ignore[arg-type]
444
+ temperature = read_scalar_field_allow_uniform(foam_path(directory, "T"), len(centres)) # type: ignore[arg-type]
445
+ except (OSError, ValueError, RuntimeError) as exc:
446
+ result.preflight = {"status": "fail", "reason": f"field decoding failed: {exc}"}
447
+ return result
448
+ if not all(len(values) == len(centres) for values in (velocity, rho, pressure, temperature)):
449
+ result.preflight = {"status": "fail", "reason": "final fields have inconsistent cell counts"}
450
+ return result
451
+ x_target = min((point[0] for point in centres), key=lambda value: abs(value))
452
+ y_target = min((point[1] for point in centres), key=lambda value: abs(value))
453
+ horizontal_indices = [index for index, point in enumerate(centres) if abs(point[1] - y_target) <= 1e-10 * max(1.0, abs(y_target))]
454
+ vertical_indices = [index for index, point in enumerate(centres) if abs(point[0] - x_target) <= 1e-10 * max(1.0, abs(x_target))]
455
+ horizontal_indices.sort(key=lambda index: centres[index][0])
456
+ vertical_indices.sort(key=lambda index: centres[index][1])
457
+ columns_h = ["x", "rho", "U_x", "U_y", "U_z", "p", "T"]
458
+ columns_v = ["y", "rho", "U_x", "U_y", "U_z", "p", "T"]
459
+ rows_h = [[centres[i][0], rho[i], *velocity[i], pressure[i], temperature[i]] for i in horizontal_indices]
460
+ rows_v = [[centres[i][1], rho[i], *velocity[i], pressure[i], temperature[i]] for i in vertical_indices]
461
+ if len(rows_h) < 5 or len(rows_v) < 5:
462
+ result.preflight = {"status": "fail", "reason": "centerline preflight retained fewer than five cells", "horizontal_count": len(rows_h), "vertical_count": len(rows_v)}
463
+ return result
464
+ root = evidence_path(case, directory / "C")
465
+ refs = sorted({root, evidence_path(case, directory / "U"), evidence_path(case, directory / "rho"), evidence_path(case, directory / "p"), evidence_path(case, directory / "T")})
466
+ profiles = {
467
+ "kind": "named_profiles",
468
+ "profiles": [
469
+ {"profile_id": f"recovery/{time:g}/horizontal.xy", "columns": columns_h, "rows": rows_h},
470
+ {"profile_id": f"recovery/{time:g}/vertical.xy", "columns": columns_v, "rows": rows_v},
471
+ ],
472
+ }
473
+ result.values["centerline_profiles"] = profiles
474
+ result.values["event_locations"] = profile_event_locations(profiles)
475
+ result.evidence["centerline_profiles"] = refs
476
+ result.evidence["event_locations"] = refs
477
+ result.methods["centerline_profiles"] = "retained_final_cell_centerline_sampling.v1"
478
+ result.methods["event_locations"] = "retained_final_cell_centerline_sampling_gradient_peaks.v1"
479
+ result.source_times = [time]
480
+ result.preflight = {
481
+ "status": "pass",
482
+ "source_time": time,
483
+ "horizontal_cell_count": len(rows_h),
484
+ "vertical_cell_count": len(rows_v),
485
+ "selected_coordinates": {"x": x_target, "y": y_target},
486
+ }
487
+ if result.values["event_locations"] is None:
488
+ result.values.pop("event_locations", None)
489
+ result.evidence.pop("event_locations", None)
490
+ result.methods.pop("event_locations", None)
491
+ result.reasons.append("centerline profiles were available but no local pressure/rho gradient event was detected")
492
+ return result
493
+
494
+
495
+ def _nu_value(case: Path) -> tuple[float | None, str | None]:
496
+ for path in (case / "constant/physicalProperties", case / "constant/transportProperties", case / "constant/thermophysicalProperties"):
497
+ if not path.is_file():
498
+ continue
499
+ match = re.search(r"(?m)^\s*nu\s+(?:\[[^]]+\]\s*)?([-+0-9.eE]+)\s*;", _text(path))
500
+ if match:
501
+ return float(match.group(1)), evidence_path(case, path)
502
+ return None, None
503
+
504
+
505
+ def _vector_boundary_uniform(path: Path, patch: str) -> tuple[float, float, float] | None:
506
+ text = _text(path)
507
+ anchor = text.find("boundaryField")
508
+ block = _named_block(text, patch, max(anchor, 0))
509
+ if block is None:
510
+ return None
511
+ match = re.search(r"\bvalue\s+uniform\s*\(\s*([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s*\)\s*;", block)
512
+ return tuple(float(match.group(index)) for index in range(1, 4)) if match else None
513
+
514
+
515
+ def _first_cell_distance(case: Path) -> tuple[float | None, str | None]:
516
+ candidates = sorted(case.glob("postProcessing/wallLawSets/*/yLine.csv"))
517
+ for path in reversed(candidates):
518
+ rows = []
519
+ try:
520
+ for line in path.read_text(encoding="utf-8", errors="ignore").splitlines()[1:]:
521
+ parts = [float(item) for item in line.split(",")]
522
+ if len(parts) >= 2:
523
+ rows.append(abs(parts[1]))
524
+ except (OSError, ValueError):
525
+ continue
526
+ positive = [value for value in rows if value > 0 and math.isfinite(value)]
527
+ if positive:
528
+ return min(positive), evidence_path(case, path)
529
+ return None, None
530
+
531
+
532
+ def recover_yplus(case: Path) -> RecoveryEvidence:
533
+ result = RecoveryEvidence()
534
+ final = next(((time, directory) for time, directory in reversed(numeric_time_dirs(case)) if foam_path(directory, "wallShearStress")), None)
535
+ nu, nu_ref = _nu_value(case)
536
+ distance, distance_ref = _first_cell_distance(case)
537
+ if final is None or nu is None or distance is None:
538
+ result.preflight = {"status": "fail", "final_wall_shear": bool(final), "nu": nu, "first_cell_distance": distance}
539
+ result.reasons.append("wall shear, kinematic viscosity, or first-cell distance is absent")
540
+ return result
541
+ time, directory = final
542
+ wall_patches = [name for name, spec in _boundary_specs(case).items() if str(spec.get("type")) == "wall"]
543
+ values: list[float] = []
544
+ shear_path = foam_path(directory, "wallShearStress")
545
+ for patch in wall_patches:
546
+ vector = _vector_boundary_uniform(shear_path, patch) if shear_path else None
547
+ if vector is not None:
548
+ values.append(math.sqrt(sum(component * component for component in vector)))
549
+ if not values:
550
+ result.preflight = {"status": "fail", "reason": "wallShearStress has no parseable wall patch value"}
551
+ return result
552
+ tau = statistics_mean(values)
553
+ yplus = math.sqrt(max(tau, 0.0)) * distance / nu
554
+ if not math.isfinite(yplus):
555
+ result.preflight = {"status": "fail", "reason": "derived y+ is non-finite"}
556
+ return result
557
+ refs = [evidence_path(case, shear_path)] if shear_path else []
558
+ refs.extend(item for item in (nu_ref, distance_ref) if item)
559
+ result.values["first_cell_yplus"] = float(yplus)
560
+ result.evidence["first_cell_yplus"] = sorted(set(refs))
561
+ result.methods["first_cell_yplus"] = "retained_wall_shear_first_cell_distance.v1"
562
+ result.source_times = [time]
563
+ result.preflight = {"status": "pass", "source_time": time, "wall_patch_count": len(values), "tau_magnitude": tau, "nu": nu, "first_cell_distance": distance}
564
+ result.reasons.append("derived endpoint is an auditable wall-shear estimate, not a substituted Spalding profile")
565
+ return result
566
+
567
+
568
+ def statistics_mean(values: list[float]) -> float:
569
+ return sum(values) / len(values) if values else math.nan
570
+
571
+
572
+ def _merge_candidate(candidate: dict[str, Any], recovery: RecoveryEvidence) -> dict[str, Any]:
573
+ result = copy.deepcopy(candidate)
574
+ qois = result.setdefault("qois", {})
575
+ evidence = result.setdefault("evidence", {})
576
+ methods = result.setdefault("metric_methods", {})
577
+ resolver = result.setdefault("resolver_report", {})
578
+ for metric, value in recovery.values.items():
579
+ qois[metric] = value
580
+ evidence[metric] = sorted(set(recovery.evidence.get(metric, [])))
581
+ methods[metric] = recovery.methods.get(metric, "frozen_recovery.v1")
582
+ resolver[metric] = {
583
+ "status": "selected",
584
+ "selected_evidence": evidence[metric],
585
+ "method": methods[metric],
586
+ "physical_validation": "metric_extractor_contract.v1",
587
+ }
588
+ required = list(result.get("required_metrics", []))
589
+ missing = sorted(set(required) - set(qois))
590
+ result["missing_metrics"] = missing
591
+ result["status"] = "complete" if not missing and not result.get("extraction_errors") else "incomplete"
592
+ health = result.setdefault("health", {})
593
+ checks = health.setdefault("checks", {})
594
+ checks["principal_qoi_complete"] = not missing
595
+ checks["principal_extraction_error_free"] = not result.get("extraction_errors")
596
+ validation_errors = [
597
+ error for name, value in qois.items() if name in required for error in structured_qoi_errors(name, value)
598
+ ]
599
+ checks["structured_qoi_valid"] = not validation_errors
600
+ health["status"] = "pass" if not missing and not validation_errors and not result.get("extraction_errors") else "incomplete"
601
+ health["validation_errors"] = validation_errors + list(result.get("extraction_errors", []))
602
+ return result
603
+
604
+
605
+ def recover_case(
606
+ case_id: str,
607
+ case: Path,
608
+ reference: dict[str, Any],
609
+ *,
610
+ adapter: str,
611
+ design: dict[str, Any],
612
+ ) -> dict[str, Any]:
613
+ """Re-extract and, where justified, recover one selected incomplete case."""
614
+ original = extract_contract_case(case, case_id, design)
615
+ original_comparison = compare_case(reference, original, 1.0)
616
+ family, variant = case_id.split("/", 1)
617
+ recovery = RecoveryEvidence(preflight={"status": "not_applicable"})
618
+ if family == "ERCOFTA_pump":
619
+ recovery = recover_ercofta(case, reference, variant)
620
+ elif family == "nozzleCDV":
621
+ recovery = recover_nozzle(case, reference, adapter, variant)
622
+ elif family == "riemann2D":
623
+ recovery = recover_riemann(case)
624
+ elif family == "yPlusVerification" and variant == "1" and adapter == "easyfoam":
625
+ recovery = recover_yplus(case)
626
+ elif family == "supersonicCrossJet" and variant == "1":
627
+ recovery.reasons.append("declared interior pressure window contains no valid retained cell; global extrema are not an allowed proxy")
628
+ recovery.preflight = {"status": "fail", "check": "declared_internal_window_nonempty", "observed_cell_count": 0}
629
+ merged = _merge_candidate(original, recovery)
630
+ comparison = compare_case(reference, merged, 1.0)
631
+ if "incomplete" in str(comparison.get("status")):
632
+ recovery_status = "irrecoverable_incomplete"
633
+ elif comparison.get("status") == "out_of_tolerance":
634
+ recovery_status = "recovered_out_of_tolerance"
635
+ elif comparison.get("status") == "pass":
636
+ recovery_status = "recovered_complete"
637
+ else:
638
+ recovery_status = "recovery_evaluation_error"
639
+ return {
640
+ "case_id": case_id,
641
+ "family": family,
642
+ "variant": variant,
643
+ "case_dir": str(case.resolve()),
644
+ "original": {
645
+ "reextract_status": original_comparison.get("status"),
646
+ "reextract_missing_metrics": original_comparison.get("missing_metrics", []),
647
+ "reextract_out_of_tolerance_metrics": original_comparison.get("out_of_tolerance_metrics", []),
648
+ "reextract_candidate_missing_metrics": original.get("missing_metrics", []),
649
+ },
650
+ "recovery": {
651
+ "status": recovery_status,
652
+ "version": RECOVERY_VERSION,
653
+ "methods": recovery.methods,
654
+ "source_evidence": recovery.evidence,
655
+ "source_times": recovery.source_times,
656
+ "preflight": recovery.preflight,
657
+ "reasons": recovery.reasons,
658
+ },
659
+ "candidate": merged,
660
+ "comparison": comparison,
661
+ }
662
+
663
+
664
+ def recovery_score_record(source: dict[str, Any], recovered: dict[str, Any]) -> dict[str, Any]:
665
+ """Build a compact campaign-compatible record without rerunning checks."""
666
+ original = source
667
+ comparison = recovered["comparison"]
668
+ execution = copy.deepcopy(original.get("execution", {}))
669
+ numerical = copy.deepcopy(original.get("numerical", {}))
670
+ execution_pass = execution.get("status") == "pass"
671
+ numerical_pass = numerical.get("status") == "pass" or bool(numerical.get("pass"))
672
+ qoi_pass = bool(comparison.get("physics_grounded_qoi_pass"))
673
+ failure_categories: list[str] = []
674
+ if not execution_pass:
675
+ failure_categories.append("execution_failure")
676
+ elif "incomplete" in str(comparison.get("status", "")):
677
+ failure_categories.append("qoi_incomplete")
678
+ elif comparison.get("status") == "out_of_tolerance":
679
+ failure_categories.append("qoi_out_of_tolerance")
680
+ return {
681
+ "schema_version": "foambench.frozen_case_recovery.v1",
682
+ "case_id": recovered["case_id"],
683
+ "dataset": original.get("dataset", "extended"),
684
+ "family": recovered["family"],
685
+ "variant": recovered["variant"],
686
+ "replicate": original.get("replicate", 1),
687
+ "artifact": {
688
+ "case_dir": recovered["case_dir"],
689
+ "rollout_dir": original.get("artifact", {}).get("rollout_dir"),
690
+ "workspace_dir": original.get("artifact", {}).get("workspace_dir"),
691
+ },
692
+ "execution": execution,
693
+ "numerical": numerical,
694
+ "qoi": {
695
+ "status": "pass" if qoi_pass else comparison.get("status", "evaluation_error"),
696
+ "physics_grounded_qoi_pass": qoi_pass,
697
+ "effective_pass_ratio": float(comparison.get("qoi_pass_ratio", 0.0) or 0.0),
698
+ "candidate": recovered["candidate"],
699
+ "comparison": comparison,
700
+ },
701
+ "scores": {
702
+ "execution_pass": execution_pass,
703
+ "numerical_pass": numerical_pass,
704
+ "physics_grounded_qoi_pass": qoi_pass,
705
+ "end_to_end_pass": execution_pass and numerical_pass and qoi_pass,
706
+ },
707
+ "failure_categories": failure_categories,
708
+ "recovery": recovered["recovery"],
709
+ }
710
+
711
+
712
+ def document_checksum(path: Path) -> dict[str, Any]:
713
+ return {"path": str(path.resolve()), "sha256": sha256_file(path), "size_bytes": path.stat().st_size}