"""Compare the computed velocities along the cavity's centre lines with Ghia, Ghia and Shin (1982), Re = 1000, and check
that the flow has settled (the last two saved times agree). Lengths divided by the cavity size (0.1 m), speeds by the lid
speed (1 m/s). Run it in the case folder, after render.py:  python3 compare.py   (matplotlib came with ParaView)"""
import os
import csv, matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

# Ghia, Ghia and Shin, J. Comput. Phys. 48 (1982) 387-411, Re = 1000: u along the vertical centre line, v along the horizontal one
ghia_y = [1.0000, 0.9766, 0.9688, 0.9609, 0.9531, 0.8516, 0.7344, 0.6172, 0.5000, 0.4531, 0.2813, 0.1719, 0.1016, 0.0703, 0.0625, 0.0547, 0.0000]
ghia_u = [1.0000, 0.65928, 0.57492, 0.51117, 0.46604, 0.33304, 0.18719, 0.05702, -0.06080, -0.10648, -0.27805, -0.38289, -0.29730, -0.22220, -0.20196, -0.18109, 0.0000]
ghia_x = [1.0000, 0.9688, 0.9609, 0.9531, 0.9453, 0.9063, 0.8594, 0.8047, 0.5000, 0.2344, 0.2266, 0.1563, 0.0938, 0.0781, 0.0703, 0.0625, 0.0000]
ghia_v = [0.0000, -0.21388, -0.27669, -0.33714, -0.39188, -0.51550, -0.42665, -0.31966, 0.02526, 0.32235, 0.33075, 0.37095, 0.32627, 0.30353, 0.29012, 0.27485, 0.0000]

def read(path, along, comp):
    rows = [r for r in csv.DictReader(open(path)) if r["vtkValidPointMask"] == "1"]
    return np.array([float(r[f"Points:{along}"]) / 0.1 for r in rows]), np.array([float(r[f"U:{comp}"]) for r in rows])

y, u = read("centre_vertical.csv", 1, 0)
x, v = read("centre_horizontal.csv", 0, 1)
if os.path.exists("centre_vertical_before.csv"):          # has the flow settled? the change between the last two saved times
    yb, ub = read("centre_vertical_before.csv", 1, 0)
    xb, vb = read("centre_horizontal_before.csv", 0, 1)
    change = max(np.abs(np.interp(y, yb, ub) - u).max(), np.abs(np.interp(x, xb, vb) - v).max())
    print(f"largest change on the centre lines between the last two saved times: {change:.4f} (lid speed = 1)")
err_u = np.abs(np.interp(ghia_y[1:-1], y, u) - np.array(ghia_u[1:-1]))
err_v = np.abs(np.interp(ghia_x[::-1][1:-1], x, v) - np.array(ghia_v[::-1][1:-1]))
print(f"u on the vertical centre line:   largest difference from Ghia {err_u.max():.3f}, average {err_u.mean():.3f} (lid speed = 1)")
print(f"v on the horizontal centre line: largest difference from Ghia {err_v.max():.3f}, average {err_v.mean():.3f}")
print(f"strongest backflow u = {u.min():.3f} at y = {y[u.argmin()]:.3f} (Ghia: -0.383 at 0.172)")

# ParaView's point values at the walls are averages of the cells next to them, half a cell away; the walls' own values are
# known from the boundary conditions (the lid moves at u = 1, every wall holds the fluid still), so add them to the curves
y, u = np.r_[0.0, y[1:-1], 1.0], np.r_[0.0, u[1:-1], 1.0]
x, v = np.r_[0.0, x[1:-1], 1.0], np.r_[0.0, v[1:-1], 0.0]
fig, ax = plt.subplots(1, 2, figsize=(10, 4.6))
ax[0].plot(u, y, color="#6d3fc4", lw=1.6, label="OpenFOAM, 256 x 256")
ax[0].plot(ghia_u, ghia_y, "o", mfc="none", color="#e0a000", label="Ghia et al. (1982)")
ax[0].set(xlabel="u / U (horizontal speed)", ylabel="y / L", title="Vertical centre line")
ax[1].plot(x, v, color="#6d3fc4", lw=1.6, label="OpenFOAM, 256 x 256")
ax[1].plot(ghia_x, ghia_v, "o", mfc="none", color="#e0a000", label="Ghia et al. (1982)")
ax[1].set(xlabel="x / L", ylabel="v / U (vertical speed)", title="Horizontal centre line")
for a in ax:
    a.grid(alpha=0.3); a.legend(fontsize=9)
fig.suptitle("Lid-driven cavity at Re = 1000: our run against the benchmark")
fig.tight_layout()
fig.savefig("centreline.png", dpi=150)
print("saved centreline.png")
