| 1 | """12.2 은닉 유체 메카니즘(HFM) - 평가 |
| 2 | |
| 3 | train.py 가 저장한 가중치를 불러와 모든 시각에서 c, u, v, p 의 상대 오차를 재고, |
| 4 | 마지막 시각의 정답과 예측을 나란히 그린다. u, v, p 는 학습 때 한 번도 보여 주지 않은 값이다. |
| 5 | |
| 6 | 실행: uv run python ch12_scientific/hfm/evaluation.py (먼저 train.py 를 실행해 둔다) |
| 7 | """ |
| 8 | |
| 9 | # %% |
| 10 | from pathlib import Path |
| 11 | |
| 12 | import matplotlib.pyplot as plt |
| 13 | import torch |
| 14 | from mat_to_numpy import snapshot |
| 15 | from utils import PINN, field_errors |
| 16 | |
| 17 | from ptintro import save_fig |
| 18 | |
| 19 | FIELD_NAMES = "cuvp" # 모델 출력의 열 순서 |
| 20 | |
| 21 | |
| 22 | # %% |
| 23 | def load_model(path, device): |
| 24 | """저장된 가중치로 PINN 을 복원한다. |
| 25 | |
| 26 | 입력 정규화 통계(mean, std)도 가중치 파일에 들어 있어서 학습 데이터를 다시 볼 필요가 없다. |
| 27 | """ |
| 28 | if not Path(path).exists(): |
| 29 | raise SystemExit( |
| 30 | f"가중치 파일이 없습니다: {path}\n" |
| 31 | "먼저 `uv run python ch12_scientific/hfm/train.py` 로 학습하세요." |
| 32 | ) |
| 33 | model = PINN().to(device) |
| 34 | model.load_state_dict(torch.load(path, map_location=device, weights_only=True)) |
| 35 | return model.eval() |
| 36 | |
| 37 | |
| 38 | # %% |
| 39 | def errors_over_time(model, fields): |
| 40 | """모든 시각 스냅숏에서 상대 오차를 잰다. {물리량: [시각별 오차]} 를 돌려준다.""" |
| 41 | times = fields["T"][0] |
| 42 | history = {name: [] for name in FIELD_NAMES} |
| 43 | for index, t in enumerate(times): |
| 44 | inputs, targets = snapshot(fields, index) |
| 45 | errors, _ = field_errors(model, inputs, targets) |
| 46 | for name, value in errors.items(): |
| 47 | history[name].append(value) |
| 48 | line = " ".join(f"{name}: {value:.3f}" for name, value in errors.items()) |
| 49 | print(f"[t = {t:5.2f}] 상대 오차 {line}") |
| 50 | print("평균 상대 오차 " + " ".join(f"{k}: {sum(v) / len(v):.3f}" for k, v in history.items())) |
| 51 | return history |
| 52 | |
| 53 | |
| 54 | def plot_error_graph(times, history): |
| 55 | fig, axes = plt.subplots(2, 2, figsize=(9, 7), sharex=True) |
| 56 | fig.suptitle("Relative L2 error") |
| 57 | for ax, name in zip(axes.flat, FIELD_NAMES): |
| 58 | ax.plot(times, history[name], "o-") |
| 59 | ax.set_title(f"{name}(t, x, y)") |
| 60 | for ax in axes[1]: |
| 61 | ax.set_xlabel("time") |
| 62 | save_fig("ch12", "hfm_error_graph") |
| 63 | |
| 64 | |
| 65 | # %% |
| 66 | def plot_snapshot(model, fields, index=-1, max_points=30_000): |
| 67 | """한 시각의 정답(reference)과 예측(prediction)을 물리량별로 나란히 그린다.""" |
| 68 | inputs, targets = snapshot(fields, index) |
| 69 | _, pred = field_errors(model, inputs, targets) |
| 70 | keep = torch.randperm(len(inputs))[:max_points] # 산점도가 너무 무겁지 않게 일부만 그린다 |
| 71 | x, y = inputs[keep, 1].numpy(), inputs[keep, 2].numpy() |
| 72 | |
| 73 | fig, axes = plt.subplots(2, 4, figsize=(20, 9)) |
| 74 | for i, name in enumerate("cpuv"): |
| 75 | column = FIELD_NAMES.index(name) |
| 76 | truth, guess = targets[keep, column].numpy(), pred[keep, column].numpy() |
| 77 | row, col = divmod(i, 2) |
| 78 | for ax, values, kind in ( |
| 79 | (axes[row, 2 * col], truth, "reference"), |
| 80 | (axes[row, 2 * col + 1], guess, "prediction"), |
| 81 | ): |
| 82 | sc = ax.scatter(x, y, c=values, cmap="jet", s=2, vmin=truth.min(), vmax=truth.max()) |
| 83 | ax.set_title(f"{name} {kind}", fontsize=18) |
| 84 | ax.set_aspect("equal") |
| 85 | fig.colorbar(sc, ax=ax, shrink=0.7) |
| 86 | fig.suptitle(f"t = {fields['T'][0, index]:.2f}", fontsize=18) |
| 87 | save_fig("ch12", "hfm_last_time_prediction") |