Datasets:
Languages:
English
Size:
100K<n<1M
Tags:
additive-manufacturing
laser-powder-bed-fusion
smoothed-particle-hydrodynamics
melt-pool
keyhole
physics-simulation
DOI:
License:
| """ | |
| Example 3 — Unconditional VAE: Melt-Pool Side Profiles | |
| Trains a minimal convolutional VAE on side-profile images and generates | |
| new samples. No conditioning on process parameters. | |
| Images are loaded from frames/side/ — already border-recolored by the | |
| dataset pipeline. Only frames labeled Keyhole or Conduction are used | |
| (Initial Emptiness and Forming Phase are excluded). | |
| Architecture: 3×32×64 → latent z (dim=16) → 3×32×64 | |
| Set MAX_IMAGES to limit dataset size for a quick reviewer run. | |
| Set MAX_IMAGES = None to use all available images. | |
| Outputs saved to runs/generation_<timestamp>/: | |
| generation_epoch_NNN.png — sample grid every SAMPLE_EVERY epochs | |
| generation_loss.png — training loss curve | |
| generation_reconstructions.png | |
| generation_samples.png | |
| run.log | |
| This is a proof-of-concept, not a benchmark. | |
| """ | |
| import csv | |
| import logging | |
| import sys | |
| from datetime import datetime | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| from torch.utils.data import DataLoader, TensorDataset | |
| from PIL import Image as PILImage | |
| import matplotlib.pyplot as plt | |
| # ------------------------------------------------------------------ | |
| # Config ← edit DATA_DIRS to point at your data directories | |
| # ------------------------------------------------------------------ | |
| DATA_DIRS = [ | |
| Path(__file__).parent.parent / "rnl" / "final_data_processed", | |
| Path(__file__).parent.parent / "rnl" / "lrz_data_new_format", | |
| ] | |
| OUT_ROOT = Path(__file__).parent.parent / "runs" | |
| MAX_IMAGES = 500 # reviewer-friendly cap (None = all images) | |
| IMG_W = 64 | |
| IMG_H = 32 | |
| LATENT_DIM = 16 | |
| BATCH_SIZE = 64 | |
| EPOCHS = 50 | |
| LR = 1e-3 | |
| SAMPLE_EVERY = 10 | |
| RED_WEIGHT = 50.0 | |
| RANDOM_SEED = 42 | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| VALID_LABELS = {"Keyhole", "Conduction"} | |
| # ------------------------------------------------------------------ | |
| # Logger | |
| # ------------------------------------------------------------------ | |
| class _ColorFormatter(logging.Formatter): | |
| _COLORS = {logging.INFO: "\033[32m", logging.WARNING: "\033[33m", logging.ERROR: "\033[31m"} | |
| _RESET = "\033[0m"; _BOLD = "\033[1m" | |
| def format(self, record): | |
| color = self._COLORS.get(record.levelno, self._RESET) | |
| t = self.formatTime(record, "%H:%M:%S") | |
| return f"{self._BOLD}{t}{self._RESET} {color}{record.levelname:<8}{self._RESET} {record.getMessage()}" | |
| run_id = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| out_dir = OUT_ROOT / f"generation_{run_id}" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| log = logging.getLogger("vae") | |
| log.setLevel(logging.DEBUG) | |
| _ch = logging.StreamHandler(sys.stdout); _ch.setFormatter(_ColorFormatter()); log.addHandler(_ch) | |
| _fh = logging.FileHandler(out_dir / "run.log") | |
| _fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S")) | |
| log.addHandler(_fh) | |
| log.info("=" * 60) | |
| log.info(f"Run ID : {run_id}") | |
| log.info(f"Results : {out_dir}") | |
| log.info(f"Device : {DEVICE}") | |
| log.info(f"Resolution: {IMG_W}×{IMG_H}") | |
| log.info("=" * 60) | |
| # ------------------------------------------------------------------ | |
| # 1. Collect valid image paths from frames.csv | |
| # ------------------------------------------------------------------ | |
| img_paths = [] | |
| for data_dir in DATA_DIRS: | |
| if not data_dir.is_dir(): | |
| continue | |
| for sim_dir in sorted(data_dir.iterdir()): | |
| frames_csv = sim_dir / "frames.csv" | |
| if not frames_csv.exists(): | |
| continue | |
| for row in csv.DictReader(frames_csv.open()): | |
| if row["label"] not in VALID_LABELS: | |
| continue | |
| path = sim_dir / row["side_filename"] | |
| if path.exists(): | |
| img_paths.append(path) | |
| import random | |
| rng = random.Random(RANDOM_SEED) | |
| rng.shuffle(img_paths) | |
| if MAX_IMAGES is not None: | |
| img_paths = img_paths[:MAX_IMAGES] | |
| log.info(f"Found {len(img_paths)} valid side-profile frames") | |
| # ------------------------------------------------------------------ | |
| # 2. Load images (already border-recolored — just resize) | |
| # ------------------------------------------------------------------ | |
| log.info("Loading images ...") | |
| imgs = [] | |
| for path in img_paths: | |
| pil = PILImage.open(path).convert("RGB").resize((IMG_W, IMG_H), PILImage.Resampling.BILINEAR) | |
| imgs.append(np.array(pil)) | |
| data = torch.from_numpy( | |
| np.stack(imgs).astype(np.float32) / 255.0 | |
| ).permute(0, 3, 1, 2) # N×3×H×W | |
| loader = DataLoader(TensorDataset(data), batch_size=BATCH_SIZE, shuffle=True, generator=torch.Generator().manual_seed(RANDOM_SEED)) | |
| log.info(f"Tensor shape: {tuple(data.shape)}") | |
| # ------------------------------------------------------------------ | |
| # 3. Convolutional VAE (3×32×64 input) | |
| # | |
| # Encoder spatial progression (H×W): | |
| # 3×32×64 → 32×16×32 → 64×8×16 → 128×4×8 → 256×2×4 | |
| # Flatten → 2048 → mu / logvar (dim=16) | |
| # ------------------------------------------------------------------ | |
| class Encoder(nn.Module): | |
| def __init__(self, latent_dim): | |
| super().__init__() | |
| self.conv = nn.Sequential( | |
| nn.Conv2d(3, 32, 4, 2, 1), nn.ReLU(), | |
| nn.Conv2d(32, 64, 4, 2, 1), nn.ReLU(), | |
| nn.Conv2d(64, 128, 4, 2, 1), nn.ReLU(), | |
| nn.Conv2d(128, 256, 4, 2, 1), nn.ReLU(), | |
| ) | |
| self.fc_mu = nn.Linear(256 * 2 * 4, latent_dim) | |
| self.fc_logvar = nn.Linear(256 * 2 * 4, latent_dim) | |
| def forward(self, x): | |
| h = self.conv(x).flatten(1) | |
| return self.fc_mu(h), self.fc_logvar(h) | |
| class Decoder(nn.Module): | |
| def __init__(self, latent_dim): | |
| super().__init__() | |
| self.fc = nn.Linear(latent_dim, 256 * 2 * 4) | |
| self.deconv = nn.Sequential( | |
| nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(64, 32, 4, 2, 1), nn.ReLU(), | |
| nn.ConvTranspose2d(32, 3, 4, 2, 1), nn.Sigmoid(), | |
| ) | |
| def forward(self, z): | |
| return self.deconv(self.fc(z).view(-1, 256, 2, 4)) | |
| class VAE(nn.Module): | |
| def __init__(self, latent_dim): | |
| super().__init__() | |
| self.encoder = Encoder(latent_dim) | |
| self.decoder = Decoder(latent_dim) | |
| def reparameterise(self, mu, logvar): | |
| return mu + (0.5 * logvar).exp() * torch.randn_like(mu) | |
| def forward(self, x): | |
| mu, logvar = self.encoder(x) | |
| return self.decoder(self.reparameterise(mu, logvar)), mu, logvar | |
| def vae_loss(recon, x, mu, logvar): | |
| # Upweight melt-pool pixels (red channel dominant) so the VAE | |
| # doesn't ignore the small pool region against the background. | |
| mask = ((x[:, 0] > 0.5) & (x[:, 1] < 0.25) & (x[:, 2] < 0.25)).unsqueeze(1).float() | |
| weights = 1.0 + (RED_WEIGHT - 1.0) * mask.expand_as(x) | |
| recon_loss = (weights * (recon - x).pow(2)).sum() | |
| kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) | |
| return recon_loss + kld | |
| # ------------------------------------------------------------------ | |
| # 4. Train | |
| # ------------------------------------------------------------------ | |
| torch.manual_seed(RANDOM_SEED) | |
| model = VAE(LATENT_DIM).to(DEVICE) | |
| opt = torch.optim.Adam(model.parameters(), lr=LR) | |
| z_fixed = torch.randn(16, LATENT_DIM, device=DEVICE) | |
| loss_log = [] | |
| log.info(f"Training VAE for {EPOCHS} epochs | {len(data)} images | batch={BATCH_SIZE}") | |
| for epoch in range(1, EPOCHS + 1): | |
| model.train() | |
| total = 0.0 | |
| for (batch,) in loader: | |
| batch = batch.to(DEVICE) | |
| recon, mu, logvar = model(batch) | |
| loss = vae_loss(recon, batch, mu, logvar) | |
| opt.zero_grad(); loss.backward(); opt.step() | |
| total += loss.item() | |
| loss_per_img = total / len(data) | |
| loss_log.append(loss_per_img) | |
| log.info(f" epoch {epoch:3d}/{EPOCHS} loss/img: {loss_per_img:.4f}") | |
| if epoch % SAMPLE_EVERY == 0: | |
| model.eval() | |
| with torch.no_grad(): | |
| samples = model.decoder(z_fixed).cpu().permute(0, 2, 3, 1).numpy() | |
| fig, axes = plt.subplots(2, 8, figsize=(14, 4)) | |
| for i, ax in enumerate(axes.flat): | |
| ax.imshow(samples[i]); ax.axis("off") | |
| fig.suptitle(f"VAE samples — epoch {epoch}/{EPOCHS} (loss/img={loss_per_img:.4f})", fontsize=10) | |
| plt.tight_layout() | |
| path = out_dir / f"generation_epoch_{epoch:03d}.png" | |
| plt.savefig(path, dpi=100); plt.close(fig) | |
| log.info(f" → saved {path.name}") | |
| # ------------------------------------------------------------------ | |
| # 5. Final plots | |
| # ------------------------------------------------------------------ | |
| model.eval() | |
| log.info("Generating final plots ...") | |
| fig, ax = plt.subplots(figsize=(7, 3)) | |
| ax.plot(range(1, EPOCHS + 1), loss_log, lw=1.5) | |
| ax.set_xlabel("Epoch"); ax.set_ylabel("Loss / image") | |
| ax.set_title("VAE training loss") | |
| plt.tight_layout() | |
| plt.savefig(out_dir / "generation_loss.png", dpi=150); plt.close(fig) | |
| N_SHOW = 8 | |
| with torch.no_grad(): | |
| originals = data[:N_SHOW].to(DEVICE) | |
| recons, _, _ = model(originals) | |
| originals = originals.cpu().permute(0, 2, 3, 1).numpy() | |
| recons = recons.cpu().permute(0, 2, 3, 1).numpy() | |
| samples = model.decoder(torch.randn(16, LATENT_DIM, device=DEVICE)).cpu().permute(0, 2, 3, 1).numpy() | |
| fig, axes = plt.subplots(2, N_SHOW, figsize=(14, 3)) | |
| for i in range(N_SHOW): | |
| axes[0, i].imshow(originals[i]); axes[0, i].axis("off") | |
| axes[1, i].imshow(recons[i]); axes[1, i].axis("off") | |
| axes[0, 0].set_ylabel("Real", rotation=0, labelpad=30, va="center") | |
| axes[1, 0].set_ylabel("Recon", rotation=0, labelpad=30, va="center") | |
| fig.suptitle("VAE reconstructions — melt-pool side profiles", fontsize=11) | |
| plt.tight_layout() | |
| plt.savefig(out_dir / "generation_reconstructions.png", dpi=150); plt.close(fig) | |
| fig, axes = plt.subplots(2, 8, figsize=(14, 4)) | |
| for i, ax in enumerate(axes.flat): | |
| ax.imshow(samples[i]); ax.axis("off") | |
| fig.suptitle("Unconditional VAE samples — melt-pool side profiles", fontsize=11) | |
| plt.tight_layout() | |
| plt.savefig(out_dir / "generation_samples.png", dpi=150); plt.close(fig) | |
| log.info(f"All outputs saved to {out_dir}") | |
| log.info("Done.") | |