File size: 6,588 Bytes
74c72c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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