Subir archivos a "scripts_python"
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
@@ -23,20 +24,22 @@ def set_seed(seed=42):
|
||||
|
||||
set_seed(42)
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
|
||||
# VRAM OPTIMIZATION ENGINE
|
||||
BATCH_SIZE = 8 # Physical batch size (keeps VRAM safely under 3.5 GB)
|
||||
ACCUMULATION_STEPS = 4 # 8 x 4 = Effective Batch Size of 32!
|
||||
EPOCHS = 60 # Slightly extended to give the larger batch size room to converge
|
||||
LEARNING_RATE = 0.0003 # Tuned for an effective batch size of 32
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name)
|
||||
MODEL_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name)
|
||||
MODEL_SAVE_PATH = os.path.join(MODEL_DIR, "msi_encoder_trained.pth")
|
||||
|
||||
BATCH_SIZE = 8
|
||||
ACCUMULATION_STEPS = 4
|
||||
EPOCHS = 60
|
||||
LEARNING_RATE = 0.0003
|
||||
TEMPERATURE = 0.5
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
class MSIAugmentations:
|
||||
def __init__(self, size=256): # Enforce 256 dimension consistency
|
||||
def __init__(self, size=256):
|
||||
self.spatial_transform = transforms.Compose([
|
||||
transforms.Resize((size, size)),
|
||||
transforms.ToTensor()
|
||||
@@ -44,35 +47,21 @@ class MSIAugmentations:
|
||||
|
||||
def apply_msi_chemical_noise(self, tensor):
|
||||
x = tensor.clone()
|
||||
|
||||
# 1. Intensity Scaling (Global Concentration Shifts)
|
||||
scale_factor = random.uniform(0.8, 1.2)
|
||||
x = x * scale_factor
|
||||
|
||||
# 2. Poisson Noise Simulation (Shot Noise)
|
||||
# Scaled to avoid breaking the 0.0 - 1.0 float bounds
|
||||
vals = len(torch.unique(x))
|
||||
vals = 2 ** np.ceil(np.log2(vals)) if vals > 0 else 32
|
||||
# Add soft, random Gaussian-Poisson approximation
|
||||
noise = torch.randn_like(x) * (torch.sqrt(x + 1e-5) / float(vals))
|
||||
x = x + noise
|
||||
|
||||
# 3. Random Missing Values (Standard Dropout - e.g., 2% pixels lost)
|
||||
random_dropout_mask = (torch.rand_like(x) > 0.02).float()
|
||||
x = x * random_dropout_mask
|
||||
|
||||
# 4. Intensity-Dependent Missing Values (Low-Signal Clipping)
|
||||
# Pixels with very low values have a higher chance of dropping out completely
|
||||
low_signal_mask = torch.rand_like(x)
|
||||
# Drop threshold scales inversely with intensity: lower values drop more easily
|
||||
drop_threshold = 0.15 * (1.0 - x)
|
||||
drop_threshold = 0.15 * (1.0 - x)
|
||||
x = torch.where(low_signal_mask > drop_threshold, x, torch.zeros_like(x))
|
||||
|
||||
return torch.clamp(x, 0.0, 1.0)
|
||||
|
||||
def __call__(self, x):
|
||||
base_tensor = self.spatial_transform(x)
|
||||
# Create two distinct chemical representations of the same underlying coordinate geometry
|
||||
return self.apply_msi_chemical_noise(base_tensor), self.apply_msi_chemical_noise(base_tensor)
|
||||
|
||||
class SimCLRMSIDataset(Dataset):
|
||||
@@ -94,32 +83,21 @@ class SimCLRMSIDataset(Dataset):
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self, projection_dim=128):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
|
||||
# High-Fidelity Custom Encoder for Padded Data
|
||||
self.features = nn.Sequential(
|
||||
# Input: 256x256x1 (Resize in transform)
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32), # Replaces BatchNorm for perfect stability at batch size = 8
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
|
||||
# 112x112 -> 56x56
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
|
||||
# 56x56 -> 28x28 (Captures true raw pixel leaf structures)
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
|
||||
# 28x28 -> 14x14
|
||||
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(32, 256),
|
||||
nn.ReLU(),
|
||||
|
||||
nn.AdaptiveAvgPool2d((1, 1)) # Yields a clean 256-dimensional vector
|
||||
nn.AdaptiveAvgPool2d((1, 1))
|
||||
)
|
||||
|
||||
self.projector = nn.Sequential(
|
||||
nn.Linear(256, 128),
|
||||
nn.ReLU(),
|
||||
@@ -128,7 +106,7 @@ class MSI_Structural_Encoder(nn.Module):
|
||||
|
||||
def forward(self, x):
|
||||
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||
h_norm = F.normalize(h, p=2, dim=1) # Projects onto the unit hypersphere
|
||||
h_norm = F.normalize(h, p=2, dim=1)
|
||||
z = self.projector(h_norm)
|
||||
return h, z
|
||||
|
||||
@@ -136,22 +114,21 @@ def nt_xent_loss(z1, z2, temperature=0.5):
|
||||
batch_size = z1.shape[0]
|
||||
z = torch.cat([z1, z2], dim=0)
|
||||
z = F.normalize(z, p=2, dim=1)
|
||||
|
||||
sim_matrix = torch.mm(z, z.t()) / temperature
|
||||
mask = torch.eye(2 * batch_size, device=z.device).bool()
|
||||
sim_matrix = sim_matrix.masked_fill(mask, -9e15)
|
||||
|
||||
targets = torch.arange(2 * batch_size, device=z.device)
|
||||
targets[:batch_size] += batch_size
|
||||
targets[batch_size:] -= batch_size
|
||||
|
||||
return F.cross_entropy(sim_matrix, targets)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"=== SimCLR Training: {dataset_name} ===")
|
||||
print(f"Launching VRAM-Optimized Contrastive Pipeline on: {DEVICE}")
|
||||
print(f"Images: {IMG_DIR}")
|
||||
print(f"Physical Batch Size: {BATCH_SIZE} | Accumulation Steps: {ACCUMULATION_STEPS} | Effective Batch Size: {BATCH_SIZE * ACCUMULATION_STEPS}")
|
||||
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
|
||||
|
||||
os.makedirs(MODEL_DIR, exist_ok=True)
|
||||
|
||||
aug_pipeline = MSIAugmentations(size=256)
|
||||
dataset = SimCLRMSIDataset(IMG_DIR, transform=aug_pipeline)
|
||||
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True, num_workers=2, pin_memory=True)
|
||||
@@ -161,8 +138,7 @@ if __name__ == "__main__":
|
||||
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS, eta_min=1e-6)
|
||||
|
||||
process = psutil.Process(os.getpid())
|
||||
|
||||
# Environment tweak to combat memory fragmentation
|
||||
|
||||
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
@@ -170,32 +146,29 @@ if __name__ == "__main__":
|
||||
model.train()
|
||||
total_loss = 0
|
||||
epoch_start = time.time()
|
||||
|
||||
optimizer.zero_grad() # Initialize gradients outside the accumulation loop
|
||||
|
||||
|
||||
optimizer.zero_grad()
|
||||
|
||||
for batch_idx, (xi, xj) in enumerate(loader):
|
||||
xi, xj = xi.to(DEVICE), xj.to(DEVICE)
|
||||
|
||||
|
||||
_, z1 = model(xi)
|
||||
_, z2 = model(xj)
|
||||
|
||||
# Scale loss by accumulation steps to ensure correct gradient weighting
|
||||
|
||||
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) / ACCUMULATION_STEPS
|
||||
loss.backward()
|
||||
|
||||
|
||||
total_loss += loss.item() * ACCUMULATION_STEPS
|
||||
|
||||
# Step the optimizer only after gathering enough gradients
|
||||
|
||||
if (batch_idx + 1) % ACCUMULATION_STEPS == 0 or (batch_idx + 1) == len(loader):
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
|
||||
|
||||
scheduler.step()
|
||||
|
||||
# Periodic cache flushing keeps VRAM overhead low
|
||||
|
||||
if epoch % 5 == 0:
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
|
||||
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {total_loss / len(loader):.4f}, Time: {time.time()-epoch_start:.2f}s, RAM Used: {process.memory_info().rss / 1024 / 1024:.1f} MB")
|
||||
|
||||
print(f"--> Exporting optimized 32-BS encoder weights to: {MODEL_SAVE_PATH}")
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
import os
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.cm as cm
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
BENCH_CSV = os.path.join(ROOT, "Benchmark_recommendation", "results", "cross_language_benchmark.csv")
|
||||
GAL = os.path.join(ROOT, "outputs")
|
||||
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
|
||||
FONT_B = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
|
||||
FONT_I = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf"
|
||||
FONT_BI = "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"
|
||||
|
||||
LIBRARIES = ["JuliaMSI", "MALDIquant", "Cardinal"]
|
||||
DATASET_LABELS = {
|
||||
"Datura_leaf": "Datura leaf (LD-LTP)",
|
||||
"Datura_root": "Datura root (LD-LTP)",
|
||||
"Human_colon": "Human colon (DESI)",
|
||||
"Mouse_bladder": "Mouse bladder (AP-SMALDI)",
|
||||
"Mouse_Liver": "Mouse liver (MALDI)",
|
||||
"Mouse_Stomach": "Mouse stomach (MALDI)",
|
||||
"San_pedro": "San Pedro (MALDI)",
|
||||
}
|
||||
RED = "#d62728"
|
||||
FIG_DPI = 400
|
||||
FIG_WIDTH_CM = 16.0
|
||||
FIG_OUT = {
|
||||
"figure1": "figure1.png",
|
||||
"figure2": "figure2.png",
|
||||
"figure3": "figure3.png",
|
||||
}
|
||||
|
||||
|
||||
def font(size, bold=False, italic=False):
|
||||
if italic:
|
||||
return ImageFont.truetype(FONT_BI if bold else FONT_I, size)
|
||||
return ImageFont.truetype(FONT_B if bold else FONT, size)
|
||||
|
||||
|
||||
def paste(img, canvas, x, y, bg=(255, 255, 255)):
|
||||
if img.mode != "RGBA":
|
||||
img = img.convert("RGBA")
|
||||
canvas.paste(img, (int(x), int(y)), img)
|
||||
|
||||
|
||||
def scale(img, height):
|
||||
w, h = img.size
|
||||
return img.resize((int(w * height / h), int(height)), Image.LANCZOS)
|
||||
|
||||
|
||||
def _finalize(img, path, min_dpi=FIG_DPI, width_cm=FIG_WIDTH_CM):
|
||||
"""Upscale to the pixel width of `width_cm` at `min_dpi` and save PNG metadata."""
|
||||
target_w = int(round(width_cm / 2.54 * min_dpi))
|
||||
if img.width < target_w:
|
||||
img = img.resize((target_w, int(img.height * target_w / img.width)), Image.LANCZOS)
|
||||
img.save(path, dpi=(min_dpi, min_dpi))
|
||||
print(f"wrote {path}")
|
||||
|
||||
|
||||
def _bench_dataset_order(df):
|
||||
size_map = df.groupby("Dataset")["FileSize_MB"].first()
|
||||
return list(size_map.sort_values().index)
|
||||
|
||||
|
||||
def _bench_panel(df, datasets, y_col, title, ylabel, out, failed_notes):
|
||||
viridis = cm.viridis(np.linspace(0.15, 0.85, len(LIBRARIES)))
|
||||
pal = dict(zip(LIBRARIES, viridis))
|
||||
gb = lambda mb: f"{mb/1024:.2f}" if mb / 1024 < 10 else f"{mb/1024:.1f}"
|
||||
xlabels = [f"{d.replace('_', ' ')}\n{gb(df[df['Dataset']==d]['FileSize_MB'].iloc[0])} GB" for d in datasets]
|
||||
|
||||
fig, ax = plt.subplots(figsize=(9, 5), dpi=300)
|
||||
x = np.arange(len(datasets))
|
||||
width = 0.25
|
||||
for idx, lib in enumerate(LIBRARIES):
|
||||
lib_df = df[df["Library"] == lib].set_index("Dataset").reindex(datasets).reset_index()
|
||||
vals = lib_df[y_col].astype(float)
|
||||
ax.bar(x + (idx - 1) * width, vals, width, label=lib, color=pal[lib], linewidth=0)
|
||||
for xi, v in zip(x, vals):
|
||||
if np.isnan(v) and lib == "MALDIquant":
|
||||
ax.plot(xi, ax.get_ylim()[1] * 0.45, "X", color=RED, ms=16, mec=RED, mew=3)
|
||||
ax.set_yscale("log")
|
||||
ax.set_title(title, fontsize=12, fontweight="bold", pad=10)
|
||||
ax.set_ylabel(ylabel, fontsize=11, fontweight="bold")
|
||||
ax.set_xticks(x)
|
||||
ax.set_xticklabels(xlabels, fontsize=9, fontweight="bold", rotation=15)
|
||||
ax.spines["top"].set_visible(False)
|
||||
ax.spines["right"].set_visible(False)
|
||||
ax.legend(title="Library", frameon=True, facecolor="white", loc="upper left")
|
||||
if failed_notes:
|
||||
ax.annotate(failed_notes, xy=(0.98, 0.04), xycoords="axes fraction",
|
||||
ha="right", va="bottom", fontsize=8, color=RED, style="italic")
|
||||
plt.tight_layout()
|
||||
plt.savefig(out, dpi=300, bbox_inches="tight")
|
||||
plt.close()
|
||||
print(f"wrote {out}")
|
||||
|
||||
|
||||
def build_fig1():
|
||||
df = pd.read_csv(BENCH_CSV)
|
||||
datasets = _bench_dataset_order(df)
|
||||
tmp_through = os.path.join(ROOT, "outputs", "_tmp_through.png")
|
||||
tmp_mem = os.path.join(ROOT, "outputs", "_tmp_mem.png")
|
||||
_bench_panel(df, datasets, "Throughput_SPS",
|
||||
"Slice Generation Throughput",
|
||||
"Throughput (Slices Per Second) - Log Scale",
|
||||
tmp_through,
|
||||
None)
|
||||
_bench_panel(df, datasets, "LoadMem_MB",
|
||||
"Memory Consumption during Load",
|
||||
"Memory (MB) - Log Scale",
|
||||
tmp_mem,
|
||||
None)
|
||||
|
||||
tp = Image.open(tmp_through).convert("RGBA")
|
||||
mem = Image.open(tmp_mem).convert("RGBA")
|
||||
h = 900
|
||||
tp = scale(tp, h)
|
||||
mem = scale(mem, h)
|
||||
gap = 40
|
||||
W = tp.width + mem.width + gap + 160
|
||||
H = h + 120
|
||||
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
||||
paste(tp, canvas, 60, 70)
|
||||
paste(mem, canvas, 60 + tp.width + gap, 70)
|
||||
d = ImageDraw.Draw(canvas)
|
||||
f = font(42, bold=True)
|
||||
d.text((60, 10), "A Slice-generation throughput (slices/s, log scale)", font=f, fill="black")
|
||||
d.text((60 + tp.width + gap, 10), "B Peak load memory (MB, log scale)", font=f, fill="black")
|
||||
out = os.path.join(ROOT, FIG_OUT["figure1"])
|
||||
_finalize(canvas, out)
|
||||
os.remove(tmp_through)
|
||||
os.remove(tmp_mem)
|
||||
print(f"wrote {out}")
|
||||
|
||||
|
||||
ION_TARGETS = [
|
||||
("Scopolamine", 304.17),
|
||||
("Atropine/Hyoscyamine", 290.08),
|
||||
("6-Hydroxyhyoscyamine", 306.25),
|
||||
("Tropinone", 140.17),
|
||||
("Tropine", 142.08),
|
||||
("Cuscohygrine", 225.92),
|
||||
]
|
||||
|
||||
|
||||
def _find_ions(ds, tol=0.12):
|
||||
"""Find tropane-related ions in the feature matrix by target m/z."""
|
||||
csvp = os.path.join(GAL, ds, "msi_clusters_results.csv")
|
||||
df = pd.read_csv(csvp)
|
||||
found = []
|
||||
for name, mz in ION_TARGETS:
|
||||
sub = df[(df["mz"] - mz).abs() <= tol]
|
||||
if sub.empty:
|
||||
continue
|
||||
row = sub.loc[(sub["mz"] - mz).abs().idxmin()]
|
||||
found.append((name, row["ion_image"], row["mz"], row["cluster"]))
|
||||
return found
|
||||
|
||||
|
||||
def _ion_grid(ds, n_cols, ion_h=230, cap_h=78, gap=24):
|
||||
"""Return an annotated grid (n_cols x n_rows) of viridis tropane ion images."""
|
||||
ions = _find_ions(ds)
|
||||
imgs = []
|
||||
for name, ion, mz, cluster in ions:
|
||||
p = os.path.join(GAL, "ion_images_viridis", ds, ion)
|
||||
if not os.path.exists(p):
|
||||
p = os.path.join(GAL, "ion_images", ds, ion)
|
||||
im = Image.open(p).convert("RGBA")
|
||||
iw = int(im.width * ion_h / im.height)
|
||||
imgs.append((im.resize((iw, ion_h), Image.LANCZOS), name, mz, cluster))
|
||||
if not imgs:
|
||||
return None, 0, 0
|
||||
n_rows = (len(imgs) + n_cols - 1) // n_cols
|
||||
cell_w = ion_h # square ion images
|
||||
grid_w = n_cols * cell_w + (n_cols - 1) * gap
|
||||
grid_h = n_rows * (ion_h + cap_h) + (n_rows - 1) * gap
|
||||
grid = Image.new("RGBA", (grid_w, grid_h), (255, 255, 255))
|
||||
d = ImageDraw.Draw(grid)
|
||||
fl_name = font(22)
|
||||
fl_mz = font(20)
|
||||
fl_mz_i = font(20, italic=True)
|
||||
for i, (im, name, mz, cluster) in enumerate(imgs):
|
||||
r, c = divmod(i, n_cols)
|
||||
x = c * (cell_w + gap)
|
||||
y = r * (ion_h + cap_h + gap)
|
||||
paste(im, grid, x, y)
|
||||
cx = x + im.width // 2
|
||||
d.text((cx - d.textlength(name, font=fl_name) / 2, y + ion_h + 6), name, font=fl_name, fill="black")
|
||||
t1 = "m/z"
|
||||
t2 = f" {mz:.2f} · Cluster {cluster}"
|
||||
w1 = d.textlength(t1, font=fl_mz_i)
|
||||
w2 = d.textlength(t2, font=fl_mz)
|
||||
tx = cx - (w1 + w2) / 2
|
||||
d.text((tx, y + ion_h + 34), t1, font=fl_mz_i, fill="black")
|
||||
d.text((tx + w1, y + ion_h + 34), t2, font=fl_mz, fill="black")
|
||||
return grid, grid_w, grid_h
|
||||
|
||||
|
||||
def build_fig2():
|
||||
ds_list = ["Datura_leaf", "Datura_root"]
|
||||
n_cols = {"Datura_leaf": 3, "Datura_root": 2}
|
||||
plot_h = 980
|
||||
ion_h = 430
|
||||
sep = 30
|
||||
panels = []
|
||||
for ds in ds_list:
|
||||
p = os.path.join(GAL, ds, "figures", "cluster_validation_detailed_plot.png")
|
||||
img = Image.open(p).convert("RGBA")
|
||||
w = int(img.width * plot_h / img.height)
|
||||
plot = img.resize((w, plot_h), Image.LANCZOS)
|
||||
grid, gw, gh = _ion_grid(ds, n_cols[ds], ion_h=ion_h)
|
||||
if grid is None:
|
||||
panel_w, panel_h = plot.width, plot_h
|
||||
panel = Image.new("RGBA", (panel_w, panel_h), (255, 255, 255))
|
||||
paste(plot, panel, 0, 0)
|
||||
else:
|
||||
panel_w = plot.width + sep + gw
|
||||
panel_h = max(plot_h, gh)
|
||||
panel = Image.new("RGBA", (panel_w, panel_h), (255, 255, 255))
|
||||
paste(plot, panel, 0, (panel_h - plot_h) // 2)
|
||||
paste(grid, panel, plot.width + sep, (panel_h - gh) // 2)
|
||||
panels.append((panel, ds))
|
||||
maxw = max(p[0].width for p in panels)
|
||||
cell_h = max(p[0].height for p in panels) + 70
|
||||
W = maxw + 80
|
||||
H = len(panels) * cell_h + 10
|
||||
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
||||
d = ImageDraw.Draw(canvas)
|
||||
f = font(32)
|
||||
for i, (panel, ds) in enumerate(panels):
|
||||
x = 40 + (maxw - panel.width) // 2
|
||||
y = 10 + i * cell_h
|
||||
paste(panel, canvas, x, y)
|
||||
d.text((x, y + panel.height + 10), DATASET_LABELS[ds], font=f, fill="black")
|
||||
out = os.path.join(ROOT, FIG_OUT["figure2"])
|
||||
_finalize(canvas, out)
|
||||
|
||||
|
||||
def _bio_ions(ds):
|
||||
"""Curated biologically interpretable ions per dataset: (target_mz, compound, adduct)."""
|
||||
curated = {
|
||||
"Mouse_bladder": [
|
||||
(703.58, "Sphingomyelin (SM 34:1, d18:1/16:0)", "[M+H]+"),
|
||||
(760.58, "Phosphatidylcholine (PC 34:1)", "[M+H]+"),
|
||||
(725.54, "Sphingomyelin (SM 34:1, d18:1/16:0)", "[M+Na]+"),
|
||||
(716.05, "Reference phospholipid", ""),
|
||||
],
|
||||
"Human_colon": [
|
||||
(885.55, "Phosphatidylinositol (PI 38:4, 18:0/20:4)", "[M-H]-"),
|
||||
(861.55, "Phosphatidylinositol (PI 36:2)", "[M-H]-"),
|
||||
(747.52, "Phosphatidylglycerol (PG 34:1)", "[M-H]-"),
|
||||
(788.54, "Phosphatidylserine (PS 36:1, 18:0/18:1)", "[M-H]-"),
|
||||
],
|
||||
}
|
||||
csvp = os.path.join(GAL, ds, "msi_clusters_results.csv")
|
||||
df = pd.read_csv(csvp)
|
||||
found = []
|
||||
for mz, compound, adduct in curated.get(ds, []):
|
||||
sub = df[(df["mz"] - mz).abs() <= 0.12]
|
||||
if sub.empty:
|
||||
continue
|
||||
row = sub.loc[(sub["mz"] - mz).abs().idxmin()]
|
||||
found.append((row["ion_image"], row["mz"], row["cluster"], compound, adduct))
|
||||
return found
|
||||
|
||||
|
||||
def _wrap(draw, text, font, max_w):
|
||||
"""Greedy word-wrap `text` into lines each fitting within `max_w` px."""
|
||||
lines = []
|
||||
for word in text.split():
|
||||
if not lines:
|
||||
lines.append(word)
|
||||
elif draw.textlength(lines[-1] + " " + word, font=font) <= max_w:
|
||||
lines[-1] += " " + word
|
||||
else:
|
||||
lines.append(word)
|
||||
return lines
|
||||
|
||||
|
||||
def build_fig3():
|
||||
ds_list = ["Mouse_bladder", "Human_colon"]
|
||||
tsne_h = 980
|
||||
ion_h = 330
|
||||
cap_h = 92
|
||||
per_row = 2
|
||||
rows = []
|
||||
for ds in ds_list:
|
||||
tsne = Image.open(os.path.join(GAL, ds, "msi_tsne_plot.png")).convert("RGBA")
|
||||
tsne = scale(tsne, tsne_h)
|
||||
reps = []
|
||||
for ion, mz, c, compound, adduct in _bio_ions(ds):
|
||||
p = os.path.join(GAL, "ion_images_viridis", ds, ion)
|
||||
if not os.path.exists(p):
|
||||
p = os.path.join(GAL, "ion_images", ds, ion)
|
||||
im = Image.open(p).convert("RGBA")
|
||||
w = int(im.width * ion_h / im.height)
|
||||
reps.append((im.resize((w, ion_h), Image.LANCZOS), c, mz, compound, adduct))
|
||||
n = len(reps)
|
||||
nrows = (n + per_row - 1) // per_row
|
||||
gapx = 18
|
||||
gapy = 30
|
||||
strip_w = max((r[0].width for r in reps), default=0)
|
||||
strip_h = nrows * (ion_h + cap_h) + (nrows - 1) * gapy
|
||||
panel = Image.new("RGBA", (tsne.width + 36 + strip_w, max(tsne_h, strip_h)), (255, 255, 255))
|
||||
paste(tsne, panel, 0, (panel.height - tsne_h) // 2)
|
||||
d = ImageDraw.Draw(panel)
|
||||
fm = font(20, italic=True)
|
||||
fmz = font(20)
|
||||
flab = font(18)
|
||||
x0 = tsne.width + 36
|
||||
for i, (im, c, mz, compound, adduct) in enumerate(reps):
|
||||
r, col = divmod(i, per_row)
|
||||
x = x0 + col * (strip_w + gapx)
|
||||
y = r * (ion_h + cap_h + gapy)
|
||||
paste(im, panel, x, y)
|
||||
t1 = f"m/z"
|
||||
t2 = f" {mz:.2f} · Cluster {c}"
|
||||
w1 = d.textlength(t1, font=fm)
|
||||
w2 = d.textlength(t2, font=fmz)
|
||||
d.text((x, y + ion_h + 4), t1, font=fm, fill="black")
|
||||
d.text((x + w1, y + ion_h + 4), t2, font=fmz, fill="black")
|
||||
lbl = f"Putative: {compound}" + (f" {adduct}" if adduct else "")
|
||||
for j, line in enumerate(_wrap(d, lbl, flab, strip_w)):
|
||||
d.text((x, y + ion_h + 34 + j * 22), line, font=flab, fill="black")
|
||||
rows.append((panel, ds))
|
||||
maxw = max(p[0].width for p in rows)
|
||||
cell_h = max(p[0].height for p in rows) + 70
|
||||
W = maxw + 80
|
||||
H = len(rows) * cell_h + 10
|
||||
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
||||
d = ImageDraw.Draw(canvas)
|
||||
f = font(32)
|
||||
for i, (panel, ds) in enumerate(rows):
|
||||
x = 40
|
||||
y = 10 + i * cell_h
|
||||
paste(panel, canvas, x, y)
|
||||
d.text((x, y + panel.height + 10), DATASET_LABELS[ds], font=f, fill="black")
|
||||
out = os.path.join(ROOT, FIG_OUT["figure3"])
|
||||
_finalize(canvas, out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_fig1()
|
||||
build_fig2()
|
||||
build_fig3()
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, transforms
|
||||
@@ -11,7 +12,6 @@ from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_har
|
||||
import matplotlib.pyplot as plt
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
@@ -24,12 +24,15 @@ def set_seed(seed=42):
|
||||
|
||||
set_seed(42)
|
||||
|
||||
# CONFIGURATION
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name)
|
||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name)
|
||||
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
||||
K_RANGE = range(2, 21) # overridden per-dataset below to respect small corpora
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
@@ -53,11 +56,10 @@ class MSI_Structural_Encoder(nn.Module):
|
||||
def forward(self, x):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
# 1. LOAD MODEL AND EXTRACT FEATURES
|
||||
def extract_features():
|
||||
model = MSI_Structural_Encoder()
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
||||
raise FileNotFoundError(f"Model not found at {MODEL_PATH}")
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
@@ -69,9 +71,9 @@ def extract_features():
|
||||
|
||||
features = []
|
||||
if not os.path.exists(IMG_DIR):
|
||||
raise FileNotFoundError(f"No se encontró el directorio de imágenes en {IMG_DIR}")
|
||||
raise FileNotFoundError(f"Image directory not found at {IMG_DIR}")
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
|
||||
|
||||
print(f"Extracting features from {len(img_names)} images on {DEVICE}...")
|
||||
with torch.no_grad():
|
||||
for i, name in enumerate(img_names):
|
||||
@@ -80,21 +82,24 @@ def extract_features():
|
||||
img = Image.open(img_path).convert("L")
|
||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||
feat = model(img_t)
|
||||
# CRITICAL FIX: Project explicitly onto the unit hypersphere
|
||||
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat_norm.cpu().numpy().flatten())
|
||||
|
||||
|
||||
return np.array(features)
|
||||
|
||||
# 2. EVALUATE K-MEANS
|
||||
if __name__ == "__main__":
|
||||
X = extract_features()
|
||||
|
||||
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
|
||||
|
||||
n_components = max(2, min(50, X.shape[0], X.shape[1]))
|
||||
pca = PCA(n_components=n_components, random_state=42)
|
||||
X_pca = pca.fit_transform(X)
|
||||
# CRITICAL FIX: Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means equivalent
|
||||
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
|
||||
|
||||
K_RANGE = range(2, min(21, X.shape[0])) # K must be < n_samples for silhouette
|
||||
if K_RANGE.stop - K_RANGE.start < 2:
|
||||
print("Too few ions to evaluate clustering (need at least 3).")
|
||||
K_RANGE = range(2, 3)
|
||||
|
||||
inertias = []
|
||||
silhouettes = []
|
||||
davies_bouldin = []
|
||||
@@ -105,9 +110,8 @@ if __name__ == "__main__":
|
||||
print(f"Calculating for K={k}...")
|
||||
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
||||
labels = kmeans.fit_predict(X_pca)
|
||||
|
||||
|
||||
inertias.append(kmeans.inertia_)
|
||||
# CRITICAL FIX: Evaluate using cosine distance on the un-reduced features
|
||||
silhouettes.append(silhouette_score(X, labels, metric='cosine'))
|
||||
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
||||
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
||||
@@ -139,18 +143,40 @@ if __name__ == "__main__":
|
||||
ax4.grid(True)
|
||||
|
||||
plt.tight_layout()
|
||||
output_plot = os.path.join(BASE_DIR, "..", "figures", "cluster_validation_detailed_plot.png")
|
||||
os.makedirs(os.path.dirname(output_plot), exist_ok=True)
|
||||
plt.savefig(output_plot)
|
||||
print(f"Plot saved as '{output_plot}'")
|
||||
os.makedirs(FIGURES_DIR, exist_ok=True)
|
||||
output_plot = os.path.join(FIGURES_DIR, "cluster_validation_detailed_plot.png")
|
||||
plt.savefig(output_plot, dpi=300, bbox_inches="tight")
|
||||
print(f"Plot saved: {output_plot}")
|
||||
|
||||
idx_10 = list(K_RANGE).index(10)
|
||||
print(f"\n--- RESULTS FOR K=10 ---")
|
||||
print(f"Silhouette Score: {silhouettes[idx_10]:.4f}")
|
||||
print(f"Davies-Bouldin Index: {davies_bouldin[idx_10]:.4f}")
|
||||
print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_10]:.4f}")
|
||||
|
||||
print(f"\n--- MATHEMATICAL SUGGESTIONS ---")
|
||||
print(f"Best K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}")
|
||||
print(f"Best K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}")
|
||||
print(f"Best K (Calinski-Harabasz): {K_RANGE[np.argmax(calinski_harabasz)]}")
|
||||
best_k_sil = K_RANGE[np.argmax(silhouettes)]
|
||||
best_k_db = K_RANGE[np.argmin(davies_bouldin)]
|
||||
best_k_ch = K_RANGE[np.argmax(calinski_harabasz)]
|
||||
|
||||
print(f"\n--- RESULTS FOR {dataset_name.upper()} ---")
|
||||
print(f"Best K (Silhouette): {best_k_sil}")
|
||||
print(f"Best K (Davies-Bouldin): {best_k_db}")
|
||||
print(f"Best K (Calinski-Harabasz):{best_k_ch}")
|
||||
|
||||
# Save results CSV
|
||||
import csv
|
||||
results_path = os.path.join(OUTPUT_DIR, "best_k_results.csv")
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
with open(results_path, 'w', newline='') as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(['metric', 'value'])
|
||||
w.writerow(['best_k_silhouette', best_k_sil])
|
||||
w.writerow(['best_k_davies_bouldin', best_k_db])
|
||||
w.writerow(['best_k_calinski_harabasz', best_k_ch])
|
||||
w.writerow(['silhouette_score_k10', silhouettes[list(K_RANGE).index(10)]])
|
||||
w.writerow(['davies_bouldin_k10', davies_bouldin[list(K_RANGE).index(10)]])
|
||||
w.writerow(['calinski_harabasz_k10', calinski_harabasz[list(K_RANGE).index(10)]])
|
||||
|
||||
# Save per-K scores as CSV
|
||||
scores_path = os.path.join(OUTPUT_DIR, "clustering_scores.csv")
|
||||
with open(scores_path, 'w', newline='') as f:
|
||||
w = csv.writer(f)
|
||||
w.writerow(['k', 'silhouette', 'davies_bouldin', 'calinski_harabasz'])
|
||||
for i, k in enumerate(K_RANGE):
|
||||
w.writerow([k, silhouettes[i], davies_bouldin[i], calinski_harabasz[i]])
|
||||
print(f"Results saved to: {results_path}")
|
||||
print(f"Scores saved to: {scores_path}")
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import random
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn.decomposition import PCA
|
||||
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
|
||||
import matplotlib.pyplot as plt
|
||||
import torch.nn.functional as F
|
||||
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
torch.backends.cudnn.deterministic = True
|
||||
torch.backends.cudnn.benchmark = False
|
||||
|
||||
set_seed(42)
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images")
|
||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs_k5")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K_RANGE = range(2, 21)
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(32, 256),
|
||||
nn.ReLU(),
|
||||
nn.AdaptiveAvgPool2d((1, 1))
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
def extract_features():
|
||||
model = MSI_Structural_Encoder()
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"Model not found at {MODEL_PATH}")
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor(),
|
||||
])
|
||||
|
||||
features = []
|
||||
if not os.path.exists(IMG_DIR):
|
||||
raise FileNotFoundError(f"Image directory not found at {IMG_DIR}")
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
|
||||
print(f"Extracting features from {len(img_names)} images on {DEVICE}...")
|
||||
with torch.no_grad():
|
||||
for i, name in enumerate(img_names):
|
||||
if i % 100 == 0: print(f"Processing image {i}/{len(img_names)}...")
|
||||
img_path = os.path.join(IMG_DIR, name)
|
||||
img = Image.open(img_path).convert("L")
|
||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||
feat = model(img_t)
|
||||
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat_norm.cpu().numpy().flatten())
|
||||
|
||||
return np.array(features)
|
||||
|
||||
if __name__ == "__main__":
|
||||
X = extract_features()
|
||||
|
||||
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
|
||||
X_pca = pca.fit_transform(X)
|
||||
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
|
||||
|
||||
inertias = []
|
||||
silhouettes = []
|
||||
davies_bouldin = []
|
||||
calinski_harabasz = []
|
||||
|
||||
print("Evaluating different K values...")
|
||||
for k in K_RANGE:
|
||||
print(f"Calculating for K={k}...")
|
||||
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
||||
labels = kmeans.fit_predict(X_pca)
|
||||
|
||||
inertias.append(kmeans.inertia_)
|
||||
silhouettes.append(silhouette_score(X, labels, metric='cosine'))
|
||||
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
||||
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
||||
|
||||
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
|
||||
|
||||
ax1.plot(K_RANGE, inertias, 'o-', color='tab:red')
|
||||
ax1.set_title('Elbow Method (Inertia)')
|
||||
ax1.set_xlabel('Number of Clusters (k)')
|
||||
ax1.set_ylabel('Sum of Squared Errors')
|
||||
ax1.grid(True)
|
||||
|
||||
ax2.plot(K_RANGE, silhouettes, 's-', color='tab:blue')
|
||||
ax2.set_title('Silhouette Score (Higher is better)')
|
||||
ax2.set_xlabel('Number of Clusters (k)')
|
||||
ax2.set_ylabel('Score')
|
||||
ax2.grid(True)
|
||||
|
||||
ax3.plot(K_RANGE, davies_bouldin, '^-', color='tab:green')
|
||||
ax3.set_title('Davies-Bouldin Index (Lower is better)')
|
||||
ax3.set_xlabel('Number of Clusters (k)')
|
||||
ax3.set_ylabel('Score')
|
||||
ax3.grid(True)
|
||||
|
||||
ax4.plot(K_RANGE, calinski_harabasz, 'd-', color='tab:orange')
|
||||
ax4.set_title('Calinski-Harabasz Index (Higher is better)')
|
||||
ax4.set_xlabel('Number of Clusters (k)')
|
||||
ax4.set_ylabel('Score')
|
||||
ax4.grid(True)
|
||||
|
||||
plt.tight_layout()
|
||||
output_plot = os.path.join(OUTPUT_DIR, "figures", "cluster_validation_detailed_plot.png")
|
||||
os.makedirs(os.path.dirname(output_plot), exist_ok=True)
|
||||
plt.savefig(output_plot)
|
||||
print(f"Plot saved as '{output_plot}'")
|
||||
|
||||
# Print all k values sorted by Silhouette
|
||||
print("\n--- ALL K VALUES (sorted by Silhouette) ---")
|
||||
k_scores = list(zip(K_RANGE, silhouettes, davies_bouldin, calinski_harabasz))
|
||||
k_scores.sort(key=lambda x: x[1], reverse=True)
|
||||
for k, sil, db, ch in k_scores:
|
||||
marker = " ◀" if k == 5 else ""
|
||||
print(f" K={k:2d}: Silhouette={sil:.4f} DB={db:.4f} CH={ch:.1f}{marker}")
|
||||
|
||||
idx_5 = list(K_RANGE).index(5)
|
||||
idx_10 = list(K_RANGE).index(10)
|
||||
print(f"\n--- RESULTS FOR K=5 ---")
|
||||
print(f"Silhouette Score: {silhouettes[idx_5]:.4f}")
|
||||
print(f"Davies-Bouldin Index: {davies_bouldin[idx_5]:.4f}")
|
||||
print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_5]:.4f}")
|
||||
print(f"\n--- RESULTS FOR K=10 ---")
|
||||
print(f"Silhouette Score: {silhouettes[idx_10]:.4f}")
|
||||
print(f"Davies-Bouldin Index: {davies_bouldin[idx_10]:.4f}")
|
||||
print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_10]:.4f}")
|
||||
|
||||
print(f"\n--- MATHEMATICAL SUGGESTIONS ---")
|
||||
print(f"Best K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}")
|
||||
print(f"Best K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}")
|
||||
print(f"Best K (Calinski-Harabasz): {K_RANGE[np.argmax(calinski_harabasz)]}")
|
||||
@@ -0,0 +1,184 @@
|
||||
import os
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import random
|
||||
from sklearn.decomposition import PCA
|
||||
from sklearn.manifold import TSNE
|
||||
from sklearn.cluster import KMeans
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.colors as mcolors
|
||||
import pandas as pd
|
||||
import torch.nn.functional as F
|
||||
import plotly.express as px
|
||||
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.manual_seed(seed)
|
||||
torch.cuda.manual_seed_all(seed)
|
||||
|
||||
set_seed(42)
|
||||
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
TARGET_K = int(sys.argv[2]) if len(sys.argv) > 2 else 10
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name)
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", dataset_name, "msi_encoder_trained.pth")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name)
|
||||
FIGURES_DIR = os.path.join(OUTPUT_DIR, "figures")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(32, 256),
|
||||
nn.ReLU(),
|
||||
nn.AdaptiveAvgPool2d((1, 1))
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||
return h
|
||||
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||
model = MSI_Structural_Encoder()
|
||||
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
class MSIDatasetInference(Dataset):
|
||||
def __init__(self, img_dir):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||
self.transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
return len(self.img_names)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||
image = Image.open(img_path).convert("L")
|
||||
return self.transform(image), self.img_names[idx]
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"=== t-SNE + K-Means: {dataset_name} (K={TARGET_K}) ===")
|
||||
print("Loading specialized custom MSI Structural Encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetInference(IMG_DIR)
|
||||
loader = DataLoader(dataset, batch_size=64, shuffle=False, num_workers=2)
|
||||
|
||||
features = []
|
||||
ion_names = []
|
||||
|
||||
print("Extracting and L2-normalizing features from custom manifold...")
|
||||
with torch.no_grad():
|
||||
for img, names in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
feat = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat.cpu().numpy())
|
||||
ion_names.extend(names)
|
||||
|
||||
features = np.concatenate(features, axis=0)
|
||||
print(f" Feature matrix: {features.shape}")
|
||||
|
||||
# PCA for denoising (retain 95% variance)
|
||||
pca = PCA(n_components=min(50, features.shape[0], features.shape[1]), random_state=42)
|
||||
features_pca = pca.fit_transform(features)
|
||||
# Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means
|
||||
features_pca = features_pca / np.linalg.norm(features_pca, axis=1, keepdims=True)
|
||||
print(f" PCA components: {features_pca.shape[1]} (explained variance: {pca.explained_variance_ratio_.sum():.3f})")
|
||||
|
||||
print(f"Executing Spherical K-Means (via re-normalized PCA) strictly constrained to K={TARGET_K}...")
|
||||
clusterer = KMeans(n_clusters=TARGET_K, init='k-means++', n_init=20, random_state=42)
|
||||
labels = clusterer.fit_predict(features_pca)
|
||||
|
||||
print("Projecting t-SNE map...")
|
||||
tsne = TSNE(
|
||||
n_components=2,
|
||||
perplexity=min(30, max(5, features.shape[0] - 1)),
|
||||
learning_rate='auto',
|
||||
init='pca',
|
||||
random_state=42
|
||||
)
|
||||
embeddings_2d = tsne.fit_transform(features_pca)
|
||||
|
||||
output_dir = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name)
|
||||
figures_dir = os.path.join(output_dir, "figures")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
|
||||
plt.figure(figsize=(10, 8))
|
||||
base_cmap = plt.cm.tab20
|
||||
cluster_colors = [base_cmap(i % 20) for i in range(TARGET_K)]
|
||||
cmap = mcolors.ListedColormap(cluster_colors)
|
||||
bounds = np.arange(TARGET_K + 1) - 0.5
|
||||
norm = mcolors.BoundaryNorm(bounds, cmap.N)
|
||||
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap=cmap, norm=norm, alpha=0.9, edgecolors='none', s=45)
|
||||
cbar = plt.colorbar(scatter, ticks=range(TARGET_K))
|
||||
cbar.set_label(f'Metabolic Domain ID (K={TARGET_K})')
|
||||
|
||||
plt.title(f"t-SNE Visualization: {dataset_name} (K={TARGET_K})")
|
||||
plt.xlabel("t-SNE Dimension 1")
|
||||
plt.ylabel("t-SNE Dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.3)
|
||||
|
||||
plt.savefig(os.path.join(output_dir, "msi_tsne_plot.png"), dpi=300, bbox_inches='tight')
|
||||
plt.close()
|
||||
print(f" t-SNE saved to: outputs/{dataset_name}/msi_tsne_plot.png")
|
||||
|
||||
print("Exporting Interactive Plotly t-SNE...")
|
||||
mz_values = [float(n.replace("ion_", "").replace(".png", "")) for n in ion_names]
|
||||
df_plot = pd.DataFrame({
|
||||
't-SNE Dimension 1': embeddings_2d[:, 0],
|
||||
't-SNE Dimension 2': embeddings_2d[:, 1],
|
||||
'Cluster': [str(lbl) for lbl in labels],
|
||||
'm/z': mz_values,
|
||||
'Filename': ion_names
|
||||
})
|
||||
|
||||
fig = px.scatter(
|
||||
df_plot,
|
||||
x='t-SNE Dimension 1',
|
||||
y='t-SNE Dimension 2',
|
||||
color='Cluster',
|
||||
hover_data=['m/z', 'Filename'],
|
||||
title=f"Interactive t-SNE: {dataset_name} (K={TARGET_K})",
|
||||
category_orders={"Cluster": [str(i) for i in range(TARGET_K)]}
|
||||
)
|
||||
|
||||
plotly_out = os.path.join(figures_dir, "msi_tsne_interactive.html")
|
||||
fig.write_html(plotly_out)
|
||||
print(f" Interactive t-SNE saved to: outputs/{dataset_name}/figures/msi_tsne_interactive.html")
|
||||
|
||||
print("Exporting synchronized cluster assignments...")
|
||||
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||
df_results['mz'] = df_results['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
df_results.to_csv(os.path.join(output_dir, "msi_clusters_results.csv"), index=False)
|
||||
|
||||
print(f"Process complete for {dataset_name}.")
|
||||
Reference in New Issue
Block a user