File size: 4,488 Bytes
a2efc8e |
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 |
#!/usr/bin/env python3
"""
Plot a single sample from the Chladni 2D dataset.
Visualizes the forcing function and displacement response patterns
for a single Chladni plate sample using imshow plots.
"""
import numpy as np
import matplotlib.pyplot as plt
from dataset import Chladni2DDataset
def plot_chladni_sample(sample, save_path="sample_plot.png"):
"""
Plot a single sample from the Chladni 2D dataset.
Creates side-by-side imshow plots of the forcing function and
displacement response patterns. The forcing function shows the
spatial distribution of applied forces, while the displacement
response shows the resulting vibration pattern of the plate.
Args:
sample (dict): Dictionary returned by Chladni2DDataset containing
forcing patterns, displacement responses, and metadata
save_path (str): Path to save the plot image (default: "sample_plot.png")
Example:
>>> dataset = Chladni2DDataset()
>>> sample = next(iter(dataset))
>>> plot_chladni_sample(sample, "my_plot.png")
Saved plot: my_plot.png
"""
# Extract data
forcing = sample["forcing"] # 2D forcing function
displacement = sample["displacement"] # 2D displacement response
frequency = sample["frequency"]
# Create figure with subplots
fig, axs = plt.subplots(1, 2, figsize=(15, 6), facecolor="white")
# Plot 1: Forcing function S
ax1 = axs[0]
ax1.set_facecolor("white")
im1 = ax1.imshow(
forcing.T,
extent=[0, sample["plate_length_x"], 0, sample["plate_length_y"]],
origin='lower',
cmap="viridis",
aspect='equal'
)
ax1.set_xlabel("X axis (m)", fontsize=14)
ax1.set_ylabel("Y axis (m)", fontsize=14)
ax1.set_title("Forcing Function S(x,y)", fontsize=16, fontweight="bold")
ax1.tick_params(labelsize=12)
ax1.grid(True, alpha=0.3)
# Add colorbar with proper labels
cbar1 = plt.colorbar(im1, ax=ax1)
cbar1.set_label("Forcing Amplitude", rotation=270, labelpad=25, fontsize=14)
cbar1.ax.tick_params(labelsize=12)
# Plot 2: Displacement response Z
ax2 = axs[1]
ax2.set_facecolor("white")
im2 = ax2.imshow(
displacement.T,
extent=[0, sample["plate_length_x"], 0, sample["plate_length_y"]],
origin='lower',
cmap="RdBu_r",
aspect='equal'
)
ax2.set_xlabel("X axis (m)", fontsize=14)
ax2.set_ylabel("Y axis (m)", fontsize=14)
ax2.set_title(
f"Displacement Response Z(x,y), f = {frequency:.2f} Hz",
fontsize=16,
fontweight="bold",
)
ax2.tick_params(labelsize=12)
ax2.grid(True, alpha=0.3)
# Add colorbar
cbar2 = plt.colorbar(im2, ax=ax2)
cbar2.set_label("Displacement Amplitude", rotation=270, labelpad=25, fontsize=14)
cbar2.ax.tick_params(labelsize=12)
plt.tight_layout()
# Save the plot
plt.savefig(save_path, facecolor="white", dpi=150, bbox_inches="tight")
print(f"Saved plot: {save_path}")
plt.show()
plt.close(fig)
if __name__ == "__main__":
"""
Generate and visualize a sample from the Chladni 2D dataset.
This script creates a dataset instance, generates a single sample,
prints information about the sample structure, and creates a
visualization showing both the forcing pattern and displacement response.
"""
# Set random seed for reproducibility
np.random.seed(42)
print("Chladni 2D Dataset Visualization")
print("=" * 35)
# Create dataset instance
dataset = Chladni2DDataset(numPoints=50, n_range=10, m_range=10)
print(f"Dataset configuration:")
print(f" Grid resolution: {dataset.numPoints}x{dataset.numPoints}")
print(f" Modal basis: {dataset.n_range}x{dataset.m_range}")
print(f" Plate dimensions: {dataset.L:.3f}x{dataset.M:.3f} m")
print(f" Driving frequency: {dataset.omega/(2*np.pi):.1f} Hz")
# Generate a single sample
dataset_iter = iter(dataset)
sample = next(dataset_iter)
sample = next(dataset_iter)
print(f"\nSample structure:")
print("-" * 20)
for key, value in sample.items():
if hasattr(value, 'shape'):
print(f" {key:20s}: {str(value.shape):15s}")
else:
print(f" {key:20s}: {type(value).__name__} = {value}")
# Plot the sample
print(f"\nGenerating visualization...")
plot_chladni_sample(sample)
print("Visualization complete!") |