ORNL-LPBF-Cylinders / scripts /generate_photodiode_previews.py
ppak10's picture
Adds scripts for generating previews.
0220f4d
#!/usr/bin/env python3
"""Generate photodiode preview videos from LPBF HDF5 scan data.
This script processes photodiode point data to create animated videos
showing the laser scan progression for each layer. Each video shows
the cumulative thermal intensity as the laser scans across the build.
Output: One MP4 video per layer in previews/photodiode/
"""
import h5py
import numpy as np
from pathlib import Path
from PIL import Image
import subprocess
import tempfile
import multiprocessing as mp
from functools import partial
import os
HDF5_PATH = Path(__file__).parent.parent / "source/2024-05-01 M2 AMMTO Fatigue Blanks 05.hdf5"
PREVIEW_DIR = Path(__file__).parent.parent / "previews"
# Video settings
FPS = 30
FRAME_DURATION = 0.5 # seconds of real time per video frame
IMG_SIZE = 1024
# Multiprocessing settings
NUM_WORKERS = max(1, mp.cpu_count() - 2) # Leave 2 cores free
def generate_layer_video_worker(layer: int) -> tuple[int, bool]:
"""Worker function to generate a video for a single layer.
Opens its own HDF5 file handle for thread safety.
Args:
layer: Layer index
Returns:
Tuple of (layer, success)
"""
output_path = PREVIEW_DIR / "photodiode" / f"layer_{layer:04d}.mp4"
if output_path.exists():
return (layer, True)
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
try:
with h5py.File(HDF5_PATH, "r") as f:
success = _generate_layer_video(f, layer, output_path, temp_path)
except Exception as e:
print(f" Layer {layer} error: {e}")
success = False
return (layer, success)
def _generate_layer_video(f: h5py.File, layer: int, output_path: Path, temp_dir: Path) -> bool:
"""Generate a video for a single layer from photodiode data.
Args:
f: Open HDF5 file handle
layer: Layer index
output_path: Path for output video
temp_dir: Temporary directory for frames
Returns:
True if successful, False otherwise
"""
point_key = f'{layer} point'
line_key = f'{layer} line'
if point_key not in f['scans'] or line_key not in f['scans']:
return False
point = f[f'scans/{point_key}'][:]
line = f[f'scans/{line_key}'][:]
if len(point) == 0 or len(line) == 0:
return False
x, y, intensity = point[:, 0], point[:, 1], point[:, 2]
time = line[:, 4]
t_min, t_max = time.min(), time.max()
duration = t_max - t_min
if duration <= 0:
return False
# Calculate bounds for rasterization
x_min, x_max = x.min() - 5, x.max() + 5
y_min, y_max = y.min() - 5, y.max() + 5
# Points per frame
n_frames = max(1, int(duration / FRAME_DURATION))
points_per_frame = len(point) // n_frames
if points_per_frame == 0:
return False
# Generate frames
for frame_idx in range(n_frames):
end_idx = min((frame_idx + 1) * points_per_frame, len(point))
# Cumulative: show all points up to this time
frame_x = x[:end_idx]
frame_y = y[:end_idx]
frame_i = intensity[:end_idx]
# Rasterize to image
img = np.zeros((IMG_SIZE, IMG_SIZE), dtype=np.float32)
counts = np.zeros((IMG_SIZE, IMG_SIZE), dtype=np.float32)
# Convert coordinates to pixel indices
px = ((frame_x - x_min) / (x_max - x_min) * (IMG_SIZE - 1)).astype(int)
py = ((frame_y - y_min) / (y_max - y_min) * (IMG_SIZE - 1)).astype(int)
# Clip to valid range
valid = (px >= 0) & (px < IMG_SIZE) & (py >= 0) & (py < IMG_SIZE)
px, py, fi = px[valid], py[valid], frame_i[valid]
# Accumulate intensities
np.add.at(img, (py, px), fi)
np.add.at(counts, (py, px), 1)
# Average where we have data
mask = counts > 0
img[mask] /= counts[mask]
# Normalize to uint8
if img.max() > 0:
img = (img / img.max() * 255).astype(np.uint8)
else:
img = img.astype(np.uint8)
Image.fromarray(img).save(temp_dir / f'frame_{frame_idx:04d}.png')
# Create video with ffmpeg
cmd = [
"ffmpeg",
"-y",
"-framerate", str(FPS),
"-i", str(temp_dir / "frame_%04d.png"),
"-c:v", "libx264",
"-preset", "medium",
"-crf", "23",
"-pix_fmt", "yuv420p",
str(output_path)
]
result = subprocess.run(cmd, capture_output=True, text=True)
return result.returncode == 0
def main():
print("=" * 60)
print("Photodiode Preview Generator")
print("=" * 60)
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("Error: ffmpeg not found. Install with: sudo apt install ffmpeg")
return
output_dir = PREVIEW_DIR / "photodiode"
output_dir.mkdir(parents=True, exist_ok=True)
# Get list of layers to process
with h5py.File(HDF5_PATH, "r") as f:
scan_keys = list(f['scans'].keys())
layers = sorted(set(int(k.split()[0]) for k in scan_keys))
n_layers = len(layers)
print(f"\nFound {n_layers} layers with scan data")
# Filter to only layers that need processing
layers_to_process = [
layer for layer in layers
if not (output_dir / f"layer_{layer:04d}.mp4").exists()
]
n_existing = n_layers - len(layers_to_process)
if n_existing > 0:
print(f" Skipping {n_existing} existing videos")
if not layers_to_process:
print(" All videos already exist!")
else:
print(f" Processing {len(layers_to_process)} layers with {NUM_WORKERS} workers...")
# Process in parallel
completed = 0
failed = 0
with mp.Pool(NUM_WORKERS) as pool:
for layer, success in pool.imap_unordered(generate_layer_video_worker, layers_to_process):
if success:
completed += 1
else:
failed += 1
total_done = completed + failed
if total_done % 50 == 0 or total_done == len(layers_to_process):
print(f" Progress: {total_done}/{len(layers_to_process)} "
f"(completed: {completed}, failed: {failed})")
print(f"\n Results: {completed} completed, {failed} failed")
print("\n" + "=" * 60)
print("Photodiode preview generation complete!")
print("=" * 60)
if __name__ == "__main__":
main()