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
|
||||
from torchvision import models, transforms
|
||||
@@ -13,7 +14,6 @@ import matplotlib.pyplot as plt
|
||||
from scipy.stats import ttest_ind
|
||||
import torch.nn.functional as F
|
||||
|
||||
# 0. REPRODUCIBILITY
|
||||
def set_seed(seed=42):
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
@@ -26,12 +26,15 @@ def set_seed(seed=42):
|
||||
|
||||
set_seed(42)
|
||||
|
||||
# CONFIGURATION
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
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, "..", "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 = 10
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
@@ -55,7 +58,6 @@ class MSI_Structural_Encoder(nn.Module):
|
||||
def forward(self, x):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
# 1. DATA LOADING
|
||||
def load_images():
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
raw_pixels = []
|
||||
@@ -95,19 +97,19 @@ def extract_simclr_features(img_names):
|
||||
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. VALIDATION TASKS
|
||||
def baseline_comparison(X_raw, X_simclr):
|
||||
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
|
||||
pca_raw = PCA(n_components=50, random_state=42)
|
||||
pca_raw = PCA(n_components=min(50, X_raw.shape[0], X_raw.shape[1]), random_state=42)
|
||||
X_pca_raw = pca_raw.fit_transform(X_raw)
|
||||
|
||||
pca_simclr = PCA(n_components=50, random_state=42)
|
||||
pca_simclr = PCA(n_components=min(50, X_simclr.shape[0], X_simclr.shape[1]), random_state=42)
|
||||
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
|
||||
# Restore unit hypersphere geometry after PCA for Spherical K-Means
|
||||
X_pca_simclr = X_pca_simclr / np.linalg.norm(X_pca_simclr, axis=1, keepdims=True)
|
||||
|
||||
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
|
||||
labels_raw = km_raw.fit_predict(X_pca_raw)
|
||||
@@ -132,8 +134,10 @@ def stability_analysis(X_features):
|
||||
all_labels = []
|
||||
metrics_list = []
|
||||
|
||||
pca = PCA(n_components=50, random_state=42)
|
||||
pca = PCA(n_components=min(50, X_features.shape[0], X_features.shape[1]), random_state=42)
|
||||
X_pca = pca.fit_transform(X_features)
|
||||
# Re-normalize after PCA to match Spherical K-Means used in graph_tsne_msi.py
|
||||
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
|
||||
|
||||
for seed in seeds:
|
||||
km = KMeans(n_clusters=K, random_state=seed, n_init=10)
|
||||
@@ -146,7 +150,7 @@ def stability_analysis(X_features):
|
||||
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 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):
|
||||
@@ -178,14 +182,16 @@ def isotope_validation(X_features, mzs):
|
||||
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
|
||||
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
|
||||
|
||||
os.makedirs(FIGURES_DIR, exist_ok=True)
|
||||
plt.figure(figsize=(8, 6))
|
||||
plt.boxplot([isotope_dist, random_dist], tick_labels=['Isotopic Pairs', 'Random Pairs'])
|
||||
plt.title('Latent Space Distances: Isotopes vs Random')
|
||||
plt.title(f'Latent Space Distances: Isotopes vs Random ({dataset_name})')
|
||||
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")
|
||||
plt.savefig(os.path.join(FIGURES_DIR, "isotope_validation_plot.png"))
|
||||
print(f"Isotope validation plot saved to: outputs/{dataset_name}/figures/isotope_validation_plot.png")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"=== Quantitative Validation: {dataset_name} (K={K}) ===")
|
||||
if not os.path.exists(IMG_DIR):
|
||||
print(f"Error: IMG_DIR {IMG_DIR} not found. Generate ion images first.")
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
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
|
||||
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 = 5
|
||||
|
||||
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 load_images():
|
||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
raw_pixels = []
|
||||
mzs = []
|
||||
|
||||
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())
|
||||
|
||||
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 = MSI_Structural_Encoder()
|
||||
if os.path.exists(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 = []
|
||||
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("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)
|
||||
|
||||
def baseline_comparison(X_raw, X_simclr):
|
||||
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
|
||||
pca_raw = PCA(n_components=50, random_state=42)
|
||||
X_pca_raw = pca_raw.fit_transform(X_raw)
|
||||
|
||||
pca_simclr = PCA(n_components=50, random_state=42)
|
||||
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
|
||||
X_pca_simclr = X_pca_simclr / np.linalg.norm(X_pca_simclr, axis=1, keepdims=True)
|
||||
|
||||
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))
|
||||
|
||||
figures_dir = os.path.join(OUTPUT_DIR, "figures")
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
df_metrics.to_csv(os.path.join(figures_dir, "baseline_comparison_k5.csv"), 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)
|
||||
X_pca = X_pca / np.linalg.norm(X_pca, axis=1, keepdims=True)
|
||||
|
||||
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))
|
||||
|
||||
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)")
|
||||
|
||||
results = {
|
||||
"mean_silhouette": np.mean(metrics_list),
|
||||
"std_silhouette": np.std(metrics_list),
|
||||
"mean_ari": np.mean(ari_scores),
|
||||
}
|
||||
figures_dir = os.path.join(OUTPUT_DIR, "figures")
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
pd.DataFrame([results]).to_csv(os.path.join(figures_dir, "stability_k5.csv"), index=False)
|
||||
|
||||
def isotope_validation(X_features, mzs):
|
||||
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
|
||||
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
|
||||
|
||||
isotope_dist = []
|
||||
random_dist = []
|
||||
|
||||
for i in range(len(mzs)):
|
||||
for j in range(i + 1, len(mzs)):
|
||||
diff = abs(mzs[i] - mzs[j])
|
||||
if 0.95 <= diff <= 1.05:
|
||||
dist = np.linalg.norm(X_norm[i] - X_norm[j])
|
||||
isotope_dist.append(dist)
|
||||
|
||||
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)")
|
||||
|
||||
figures_dir = os.path.join(OUTPUT_DIR, "figures")
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
plt.figure(figsize=(8, 6))
|
||||
plt.boxplot([isotope_dist, random_dist], tick_labels=['Isotopic Pairs', 'Random Pairs'])
|
||||
plt.title('Latent Space Distances: Isotopes vs Random (K=5)')
|
||||
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
|
||||
plt.savefig(os.path.join(figures_dir, "isotope_validation_k5.png"))
|
||||
print(f"Isotope validation plot saved to outputs_k5/figures/isotope_validation_k5.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:
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
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)
|
||||
@@ -9,8 +9,8 @@ from sklearn.cluster import KMeans
|
||||
import torch.nn.functional as F
|
||||
|
||||
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")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images")
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
@@ -47,7 +47,6 @@ def load_encoder_diagnostic(path):
|
||||
if __name__ == "__main__":
|
||||
encoder = load_encoder_diagnostic(ENCODER_PATH)
|
||||
|
||||
# Load targets directly to test raw alignment
|
||||
img_155 = os.path.join(IMG_DIR, "ion_155.75.png")
|
||||
img_156 = os.path.join(IMG_DIR, "ion_156.07.png")
|
||||
|
||||
@@ -57,7 +56,6 @@ if __name__ == "__main__":
|
||||
])
|
||||
|
||||
if os.path.exists(img_155) and os.path.exists(img_156):
|
||||
# Convert to Grayscale "L"
|
||||
t_155 = transform(Image.open(img_155).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
t_156 = transform(Image.open(img_156).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
|
||||
@@ -65,9 +63,7 @@ if __name__ == "__main__":
|
||||
f_155 = encoder(t_155)
|
||||
f_156 = encoder(t_156)
|
||||
|
||||
# Check directional similarity
|
||||
sim = F.cosine_similarity(f_155, f_156)
|
||||
print(f"\n--- Feature Diagnostics ---")
|
||||
print(f"Cosine Similarity between Vein Ions (155.75 vs 156.07): {sim.item():.4f}")
|
||||
print("If this value is below 0.85, the loaded weight file is treating them as different shapes.")
|
||||
|
||||
|
||||
@@ -5,9 +5,12 @@ import pandas as pd
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from torchvision import transforms
|
||||
|
||||
# Copy the exact encoder structure from your scripts
|
||||
import torch.nn as nn
|
||||
|
||||
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")
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
@@ -30,8 +33,6 @@ class MSI_Structural_Encoder(nn.Module):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
DEVICE = torch.device("cpu")
|
||||
IMG_DIR = "datos_para_ai"
|
||||
MODEL_PATH = "models/msi_encoder_trained.pth"
|
||||
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
print("Model not found. Please ensure you are in the correct directory.")
|
||||
@@ -44,7 +45,6 @@ model.eval()
|
||||
transform = transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor()])
|
||||
|
||||
def get_vector(mz_target):
|
||||
# Find the file closest to mz_target
|
||||
files = [f for f in os.listdir(IMG_DIR) if f.endswith('.png')]
|
||||
mzs = [float(f.replace("ion_", "").replace(".png", "")) for f in files]
|
||||
idx = np.argmin(np.abs(np.array(mzs) - mz_target))
|
||||
@@ -64,21 +64,18 @@ def get_vector(mz_target):
|
||||
|
||||
print("--- INTERNAL VALIDATION: ISOTOPIC & STRUCTURAL COHERENCE ---")
|
||||
|
||||
# Test 1: Isotopic Coherence (Atropine and its +1 Isotope)
|
||||
v1, mz1 = get_vector(290.02)
|
||||
v2, mz2 = get_vector(291.00)
|
||||
if v1 is not None and v2 is not None:
|
||||
sim = np.dot(v1, v2)
|
||||
print(f"Isotopic Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz2:.2f} (+1 Isotope): Cosine Similarity = {sim:.4f}")
|
||||
|
||||
# Test 2: Structural Coherence (Atropine and Scopolamine - both vascular)
|
||||
v3, mz3 = get_vector(304.00)
|
||||
if v1 is not None and v3 is not None:
|
||||
sim = np.dot(v1, v3)
|
||||
print(f"Biological Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz3:.2f} (Scopolamine): Cosine Similarity = {sim:.4f}")
|
||||
|
||||
# Test 3: Unrelated Coherence (Atropine vs random background or non-vascular)
|
||||
v4, mz4 = get_vector(142.09) # Tropine (paravascular, should be lower than scopolamine)
|
||||
v4, mz4 = get_vector(142.09)
|
||||
if v1 is not None and v4 is not None:
|
||||
sim = np.dot(v1, v4)
|
||||
print(f"Divergent Match -> m/z {mz1:.2f} (Atropine) vs m/z {mz4:.2f} (Tropine): Cosine Similarity = {sim:.4f}")
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
import sys
|
||||
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__))
|
||||
# Strictly use the root results file generated by graficar_tsne_msi.py
|
||||
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "leaf"
|
||||
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "galleries")
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
CSV_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name, "msi_clusters_results.csv")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images", dataset_name)
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", dataset_name, "galleries")
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
# 2. PROCESSING
|
||||
if os.path.exists(CSV_PATH):
|
||||
print(f"=== Cluster Galleries: {dataset_name} ===")
|
||||
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)
|
||||
|
||||
@@ -26,18 +25,16 @@ if os.path.exists(CSV_PATH):
|
||||
else:
|
||||
for cluster_id in sorted(df['cluster'].unique()):
|
||||
print(f"Generating gallery for Cluster {cluster_id}...")
|
||||
# Take a 3x3 sample of the cluster
|
||||
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)
|
||||
fig.suptitle(f"Cluster {cluster_id} - Ion Morphologies ({dataset_name})", 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)
|
||||
# Using 'viridis' improves human visibility of low-concentration transport traces in the veins
|
||||
ax.imshow(img, cmap='viridis')
|
||||
ax.set_title(cluster_ions[i], fontsize=8)
|
||||
else:
|
||||
@@ -45,11 +42,10 @@ if os.path.exists(CSV_PATH):
|
||||
ax.axis('off')
|
||||
|
||||
plt.tight_layout()
|
||||
# Standardized filename for consistency
|
||||
plt.savefig(f"{OUTPUT_DIR}/Gallery_cluster_{cluster_id}.png")
|
||||
plt.close()
|
||||
|
||||
print(f"\nGalleries successfully saved in: {OUTPUT_DIR}")
|
||||
print(f"\nGalleries saved in: {OUTPUT_DIR}")
|
||||
else:
|
||||
print(f"Error: Missing required results file: {CSV_PATH}")
|
||||
print("Please run 'python scripts_python/graficar_tsne_msi.py' first to generate results.")
|
||||
print("Please run 'python graph_tsne_msi.py <dataset>' first to generate results.")
|
||||
|
||||
Reference in New Issue
Block a user