vortfoil 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. vortfoil/__init__.py +61 -0
  2. vortfoil/_release/code/field/cst16_fit.py +56 -0
  3. vortfoil/_release/code/field/f0cm_final_rescore.py +136 -0
  4. vortfoil/_release/code/field/field_holdout_score.py +73 -0
  5. vortfoil/_release/code/field/naca_generator.py +162 -0
  6. vortfoil/_release/code/field/predict_field.py +759 -0
  7. vortfoil/_release/code/field/s_rule_meanside_rescore.py +36 -0
  8. vortfoil/_release/code/field/sdf2d/__init__.py +1 -0
  9. vortfoil/_release/code/field/sdf2d/geometry.py +389 -0
  10. vortfoil/_release/code/field/sdf2d/panel_inviscid.py +216 -0
  11. vortfoil/_release/code/field/state_provider.py +319 -0
  12. vortfoil/_release/code/field/step2_eval_f0c.py +115 -0
  13. vortfoil/_release/code/field/step2_rebuild_corpus_provider.py +136 -0
  14. vortfoil/_release/code/field/step2_store_preds.py +53 -0
  15. vortfoil/_release/code/field/supervised_field/__init__.py +15 -0
  16. vortfoil/_release/code/field/supervised_field/airfrans_p1_labels.py +108 -0
  17. vortfoil/_release/code/field/supervised_field/airfrans_p3_fields_v2.py +458 -0
  18. vortfoil/_release/code/field/supervised_field/field_features.py +561 -0
  19. vortfoil/_release/code/field/supervised_field/field_state_contract.py +348 -0
  20. vortfoil/_release/code/field/supervised_field/nf_eval200.py +269 -0
  21. vortfoil/_release/code/field/supervised_field/nf_eval200_v5.py +399 -0
  22. vortfoil/_release/code/field/supervised_field/nf_eval_shape.py +151 -0
  23. vortfoil/_release/code/field/supervised_field/nf_extract.py +190 -0
  24. vortfoil/_release/code/field/supervised_field/nf_extract_shape.py +106 -0
  25. vortfoil/_release/code/field/supervised_field/nf_hybrid_field.py +366 -0
  26. vortfoil/_release/code/field/supervised_field/nf_train.py +348 -0
  27. vortfoil/_release/code/field/supervised_field/nf_train_shape.py +378 -0
  28. vortfoil/_release/code/field/validate_field_boundary_layer.py +175 -0
  29. vortfoil/_release/code/field/validate_field_surface.py +99 -0
  30. vortfoil/_release/code/field/validate_predict_field.py +166 -0
  31. vortfoil/_release/code/field/vf_field_fast.py +323 -0
  32. vortfoil/_release/code/model/staged/__init__.py +0 -0
  33. vortfoil/_release/code/model/staged/common/__init__.py +136 -0
  34. vortfoil/_release/code/model/staged/common/adaf.py +315 -0
  35. vortfoil/_release/code/model/staged/common/bl_closures.py +796 -0
  36. vortfoil/_release/code/model/staged/common/bl_residuals.py +442 -0
  37. vortfoil/_release/code/model/staged/common/branch.py +176 -0
  38. vortfoil/_release/code/model/staged/common/branch_trunk.py +676 -0
  39. vortfoil/_release/code/model/staged/common/datasets.py +354 -0
  40. vortfoil/_release/code/model/staged/common/geometry.py +529 -0
  41. vortfoil/_release/code/model/staged/common/interp.py +101 -0
  42. vortfoil/_release/code/model/staged/common/lift_closure_tf.py +35 -0
  43. vortfoil/_release/code/model/staged/common/networks.py +201 -0
  44. vortfoil/_release/code/model/staged/common/panel.py +315 -0
  45. vortfoil/_release/code/model/staged/common/profile_encoder.py +89 -0
  46. vortfoil/_release/code/model/staged/common/scaling.py +74 -0
  47. vortfoil/_release/code/model/staged/common/source.py +113 -0
  48. vortfoil/_release/code/model/staged/common/wake_ode_tf.py +160 -0
  49. vortfoil/_release/code/model/staged/common/xfoil_closures.py +659 -0
  50. vortfoil/_release/code/model/staged/op1_inviscid.py +726 -0
  51. vortfoil/_release/code/model/staged/op2_bl_surrogate.py +313 -0
  52. vortfoil/_release/code/model/staged/train_op1_supervised.py +337 -0
  53. vortfoil/_release/code/view_airfoil.py +526 -0
  54. vortfoil/_release/code/view_wing.py +719 -0
  55. vortfoil/_release/code/vortfoil_app.py +1323 -0
  56. vortfoil/_release/code/vortfoil_paths.py +43 -0
  57. vortfoil/_release/code/wing_flow.py +684 -0
  58. vortfoil/_release/code/wing_nll.py +834 -0
  59. vortfoil/_release/code/wing_view.html +744 -0
  60. vortfoil/_release/weights/airfrans_surface_tokens.npz +0 -0
  61. vortfoil/_release/weights/field_decoder_f0cm_s1.npz +0 -0
  62. vortfoil/_release/weights/op1_supervised_eps0.50.scr_bd128.npz +0 -0
  63. vortfoil/_release/weights/op2_m325_BT.npz +0 -0
  64. vortfoil/_staged/__init__.py +0 -0
  65. vortfoil/_staged/common/__init__.py +136 -0
  66. vortfoil/_staged/common/adaf.py +315 -0
  67. vortfoil/_staged/common/bl_closures.py +796 -0
  68. vortfoil/_staged/common/bl_residuals.py +442 -0
  69. vortfoil/_staged/common/branch.py +176 -0
  70. vortfoil/_staged/common/branch_trunk.py +676 -0
  71. vortfoil/_staged/common/datasets.py +354 -0
  72. vortfoil/_staged/common/geometry.py +529 -0
  73. vortfoil/_staged/common/interp.py +101 -0
  74. vortfoil/_staged/common/lift_closure_tf.py +35 -0
  75. vortfoil/_staged/common/networks.py +201 -0
  76. vortfoil/_staged/common/panel.py +315 -0
  77. vortfoil/_staged/common/profile_encoder.py +89 -0
  78. vortfoil/_staged/common/scaling.py +74 -0
  79. vortfoil/_staged/common/source.py +113 -0
  80. vortfoil/_staged/common/wake_ode_tf.py +160 -0
  81. vortfoil/_staged/common/xfoil_closures.py +659 -0
  82. vortfoil/_staged/op1_inviscid.py +726 -0
  83. vortfoil/_staged/op2_bl_surrogate.py +313 -0
  84. vortfoil/api.py +305 -0
  85. vortfoil/app.py +38 -0
  86. vortfoil/cli.py +91 -0
  87. vortfoil/geometry.py +116 -0
  88. vortfoil/selfcheck.py +39 -0
  89. vortfoil/weights/MANIFEST.json +107 -0
  90. vortfoil/weights/cd_closure_poly2.npz +0 -0
  91. vortfoil/weights/lift_closure_poly2.npz +0 -0
  92. vortfoil/weights/op1_supervised_eps0.50.scr_bd128.npz +0 -0
  93. vortfoil/weights/op2_m325_BT.npz +0 -0
  94. vortfoil-2.0.0.dist-info/METADATA +645 -0
  95. vortfoil-2.0.0.dist-info/RECORD +99 -0
  96. vortfoil-2.0.0.dist-info/WHEEL +4 -0
  97. vortfoil-2.0.0.dist-info/entry_points.txt +3 -0
  98. vortfoil-2.0.0.dist-info/licenses/LICENSE +674 -0
  99. vortfoil-2.0.0.dist-info/licenses/NOTICE +67 -0
