"""Np and Nq of a four-blade pitched blade turbine in reactor R-101 from the trained
Gaussian processes of Chmltech Online Journal Vol. 106, Issue 25, with the 2-sigma
band and a range check. Needs Python 3 and NumPy. The model file gp_models.json
(in the model download) holds each process's kernel, training inputs and weights.

Usage: python3 surrogate_appendix.py 40 0.30 0.30     (angle deg, D/T, C/T)
"""
import json, math, os, sys
import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
M = json.load(open(os.path.join(HERE, "gp_models.json")))
LO, HI = np.array(M["lo"]), np.array(M["hi"])


def predict(model, x):
    """Mean and standard deviation of one Gaussian process at x."""
    s = (np.asarray(x, float) - LO) / (HI - LO)
    X = np.array(model["X"])
    d2 = (((s - X) / np.array(model["l"])) ** 2).sum(1)
    k = model["c"] * np.exp(-0.5 * d2)
    mu = k @ np.array(model["alpha"])
    var = model["c"] + model["w"] - k @ np.array(model["Kinv"]) @ k
    sd = math.sqrt(max(var, 0.0))
    return mu * model["ys"] + model["ym"], sd * model["ys"]


def main(angle, d_t, c_t):
    x = [angle, d_t, c_t]
    out = [n for n, v, lo, hi in zip(("blade angle", "D/T", "C/T"), x, LO, HI)
           if not lo <= v <= hi]
    for t in ("Np", "Nq"):
        mu, sd = predict(M["models"][t], x)
        print(f"{t} = {mu:.3f} +/- {2 * sd:.3f} (2 sigma)")
    if out:
        print("WARNING: outside the training range in " + ", ".join(out)
              + "; the answer is an extrapolation.")
    print("Coarse-mesh CFD: power numbers read low; see Section 8 of the paper.")


if __name__ == "__main__":
    if len(sys.argv) == 4:
        main(*map(float, sys.argv[1:]))
    else:
        main(45.0, 0.377, 0.333)
