
import numpy as np
import pandas as pd

grid_axis = np.linspace(-5, 5, 35)
grid_times = [2, 5, 8]

X, Y, Z = np.meshgrid(
    grid_axis,
    grid_axis,
    grid_axis,
    indexing="ij"
)

def temperature_field(x, y, z, t):
    source_1 = np.exp(-((x - 2*np.sin(t))**2 + (y - 2*np.cos(t))**2 + (z - np.sin(0.5*t))**2) / 2)
    source_2 = np.exp(-((x + 2)**2 + (y - 1)**2 + (z + 1)**2) / 3)
    source_3 = np.exp(-((x - 3)**2 + (y + 2)**2 + (z - 2)**2) / 1.5)
    wave = np.sin(2 * np.sqrt(x**2 + y**2 + z**2) - 1.5*t)
    pattern = np.sin(1.5*x + t) * np.cos(1.2*y - 0.5*t)

    return 20 + 55*source_1 + 35*source_2 + 25*source_3 + 8*wave + 5*pattern

def pressure_field(x, y, z, t):
    wave = np.sin(1.5*x - t) * np.cos(1.2*y + 0.5*t)
    source = np.exp(-((x + np.sin(t))**2 + (y - 2)**2 + z**2) / 4)
    pattern = np.sin(x*y + t) * np.cos(z - t)

    return 101325 + 2500*wave + 1800*source + 700*pattern

def velocity_field(x, y, z, t):
    source_1 = np.exp(-((x - 2)**2 + (y + 1)**2 + z**2) / 5)
    source_2 = np.exp(-((x + 2)**2 + (y - 2)**2 + z**2) / 4)

    vx = 0.8*np.sin(y + 0.5*t) + 0.5*np.cos(x - t) + 1.5*source_1 - 0.8*source_2 + 0.2*np.sin(x*y)
    vy = 0.8*np.cos(x - 0.4*t) + 0.5*np.sin(y + t) - 1.2*source_1 + 1.5*source_2 + 0.2*np.cos(x*y)
    vz = np.sin(x - t)*np.cos(y + z) + 0.5*np.sin(2*z + t)

    return vx, vy, vz

def density_field(x, y, z, t):
    return (
        1
        + 0.8*np.exp(-((x + 2)**2 + (y - 1)**2 + z**2) / 4)
        + 0.6*np.exp(-((x - 2)**2 + (y + 2)**2 + (z - 1)**2) / 2)
        + 0.2*np.sin(x + t)*np.cos(y - z)
    )

def concentration_field(x, y, z, t):
    return (
        10
        + 40*np.exp(-((x - 2*np.sin(t))**2 + (y - 1)**2 + z**2) / 2)
        + 25*np.exp(-((x + 2)**2 + (y + 2)**2 + (z - 2)**2) / 3)
        + 5*np.sin(x + y + t)*np.cos(z - t)
    )

gx = X.ravel()
gy = Y.ravel()
gz = Z.ravel()

frames = []

for t0 in grid_times:
    t = np.full(gx.shape, t0)

    vx, vy, vz = velocity_field(gx, gy, gz, t)

    frames.append(pd.DataFrame({
        "x": gx,
        "y": gy,
        "z": gz,
        "time": t,
        "temperature": temperature_field(gx, gy, gz, t),
        "pressure": pressure_field(gx, gy, gz, t),
        "velocity_x": vx,
        "velocity_y": vy,
        "velocity_z": vz,
        "speed": np.sqrt(vx**2 + vy**2 + vz**2),
        "density": density_field(gx, gy, gz, t),
        "concentration": concentration_field(gx, gy, gz, t)
    }))

df = pd.concat(frames, ignore_index=True)

df.to_csv("../data/spatial_grid.csv", index=False)

print(df.head())
print(f"Generated {len(df)} points")

