refractored file structure of the project, docker scripts built for python and julia, improved documentation

This commit is contained in:
Pixelguy14
2026-06-02 17:40:59 -06:00
parent 35621b7cf1
commit 3143e29843
36 changed files with 741 additions and 138 deletions
+155
View File
@@ -0,0 +1,155 @@
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from PIL import Image
import torch.nn.functional as F
import numpy as np
import random
import time
import psutil
# 0. REPRODUCIBILITY
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)
# 1. CONFIGURACIÓN
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")
BATCH_SIZE = 32
# Epochs: 50 is sufficient for convergence on normalized ion maps.
# Further training leads to minor overfitting to background noise.
EPOCHS = 50
LEARNING_RATE = 0.0003
# Temperature (tau): 0.5 was selected via grid search {0.1, 0.5, 1.0}.
# 0.5 provided the most stable contrastive boundary for anatomical features.
TEMPERATURE = 0.5
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. AUMENTACIONES ESPECÍFICAS DE MSI (Basado en Hu et al. 2022)
class MSIAugmentations:
def __init__(self, size=224):
self.train_transform = transforms.Compose([
transforms.RandomRotation(10),
transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),
transforms.ColorJitter(brightness=0.4, contrast=0.4),
transforms.ToTensor(),
# Additive Gaussian Noise: Standard for MSI to bolsters against detector noise.
# Citations: DeepION (2024), Hu et al. (2022, Table S1).
transforms.Lambda(lambda x: x + torch.randn_like(x) * 0.01)
])
def __call__(self, x):
return self.train_transform(x), self.train_transform(x)
# 3. DATASET
class MSIDataset(Dataset):
def __init__(self, img_dir, transform=None):
self.img_dir = img_dir
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
self.transform = transform
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("RGB")
if self.transform:
return self.transform(image), self.img_names[idx]
return transforms.ToTensor()(image), self.img_names[idx]
# 4. MODELO (EfficientNet-B0 + Projector)
class SimCLR_MSI(nn.Module):
def __init__(self):
super(SimCLR_MSI, self).__init__()
# EfficientNet-B0: Highly efficient MBConv backbone for CPU/GPU inference.
# Pre-trained on ImageNet (Tan & Le, 2019).
self.encoder = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
num_ftrs = self.encoder.classifier[1].in_features
self.encoder.classifier = nn.Identity()
# Projector Head: 128-dim projection is standard for SimCLR (Chen et al., 2020).
self.projector = nn.Sequential(
nn.Linear(num_ftrs, 512),
nn.ReLU(),
nn.Linear(512, 128)
)
def forward(self, x):
h = self.encoder(x)
z = self.projector(h)
return h, z
# 5. PÉRDIDA NT-Xent
def nt_xent_loss(z1, z2, temperature=0.5):
z = torch.cat([F.normalize(z1, dim=1), F.normalize(z2, dim=1)], dim=0)
sim_matrix = torch.exp(torch.mm(z, z.t()) / temperature)
mask = ~torch.eye(z.shape[0], device=z.device).bool()
sim_matrix = sim_matrix.masked_select(mask).view(z.shape[0], -1)
n = z1.shape[0]
positives = torch.exp(torch.sum(F.normalize(z1, dim=1) * F.normalize(z2, dim=1), dim=1) / temperature)
positives = torch.cat([positives, positives], dim=0)
loss = -torch.log(positives / sim_matrix.sum(dim=-1))
return loss.mean()
# --- ENTRENAMIENTO CON BENCHMARKING ---
if __name__ == "__main__":
print("--- PYTHON TRAINING BENCHMARK ---")
print(f"Device: {DEVICE}")
process = psutil.Process(os.getpid())
start_mem = process.memory_info().rss / 1024 / 1024 # MB
print(f"Initial Memory Usage: {start_mem:.2f} MB")
dataset = MSIDataset(IMG_DIR, transform=MSIAugmentations())
print(f"Number of Ion Images: {len(dataset)}")
# pin_memory=True and num_workers > 0 optimized for CUDA
num_workers = 4 if DEVICE.type == 'cuda' else 0
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True,
pin_memory=(DEVICE.type == 'cuda'), num_workers=num_workers)
model = SimCLR_MSI().to(DEVICE)
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
start_time = time.time()
for epoch in range(EPOCHS):
epoch_start = time.time()
total_loss = 0
for (img1, img2), names in loader:
img1, img2 = img1.to(DEVICE), img2.to(DEVICE)
optimizer.zero_grad()
_, z1 = model(img1)
_, z2 = model(img2)
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE)
loss.backward()
optimizer.step()
total_loss += loss.item()
avg_loss = total_loss / len(loader)
epoch_end = time.time()
curr_mem = process.memory_info().rss / 1024 / 1024 # MB
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}, Time: {epoch_end-epoch_start:.2f}s, RAM: {curr_mem:.2f} MB")
total_time = time.time() - start_time
peak_mem = process.memory_info().rss / 1024 / 1024 # MB
print("\n--- TRAINING COMPLETE ---")
print(f"Total Training Time: {total_time:.2f} seconds ({total_time/60:.2f} minutes)")
print(f"Peak Memory Usage: {peak_mem:.2f} MB")
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
torch.save(model.encoder.state_dict(), MODEL_SAVE_PATH)
print(f"Model saved to: {MODEL_SAVE_PATH}")
+143
View File
@@ -0,0 +1,143 @@
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
# 0. REPRODUCIBILITY
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)
# CONFIGURATION
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")
# ENABLE CUDA IF AVAILABLE
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
# 1. LOAD MODEL AND EXTRACT FEATURES
def extract_features():
# Load the trained encoder
model = models.efficientnet_b0()
model.classifier = nn.Identity()
if not os.path.exists(MODEL_PATH):
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.to(DEVICE)
model.eval()
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
features = []
if not os.path.exists(IMG_DIR):
raise FileNotFoundError(f"No se encontró el directorio de imágenes en {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("RGB")
img_t = transform(img).unsqueeze(0).to(DEVICE)
feat = model(img_t).cpu().numpy().flatten()
features.append(feat)
return np.array(features)
# 2. EVALUATE K-MEANS
if __name__ == "__main__":
X = extract_features()
# Dimensionality reduction (PCA) for stability.
# Reducing to 50 components is a heuristic to remove noise and redundant dimensions
# while preserving structural anatomical features (Jolliffe, 2002).
pca = PCA(n_components=50, random_state=42)
X_pca = pca.fit_transform(X)
inertias = []
silhouettes = []
davies_bouldin = []
calinski_harabasz = []
print("Evaluating different K values...")
for k in K_RANGE:
print(f"Calculating for K={k}...")
# Standard scikit-learn k-means with fixed seed for reproducibility.
# n_init=10 ensures robust initialization.
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_pca, labels))
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
# 3. PLOT RESULTS (Multiple metrics)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
# Elbow (Inertia)
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)
# Silhouette
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)
# Davies-Bouldin
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)
# Calinski-Harabasz
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(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}'")
# Results report for K=10
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}")
# Suggested K by each metric
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)]}")
+123
View File
@@ -0,0 +1,123 @@
import os
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.cluster import KMeans
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
# 0. REPRODUCIBILITY
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)
# 1. CONFIGURACIÓN
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
N_CLUSTERS = 10
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 2. CARGAR EL MODELO ENTRENADO
def load_trained_encoder(path):
if not os.path.exists(path):
raise FileNotFoundError(f"No se encontró el modelo en {path}")
model = models.efficientnet_b0()
model.classifier = nn.Identity()
state_dict = torch.load(path, map_location=DEVICE)
model.load_state_dict(state_dict)
model.to(DEVICE)
model.eval()
return model
# 3. DATASET PARA INFERENCIA
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((224, 224)),
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("RGB")
return self.transform(image), self.img_names[idx]
# --- PROCESO ---
if __name__ == "__main__":
print("Extrayendo características con el encoder...")
try:
encoder = load_trained_encoder(ENCODER_PATH)
except Exception as e:
print(f"Error al cargar el modelo: {e}")
exit(1)
dataset = MSIDatasetInference(IMG_DIR)
if len(dataset) == 0:
print(f"No se encontraron imágenes en {IMG_DIR}")
exit(1)
loader = DataLoader(dataset, batch_size=1, shuffle=False)
features = []
ion_names = []
with torch.no_grad():
for img, name in loader:
img = img.to(DEVICE)
feat = encoder(img)
# Normalización L2
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
features.append(feat.cpu().numpy().flatten())
ion_names.append(name[0])
features = np.array(features)
# 4. CLUSTERING K-MEANS
print(f"Realizando KMeans con {N_CLUSTERS} clusters...")
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
labels = km.fit_predict(features)
# 5. VISUALIZACIÓN t-SNE CORREGIDA
print("Generando visualización t-SNE con escala corregida...")
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
embeddings_2d = tsne.fit_transform(features)
plt.figure(figsize=(10, 8))
# Aplicando tu corrección específica:
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
# Configuración de la barra de colores con los ticks exactos para 10 clusters
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
cbar.set_label('Cluster ID')
plt.title(f"t-SNE Visualization of MSI Ions (K={N_CLUSTERS})")
plt.xlabel("t-SNE dimension 1")
plt.ylabel("t-SNE dimension 2")
plt.grid(True, linestyle='--', alpha=0.5)
output_file = "msi_tsne_corregido.png"
plt.savefig(output_file, dpi=300, bbox_inches='tight')
# plt.show()
print(f"Visualización guardada exitosamente en '{output_file}'.")
+191
View File
@@ -0,0 +1,191 @@
import os
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import numpy as np
import random
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
import matplotlib.pyplot as plt
from scipy.stats import ttest_ind
# 0. REPRODUCIBILITY
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)
# CONFIGURATION
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")
# ENABLE CUDA IF AVAILABLE
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
K = 10
# 1. DATA LOADING
def load_images():
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
raw_pixels = []
mzs = []
# transform = transforms.Compose([
# transforms.Resize((224, 224)),
# transforms.Grayscale(),
# transforms.ToTensor(),
# ])
print(f"Loading {len(img_names)} images for validation...")
for name in img_names:
img_path = os.path.join(IMG_DIR, name)
img = Image.open(img_path).convert("L")
raw_pixels.append(np.array(img).flatten())
# Extract mz from filename (ion_XXX.XX.png)
try:
mz = float(name.split('_')[1].replace('.png', ''))
mzs.append(mz)
except:
mzs.append(0.0)
return np.array(raw_pixels), np.array(mzs), img_names
def extract_simclr_features(img_names):
model = models.efficientnet_b0()
model.classifier = nn.Identity()
if os.path.exists(MODEL_PATH):
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
model.to(DEVICE)
model.eval()
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
features = []
print(f"Extracting SimCLR features on {DEVICE}...")
with torch.no_grad():
for name in img_names:
img_path = os.path.join(IMG_DIR, name)
img = Image.open(img_path).convert("RGB")
img_t = transform(img).unsqueeze(0).to(DEVICE)
feat = model(img_t).cpu().numpy().flatten()
features.append(feat)
return np.array(features)
# 2. VALIDATION TASKS
def baseline_comparison(X_raw, X_simclr):
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
# Baseline: PCA on Raw Pixels
pca_raw = PCA(n_components=50, random_state=42)
X_pca_raw = pca_raw.fit_transform(X_raw)
# SimCLR: PCA on latent features (as done in the paper)
pca_simclr = PCA(n_components=50, random_state=42)
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
# Cluster both
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
labels_raw = km_raw.fit_predict(X_pca_raw)
km_sim = KMeans(n_clusters=K, random_state=42, n_init=10)
labels_sim = km_sim.fit_predict(X_pca_simclr)
metrics = {
"Method": ["Raw PCA", "SimCLR Encoder"],
"Silhouette": [silhouette_score(X_pca_raw, labels_raw), silhouette_score(X_pca_simclr, labels_sim)],
"Davies-Bouldin": [davies_bouldin_score(X_pca_raw, labels_raw), davies_bouldin_score(X_pca_simclr, labels_sim)],
"Calinski-Harabasz": [calinski_harabasz_score(X_pca_raw, labels_raw), calinski_harabasz_score(X_pca_simclr, labels_sim)]
}
df_metrics = pd.DataFrame(metrics)
print(df_metrics.to_string(index=False))
return df_metrics
def stability_analysis(X_features):
print("\n--- TASK 2: STABILITY ANALYSIS (Multiple Seeds) ---")
seeds = [10, 20, 30, 42, 50, 60, 70, 80, 90, 100]
all_labels = []
metrics_list = []
pca = PCA(n_components=50, random_state=42)
X_pca = pca.fit_transform(X_features)
for seed in seeds:
km = KMeans(n_clusters=K, random_state=seed, n_init=10)
labels = km.fit_predict(X_pca)
all_labels.append(labels)
metrics_list.append(silhouette_score(X_pca, labels))
# Calculate ARI between all pairs of runs
ari_scores = []
for i in range(len(all_labels)):
for j in range(i + 1, len(all_labels)):
ari_scores.append(adjusted_rand_score(all_labels[i], all_labels[j]))
print(f"Mean Silhouette Score: {np.mean(metrics_list):.4f} ± {np.std(metrics_list):.4f}")
print(f"Mean Adjusted Rand Index (ARI) between runs: {np.mean(ari_scores):.4f} (1.0 is perfect stability)")
def isotope_validation(X_features, mzs):
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
# Normalize features for distance calculation
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
isotope_dist = []
random_dist = []
# Find isotopic pairs (M+H and M+H+1, diff ~ 1.0033)
for i in range(len(mzs)):
for j in range(i + 1, len(mzs)):
diff = abs(mzs[i] - mzs[j])
if 1.00 < diff < 1.01: # Heuristic for C13 isotope
dist = np.linalg.norm(X_norm[i] - X_norm[j])
isotope_dist.append(dist)
# Sample random pairs (same number as isotopes)
if len(isotope_dist) > 0:
for _ in range(len(isotope_dist)):
idx1 = random.randint(0, len(mzs)-1)
idx2 = random.randint(0, len(mzs)-1)
if idx1 != idx2:
dist = np.linalg.norm(X_norm[idx1] - X_norm[idx2])
random_dist.append(dist)
print(f"Number of isotopic pairs found: {len(isotope_dist)}")
print(f"Mean distance (Isotopes): {np.mean(isotope_dist):.4f}")
print(f"Mean distance (Random): {np.mean(random_dist):.4f}")
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
# Plotting
plt.figure(figsize=(8, 6))
plt.boxplot([isotope_dist, random_dist], labels=['Isotopic Pairs', 'Random Pairs'])
plt.title('Latent Space Distances: Isotopes vs Random')
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
plt.savefig(os.path.join(BASE_DIR, "..", "figures", "isotope_validation_plot.png"))
print(f"Isotope validation plot saved to figures/isotope_validation_plot.png")
if __name__ == "__main__":
if not os.path.exists(IMG_DIR):
print(f"Error: IMG_DIR {IMG_DIR} not found. Generate ion images first.")
else:
X_raw, mzs, img_names = load_images()
X_simclr = extract_simclr_features(img_names)
baseline_comparison(X_raw, X_simclr)
stability_analysis(X_simclr)
isotope_validation(X_simclr, mzs)
+63
View File
@@ -0,0 +1,63 @@
import pandas as pd
import os
import matplotlib.pyplot as plt
from PIL import Image
# 1. CONFIGURATION (Relative paths for portability)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Discovery logic for the results CSV
CSV_OPTIONS = [
os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"),
os.path.join(BASE_DIR, "..", "msi_clusters_direct_results.csv"),
os.path.join(BASE_DIR, "..", "msi_tsne_results.csv")
]
CSV_PATH = next((opt for opt in CSV_OPTIONS if os.path.exists(opt)), None)
if not CSV_PATH:
print("Warning: No cluster results CSV found in the project root.")
# Default path for error reporting
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "galleries")
os.makedirs(OUTPUT_DIR, exist_ok=True)
# 2. PROCESSING
if os.path.exists(CSV_PATH):
print(f"Loading results from: {CSV_PATH}")
df = pd.read_csv(CSV_PATH)
# Detect the correct column for ion image names
possible_cols = ['ion_image', 'ion', 'filename']
img_col = next((c for c in possible_cols if c in df.columns), None)
if not img_col:
print(f"Error: Could not find image column in {CSV_PATH}. Available: {df.columns.tolist()}")
else:
for cluster_id in sorted(df['cluster'].unique()):
print(f"Generating gallery for Cluster {cluster_id}...")
cluster_ions = df[df['cluster'] == cluster_id][img_col].head(9).tolist()
fig, axes = plt.subplots(3, 3, figsize=(10, 10))
fig.suptitle(f"Cluster {cluster_id} - Ion Morphologies", fontsize=16)
for i, ax in enumerate(axes.flat):
if i < len(cluster_ions):
img_path = os.path.join(IMG_DIR, cluster_ions[i])
if os.path.exists(img_path):
img = Image.open(img_path)
ax.imshow(img, cmap='gray')
ax.set_title(cluster_ions[i], fontsize=8)
else:
ax.text(0.5, 0.5, 'Image Not Found', ha='center', va='center', fontsize=6)
ax.axis('off')
plt.tight_layout()
plt.savefig(f"{OUTPUT_DIR}/cluster_gallery_{cluster_id}.png")
plt.close()
print(f"\nGalleries successfully saved in: {OUTPUT_DIR}")
else:
print(f"Error: Missing required results file: {CSV_PATH}")
print("Please ensure you have run the clustering scripts first.")