"""Mesh study calculator: observed order, extrapolated value, GCI, and the cost of going finer
(Chmltech Online Journal, Vol. 106, Issue 31, appendix). Python 3, standard library only.

Give three or more meshes of the same case, coarse to fine, each with its cell count, the quantity you need and the
solver CPU time. The script applies the grid convergence index procedure of Celik et al. (2008) to the three finest
meshes, then uses the observed order and the cost growth between the two finest meshes to estimate what one more
level would cost, and what it would cost to bring the error against the extrapolated value down to a target. This is
the projection method of the paper (Tables 5 and 6). The GCI is about 1.25 times that error when the order holds.
A projection far beyond the meshes run is an order-of-magnitude guide only: it assumes the order and cost growth hold.

Usage:
    python3 meshcost_appendix.py --dim 2 --target 1 \\
        16000,5608.4,63  31944,5716.8,148  64000,5800.8,387
Each mesh is cells,value,cpu_seconds. --dim is 2 for a 2D or one-cell-thick slice case, 3 for a full 3D mesh.
--target is the error you need against the extrapolated value, in per cent (default 5).
"""
import argparse, math


def gci3(phi1, phi2, phi3, r21, r32, fs=1.25):
    e21, e32 = phi2 - phi1, phi3 - phi2
    if e21 == 0 or e32 == 0: return None
    s = 1.0 if e32 / e21 > 0 else -1.0
    p = abs(math.log(abs(e32 / e21))) / math.log(r21)
    for _ in range(200):
        try: q = math.log((r21 ** p - s) / (r32 ** p - s))
        except ValueError: break
        pn = abs(math.log(abs(e32 / e21)) + q) / math.log(r21)
        if abs(pn - p) < 1e-10: p = pn; break
        p = pn
    out = dict(p=p, monotone=s > 0, converging=abs(e21) < abs(e32), change=abs(e21 / phi1))
    if out["monotone"] and out["converging"]:
        out["ext"] = (r21 ** p * phi1 - phi2) / (r21 ** p - 1)
        out["gci"] = fs * out["change"] / (r21 ** p - 1)
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("meshes", nargs="+", help="cells,value,cpu_seconds, coarse to fine")
    ap.add_argument("--dim", type=int, default=3)
    ap.add_argument("--target", type=float, default=5.0, help="target error against the extrapolated value, per cent")
    a = ap.parse_args()
    m = []
    for s in a.meshes:
        parts = s.split(",")
        if len(parts) != 3:
            raise SystemExit(f"each mesh needs three values, cells,value,cpu_seconds (got '{s}')")
        try: m.append(tuple(float(x) for x in parts))
        except ValueError: raise SystemExit(f"could not read '{s}' as three numbers: cells,value,cpu_seconds")
    if len(m) < 3: raise SystemExit("give at least three meshes")
    (n3, f3, t3), (n2, f2, t2), (n1, f1, t1) = m[-3:]
    r21, r32 = (n1 / n2) ** (1 / a.dim), (n2 / n3) ** (1 / a.dim)
    g = gci3(f1, f2, f3, r21, r32)
    print(f"Refinement ratios r21 = {r21:.3f}, r32 = {r32:.3f}")
    if g is None:
        print("Two meshes gave the same value: no order can be found. Check convergence of each run."); return
    print(f"Observed order p = {g['p']:.2f}; change fine to medium = {g['change'] * 100:.2f}%")
    if "gci" not in g:
        print("The changes do not shrink steadily (" + ("oscillating" if not g["monotone"] else "growing") + "): no GCI is defined.")
        print("Run a finer mesh, or check that every run converged and that the meshes are refined the same way."); return
    print(f"Extrapolated value = {g['ext']:.6g}; GCI of the fine mesh = {g['gci'] * 100:.2f}%  (fine value {f1:.6g})")
    alpha = math.log(t1 / t2) / math.log(n1 / n2) if t2 > 0 and n1 != n2 else 1.0
    n_next, t_next = n1 * r21 ** a.dim, t1 * (r21 ** a.dim) ** alpha
    gci_next = g["gci"] / r21 ** g["p"]
    print(f"CPU time grows as cells^{alpha:.2f}. One more level (r = {r21:.2f}): about {n_next:,.0f} cells, "
          f"{t_next / 3600:.2f} h of CPU, expected GCI about {gci_next * 100:.2f}%")
    err = abs(f1 - g["ext"]) / abs(g["ext"])
    print(f"Fine mesh is {err * 100:.2f}% from the extrapolated value.")
    if err * 100 <= a.target:
        print(f"The fine mesh already meets the {a.target:g}% target.")
    else:
        n_t = n1 * (err * 100 / a.target) ** (a.dim / g["p"])
        t_t = t1 * (n_t / n1) ** alpha
        print(f"To reach {a.target:g}% from the extrapolated value: about {n_t:,.0f} cells and {t_t / 3600:,.1f} h of CPU "
              f"({t_t / 86400:,.1f} days), if the order and cost growth hold. Treat this as an order of magnitude.")


if __name__ == "__main__":
    main()
