|
| 1 | +import torch |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +from typing import Optional, Union, List |
| 4 | +import numpy as np |
| 5 | + |
| 6 | + |
| 7 | +def plot_result( |
| 8 | + x: Union[torch.Tensor, List[float], "np.ndarray"], |
| 9 | + y: Union[torch.Tensor, List[float], "np.ndarray"], |
| 10 | + x_data: Union[torch.Tensor, List[float], "np.ndarray"], |
| 11 | + y_data: Union[torch.Tensor, List[float], "np.ndarray"], |
| 12 | + yh: Union[torch.Tensor, List[float], "np.ndarray"], |
| 13 | + current_step: int, |
| 14 | + xp: Optional[Union[torch.Tensor, List[float], "np.ndarray"]] = None, |
| 15 | + figure_size: tuple = (8, 4), |
| 16 | + xlims: Optional[tuple] = (-1.25, 31.05), |
| 17 | + ylims: Optional[tuple] = (-0.65, 2.25), |
| 18 | + show_plot: bool = True, |
| 19 | + save_path: Optional[str] = None, |
| 20 | +) -> None: |
| 21 | + """Plots the results of a PINN training, comparing predictions with exact solutions. |
| 22 | +
|
| 23 | + Displays the neural network's prediction, the exact solution, training data points, |
| 24 | + and optionally, collocation points. |
| 25 | +
|
| 26 | + Args: |
| 27 | + x (Union[torch.Tensor, List[float], "np.ndarray"]): |
| 28 | + The x-coordinates for the continuous plots (e.g., time points). |
| 29 | + y (Union[torch.Tensor, List[float], "np.ndarray"]): |
| 30 | + The y-coordinates of the exact solution corresponding to `x`. |
| 31 | + x_data (Union[torch.Tensor, List[float], "np.ndarray"]): |
| 32 | + The x-coordinates of the training data points. |
| 33 | + y_data (Union[torch.Tensor, List[float], "np.ndarray"]): |
| 34 | + The y-coordinates of the training data points. |
| 35 | + yh (Union[torch.Tensor, List[float], "np.ndarray"]): |
| 36 | + The y-coordinates of the neural network's prediction corresponding to `x`. |
| 37 | + current_step (int): |
| 38 | + The current training step or epoch number to display on the plot. |
| 39 | + xp (Optional[Union[torch.Tensor, List[float], "np.ndarray"]], optional): |
| 40 | + The x-coordinates of the collocation points. If None, these are not plotted. |
| 41 | + Defaults to None. |
| 42 | + figure_size (tuple, optional): |
| 43 | + Size of the matplotlib figure. Defaults to (8, 4). |
| 44 | + xlims (Optional[tuple], optional): |
| 45 | + Tuple defining the x-axis limits. If None, matplotlib's default is used. |
| 46 | + Defaults to (-1.25, 31.05). |
| 47 | + ylims (Optional[tuple], optional): |
| 48 | + Tuple defining the y-axis limits. If None, matplotlib's default is used. |
| 49 | + Defaults to (-0.65, 2.25). |
| 50 | + show_plot (bool, optional): |
| 51 | + Whether to display the plot using `plt.show()`. Defaults to True. |
| 52 | + save_path (Optional[str], optional): |
| 53 | + If provided, the path to save the figure to. If None, the figure is not saved. |
| 54 | + Defaults to None. |
| 55 | +
|
| 56 | + Examples: |
| 57 | + >>> from spotpython.pinns.plot.result import plot_result |
| 58 | + >>> import torch |
| 59 | + >>> import numpy as np |
| 60 | + >>> # Generate some dummy data |
| 61 | + >>> x_plot = torch.linspace(0, 30, 100) |
| 62 | + >>> y_exact = torch.sin(x_plot / 5) |
| 63 | + >>> y_pred = torch.sin(x_plot / 5 + 0.1) # Slightly off prediction |
| 64 | + >>> x_train = torch.rand(10) * 30 |
| 65 | + >>> y_train = torch.sin(x_train / 5) |
| 66 | + >>> collocation_points = torch.rand(50) * 30 |
| 67 | + >>> current_training_step = 1000 |
| 68 | + >>> # plot_result( # This would show a plot if run in an interactive environment |
| 69 | + ... # x_plot, y_exact, x_train, y_train, y_pred, |
| 70 | + ... # current_training_step, xp=collocation_points, |
| 71 | + ... # show_plot=False, save_path="temp_plot.png" |
| 72 | + ... # ) |
| 73 | + >>> # To avoid actual plotting in doctest, we'll just confirm it runs |
| 74 | + >>> try: |
| 75 | + ... plot_result( |
| 76 | + ... x_plot.numpy(), y_exact.numpy(), x_train.numpy(), y_train.numpy(), y_pred.numpy(), |
| 77 | + ... current_training_step, xp=collocation_points.numpy(), |
| 78 | + ... show_plot=False |
| 79 | + ... ) |
| 80 | + ... except Exception as e: |
| 81 | + ... print(f"Plotting failed: {e}") |
| 82 | +
|
| 83 | + Note: |
| 84 | + If using PyTorch tensors as input, they will be detached and moved to CPU |
| 85 | + before plotting. Consider converting to NumPy arrays beforehand if preferred. |
| 86 | +
|
| 87 | + References: |
| 88 | + - Solving differential equations using physics informed deep learning: a hand-on tutorial with benchmark tests. Baty, Hubert and Baty, Leo. April 2023. |
| 89 | + """ |
| 90 | + |
| 91 | + # Convert tensors to numpy arrays for plotting if they are tensors |
| 92 | + def to_numpy(data): |
| 93 | + if isinstance(data, torch.Tensor): |
| 94 | + return data.detach().cpu().numpy() |
| 95 | + return data |
| 96 | + |
| 97 | + x_np = to_numpy(x) |
| 98 | + y_np = to_numpy(y) |
| 99 | + x_data_np = to_numpy(x_data) |
| 100 | + y_data_np = to_numpy(y_data) |
| 101 | + yh_np = to_numpy(yh) |
| 102 | + if xp is not None: |
| 103 | + xp_np = to_numpy(xp) |
| 104 | + else: |
| 105 | + xp_np = None |
| 106 | + |
| 107 | + plt.figure(figsize=figure_size) |
| 108 | + plt.plot(x_np, yh_np, color="tab:red", linewidth=2, alpha=0.8, label="NN prediction") |
| 109 | + plt.plot(x_np, y_np, color="blue", linewidth=2, alpha=0.8, linestyle="--", label="Exact solution") |
| 110 | + plt.scatter(x_data_np, y_data_np, s=60, color="tab:red", alpha=0.4, label="Training data") |
| 111 | + |
| 112 | + if xp_np is not None: |
| 113 | + # Create y-values for collocation points at y=0 or a specified level |
| 114 | + # Original code used -0*torch.ones_like(xp), which is just zeros. |
| 115 | + xp_y_values = np.zeros_like(xp_np) |
| 116 | + plt.scatter(xp_np, xp_y_values, s=30, color="tab:green", alpha=0.4, label="Collocation points") |
| 117 | + |
| 118 | + legend_handle = plt.legend(loc=(0.67, 0.62), frameon=False, fontsize="large") |
| 119 | + plt.setp(legend_handle.get_texts(), color="k") |
| 120 | + |
| 121 | + if xlims: |
| 122 | + plt.xlim(xlims) |
| 123 | + if ylims: |
| 124 | + plt.ylim(ylims) |
| 125 | + |
| 126 | + plt.text(0.05, 0.95, f"Training step: {current_step}", fontsize="xx-large", color="k", transform=plt.gca().transAxes, ha="left", va="top") |
| 127 | + |
| 128 | + plt.ylabel("y", fontsize="xx-large") |
| 129 | + plt.xlabel("Time", fontsize="xx-large") |
| 130 | + plt.axis("on") |
| 131 | + plt.grid(True, linestyle="--", alpha=0.7) |
| 132 | + |
| 133 | + if save_path: |
| 134 | + plt.savefig(save_path, dpi=300, bbox_inches="tight") |
| 135 | + |
| 136 | + if show_plot: |
| 137 | + plt.show() |
| 138 | + else: |
| 139 | + plt.close() # Close the figure if not shown to free memory |
0 commit comments