File size: 10,149 Bytes
8550bd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""
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.")