File size: 6,303 Bytes
40b99fb | 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | from __future__ import annotations
import sys
from collections.abc import Mapping
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import torch
import yaml
from matplotlib.patches import Polygon
PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from data_utils import ( # noqa: E402
build_evaluation_points,
combined_coordinates,
combined_exact_solution,
load_mat_data,
)
from model.xpinn import XPINNPoisson2D # noqa: E402
DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"
def load_config(path: Path) -> dict:
with path.open("r", encoding="utf-8") as stream:
config = yaml.safe_load(stream)
if not isinstance(config, dict) or "root" not in config:
raise ValueError(f"config must contain a 'root' mapping: {path}")
return config["root"]
def project_path(value: str | Path) -> Path:
path = Path(value).expanduser()
return path if path.is_absolute() else PROJECT_ROOT / path
def resolve_device(requested: str) -> torch.device:
if requested == "auto":
return torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = torch.device(requested)
if device.type == "cuda" and not torch.cuda.is_available():
raise RuntimeError("CUDA/DCU was requested but torch.cuda.is_available() is false")
return device
def resolve_dtype(name: str) -> torch.dtype:
try:
return {"float32": torch.float32, "float64": torch.float64}[name]
except KeyError as error:
raise ValueError(f"unsupported dtype: {name}") from error
def load_model(
checkpoint_path: Path,
fallback_model_config: dict,
device: torch.device,
dtype: torch.dtype,
) -> XPINNPoisson2D:
if not checkpoint_path.is_file():
raise FileNotFoundError(
f"checkpoint not found: {checkpoint_path}. Run scripts/train.py first."
)
checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
if not isinstance(checkpoint, Mapping):
raise ValueError(f"invalid XPINN checkpoint: {checkpoint_path}")
if "model_state" in checkpoint:
state = checkpoint["model_state"]
model_config = checkpoint.get("model_config", fallback_model_config)
elif checkpoint and all(torch.is_tensor(value) for value in checkpoint.values()):
state = checkpoint
model_config = fallback_model_config
else:
raise ValueError(f"checkpoint contains no model state: {checkpoint_path}")
model = XPINNPoisson2D(model_config, dtype=dtype).to(device=device, dtype=dtype)
model.load_state_dict(state, strict=True)
model.eval()
return model
def predict(
model: XPINNPoisson2D, evaluation_points: dict[str, torch.Tensor]
) -> np.ndarray:
with torch.no_grad():
predictions = model.predict(
evaluation_points["xy1"],
evaluation_points["xy2"],
evaluation_points["xy3"],
)
return torch.cat(predictions).cpu().numpy().reshape(-1)
def mask_polygon(data: Mapping) -> np.ndarray:
boundary_x = np.asarray(data["xb"]).reshape(-1)
boundary_y = np.asarray(data["yb"]).reshape(-1)
return np.vstack(
(
np.column_stack((boundary_x, boundary_y)),
np.array(
[
[1.8, boundary_y[-1]],
[1.8, -1.7],
[-1.6, -1.7],
[-1.6, 1.55],
[1.8, 1.55],
[1.8, boundary_y[-1]],
]
),
np.array([[boundary_x[-1], boundary_y[-1]]]),
)
)
def save_figure(
data: Mapping,
exact: np.ndarray,
prediction: np.ndarray,
output_path: Path,
) -> None:
x, y = combined_coordinates(data)
if exact.size != x.size or prediction.size != x.size:
raise ValueError("plot coordinates, exact values, and predictions must have equal size")
triangulation = tri.Triangulation(x, y)
polygon = mask_polygon(data)
fields = (
("Exact", exact),
("XPINN", prediction),
("Absolute error", np.abs(exact - prediction)),
)
figure, axes = plt.subplots(1, 3, figsize=(18, 5))
for axis, (title, field) in zip(axes, fields, strict=True):
contour = axis.tricontourf(triangulation, field, 100, cmap="jet")
axis.add_patch(
Polygon(polygon, closed=True, facecolor="white", edgecolor="white")
)
axis.plot(data["xi1"].reshape(-1), data["yi1"].reshape(-1), "w-", linewidth=0.5)
axis.plot(data["xi2"].reshape(-1), data["yi2"].reshape(-1), "w-", linewidth=0.5)
axis.set_title(title)
axis.set_xlabel("x")
axis.set_ylabel("y")
axis.set_aspect("equal")
figure.colorbar(contour, ax=axis)
figure.tight_layout()
figure.savefig(output_path, dpi=150)
plt.close(figure)
def main() -> None:
config_path = DEFAULT_CONFIG.resolve()
config = load_config(config_path)
common = config["common"]
device = resolve_device(str(common["device"]))
dtype = resolve_dtype(str(common["dtype"]))
data_path = project_path(config["data"]["mat_file"])
weight_dir = project_path(common["weight_dir"])
result_dir = project_path(common["result_dir"])
checkpoint_path = weight_dir / config["training"]["checkpoint_name"]
output_path = result_dir / config["inference"]["figure_name"]
result_dir.mkdir(parents=True, exist_ok=True)
print(f"Config: {config_path}")
print(f"Data: {data_path}")
print(f"Checkpoint: {checkpoint_path}")
print(f"Device: {device}")
data = load_mat_data(data_path)
model = load_model(checkpoint_path, config["model"], device, dtype)
evaluation_points = build_evaluation_points(data, device, dtype)
prediction = predict(model, evaluation_points)
exact = combined_exact_solution(data)
relative_l2 = float(
np.linalg.norm(exact - prediction) / np.linalg.norm(exact)
)
save_figure(data, exact, prediction, output_path)
print(f"Relative L2={relative_l2:.6e}")
print(f"Plot: {output_path}")
if __name__ == "__main__":
main()
|