"""Check an OpenFOAM solver log for silently skipped solves (Chmltech Online Journal, Vol. 106, Issue 28, Appendix).

A solver line ending "No Iterations 0" means the field was not solved that iteration: its initial residual was already
below the tolerance. That is harmless once the case has settled, and a warning sign while the quantity you report is
still moving. This script reads one or more logs in order (for example log.simpleFoam.part1 log.simpleFoam), finds the
first skipped solve of each field, and reports how much a monitored quantity changed between that iteration and the
end of the log.

The monitored quantity is read with a regular expression. By default it is the pressure gradient written by the
meanVelocityForce source ("Pressure gradient source: ... pressure gradient = <value>"); give --monitor to read
another number, for example a residual or a value your own function writes to the log.

Usage: python3 agentcfd_appendix.py LOG [LOG ...] [--monitor REGEX] [--skip-before N] [--tol 1e-3]
Python 3, standard library only. Prints one line per field and a verdict."""
import argparse, re, sys

SOLVE = re.compile(r"Solving for (\w+), Initial residual = (\S+), Final residual = \S+, No Iterations (\d+)")
TIME = re.compile(r"^Time = (\S+)")
DEFAULT = r"Pressure gradient source: .*pressure gradient = (\S+)"


def read(paths, monitor):
    t, rows, mon = 0.0, {}, []
    for p in paths:
        with open(p, errors="ignore") as fh:
            for line in fh:
                m = TIME.match(line)
                if m:
                    try: t = float(m.group(1))
                    except ValueError: pass
                    continue
                m = SOLVE.search(line)
                if m:
                    f, res, n = m.group(1), float(m.group(2)), int(m.group(3))
                    d = rows.setdefault(f, dict(first_skip=None, skips=0, solves=0, last_res=None))
                    d["solves"] += 1; d["last_res"] = res
                    if n == 0:
                        d["skips"] += 1
                        if d["first_skip"] is None: d["first_skip"] = t
                    continue
                m = monitor.search(line)
                if m:
                    try: mon.append((t, float(m.group(1))))
                    except ValueError: pass
    return rows, mon


def value_at(mon, t):
    """Monitored value at the last record at or before iteration t."""
    best = None
    for tt, v in mon:
        if tt <= t: best = v
        else: break
    return best


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("logs", nargs="+")
    ap.add_argument("--monitor", default=DEFAULT, help="regular expression with one group: the number to watch")
    ap.add_argument("--skip-before", type=float, default=5, help="ignore skips before this iteration (start-up)")
    ap.add_argument("--tol", type=float, default=1e-3, help="relative change after the first skip that counts as moving")
    a = ap.parse_args()
    rows, mon = read(a.logs, re.compile(a.monitor))
    if not rows: sys.exit("no solver lines found")
    end = mon[-1][1] if mon else None
    print(f"{'field':10s} {'solves':>8s} {'skipped':>8s} {'first skip':>11s} {'last residual':>14s}  change of monitor after first skip")
    worst = 0.0
    for f, d in sorted(rows.items()):
        fs = d["first_skip"] if d["first_skip"] is not None and d["first_skip"] > a.skip_before else None
        ch = ""
        if fs is not None and end is not None:
            v0 = value_at(mon, fs)
            if v0:
                rel = abs(end - v0) / abs(v0); worst = max(worst, rel); ch = f"{rel:.2%} ({v0:.6g} -> {end:.6g})"
        print(f"{f:10s} {d['solves']:8d} {d['skips']:8d} {('-' if fs is None else f'{fs:g}'):>11s} {d['last_res']:14.3e}  {ch}")
    if not mon:
        print("No monitored value found: give --monitor to say what to watch.")
    elif worst > a.tol:
        print(f"WARNING: a field stopped being solved while the monitored value was still changing (by {worst:.2%}). "
              "Run longer or tighten the tolerance before you trust the result.")
    else:
        print(f"OK: after the first skipped solve the monitored value changed by at most {worst:.2%}.")


if __name__ == "__main__":
    main()
