Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
525 lines (440 loc) · 17.7 KB
/
Copy pathutils.py
File metadata and controls
525 lines (440 loc) · 17.7 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import os
import jax
import jax.numpy as jnp
import equinox as eqx
import numpy as np
import glob
import tifffile
import matplotlib.pyplot as plt
import stackview
from skimage.restoration import richardson_lucy
from pathlib import Path
from typing import Tuple, Optional
from tifffile import imread
# ───────────── File I/O Utilities ─────────────
def log_to_file(text, log_path="train_debug.log"):
"""
Append text to a log file.
"""
with open(log_path, "a") as f:
f.write(text + "\n")
def load_ome_tif(filename):
"""
load 3D data from an OME-TIFF file.
"""
return tifffile.imread(filename) #np.ndarray
def load_data(filename):
"""
helper to load 3D data from a .npy file.
"""
return np.load(filename)
def save_data(filename, data):
"""
Save data to a .npy file.
"""
np.save(filename, data)
def save_ome_tiff(filename, data):
"""
Save data to an OME-TIFF file.
"""
tifffile.imwrite(filename, data)
def load_image(filepath: str):
"""
Load a 3D OME-TIFF file and preprocess it.
Our immages are in shape (D, H, W).
"""
images = tifffile.imread(filepath)
images = images.astype(np.float32)
# Normalize to [0,1]
images /= images.max()
# If images are (D, H, W), add batch and channel dimensions: (1, 1, D, H, W)
if images.ndim == 3:
images = images[None, None, ...]
# If images are (B, D, H, W), add a channel dimension: (B, 1, D, H, W)
elif images.ndim == 4:
images = images[:, None, ...]
return images
# ───────────── Dataset Handling and Volume Utilities ─────────────
def chop_volume(volume, shape):
"""
Chop a 3D volume into smaller cubes of given shape.
"""
D, H, W = volume.shape
d, h, w = shape
cubes = []
for z in range(0, D - d + 1, d):
for y in range(0, H - h + 1, h):
for x in range(0, W - w + 1, w):
vol_cube = volume[z:z + d, y:y + h, x:x + w]
cubes.append(vol_cube)
return cubes
def normalize_image(img):
"""
Normalize a 3D image to the range [0, 1].
"""
img_min = img.min()
img_max = img.max()
if img_max == img_min:
# Avoid divide-by-zero — return zeros if the image is flat
return np.zeros_like(img)
return (img - img_min) / (img_max - img_min)
def fix_slice_count(data):
"""
Ensure the z stack has exactly 32 slices by adding slices of zeros evenly to the top and bottom if needed.
"""
current_slices = data.shape[0]
if current_slices != 32:
diff = 32 - current_slices
pad_top = diff // 2
pad_bottom = diff - pad_top
padding = ((pad_top, pad_bottom), (0, 0), (0, 0)) # Only pad the z-dimension
data = np.pad(data, padding, mode='constant', constant_values=0)
return data
def create_dataset(gt_images, degraded_images, batch_size: int):
"""
shuffling and batching the degraded and ground truth images.
returns a list of batches, each as a tuple (ground_truth_batch, degraded_batch), need dims to be (B, D, H, W, C) !! EQUINOX IS CHANNEL LAST
"""
num_samples = len(gt_images)
indices = np.arange(num_samples)
np.random.shuffle(indices)
# Add a channel axis to the images (assuming grayscale, so 1 channel)
degraded_images = np.expand_dims(degraded_images, axis=1)
gt_images = np.expand_dims(gt_images, axis=1)
# degraded_images = np.array(degraded_images)
# gt_images = np.array(gt_images)
batches = []
for start in range(0, num_samples, batch_size):
batch_idx = indices[start:start + batch_size]
degraded_batch = jnp.array(degraded_images[batch_idx]) # Ensure that degraded_batch is a JAX array
ground_truth_batch = jnp.array(gt_images[batch_idx]) # Ensure that gt_batch is a JAX array
batches.append((ground_truth_batch, degraded_batch))
return batches
def train_test_split(gt_images, sim_images, train_size=0.8, seed = 7):
"""
Split the dataset into training and testing sets.
"""
num_samples = len(gt_images)
indices = np.arange(num_samples)
np.random.seed(seed)
np.random.shuffle(indices)
train_size = int(train_size * num_samples)
train_indices = indices[:train_size]
test_indices = indices[train_size:]
train_gt = [gt_images[i] for i in train_indices]
train_sim = [sim_images[i] for i in train_indices]
test_gt = [gt_images[i] for i in test_indices]
test_sim = [sim_images[i] for i in test_indices]
return train_gt, train_sim, test_gt, test_sim
# ───────────── Sample Loading ─────────────
def load_sample_triplet(dataset_dir, index=0, ext=".ome.tif"):
"""
Load the ideal, measured, and degraded volumes for a given sample index from a dataset.
Returns:
tuple: (ideal_volume, measured_volume, degraded_volume)
"""
base_dir = "/home/dcorrea/deconvolution/data/tubes"
ideal_dir = os.path.join(base_dir, "ideal")
measured_dir = os.path.join(base_dir, dataset_dir, "measured")
degraded_dir = os.path.join(base_dir, dataset_dir, "degraded")
fname = f"sample_{index}{ext}"
measured_fname = f"sample_{index}_measured{ext}"
degraded_fname = f"sample_{index}_degraded{ext}"
def load(path):
if path.endswith(".npy"):
return np.load(path)
else:
return imread(path)
ideal_path = os.path.join(ideal_dir, fname)
measured_path = os.path.join(measured_dir, measured_fname)
degraded_path = os.path.join(degraded_dir, degraded_fname)
assert os.path.exists(ideal_path), f"Missing: {ideal_path}"
assert os.path.exists(measured_path), f"Missing: {measured_path}"
assert os.path.exists(degraded_path), f"Missing: {degraded_path}"
ideal = fix_slice_count(load(ideal_path))
return ideal, load(measured_path), load(degraded_path)
def load_dataset_files(ground_truth_dir, simulated_dir,):
"""
Load ground truth and simulated images from specified directories.
"""
# Load all files
gt_files = glob.glob(os.path.join(ground_truth_dir, "*.ome.tif"))
sim_files = glob.glob(os.path.join(simulated_dir, "*.ome.tif"))
# Build a lookup from sample ID to file path
gt_dict = {}
for path in gt_files:
# Extract sample ID, e.g., "sample_24" from "sample_24.ome.tif"
basename = os.path.basename(path)
sample_id = basename.replace("_measured.ome.tif", "")
gt_dict[sample_id] = path
sim_dict = {}
for path in sim_files:
basename = os.path.basename(path)
# Extract matching ID, e.g., "sample_24" from "sample_24_simulated.ome.tif"
sample_id = basename.replace("_degraded.ome.tif", "")
sim_dict[sample_id] = path
# Only keep samples that have both GT and simulated files
common_ids = sorted(set(gt_dict.keys()) & set(sim_dict.keys()))
if len(common_ids) == 0:
raise ValueError("No matching pairs found between GT and simulated images!")
gt_images = [load_ome_tif(gt_dict[sid]) for sid in common_ids]
sim_images = [load_ome_tif(sim_dict[sid]) for sid in common_ids]
gt_images = [fix_slice_count(img) for img in gt_images]
sim_images = [np.clip(fix_slice_count(img), 0, 1) for img in sim_images]
return gt_images, sim_images
# ───────────── Sample Loading ─────────────
def data_loader(gt_images, sim_images, batch_size, key=None, shuffle=True):
"""
Yields batches of (gt_batch, degraded_batch) each shaped (B, C, D, H, W).
"""
# gt_images, sim_images are lists of arrays
gt_images = np.stack(gt_images, axis=0) # (N, D, H, W)
sim_images = np.stack(sim_images, axis=0)
num_samples = len(gt_images)
if len(sim_images) != num_samples:
raise ValueError("GT and Sim images must have the same length")
# For 3D volumes with no channel dimension, add one:
# (N, D, H, W) -> (N, 1, D, H, W)
if gt_images.ndim == 4:
gt_images = np.expand_dims(gt_images, axis=1)
if sim_images.ndim == 4:
sim_images = np.expand_dims(sim_images, axis=1)
# Shuffle
if key is not None:
# shuffle with jax.random
indices = jax.random.permutation(key, num_samples)
indices = np.array(indices) # convert to np array
else:
indices = np.arange(num_samples)
if shuffle:
np.random.shuffle(indices)
#create the batch
for start in range(0, num_samples, batch_size):
batch_idx = indices[start : start + batch_size]
# Convert each batch to JAX arrays
gt_batch = jnp.array(gt_images[batch_idx]) # shape (B, C, D, H, W)
sim_batch = jnp.array(sim_images[batch_idx]) # shape (B, C, D, H, W)
yield (gt_batch, sim_batch)
# ───────────── Model Save/Load ─────────────
def save_model(model, path):
"""
Save the model to a file using Equinox's tree serialization.
"""
eqx.tree_serialise_leaves(path, model)
def load_model(path, model_template):
"""
Load a model from a file using Equinox's tree deserialization.
"""
return eqx.tree_deserialise_leaves(path, model_template)
# ───────────── Visualization 2D/3D Views ─────────────
def visualize_3d_slices_save(
gt_volume, sim_volume, pred_volume,
psf_file="/home/dcorrea/deconvolution/data/tubes/Gaussian/psf_gaussian.npy",
iterations=30,
save_dir="./",
basename="volume",
slice_index=None,
common_contrast=True,
):
"""Save a 4-panel comparison figure (GT, measured, prediction, RL)."""
# ------------------------------------------------------------------ load + prep
psf = np.load(psf_file)
print("PSF file:", psf_file)
gt_volume = gt_volume[0, 0]
sim_volume = sim_volume[0, 0]
pred_volume = pred_volume[0, 0]
slice_index = slice_index or (gt_volume.shape[0] // 2)
sim_clipped = np.clip(sim_volume, 0, 1)
rl_deconvolved = richardson_lucy(sim_clipped, psf, num_iter=iterations)
images = [gt_volume, sim_volume, pred_volume, rl_deconvolved]
titles = ["Measured", "Degraded", "Prediction",
f"Richardson–Lucy ({iterations} iters)"]
# pick shared contrast so the eye can compare intensity ranges
if common_contrast:
global_min = min(np.min(img) for img in images)
global_max = max(np.max(img) for img in images)
clim = (global_min, global_max)
else:
clim = None
# ------------------------------------------------------------------ plotting
fig, axes = plt.subplots(1, 4, figsize=(24, 6))
for ax, vol, ttl in zip(axes, images, titles):
sl = vol[slice_index]
im = ax.imshow(sl, cmap="gray", vmin=clim[0], vmax=clim[1]) if clim else ax.imshow(sl, cmap="gray")
ax.set_title(ttl, fontsize=11)
ax.axis("off")
# overlay min / max
ax.text(0.03, 0.05,
f"min {sl.min():.3f}\nmax {sl.max():.3f}",
color="white", fontsize=8,
ha="left", va="bottom", transform=ax.transAxes,
bbox=dict(boxstyle="round,pad=0.2", fc="black", alpha=0.4))
plt.tight_layout()
# ------------------------------------------------------------------ save
Path(save_dir).mkdir(parents=True, exist_ok=True)
fig_path = os.path.join(save_dir, f"{basename}_comparison.png")
plt.savefig(fig_path, dpi=300, bbox_inches="tight")
plt.close()
print(f"Saved comparison image → {fig_path}")
def plot_sample_triplet(ideal, measured, degraded, slice_idx=None, title_prefix="Sample0"):
"""
Plots a side-by-side comparison of ideal, measured, and degraded 3D volumes.
Args:
ideal, measured, degraded: 3D numpy arrays
slice_idx: specific z-slice to visualize (if None, use middle slice)
title_prefix: title text to prefix on each subplot
"""
assert ideal.ndim == 3 and measured.ndim == 3 and degraded.ndim == 3, "Inputs must be 3D volumes."
if slice_idx is None:
slice_idx = ideal.shape[0] // 2 # use middle slice
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
cmap = "gray"
axes[0].imshow(ideal[slice_idx], cmap=cmap)
axes[0].set_title(f"{title_prefix} - Ideal")
axes[1].imshow(measured[slice_idx], cmap=cmap)
axes[1].set_title(f"{title_prefix} - Measured")
axes[2].imshow(degraded[slice_idx], cmap=cmap)
axes[2].set_title(f"{title_prefix} - Degraded")
for ax in axes:
ax.axis("off")
plt.tight_layout()
plt.show()
def plot_sample_triplet_zoom(
ideal: np.ndarray,
measured: np.ndarray,
degraded: np.ndarray,
*,
slice_idx: Optional[int] = None,
patch_center: Optional[Tuple[int, int]] = None, # (row, col) in the slice
patch_size: int = 128,
random_patch: bool = False,
title_prefix: str = "Sample_0",
) -> None:
"""
Shows a zoomed-in 128×128 patch from the same location in the
ideal, measured and degraded volumes.
Args
----
ideal, measured, degraded : np.ndarray
3-D volumes with shape (Z, Y, X).
slice_idx : int, optional
Which z-slice to use. If None, the central slice is chosen.
patch_center : (row, col), optional
Centre (Y, X) coordinate of the patch in the slice. If None
and random_patch is False, uses the slice centre. If
random_patch is True, chooses a valid random centre.
patch_size : int
Size of the square patch (default 128).
random_patch : bool
If True and patch_center is None, pick a random valid patch.
title_prefix : str
Prefix for subplot titles.
"""
# ----------------- basic checks -----------------
assert ideal.ndim == measured.ndim == degraded.ndim == 3, "Inputs must be 3-D volumes"
assert ideal.shape == measured.shape == degraded.shape, "Volumes must have the same shape"
z, h, w = ideal.shape
if slice_idx is None:
slice_idx = z // 2
assert 0 <= slice_idx < z, "slice_idx out of bounds"
# ------------- choose patch coordinates ----------
half = patch_size // 2
if patch_center is None:
if random_patch:
# leave a margin so the patch stays inside the slice
row = np.random.randint(half, h - half)
col = np.random.randint(half, w - half)
else:
row, col = h // 2, w // 2
else:
row, col = patch_center
assert half <= row < h - half and half <= col < w - half, "patch_center too close to edge"
r0, r1 = row - half, row + half
c0, c1 = col - half, col + half
# ------------------- crop ------------------------
def crop(vol):
return vol[slice_idx, r0:r1, c0:c1]
ideal_patch = crop(ideal)
measured_patch = crop(measured)
degraded_patch = crop(degraded)
# ------------------ plotting ---------------------
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
cmap = "gray"
for ax, img, lbl in zip(
axes,
[ideal_patch, measured_patch, degraded_patch],
["Ideal", "Measured", "Degraded"],
):
ax.imshow(img, cmap=cmap, interpolation="nearest")
ax.set_title(f"{title_prefix} – {lbl}")
ax.axis("off")
plt.tight_layout()
plt.show()
# ───────────── Plot Training Loss ─────────────
def plot_loss_show(train_losses, test_losses):
"""
Plot training and test losses over epochs.
"""
plt.figure(figsize=(10, 6))
plt.plot(train_losses, label='Train Loss', color='blue', linestyle='--', marker='o')
plt.plot(test_losses, label='Test Loss', color='orange', linestyle='--', marker='x')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Test Loss over epochs')
plt.legend()
plt.grid(True)
plt.show()
def plot_loss_justloss(train_losses, test_losses, save_path="loss_plot.png"):
"""
Plot training and test losses over epochs and save the figure.
"""
plt.figure(figsize=(10, 6))
plt.plot(train_losses, label='Train Loss', color='blue', linestyle='--', marker='o')
plt.plot(test_losses, label='Test Loss', color='orange', linestyle='--', marker='x')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Test Loss over epochs')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig(save_path)
plt.close()
def plot_loss(
train_total_loss, test_total_loss,
train_mae, test_mae,
train_ssim, test_ssim,
save_path="loss_plot.png"
):
"""
Plot total loss, MAE, and SSIM over epochs and save the figure.
"""
epochs = range(len(train_total_loss))
plt.figure(figsize=(14, 8))
# Plot total loss
plt.subplot(3, 1, 1)
plt.plot(epochs, train_total_loss, label='Train Total Loss', color='blue', linestyle='--', marker='o')
plt.plot(epochs, test_total_loss, label='Test Total Loss', color='orange', linestyle='--', marker='x')
plt.ylabel('Total Loss')
plt.title('Total Loss')
plt.legend()
plt.grid(True)
# Plot MAE
plt.subplot(3, 1, 2)
plt.plot(epochs, train_mae, label='Train MAE', color='green', linestyle='--', marker='o')
plt.plot(epochs, test_mae, label='Test MAE', color='red', linestyle='--', marker='x')
plt.ylabel('Mean Absolute Error')
plt.title('MAE per Epoch')
plt.legend()
plt.grid(True)
# Plot SSIM
plt.subplot(3, 1, 3)
plt.plot(epochs, train_ssim, label='Train SSIM', color='purple', linestyle='--', marker='o')
plt.plot(epochs, test_ssim, label='Test SSIM', color='brown', linestyle='--', marker='x')
plt.xlabel('Epoch')
plt.ylabel('SSIM')
plt.title('SSIM per Epoch')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig(save_path)
plt.close()