"""ParaView without a screen: the cavity's speed with streamlines at the last saved time, and the velocity along the two
centre lines at the last two saved times (for the comparison with Ghia et al., and to see whether the flow has settled).
Run it in the case folder, after touch cavity1000.foam:  pvpython --no-mpi render.py"""
from paraview.simple import *
case = OpenFOAMReader(FileName="cavity1000.foam")
case.MeshRegions = ["internalMesh"]
case.CellArrays = ["U", "p"]
case.UpdatePipelineInformation()
t = case.TimestepValues[-1] if case.TimestepValues else 0
case.UpdatePipeline(t)
print("time shown:", t)
cells = CellDatatoPointData(Input=case)
view = CreateRenderView(); view.ViewSize = [1200, 1000]; view.OrientationAxesVisibility = 0; view.Background = [1, 1, 1]
try:
    view.UseColorPaletteForBackground = 0
except AttributeError:
    pass
view.ViewTime = t
sl = Slice(Input=cells); sl.SliceType.Origin = [0.05, 0.05, 0.005]; sl.SliceType.Normal = [0, 0, 1]
d = Show(sl, view); ColorBy(d, ("POINTS", "U", "Magnitude"))
lut = GetColorTransferFunction("U"); lut.ApplyPreset("Viridis (matplotlib)", True); lut.RescaleTransferFunction(0.0, 1.0)
bar = GetScalarBar(lut, view); bar.Title = "speed (m/s)"; bar.ComponentTitle = ""; bar.TitleColor = [0, 0, 0]; bar.LabelColor = [0, 0, 0]
d.SetScalarBarVisibility(view, True)
bar.WindowLocation = "Any Location"; bar.Position = [0.86, 0.25]; bar.ScalarBarLength = 0.5; bar.RangeLabelFormat = "%-#.1f"; bar.TitleFontSize = 20; bar.LabelFontSize = 18
st = StreamTracer(Input=sl, SeedType="Line"); st.SeedType.Point1 = [0.001, 0.05, 0.005]; st.SeedType.Point2 = [0.099, 0.05, 0.005]; st.SeedType.Resolution = 18
st.Vectors = ["POINTS", "U"]; st.MaximumStreamlineLength = 2.0
s = Show(st, view); s.DiffuseColor = [1, 1, 1]; s.AmbientColor = [1, 1, 1]; ColorBy(s, None); s.LineWidth = 1.0
view.CameraPosition = [0.058, 0.05, 0.3]; view.CameraFocalPoint = [0.058, 0.05, 0.005]; view.CameraViewUp = [0, 1, 0]; view.CameraParallelProjection = 1; view.CameraParallelScale = 0.056
SaveScreenshot("cavity_speed.png", view, ImageResolution=[1200, 1000])
# the two centre lines, as CSV: at the last saved time, and at the one before (to see whether the flow still changes)
times = list(case.TimestepValues)
for when, suffix in ((t, ""), (times[-2] if len(times) > 1 else t, "_before")):
    for name, p1, p2 in (("vertical", [0.05, 0.0, 0.005], [0.05, 0.1, 0.005]), ("horizontal", [0.0, 0.05, 0.005], [0.1, 0.05, 0.005])):
        line = PlotOverLine(Input=cells)
        try:
            line.Point1, line.Point2 = p1, p2
        except AttributeError:
            line.Source.Point1, line.Source.Point2 = p1, p2
        line.Resolution = 400
        line.UpdatePipeline(when)
        SaveData(f"centre_{name}{suffix}.csv", proxy=line)
print(f"saved cavity_speed.png and the centre lines at t = {t} and t = {times[-2] if len(times) > 1 else t}")