vortfoil/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ # -*- coding: utf-8 -*-
2
+ """VortFoil: a vortex-panel-informed neural operator for steady airfoil flow.
3
+
4
+ import vortfoil
5
+ vf = vortfoil.load_model()
6
+ r = vf.predict(cst=cst16, alpha=4.0, Re=1e6)
7
+ print(r.cl, r.cd, r.cm)
8
+
9
+ ``vortfoil.about()`` prints what this build is: the weights it carries, the recipe they were trained
10
+ with, the populations they were evaluated on and the scores it reproduces.
11
+ """
12
+ import os
13
+ os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") # the vortfoil command (cli, app) enters here, before numpy: OpenBLAS
14
+ # threads beside TensorFlow's made a field-route panel solve 0.35 s on Windows (1.5 ms single); no effect on macOS (Accelerate)
15
+ from .api import VortFoil, SurfacePrediction, RangeWarning, BL_X, manifest
16
+ from . import geometry
17
+
18
+ __version__ = "2.0.0"
19
+ __all__ = ["VortFoil", "SurfacePrediction", "RangeWarning", "BL_X", "load_model", "about", "manifest", "geometry", "__version__"]
20
+
21
+ _CACHE = {}
22
+
23
+
24
+ def load_model(mode="graph", device="cpu", max_batch=None, weights_dir=None, cache=True):
25
+ """Load the deployed model. ``mode`` is 'graph' (compiled) or 'eager'; ``device`` is 'cpu',
26
+ 'gpu' or 'auto'. Repeated calls with the same settings reuse the loaded operators."""
27
+ key = (mode, device, max_batch, weights_dir)
28
+ if cache and key in _CACHE:
29
+ return _CACHE[key]
30
+ model = VortFoil(mode=mode, device=device, max_batch=max_batch, weights_dir=weights_dir)
31
+ if cache:
32
+ _CACHE[key] = model
33
+ return model
34
+
35
+
36
+ def about(stream=None):
37
+ """Print the build record: weights, recipe, evaluation populations, scores, citation."""
38
+ import json
39
+ import sys
40
+ m = manifest()
41
+ out = stream or sys.stdout
42
+ w = out.write
43
+ w(f"VortFoil {__version__} -- {m['model']['description']}\n\n")
44
+ w("Components\n")
45
+ for c in m["model"]["components"]:
46
+ w(f" - {c}\n")
47
+ w("\nWeights\n")
48
+ for k, v in m["weights"].items():
49
+ w(f" {k:16s} {v['file']:42s} sha256 {v['sha256'][:12]}\n")
50
+ w("\nScores this build reproduces (R^2 against XFOIL)\n")
51
+ for pop, d in m["evaluation"].items():
52
+ w(f" {pop} (n={d['n']}): " + ", ".join(f"{k} {v}" for k, v in d["scores"].items()) + "\n")
53
+ w(f"\n {m['evaluation_note']}\n")
54
+ w("\nInference cost (measured; absolutes are host dependent)\n")
55
+ for k, v in m["inference_cost"].items():
56
+ w(f" {k:34s} {v}\n")
57
+ w("\nLimits\n")
58
+ for lim in m["limits"]:
59
+ w(f" - {lim}\n")
60
+ w(f"\nCitation\n {m['citation']}\n")
61
+ return None
@@ -0,0 +1,56 @@
1
+ """Least-squares CST16 fit of a G241 contour, in the exact form staged/common/geometry.py evaluates.
2
+
3
+ G241 contract: node 0 upper TE, node 120 LE, node 240 lower TE (CCW). OP1 with n_surface_pts=121
4
+ stitches its own loop in the same order, so a fitted CST16 lets OP1 be evaluated on a G241 shape.
5
+ Form (cst_geometry_batch_tf, 16-d coeffs -> no LE-weight, no TE-gap term):
6
+ y_u(x) = C(x) * sum_i a_u,i B_i(x), y_l(x) = -C(x) * sum_i a_l,i B_i(x),
7
+ C(x) = x^0.5 (1-x)^1.0, B_i = Bernstein degree 7 (8 per surface).
8
+ A blunt TE cannot be represented (C(1)=0); the gate reports the error with and without the TE node.
9
+ """
10
+ import numpy as np
11
+ from math import comb
12
+
13
+ N_BERN, N1, N2 = 8, 0.5, 1.0
14
+
15
+
16
+ def basis(x):
17
+ x = np.asarray(x, np.float64); n = N_BERN - 1
18
+ C = np.clip(x, 0, 1) ** N1 * (1.0 - np.clip(x, 0, 1)) ** N2
19
+ B = np.stack([comb(n, i) * x**i * (1 - x)**(n - i) for i in range(N_BERN)], 1)
20
+ return C[:, None] * B # (P, 8)
21
+
22
+
23
+ def fit_g241(g):
24
+ """g: (241,2) -> (cst16 float32, err dict). Upper = nodes 120..0 (LE->TE), lower = nodes 120..240."""
25
+ xu, yu = g[120::-1, 0], g[120::-1, 1]
26
+ xl, yl = g[120:, 0], g[120:, 1]
27
+ Pu, Pl = basis(xu), basis(xl)
28
+ au = np.linalg.lstsq(Pu, yu, rcond=None)[0]
29
+ al = np.linalg.lstsq(Pl, -yl, rcond=None)[0]
30
+ ru = np.abs(Pu @ au - yu); rl = np.abs(-(Pl @ al) - yl)
31
+ err = {"max": float(max(ru.max(), rl.max())),
32
+ "max_excl_te": float(max(ru[:-1].max(), rl[:-1].max())),
33
+ "rms": float(np.sqrt(np.mean(np.r_[ru, rl] ** 2))),
34
+ "te_gap": float(abs(g[0, 1] - g[-1, 1]))}
35
+ return np.r_[au, al].astype(np.float32), err
36
+
37
+
38
+ if __name__ == "__main__":
39
+ # self-check: a CST16 shape rendered on the cosine grid must fit itself to fp precision
40
+ import sys, os
41
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # <release>/code
42
+ import vortfoil_paths as VP; VP.add_paths()
43
+ os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
44
+ import tensorflow as tf; tf.config.set_visible_devices([], "GPU")
45
+ from staged.common.geometry import build_single_loop_contour_cst_tf
46
+ # uiuc_cst.npz is the CST-16 training deck; it is NOT shipped in this release
47
+ # (see README). Point UIUC_CST_NPZ at it to run this self-check.
48
+ UIUC_CST_NPZ = os.environ.get("UIUC_CST_NPZ", os.path.join(VP.DATA_EVAL, "uiuc_cst.npz"))
49
+ c = np.load(UIUC_CST_NPZ, allow_pickle=True)["cst_test"][:5].astype(np.float32)
50
+ geom = build_single_loop_contour_cst_tf(tf.constant(c), n_surface_pts=121)
51
+ G = np.stack([geom["x_nodes"].numpy(), geom["y_nodes"].numpy()], -1)
52
+ for i in range(5):
53
+ cf, e = fit_g241(G[i])
54
+ assert np.abs(cf - c[i]).max() < 1e-4, (i, np.abs(cf - c[i]).max())
55
+ assert e["max"] < 1e-6, e
56
+ print("self-check OK: CST16 -> loop -> fit recovers coefficients to <1e-4, recon <1e-6")
@@ -0,0 +1,136 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Operator-conditioned field decoder (2026-10-02): every manuscript field number that uses it, recomputed for the deployed
3
+ weight file weights/field_decoder_f0cm_s1.npz, which is trained AND scored with
4
+ s = clip((max(H_TE,upper, H_TE,lower) - 2)/8, 0, 1) = state_provider.ConfirmedStateProvider(s_rule="teH").
5
+
6
+ Arms (AirfRANS full_test, 200 cases, sorted manifest order; harness and scorer of state_provider, bootstrap R.paired):
7
+ CM f0cm_s1, provider cl + max-side s (must reproduce step2_eval_f0cm_20260925T213247Z s1, <=1e-6 rel)
8
+ DB drop-in "both" on the XFOIL-conditioned run 2 (f0a_s2): provider cl + max-side s
9
+ DL drop-in "lift only" on run 2: provider cl + XFOIL s
10
+ CX f0cm_s1, XFOIL cl + max-side s (C_l substitution, diagnostic)
11
+ CB f0cm_s1, (provider cl - 0.0294) + max-side s (bias-corrected, diagnostic)
12
+ CMm f0cm_s1, provider cl + mean-side s (evaluation-rule sensitivity)
13
+ Comparator: the sealed per-case array of the XFOIL-conditioned run 2 (evaluation_runs/, mse_all_<channel>).
14
+ Every array is also checked against the shipped record results/f0cm_final_rescore_20261002T051450Z/per_case.npz (<=1e-6 rel).
15
+ --limit N scores the first N cases, runs the checks on rows 0..N-1 and writes nothing.
16
+ python code/field/f0cm_final_rescore.py [--workers 8] [--limit N] (needs AIRFRANS_ROOT)
17
+ """
18
+ import os, sys, json, datetime
19
+ HERE = os.path.dirname(os.path.abspath(__file__))
20
+ sys.path.insert(0, HERE)
21
+ import s_rule_meanside_rescore as R # imports the provider module first (pins BLAS / CUDA before numpy)
22
+ import numpy as np
23
+ import multiprocessing as mp
24
+
25
+ VP, G, DG = R.VP, R.G, R.DG
26
+ REPO = VP.RELEASE_ROOT
27
+ CM_W, F0A2_W = os.path.join(VP.WEIGHTS, "field_decoder_f0cm_s1.npz"), os.path.join(VP.WEIGHTS, "field_decoder_f0a_s2.npz")
28
+ CM_SHA = "5e72da181372c9b966f2b306c32f9a92aaa069704979646ed713726718568c33"
29
+ STEP2 = os.path.join(VP.RESULTS, "step2_eval_f0cm_20260925T213247Z", "per_case.npz")
30
+ RUN2 = os.path.join(G.EVAL_RUNS, G.SEALED[2], "per_case_metrics.npz")
31
+ SHIPPED = os.path.join(VP.RESULTS, "f0cm_final_rescore_20261002T051450Z", "per_case.npz")
32
+ S_MAX = "clip((max(H_TE,upper, H_TE,lower) - 2)/8, 0, 1) = state_provider.ConfirmedStateProvider(s_rule='teH')"
33
+
34
+
35
+ def _init(files, sx, mode, clx, side):
36
+ G._init(files, sx)
37
+ DG._CLX = clx
38
+ base = G.ConfirmedStateProvider(s_rule="teH_mean" if side == "mean" else "teH")
39
+ G._PROV = base if mode == "none" else DG.ClOverrideProvider(base, mode)
40
+
41
+
42
+ def run(cases, files, sx, mode, clx, side, nw):
43
+ with mp.Pool(nw, initializer=_init, initargs=(files, sx, mode, clx, side)) as pool:
44
+ rows = pool.map(G._work, cases, chunksize=2)
45
+ bad = [r for r in rows if r["status"] != "ok"]
46
+ for r in bad[:3]:
47
+ print(" ERROR", r["case"], r["error"], r.get("tb", "")[-600:])
48
+ assert not bad and [r["case"] for r in rows] == cases
49
+ return rows
50
+
51
+
52
+ def maxrel(a, b):
53
+ a, b = np.asarray(a, np.float64), np.asarray(b, np.float64); d = np.abs(a - b)
54
+ with np.errstate(divide="ignore", invalid="ignore"):
55
+ return float(np.max(np.where(d == 0, 0.0, d / np.abs(b))))
56
+
57
+
58
+ def main():
59
+ arg = lambda k, d=None: sys.argv[sys.argv.index(k) + 1] if k in sys.argv else d
60
+ nw = int(arg("--workers", "8")); lim = int(arg("--limit", "0"))
61
+ assert G.sha(CM_W) == CM_SHA
62
+ from supervised_field.nf_eval200 import ROOT
63
+ cases = sorted(json.load(open(os.path.join(ROOT, "manifest.json")))["full_test"])[: lim or None]
64
+ sealed = np.load(os.path.join(G.EVAL_RUNS, G.SEALED[0], "per_case_metrics.npz"), allow_pickle=True)
65
+ r2 = np.load(RUN2, allow_pickle=True)
66
+ assert np.array_equal(r2["s_val"], sealed["s_val"]) # XFOIL s: the same for runs 0 and 2
67
+ sx = {str(c): float(v) for c, v in zip(sealed["case"], sealed["s_val"])}
68
+ clx = {}
69
+ for i in range(len(sealed["case"])):
70
+ prm = sealed["prm4"][i][:int(sealed["n_prm"][i])]
71
+ clx[(tuple(np.round(np.asarray(prm, np.float64), 4)), round(float(sealed["alpha"][i]), 3), round(float(sealed["Re"][i]) / 1e3))] = float(sealed["cl_used"][i])
72
+ i2 = {str(c): i for i, c in enumerate(r2["case"])}
73
+ X2 = np.column_stack([r2[f"mse_all_{c}"][[i2[n] for n in cases]] for c in G.FIELDS]) # sealed run 2, sorted case order
74
+ st = np.load(STEP2, allow_pickle=True); assert list(st["case"])[:len(cases)] == cases
75
+ CM_ref = np.column_stack([st[f"mse_all_{c}_s1"] for c in G.FIELDS])[:len(cases)]
76
+
77
+ P0 = run(cases, {0: F0A2_W, 1: CM_W}, sx, "none", clx, "max", nw); print("[P0 max-side: CM, DB, DL] ok", flush=True)
78
+ P1 = run(cases, {0: CM_W}, {}, "xfoil", clx, "max", nw); print("[P1 CX] ok", flush=True)
79
+ P2 = run(cases, {0: CM_W}, {}, "bias", clx, "max", nw); print("[P2 CB] ok", flush=True)
80
+ P3 = run(cases, {0: CM_W}, {}, "none", clx, "mean", nw); print("[P3 CMm] ok", flush=True)
81
+ A = dict(CM=R.arr(P0, "A_op1cl_op2s", 1, "all"), DB=R.arr(P0, "A_op1cl_op2s", 0, "all"), DL=R.arr(P0, "D_op1cl_xfoils", 0, "all"),
82
+ CX=R.arr(P1, "A_op1cl_op2s", 0, "all"), CB=R.arr(P2, "A_op1cl_op2s", 0, "all"), CMm=R.arr(P3, "A_op1cl_op2s", 0, "all"))
83
+ alpha = np.array([r["alpha"] for r in P0])
84
+ arrays = dict(case=np.array(cases), alpha=alpha, channels=np.array(G.FIELDS), xfoil_conditioned_run2_sealed_all=X2,
85
+ cl_provider=np.array([r["cl_used"] for r in P0]), s_max=np.array([r["s_val"] for r in P0]), s_mean=np.array([r["s_val"] for r in P3]),
86
+ cl_xfoil=np.array([r["cl_used"] for r in P1]), s_xfoil=np.array([sx[c] for c in cases]), **{f"{k}_all": v for k, v in A.items()})
87
+ n = len(cases); sh = np.load(SHIPPED, allow_pickle=True)
88
+ assert [str(c) for c in sh["case"][:n]] == cases and [str(c) for c in sh["channels"]] == list(G.FIELDS)
89
+ vs_shipped = {k: maxrel(v, sh[k][:n]) for k, v in arrays.items() if k not in ("case", "channels")}
90
+ checks = dict(CM_vs_step2_eval_f0cm_s1_maxrel=maxrel(A["CM"], CM_ref), vs_shipped_record_maxrel=vs_shipped,
91
+ CMm_s_is_mean_side_of_P0=bool(np.allclose([r["s_val"] for r in P3], [np.clip((r["diag"]["H_TE"] - 2) / 8, 0, 1) for r in P0])))
92
+ print(f"[checks] rows 0..{n - 1}: CM vs step2_eval_f0cm s1 {checks['CM_vs_step2_eval_f0cm_s1_maxrel']:.1e}; vs the shipped record "
93
+ + ", ".join(f"{k} {v:.1e}" for k, v in vs_shipped.items()), flush=True)
94
+ assert checks["CM_vs_step2_eval_f0cm_s1_maxrel"] <= 1e-6 and max(vs_shipped.values()) <= 1e-6 and checks["CMm_s_is_mean_side_of_P0"], checks
95
+ if lim:
96
+ print(f"[limit {n}] rows 0..{n - 1} of {os.path.relpath(SHIPPED, REPO)} reproduced, max relative difference "
97
+ f"{max(vs_shipped.values()):.2e}; nothing written", flush=True)
98
+ return
99
+
100
+ mean = lambda v: dict(zip(G.FIELDS, v.mean(0).tolist()))
101
+ vsM = lambda v: {c: float(v[:, j].mean() / R.MARIO[c]) for j, c in enumerate(G.FIELDS)}
102
+ utc = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
103
+ res = dict(schema="F0CM_FINAL_RESCORE_V1", utc=utc, script=os.path.relpath(__file__, REPO), script_sha256=G.sha(__file__),
104
+ provider_module_sha256=G.sha(G.__file__), n_cases=len(cases), split="AirfRANS full_test, sorted manifest order",
105
+ provider_rule=S_MAX, cl_rule="OP1 readout C_l^gamma = 2*sum(gamma*ds)", cl_bias_CB=DG.CL_BIAS,
106
+ weights=dict(f0cm_s1=dict(file=os.path.basename(CM_W), sha256=G.sha(CM_W)), f0a_s2=dict(file=os.path.basename(F0A2_W), sha256=G.sha(F0A2_W))),
107
+ comparator=dict(name="XFOIL-conditioned decoder run 2, sealed", file=os.path.relpath(RUN2, REPO), key="mse_all_<channel>"),
108
+ mario_published=R.MARIO, bootstrap="R.paired: case bootstrap B=10000, rng default_rng(0), channels in order", checks=checks,
109
+ arms=dict(CM="f0cm_s1, provider cl + max-side s", DB="run 2, provider cl + max-side s", DL="run 2, provider cl + XFOIL s",
110
+ CX="f0cm_s1, XFOIL cl + max-side s", CB="f0cm_s1, provider cl - 0.0294 + max-side s", CMm="f0cm_s1, provider cl + mean-side s"),
111
+ mean={k: mean(v) for k, v in A.items()} | dict(XF2=mean(X2)), vs_MARIO={k: vsM(v) for k, v in A.items()} | dict(XF2=vsM(X2)),
112
+ paired_vs_xfoil_conditioned_run2={k: R.paired(A[k], X2) for k in ("CM", "DB", "DL")},
113
+ cl_substitution_vs_CM=dict(xfoil_cl=R.paired(A["CX"], A["CM"]), bias_corrected_cl=R.paired(A["CB"], A["CM"])),
114
+ eval_rule_sensitivity_CMm_over_CM=R.paired(A["CMm"], A["CM"]), by_alpha_band={})
115
+ for lo, hi in R.BANDS:
116
+ m = (alpha >= lo) & (alpha < hi)
117
+ res["by_alpha_band"][f"[{lo},{hi})"] = dict(
118
+ n=int(m.sum()), abs={k: mean(v[m]) for k, v in A.items()} | dict(XF2=mean(X2[m])),
119
+ over_xfoil_conditioned_run2={k: dict(zip(G.FIELDS, (v[m].mean(0) / X2[m].mean(0)).tolist())) for k, v in A.items()},
120
+ over_MARIO_aggregate={k: vsM(v[m]) for k, v in A.items()} | dict(XF2=vsM(X2[m])))
121
+ OUT = os.path.join(VP.RESULTS, f"f0cm_final_rescore_{utc}"); assert not os.path.exists(OUT); os.makedirs(OUT)
122
+ json.dump(res, open(os.path.join(OUT, "result.json"), "w"), indent=1)
123
+ np.savez(os.path.join(OUT, "per_case.npz"), **arrays)
124
+ f = lambda d: " ".join(f"{c} {d[c]['R']:.2f}[{d[c]['ci95'][0]:.2f},{d[c]['ci95'][1]:.2f}] n{d[c]['n_improved']}" for c in G.FIELDS)
125
+ for k in A:
126
+ print(f"[{k}] mean " + " ".join(f"{c} {v:.3e}" for c, v in res["mean"][k].items()) + " | /MARIO " + " ".join(f"{v:.2f}" for v in res["vs_MARIO"][k].values()), flush=True)
127
+ for k, d in res["paired_vs_xfoil_conditioned_run2"].items():
128
+ print(f"[{k}/XF2] {f(d)}", flush=True)
129
+ for k, d in res["cl_substitution_vs_CM"].items():
130
+ print(f"[{k}/CM] {f(d)}", flush=True)
131
+ print(f"[CMm/CM] {f(res['eval_rule_sensitivity_CMm_over_CM'])}", flush=True)
132
+ print(f"[rescore] wrote {OUT}", flush=True)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()
@@ -0,0 +1,73 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Validation-holdout score of field-decoder weight files, computed as the trainer's holdout() does (sealed trainer 0d8ed19d,
3
+ code/field/supervised_field/nf_train_shape.py): per-channel standardized MSE pooled over all rows of the 20-case validation
4
+ holdout named in the file's run_config, and the mean of the four channels (the deployed-weight selection score).
5
+ Forward pass in numpy (supervised_field/nf_eval_shape.fwd_np / encode_np) instead of TF.
6
+
7
+ Source of both deployed decoders' validation scores: results/f0a_holdout_rescore_20260930.jsonl (XFOIL-conditioned, run 2
8
+ 0.00372) and results/f0cm_holdout_rescore.json (operator-conditioned, run 1 0.00262). The corpus is the one named in
9
+ run_config, looked up by basename in VORTFOIL_CORPUS_DIR (the AirfRANS-derived training corpora are not shipped); the tokens
10
+ are weights/airfrans_surface_tokens.npz, the release name of _nf_shape_tokens_airfrans.npz. Both must match their recorded sha256.
11
+ VORTFOIL_CORPUS_DIR=/path/to/corpora python code/field/field_holdout_score.py weights/field_decoder_f0a_s{0,1,2}.npz
12
+ VORTFOIL_CORPUS_DIR=/path/to/corpora python code/field/field_holdout_score.py weights/field_decoder_f0cm_s{0,1,2}.npz
13
+ """
14
+ import os, sys, json, hashlib
15
+ import numpy as np
16
+
17
+ HERE = os.path.dirname(os.path.abspath(__file__))
18
+ sys.path.insert(0, os.path.dirname(HERE)) # <release>/code
19
+ import vortfoil_paths as VP # noqa: E402
20
+ REPO = VP.add_paths()
21
+ SF = os.environ.get("VORTFOIL_CORPUS_DIR", os.path.join(VP.FIELD, "supervised_field"))
22
+ TOKENS = os.path.join(VP.WEIGHTS, "airfrans_surface_tokens.npz") # cd27519b, every run_config tokens_sha256
23
+ from supervised_field.nf_eval_shape import fwd_np, encode_np # noqa: E402
24
+
25
+ FIELDS = ("ux", "uy", "p", "nut")
26
+ _CACHE = {}
27
+
28
+
29
+ def sha256(p):
30
+ h = hashlib.sha256()
31
+ with open(p, "rb") as f:
32
+ for b in iter(lambda: f.read(1 << 22), b""):
33
+ h.update(b)
34
+ return h.hexdigest()
35
+
36
+
37
+ def load(path, want_sha):
38
+ if path not in _CACHE:
39
+ got = sha256(path)
40
+ assert got == want_sha, f"{path}: sha {got[:12]} != run_config {want_sha[:12]}"
41
+ _CACHE[path] = np.load(path, allow_pickle=True)
42
+ return _CACHE[path]
43
+
44
+
45
+ def score(wpath):
46
+ w = dict(np.load(wpath, allow_pickle=True))
47
+ cfg = json.loads(str(w["run_config"]))
48
+ z = load(os.path.join(SF, os.path.basename(cfg["corpus"].replace("\\", "/"))), cfg["corpus_sha256"])
49
+ tz = load(TOKENS, cfg["tokens_sha256"])
50
+ names = [str(x) for x in z["names"]]
51
+ cid = z["case_id"].astype(np.int64)
52
+ tmap = {str(n): i for i, n in enumerate(tz["names"])}
53
+ tok = tz["surf_tokens"].astype(np.float32)
54
+ s_case = np.asarray(z["s"], np.float32)
55
+ err, rows = [], 0
56
+ for nm in cfg["holdout_names"]:
57
+ ci = names.index(nm)
58
+ m = cid == ci
59
+ zc = encode_np(tok[tmap[nm]].astype(np.float64), w)
60
+ pred = fwd_np(z["X"][m].astype(np.float64), np.full(int(m.sum()), float(s_case[ci])), z["PAINT"][m].astype(np.float64), zc, w)
61
+ err.append(((pred - z["TRUTH"][m].astype(np.float64)) / w["std"][None, :]) ** 2)
62
+ rows += int(m.sum())
63
+ assert rows == cfg["holdout_rows"] and len(cfg["holdout_names"]) == cfg["holdout_cases"], (rows, cfg["holdout_rows"])
64
+ e = np.concatenate(err).mean(0)
65
+ return dict(file=os.path.relpath(wpath, REPO) if wpath.startswith(REPO) else wpath, sha256=sha256(wpath), seed=cfg.get("train_seed"),
66
+ corpus=os.path.basename(cfg["corpus"].replace("\\", "/")), holdout_cases=len(cfg["holdout_names"]), holdout_rows=rows,
67
+ **{f: float(v) for f, v in zip(FIELDS, e)}, score=float(e.mean()))
68
+
69
+
70
+ if __name__ == "__main__":
71
+ for p in sys.argv[1:]:
72
+ r = score(os.path.abspath(p))
73
+ print(json.dumps(r), flush=True)
@@ -0,0 +1,162 @@
1
+ # -*- coding: utf-8 -*-
2
+ # NACA 4- and 5-digit section generator, copied verbatim from the airfrans package 0.1.5.1
3
+ # (airfrans/naca_generator.py, https://github.com/Extrality/airfrans_lib), MIT License, Copyright (c) 2023 Extrality (full text below).
4
+ # The AirfRANS cases (and so the field decoder's training sections) were generated with this function; it is
5
+ # vendored so that code/field/predict_field.py and code/view_airfoil.py need no airfrans install. See NOTICE.
6
+ #
7
+ # MIT License
8
+ #
9
+ # Copyright (c) 2023 Extrality
10
+ #
11
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ # of this software and associated documentation files (the "Software"), to deal
13
+ # in the Software without restriction, including without limitation the rights
14
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ # copies of the Software, and to permit persons to whom the Software is
16
+ # furnished to do so, subject to the following conditions:
17
+ #
18
+ # The above copyright notice and this permission notice shall be included in all
19
+ # copies or substantial portions of the Software.
20
+ #
21
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ # SOFTWARE.
28
+ import numpy as np
29
+
30
+ def thickness_dist(t, x, CTE = True):
31
+ """
32
+ Standard NACA profile to warp with the help of a camber line to define all the
33
+ 4 and 5 digits profiles.
34
+
35
+ Args:
36
+ t (float): Thickness of the airfoil in percentage of the chord length.
37
+ x (np.ndarray): Abscissas in chord unit.
38
+ CTE (bool, optional): If ``True`` the profile will be closed at the trailing edge. Default: ``True``
39
+ """
40
+ # CTE for close trailing edge
41
+ if CTE:
42
+ a = -0.1036
43
+ else:
44
+ a = -0.1015
45
+ return 5*t*(0.2969*np.sqrt(x) - 0.1260*x - 0.3516*x**2 + 0.2843*x**3 + a*x**4)
46
+
47
+ def camber_line(params, x):
48
+ """
49
+ Camber line definition for the NACA 4 and 5 digits series.
50
+
51
+ Args:
52
+ params (np.ndarray): Parameters of the NACA 4 or 5 digits profile (ndarray of shape `(3)` or `(4)`).
53
+ x (np.ndarray): Abscissas in chord unit.
54
+ """
55
+ y_c = np.zeros_like(x)
56
+ dy_c = np.zeros_like(x)
57
+
58
+ if len(params) == 2:
59
+ m = params[0]/100
60
+ p = params[1]/10
61
+
62
+ if p == 0:
63
+ dy_c = -2*m*x
64
+ return y_c, dy_c
65
+ elif p == 1:
66
+ dy_c = 2*m*(1 - x)
67
+ return y_c, dy_c
68
+
69
+ mask1 = (x < p)
70
+ mask2 = (x >= p)
71
+ y_c[mask1] = (m/p**2)*(2*p*x[mask1] - x[mask1]**2)
72
+ dy_c[mask1] = (2*m/p**2)*(p - x[mask1])
73
+ y_c[mask2] = (m/(1 - p)**2)*((1 - 2*p) + 2*p*x[mask2] - x[mask2]**2)
74
+ dy_c[mask2] = (2*m/(1 - p)**2)*(p - x[mask2])
75
+
76
+ elif len(params) == 3:
77
+ l, p, q = params
78
+ c_l, x_f = 3/20*l, p/20
79
+
80
+ f = lambda x: x*(1 - np.sqrt(x/3)) - x_f
81
+ df = lambda x: 1 - 3*np.sqrt(x/3)/2
82
+ old_m = np.array(0.5)
83
+ cond = True
84
+ while cond:
85
+ new_m = np.max(np.array([old_m - f(old_m)/df(old_m), 0]))
86
+ cond = (np.abs(old_m - new_m) > 1e-15)
87
+ old_m = new_m
88
+ m = old_m
89
+ r = (3*m - 7*m**2 + 8*m**3 - 4*m**4)/np.sqrt(m*(1 - m)) - 3/2*(1 - 2*m)*(np.pi/2 - np.arcsin(1 - 2*m))
90
+ k_1 = c_l/r
91
+
92
+ mask1 = (x <= m)
93
+ mask2 = (x > m)
94
+ if q == 0:
95
+ y_c[mask1] = k_1*((x[mask1]**3 - 3*m*x[mask1]**2 + m**2*(3 - m)*x[mask1]))
96
+ dy_c[mask1] = k_1*(3*x[mask1]**2 - 6*m*x[mask1] + m**2*(3 - m))
97
+ y_c[mask2] = k_1*m**3*(1 - x[mask2])
98
+ dy_c[mask2] = -k_1*m**3*np.ones_like(dy_c[mask2])
99
+
100
+ elif q == 1:
101
+ k = (3*(m - x_f)**2 - m**3)/(1 - m)**3
102
+ y_c[mask1] = k_1*((x[mask1] - m)**3 - k*(1 - m)**3*x[mask1] - m**3*x[mask1] + m**3)
103
+ dy_c[mask1] = k_1*(3*(x[mask1] - m)**2 - k*(1 - m)**3 - m**3)
104
+ y_c[mask2] = k_1*(k*(x[mask2] - m)**3 - k*(1 - m)**3*x[mask2] - m**3*x[mask2] + m**3)
105
+ dy_c[mask2] = k_1*(3*k*(x[mask2] - m)**2 - k*(1 - m)**3 - m**3)
106
+
107
+ else:
108
+ raise ValueError('Q must be 0 for normal camber or 1 for reflex camber.')
109
+
110
+ else:
111
+ raise ValueError('The first input must be a tuple of the 2 or 3 digits that represent the camber line.')
112
+
113
+ return y_c, dy_c
114
+
115
+ def naca_generator(params, nb_samples = 400, scale = 1, origin = (0, 0), cosine_spacing = True, verbose = True, CTE = True):
116
+ """
117
+ Definition of a complete profile from the NACA 4 and 5 digits series.
118
+
119
+ Args:
120
+ params (np.ndarray): Parameters of the NACA 4 or 5 digits profile (ndarray of shape `(3)` or `(4)`).
121
+ nb_samples (int, optional): Number of points to define the profile. Default: 400
122
+ scale (float, optional): Chord length in meters. Default: 1
123
+ origine (tuple, optional): Absolute position of the leading edge. Default: `(0, 0)`
124
+ cosine_spacing (bool, optional): If ``True``, points are sampled via a cosine distance instead of uniformly. Default: ``True``
125
+ verbose (bool, optional): Comments on the generation process. Default: ``True``
126
+ CTE (bool, optional): If ``True`` the profile will be closed at the trailing edge. Default: ``True``
127
+ """
128
+ if len(params) == 3:
129
+ params_c = params[:2]
130
+ t = params[2]/100
131
+ if verbose:
132
+ print(f'Generating naca M = {params_c[0]}, P = {params_c[1]}, XX = {t*100}')
133
+ elif len(params) == 4:
134
+ params_c = params[:3]
135
+ t = params[3]/100
136
+ if verbose:
137
+ print(f'Generating naca L = {params_c[0]}, P = {params_c[1]}, Q = {params_c[2]}, XX = {t*100}')
138
+ else:
139
+ raise ValueError('The first argument must be a tuple of the 4 or 5 digits of the airfoil.')
140
+
141
+ if cosine_spacing:
142
+ beta = np.pi*np.linspace(1, 0, nb_samples + 1)
143
+ x = (1 - np.cos(beta))/2
144
+ else:
145
+ x = np.linspace(1, 0, nb_samples + 1)
146
+
147
+ y_c, dy_c = camber_line(params_c, x)
148
+ y_t = thickness_dist(t, x, CTE)
149
+ theta = np.arctan(dy_c)
150
+ x_u = x - y_t*np.sin(theta)
151
+ x_l = x + y_t*np.sin(theta)
152
+ y_u = y_c + y_t*np.cos(theta)
153
+ y_l = y_c - y_t*np.cos(theta)
154
+ x = np.concatenate([x_u, x_l[:-1][::-1]], axis = 0)
155
+ y = np.concatenate([y_u, y_l[:-1][::-1]], axis = 0)
156
+ pos = np.stack([
157
+ x*scale + origin[0],
158
+ y*scale + origin[1]
159
+ ], axis = -1
160
+ )
161
+ pos[0], pos[-1] = np.array([1, 0]), np.array([1, 0])
162
+ return pos