From adfc1fad0e1663faad5a5833c8e58013ac67b088 Mon Sep 17 00:00:00 2001 From: Carlos Date: Fri, 17 Apr 2026 23:24:44 +0200 Subject: [PATCH] Subir archivos a "/" --- all_ions_mask_triq.jl | 64 ++++++++++++++++++++ graficar_espectro_clusters.jl | 71 ++++++++++++++++++++++ graficar_tsne_msi.py | 108 ++++++++++++++++++++++++++++++++++ preparar_datos_simclr.jl | 42 +++++++++++++ visualizar_clusters.py | 34 +++++++++++ 5 files changed, 319 insertions(+) create mode 100644 all_ions_mask_triq.jl create mode 100644 graficar_espectro_clusters.jl create mode 100644 graficar_tsne_msi.py create mode 100644 preparar_datos_simclr.jl create mode 100644 visualizar_clusters.py diff --git a/all_ions_mask_triq.jl b/all_ions_mask_triq.jl new file mode 100644 index 0000000..efef561 --- /dev/null +++ b/all_ions_mask_triq.jl @@ -0,0 +1,64 @@ +using MSI_src +using Statistics, Plots, Images + +# 1. Definir función de contraste (si no la tienes ya en la sesión) +function apply_triq(img_matrix) + vals = filter(x -> x > 0 && isfinite(x), img_matrix) + if isempty(vals) return img_matrix end + q = quantile(vals, 0.98) + if q == 0 q = maximum(vals) end + return clamp.(img_matrix ./ q, 0.0, 1.0) +end + +# 2. Configuración de rutas +path_data = "Hoja.imzML" +path_mask = "region_interes.png" +output_folder = "resultados_expertos/batch_triq" +mkpath(output_folder) + +# 3. Carga de datos +data = OpenMSIData(path_data) + +# 4. Obtener espectro promedio SOLO de la zona de la máscara (ROI) +println("Calculando espectro promedio en la ROI...") +# Nota: Usamos la función de MSI_src para obtener el promedio filtrado +mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=path_mask) + +# 5. Identificar picos importantes (ej. > 2% del pico base) +max_int = maximum(avg_ints) +umbral = max_int * 0.02 # Ajusta este valor (0.01 para 1%, 0.05 para 5%) +indices_picos = findall(x -> x > umbral, avg_ints) + +println("Se encontraron $(length(indices_picos)) iones que superan el umbral.") + +# 6. Bucle para generar imágenes con TrIQ +for idx in indices_picos + mz_val = mzs[idx] + + # Validar rango (ejemplo: m/z 50 a 700) + if mz_val < 50.0 || mz_val > 700.0 + continue + end + + println("Procesando m/z: $(round(mz_val, digits=2))") + + # A. Extraer los datos crudos con la máscara aplicada + raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=path_mask) + + # B. Aplicar contraste TrIQ + enhanced_slice = apply_triq(raw_slice) + + # C. Crear el mapa de calor (Heatmap) + p = heatmap(enhanced_slice, + title="Ion m/z: $(round(mz_val, digits=2))", + color=:viridis, + aspect_ratio=:equal, + yflip=true, + xaxis=false, yaxis=false) + + # D. Guardar + nombre_archivo = "ion_$(round(mz_val, digits=2))_triq.png" + savefig(p, joinpath(output_folder, nombre_archivo)) +end + +println("--- Proceso completado. Revisa la carpeta: $output_folder ---") diff --git a/graficar_espectro_clusters.jl b/graficar_espectro_clusters.jl new file mode 100644 index 0000000..2cd5553 --- /dev/null +++ b/graficar_espectro_clusters.jl @@ -0,0 +1,71 @@ + +using MSI_src +using CSV, DataFrames +using Plots +using Statistics +using Plots.Measures + +# 1. Carga de datos +path_data = "Hoja.imzML" +path_mask = "region_interes.png" +path_clusters = "msi_clusters_results.csv" + +println("Cargando datos...") +data = OpenMSIData(path_data) +df_clusters = CSV.read(path_clusters, DataFrame) + +# 2. Obtener Espectro Promedio (Referencia única) +mzs_repo, ints_repo = MSI_src.get_average_spectrum(data, mask_path=path_mask) + +# 3. Configurar el gráfico base (Línea gris fina y limpia) +p = plot(mzs_repo, ints_repo, + linecolor = :darkgray, + linewidth = 0.8, + label = "Espectro Promedio (Referencia)", + xlabel = "m/z", + ylabel = "Intensidad Relativa", + title = "Mapeo de Clusters sobre Patrón Isotópico", + size = (1200, 600), + legend = :outerright, + grid = false, # Estilo limpio de artículo + framestyle = :box, # Marco completo + left_margin = 15mm, + bottom_margin = 15mm +) + +# 4. Paleta de colores distintiva +colores_clusters = palette(:tab10) + +# 5. Colorear picos específicos (Sticks) +println("Resaltando clusters químicos...") +for cluster_id in sort(unique(df_clusters.cluster)) + df_sub = filter(row -> row.cluster == cluster_id, df_clusters) + + label_listo = false + + for mz_target in df_sub.mz + # Buscar el índice del pico real en el promedio + idx = argmin(abs.(mzs_repo .- mz_target)) + + # Tolerancia para centrar el color en el pico real + if abs(mzs_repo[idx] - mz_target) < 0.1 + m = mzs_repo[idx] + i = ints_repo[idx] + + # Dibujar el "stick" del cluster sobre el espectro base + plot!(p, [m, m], [0, i], + linecolor = colores_clusters[cluster_id + 1], + linewidth = 1.2, + alpha = 1.0, # Totalmente opaco para destacar + label = label_listo ? "" : "Cluster $cluster_id" + ) + label_listo = true + end + end +end + +# 6. Guardar con alta resolución +savefig("espectro_msi_paper_style.png") +println("Gráfico final guardado como 'espectro_msi_paper_style.png'") +savefig("espectro_msi_clusters_julia.png") +println("Gráfico guardado como 'espectro_msi_clusters_julia.png'") diff --git a/graficar_tsne_msi.py b/graficar_tsne_msi.py new file mode 100644 index 0000000..9ccd80f --- /dev/null +++ b/graficar_tsne_msi.py @@ -0,0 +1,108 @@ +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 +from sklearn.cluster import KMeans +from sklearn.manifold import TSNE +import matplotlib.pyplot as plt +import pandas as pd + +# 1. CONFIGURACIÓN +IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai" +ENCODER_PATH = "Reporte/Model/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}'.") diff --git a/preparar_datos_simclr.jl b/preparar_datos_simclr.jl new file mode 100644 index 0000000..cd037c2 --- /dev/null +++ b/preparar_datos_simclr.jl @@ -0,0 +1,42 @@ +using MSI_src +using Statistics, Images, Interpolations + +# 1. Configuración +path_data = "Hoja.imzML" +path_mask = "region_interes.png" +output_folder = "datos_para_ai" +img_size = (224, 224) # Tamaño estándar para CNN +mkpath(output_folder) + +# 2. Carga de datos +data = OpenMSIData(path_data) + +# 3. Obtener picos importantes (puedes usar tu lógica anterior) +mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=path_mask) +umbral = maximum(avg_ints) * 0.02 +indices_picos = findall(x -> x > umbral, avg_ints) + +println("Exportando $(length(indices_picos)) iones...") + +for idx in indices_picos + mz_val = mzs[idx] + if mz_val < 50.0 || mz_val > 700.0 continue end + + # A. Extraer slice (puro, sin plots) + raw_slice = MSI_src.get_mz_slice(data, mz_val, 0.05, mask_path=path_mask) + + # B. Normalización TrIQ (como en tu script) + vals = filter(x -> x > 0 && isfinite(x), raw_slice) + if isempty(vals) continue end + q = quantile(vals, 0.98) + q = q == 0 ? maximum(vals) : q + enhanced = clamp.(raw_slice ./ q, 0.0, 1.0) + + # C. Reescalar a 224x224 (Crucial para la CNN) + # Usamos imresize de Images.jl + img_resized = imresize(enhanced, img_size) + + # D. Guardar como PNG puro (Escala de grises, sin ejes) + nombre = "ion_$(round(mz_val, digits=2)).png" + save(joinpath(output_folder, nombre), Gray.(img_resized)) +end diff --git a/visualizar_clusters.py b/visualizar_clusters.py new file mode 100644 index 0000000..113fb1e --- /dev/null +++ b/visualizar_clusters.py @@ -0,0 +1,34 @@ + +import pandas as pd +import os +import matplotlib.pyplot as plt +from PIL import Image + +# Configuración +#CSV_PATH = "msi_clusters_results.csv" +CSV_PATH = "msi_clusters_direct_results.csv" +IMG_DIR = "datos_para_ai" +OUTPUT_DIR = "resultados_clusters" +os.makedirs(OUTPUT_DIR, exist_ok=True) + +df = pd.DataFrame(pd.read_csv(CSV_PATH)) + +for cluster_id in sorted(df['cluster'].unique()): + cluster_ions = df[df['cluster'] == cluster_id]['ion_image'].head(9).tolist() + + fig, axes = plt.subplots(3, 3, figsize=(10, 10)) + fig.suptitle(f"Cluster {cluster_id} - Ejemplos de Iones", fontsize=16) + + for i, ax in enumerate(axes.flat): + if i < len(cluster_ions): + img_path = os.path.join(IMG_DIR, cluster_ions[i]) + img = Image.open(img_path) + ax.imshow(img, cmap='gray') + ax.set_title(cluster_ions[i], fontsize=8) + ax.axis('off') + + plt.tight_layout() + plt.savefig(f"{OUTPUT_DIR}/galeria_cluster_{cluster_id}.png") + plt.close() + +print(f"Galerías guardadas en {OUTPUT_DIR}. Revisa estas imágenes para identificar qué estructura representa cada cluster.")