File size: 3,212 Bytes
258a5b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Plot a single sample from the 2D Poisson equation dataset.

Visualizes the forcing function, solution field, and boundary conditions
for a single randomly generated Poisson boundary value problem.
"""

import numpy as np
import matplotlib.pyplot as plt
from dataset import PoissonDataset


def plot_poisson_sample(sample, save_path="sample_plot.png"):
    """
    Plot a single sample from the 2D Poisson equation dataset.

    Creates a 3-panel visualization showing:
    1. Forcing function f(x,y)
    2. Solution field u(x,y)
    3. Boundary conditions
    """
    fig = plt.figure(figsize=(15, 5))
    ax1 = plt.subplot(1, 3, 1)
    ax2 = plt.subplot(1, 3, 2)
    ax3 = plt.subplot(1, 3, 3)

    # Extract data from dataset return dictionary
    X, Y = sample["spatial_coordinates"]  # Shape: (2, Nx, Ny)
    solution = sample["solution_field"]  # Shape: (Nx, Ny)
    forcing = sample["forcing_function"]  # Shape: (Nx, Ny)
    bc_bottom = sample["boundary_condition_bottom"]  # Shape: (Nx,)
    bc_top_grad = sample["boundary_condition_top_gradient"]  # Shape: (Nx,)

    # Plot 1: Forcing function f(x,y)
    im1 = ax1.pcolormesh(
        X, Y, forcing, cmap="RdBu_r", shading="gouraud", rasterized=True
    )
    ax1.set_xlabel("x")
    ax1.set_ylabel("y")
    ax1.set_title("Forcing Function f(x,y)")
    ax1.set_aspect("equal")
    plt.colorbar(im1, ax=ax1, label="f(x,y)")

    # Plot 2: Solution field u(x,y)
    im2 = ax2.pcolormesh(
        X, Y, solution, cmap="viridis", shading="gouraud", rasterized=True
    )
    ax2.set_xlabel("x")
    ax2.set_ylabel("y")
    ax2.set_title("Solution u(x,y)")
    ax2.set_aspect("equal")
    plt.colorbar(im2, ax=ax2, label="u(x,y)")

    # Plot 3: Boundary conditions
    # X has shape (Nx, Ny), we want x-coordinates along boundaries
    x_bottom = X[:, 0]  # x-coordinates along bottom boundary (y=0)
    x_top = X[:, -1]  # x-coordinates along top boundary (y=Ly)

    # Flatten boundary condition arrays if needed
    bc_bottom_flat = bc_bottom.ravel() if bc_bottom.ndim > 1 else bc_bottom
    bc_top_grad_flat = bc_top_grad.ravel() if bc_top_grad.ndim > 1 else bc_top_grad

    ax3.plot(x_bottom, bc_bottom_flat, "b-", linewidth=2, label="u(x,0) = g(x)")
    ax3.plot(x_top, bc_top_grad_flat, "r--", linewidth=2, label="∂u/∂y(x,Ly) = h(x)")
    ax3.set_xlabel("x")
    ax3.set_ylabel("Boundary values")
    ax3.set_title("Boundary Conditions")
    ax3.legend()
    ax3.grid(True, alpha=0.3)

    plt.tight_layout()
    plt.savefig(save_path, dpi=200, bbox_inches="tight")
    plt.close()

    print(f"Sample visualization saved to {save_path}")


if __name__ == "__main__":
    # Set random seed for reproducibility
    np.random.seed(42)

    # Create dataset instance
    dataset = PoissonDataset()

    # Generate a single sample
    dataset_iter = iter(dataset)
    sample = next(dataset_iter)
    sample = next(dataset_iter)

    print("Sample keys:", list(sample.keys()))
    for key, value in sample.items():
        if hasattr(value, "shape"):
            print(f"{key}: shape {value.shape}")
        else:
            print(f"{key}: {type(value)} - {value}")

    # Plot the sample
    plot_poisson_sample(sample)