FSI-pde-dataset / plotting.py
ashiq24's picture
added dataloader
74c72c1
from fsi_reader import FsiDataReader
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import Triangulation
from matplotlib.animation import FuncAnimation
from scipy.interpolate import griddata
def single_plot(data, mesh_points):
data = np.squeeze(data) # Shape becomes (1317,)
print(data.shape)
print(mesh_points.shape)
x, y = mesh_points[:, 0], mesh_points[:, 1]
# Create figure with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6),
gridspec_kw={'width_ratios': [1, 1.2]})
# Approach 1: Triangulation-based contour plot
tri = Triangulation(x, y)
contour = ax1.tricontourf(tri, data, levels=40, cmap='viridis')
fig.colorbar(contour, ax=ax1, label='Value', shrink=0.3)
ax1.set_title('Contour Plot of Field Data')
ax1.set_aspect('equal')
# Approach 2: Scatter plot with interpolated background
grid_x, grid_y = np.mgrid[x.min():x.max():100j, y.min():y.max():100j]
grid_z = griddata((x, y), data, (grid_x, grid_y), method='cubic')
im = ax2.imshow(grid_z.T, origin='lower', extent=[x.min(), x.max(),
y.min(), y.max()], cmap='plasma')
ax2.scatter(x, y, c=data, edgecolor='k', lw=0.3, cmap='plasma', s=15)
fig.colorbar(im, ax=ax2, label='Interpolated Value', shrink=0.3)
ax2.set_title('Interpolated Surface with Sample Points')
# Common formatting
for ax in (ax1, ax2):
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
def create_field_animation(data_frames, mesh_frames, interval=100, save_path=None):
"""
Create an animation of time-varying 2D field data on a mesh.
Parameters:
-----------
data_frames : list of arrays
List of data arrays for each time frame (each with shape [1, 1317, 1] or similar)
mesh_frames : list of arrays or single array
Either a list of mesh coordinates for each frame or a single fixed mesh
interval : int
Delay between animation frames in milliseconds
save_path : str, optional
Path to save the GIF animation
"""
plt.rcParams.update({
'font.size': 20, # Base font size
'axes.titlesize': 20, # Title font size
'axes.labelsize': 20, # Axis label size
'xtick.labelsize': 20, # X-tick label size
'ytick.labelsize': 18, # Y-tick label size
'figure.titlesize': 22 # Super title size (if used)
})
# Determine if mesh is fixed or time-varying
mesh_varying = isinstance(mesh_frames, list)
# Get initial mesh and data
mesh_initial = mesh_frames[0] if mesh_varying else mesh_frames
data_initial = np.squeeze(data_frames[0])
# Extract coordinates
x, y = mesh_initial[:, 0], mesh_initial[:, 1]
# Create figure
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(50, 10),
gridspec_kw={'width_ratios': [1.5, 1.5]})
# Calculate global min/max for consistent colorbars
all_data = np.concatenate([np.squeeze(frame) for frame in data_frames])
vmin, vmax = all_data.min(), all_data.max()
# Create initial triangulation
tri_initial = Triangulation(x, y)
# Set up first subplot - contour
contour = ax1.tricontourf(tri_initial, data_initial, levels=40, cmap='viridis',
vmin=vmin, vmax=vmax)
# Add contour lines for better visibility
contour_lines = ax1.tricontour(tri_initial, data_initial, levels=15,
colors='black', linewidths=0.5, alpha=0.7)
fig.colorbar(contour, ax=ax1, label='Value', shrink=0.3)
ax1.set_title('Contour Plot of Field Data')
ax1.set_aspect('equal')
# Set up second subplot - interpolated surface with scatter points
grid_x, grid_y = np.mgrid[x.min():x.max():100j, y.min():y.max():100j]
grid_z = griddata((x, y), data_initial, (grid_x, grid_y), method='cubic')
im = ax2.imshow(grid_z.T, origin='lower', extent=[x.min(), x.max(),
y.min(), y.max()],
cmap='plasma', vmin=vmin, vmax=vmax)
scat = ax2.scatter(x, y, c=data_initial, edgecolor='k', lw=0.3,
cmap='plasma', s=15, vmin=vmin, vmax=vmax)
fig.colorbar(im, ax=ax2, label='Interpolated Value', shrink=0.3)
ax2.set_title('Interpolated Surface with Sample Points')
# Common formatting
for ax in (ax1, ax2):
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.grid(True, alpha=0.3)
# Add frame counter
time_text = ax1.text(0.02, 0.98, '', transform=ax1.transAxes,
fontsize=10, va='top', ha='left')
plt.tight_layout()
# Update function for animation
def update(frame):
# Get current data
data = np.squeeze(data_frames[frame])
# Get current mesh if varying
if mesh_varying:
mesh = mesh_frames[frame]
x, y = mesh[:, 0], mesh[:, 1]
tri = Triangulation(x, y)
else:
mesh = mesh_frames
x, y = mesh[:, 0], mesh[:, 1]
tri = tri_initial
# Update contour plot
for c in ax1.collections:
c.remove()
new_contour = ax1.tricontourf(tri, data, levels=40, cmap='viridis',
vmin=vmin, vmax=vmax)
new_lines = ax1.tricontour(tri, data, levels=15, colors='black',
linewidths=0.5, alpha=0.7)
# Update interpolated surface
grid_z = griddata((x, y), data, (grid_x, grid_y), method='cubic')
im.set_array(grid_z.T)
# Update scatter points
scat.set_offsets(mesh)
scat.set_array(data)
# Update frame counter
time_text.set_text(f'Frame: {frame+1}/{len(data_frames)}')
return [new_contour, new_lines, im, scat, time_text]
# Create animation
anim = FuncAnimation(fig, update, frames=len(data_frames),
interval=interval, blit=False)
# Save if path provided
if save_path:
print(f"Saving animation to {save_path}...")
if save_path.endswith('.gif'):
anim.save(save_path, writer='pillow', dpi=150)
else:
anim.save(save_path, writer='ffmpeg', dpi=150)
return anim