
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

df = pd.read_csv("../data/spatial_grid.csv")

t0 = 5
field_name = "temperature"
slice_axis = "x"

df = df[df["time"] == t0].copy()

n = 35
axis = np.linspace(-5, 5, n)

values = df[field_name].to_numpy().reshape((n, n, n))

fig, ax = plt.subplots(figsize=(8, 6))

if slice_axis == "z":
    xlabel, ylabel = "X", "Y"
elif slice_axis == "y":
    xlabel, ylabel = "X", "Z"
else:
    xlabel, ylabel = "Y", "Z"

def get_slice(i):
    if slice_axis == "z":
        return values[:, :, i].T
    elif slice_axis == "y":
        return values[:, i, :].T
    else:
        return values[i, :, :].T

image = ax.imshow(
    get_slice(0),
    extent=(-5, 5, -5, 5),
    origin="lower",
    cmap="viridis",
    aspect="equal",
    vmin=values.min(),
    vmax=values.max()
)

colorbar = fig.colorbar(image, ax=ax)
colorbar.set_label(field_name)

ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)

def update(i):
    image.set_data(get_slice(i))
    ax.set_title(
        f"{field_name} | {slice_axis.upper()} = {axis[i]:.2f}"
    )
    return image,

animation = FuncAnimation(
    fig,
    update,
    frames=n,
    interval=150,
    blit=False,
    repeat=True
)

plt.savefig("../lectures/imgs/mpl_06.png")
plt.show()
