Merge branch 'consistency_docker_reproductability-'
"Branch merge to main"
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "MSI Hybrid Workflow",
|
||||
"build": {
|
||||
"dockerfile": "../Dockerfile",
|
||||
"context": ".."
|
||||
},
|
||||
"workspaceFolder": "/app",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"settings": {
|
||||
"python.defaultInterpreterPath": "/usr/bin/python3",
|
||||
"julia.executablePath": "/usr/local/bin/julia"
|
||||
},
|
||||
"extensions": [
|
||||
"ms-python.python",
|
||||
"ms-python.vscode-pylance",
|
||||
"charliermarsh.ruff",
|
||||
"julialang.language-julia"
|
||||
]
|
||||
}
|
||||
},
|
||||
"runArgs": [
|
||||
"--gpus=all",
|
||||
"--shm-size=2gb"
|
||||
],
|
||||
"remoteUser": "root"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
data/Leaf.imzML
|
||||
data/Leaf.ibd
|
||||
data/Leaf.imzML.cache
|
||||
JuliaMSI/
|
||||
environment/Manifest.toml
|
||||
datos_para_ai/*
|
||||
@@ -1,118 +0,0 @@
|
||||
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
|
||||
|
||||
# 1. CONFIGURACIÓN
|
||||
IMG_DIR = "/home/sierra/Documentos/Prueba teams/Julia_msi_GUI-main/datos_para_ai"
|
||||
BATCH_SIZE = 32
|
||||
EPOCHS = 50
|
||||
LEARNING_RATE = 0.0003 # SimCLR suele preferir LRs más bajos
|
||||
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([
|
||||
# El paper menciona que rotaciones leves están bien, pero Blur/Noise/Color son clave
|
||||
transforms.RandomRotation(10),
|
||||
transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),
|
||||
transforms.ColorJitter(brightness=0.4, contrast=0.4),
|
||||
transforms.ToTensor(),
|
||||
# Ruido Gaussiano (Sugerido por el paper para MSI)
|
||||
transforms.Lambda(lambda x: x + torch.randn_like(x) * 0.01)
|
||||
])
|
||||
|
||||
def __call__(self, x):
|
||||
# SimCLR: Dos vistas aumentadas de la misma imagen
|
||||
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__()
|
||||
# Usamos pesos pre-entrenados como base (Transfer Learning inicial)
|
||||
self.encoder = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
|
||||
num_ftrs = self.encoder.classifier[1].in_features
|
||||
self.encoder.classifier = nn.Identity() # Quitamos el clasificador original
|
||||
|
||||
# Projector Head (MLP) - Según SimCLR original y el paper MSI
|
||||
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 (Corregida)
|
||||
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)
|
||||
|
||||
# Máscara para quitar la auto-similitud (diagonal)
|
||||
mask = ~torch.eye(z.shape[0], device=z.device).bool()
|
||||
sim_matrix = sim_matrix.masked_select(mask).view(z.shape[0], -1)
|
||||
|
||||
# Los pares positivos están en (i, i+N)
|
||||
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 ---
|
||||
if __name__ == "__main__":
|
||||
print(f"Iniciando entrenamiento en: {DEVICE}")
|
||||
dataset = MSIDataset(IMG_DIR, transform=MSIAugmentations())
|
||||
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True)
|
||||
|
||||
model = SimCLR_MSI().to(DEVICE)
|
||||
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
|
||||
|
||||
for epoch in range(EPOCHS):
|
||||
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)
|
||||
print(f"Época [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}")
|
||||
|
||||
# Guardar solo el encoder (la parte que sabe extraer características)
|
||||
torch.save(model.encoder.state_dict(), "msi_encoder_trained.pth")
|
||||
print("Entrenamiento completado. Codificador guardado en 'msi_encoder_trained.pth'.")
|
||||
@@ -0,0 +1,69 @@
|
||||
# Use NVIDIA CUDA as the base for GPU support
|
||||
FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04
|
||||
|
||||
# Set non-interactive for apt
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# 1. Install System Dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
wget \
|
||||
curl \
|
||||
python3 \
|
||||
python3-pip \
|
||||
python3-venv \
|
||||
git \
|
||||
build-essential \
|
||||
zlib1g-dev \
|
||||
libpng-dev \
|
||||
libjpeg-dev \
|
||||
libfreetype6-dev \
|
||||
xvfb \
|
||||
libgl1-mesa-glx \
|
||||
libgl1-mesa-dri \
|
||||
libglfw3 \
|
||||
libxrandr2 \
|
||||
libxinerama1 \
|
||||
libxcursor1 \
|
||||
libxi6 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 2. Install Julia 1.11.3
|
||||
RUN curl -fsSL https://julialang-s3.julialang.org/bin/linux/x64/1.11/julia-1.11.3-linux-x86_64.tar.gz | tar -xz -C /usr/local --strip-components=1
|
||||
|
||||
# 3. Setup Working Directory
|
||||
WORKDIR /app
|
||||
|
||||
# 4. Integrate JuliaMSI Framework
|
||||
COPY JuliaMSI /opt/JuliaMSI
|
||||
WORKDIR /opt/JuliaMSI
|
||||
|
||||
ENV DISPLAY=:99
|
||||
|
||||
# Instantiate framework package
|
||||
RUN xvfb-run -s "-screen 0 1024x768x24" julia --project=. -e 'using Pkg; Pkg.instantiate(); Pkg.precompile()'
|
||||
|
||||
# 5. Setup Project Root and Environments
|
||||
WORKDIR /app
|
||||
COPY environment/ /app/environment/
|
||||
|
||||
# Isolate Python dependencies for cleaner caching layers
|
||||
RUN pip3 install --no-cache-dir -r environment/requirements.txt
|
||||
|
||||
# Force Julia 1.11.3 to resolve environments natively using your fixed UUID entries
|
||||
RUN julia --project=environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
|
||||
|
||||
# Register JuliaMSI explicitly into the runtime environment project
|
||||
RUN julia --project=environment -e 'using Pkg; Pkg.develop(path="/opt/JuliaMSI")'
|
||||
|
||||
# 6. Copy Application Files
|
||||
COPY . /app
|
||||
|
||||
# 7. Final Configuration
|
||||
ENV JULIA_LOAD_PATH="/opt/JuliaMSI:/opt/JuliaMSI/src:${JULIA_LOAD_PATH}"
|
||||
ENV PYTHONPATH="/app/scripts_python:${PYTHONPATH}"
|
||||
ENV DISPLAY=:99
|
||||
|
||||
LABEL maintainer="MSI Hybrid Workflow Team"
|
||||
LABEL description="CUDA + Julia 1.11.3 + JuliaMSI Framework"
|
||||
|
||||
CMD ["/bin/bash"]
|
||||
|
After Width: | Height: | Size: 894 KiB |
|
Before Width: | Height: | Size: 161 KiB After Width: | Height: | Size: 161 KiB |
|
Before Width: | Height: | Size: 369 KiB After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 908 KiB |
@@ -5,44 +5,115 @@ This repository contains the computational pipeline for the automated anatomical
|
||||
## Key Features
|
||||
- **High-Performance Preprocessing**: Rapid `.imzML` ingestion and TrIQ normalization using Julia.
|
||||
- **Self-Supervised Learning**: Contrastive learning (SimCLR) with an EfficientNet-B0 backbone implemented in PyTorch.
|
||||
- **Empirical Clustering**: Automated anatomical segmentation using PCA and K-Means, optimized for vascular and parenchymal tissue differentiation.
|
||||
- **CPU Optimized**: Designed to run on standard consumer hardware (no GPU required for inference).
|
||||
- **Reproducibility**: Integrated Docker environment and fixed random seeds for consistent results.
|
||||
- **Performance Benchmarking**: Real-time monitoring of execution time and RAM usage across the hybrid pipeline.
|
||||
- **CUDA/GPU Support**: Optimized for NVIDIA hardware for accelerated training and inference.
|
||||
- **Hybrid Bridge**: Automated data transfer between Julia and Python ecosystems via standardized intermediate files.
|
||||
|
||||
## Project Structure
|
||||
- `scripts_julia/`: Julia scripts for mass slice extraction, TrIQ normalization, and image generation.
|
||||
- `scripts_julia/`: Julia scripts for mass slice extraction and TrIQ normalization.
|
||||
- `scripts_python/`: Python scripts for SimCLR training, feature extraction, and clustering.
|
||||
- `Model/`: Contains the pre-trained weights (`msi_encoder_trained.pth`).
|
||||
- `environment/`: Dependency list (`requirements.txt`).
|
||||
- `Articule MSI/`: Manuscript draft and documentation.
|
||||
- `models/`: Contains the pre-trained weights (`msi_encoder_trained.pth`).
|
||||
- `environment/`: Dependency files (`requirements.txt`, `Project.toml`).
|
||||
- `figures/`: Generated plots and cluster galleries.
|
||||
- `data/`: (User-provided) Location for `.imzML` and mask files.
|
||||
|
||||
## Installation
|
||||
## Reproducibility & Docker (Recommended)
|
||||
To ensure identical environments for both Julia and Python, we provide a unified Docker setup. This setup includes the **JuliaMSI** framework.
|
||||
|
||||
### Python
|
||||
It is recommended to use a virtual environment:
|
||||
### Building the Container
|
||||
Before building, ensure the `JuliaMSI` repository is present in the root directory (it was cloned from `https://git.nube-gran.de/Julian/JuliaMSI`).
|
||||
```bash
|
||||
pip install -r environment/requirements.txt
|
||||
docker build -t msi-hybrid-workflow .
|
||||
```
|
||||
|
||||
### Julia
|
||||
Ensure you have Julia installed and the following packages: `MSI.jl`, `ImzML.jl`, `Images.jl`, and `DataFrames.jl`.
|
||||
### Running the Container (CPU Mode)
|
||||
```bash
|
||||
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow
|
||||
```
|
||||
|
||||
### Running the Container (GPU/CUDA Mode)
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow
|
||||
```
|
||||
|
||||
## Usage Workflow
|
||||
|
||||
1. **Preprocessing (Julia)**:
|
||||
Run `scripts_julia/preparar_datos_simclr.jl` to convert `.imzML` data into normalized PNG ion maps.
|
||||
|
||||
2. **Training (Optional)**:
|
||||
Run `scripts_python/CNN_proof_1.py` to retrain the SimCLR encoder.
|
||||
|
||||
3. **Clustering & Mapping**:
|
||||
Use `scripts_python/cluster_msi_direct.py` to extract embeddings from the pre-trained model and generate the metabolic clusters.
|
||||
|
||||
4. **Visualization**:
|
||||
Run `scripts_python/visualizar_clusters.py` to generate the final cluster galleries.
|
||||
### 1. Preprocessing (Julia)
|
||||
Leverage Julia's performance and the **JuliaMSI** framework.
|
||||
|
||||
**Run this clean runtime instantiation command one time to sync everything down to your local directory:**
|
||||
```bash
|
||||
docker run -it --rm -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --project=/app/environment -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
|
||||
```
|
||||
|
||||
**Run the MSI Bridge (Normalization & PNG Export):**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --threads auto --project=/app/environment /app/scripts_julia/julia_msi_bridge.jl
|
||||
```
|
||||
|
||||
**Optional: Plot Cluster Spectra:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
julia --threads auto --project=/app/environment scripts_julia/graph_cluster_spectra.jl
|
||||
```
|
||||
|
||||
### 2. Representation Learning (Python)
|
||||
Train the SimCLR encoder to extract morphological features using CUDA.
|
||||
|
||||
**Run CNN Training (SimCLR):**
|
||||
```bash
|
||||
docker run -it --rm \
|
||||
--shm-size=2gb \
|
||||
--gpus all \
|
||||
-v $(pwd):/app \
|
||||
-v msi_torch_cache:/root/.cache/torch \
|
||||
msi-hybrid-workflow \
|
||||
python3 scripts_python/CNN_proof_1.py
|
||||
```
|
||||
*Note: The script automatically detects CUDA and logs per-epoch RAM usage.*
|
||||
|
||||
### 3. Clustering & Validation
|
||||
Determine optimal clusters and perform quantitative validation.
|
||||
|
||||
**Generate Clusters:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/cluster_msi_direct.py
|
||||
```
|
||||
|
||||
**Evaluate Clustering:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/evaluate_clustering.py
|
||||
```
|
||||
|
||||
**Quantitative Validation:**
|
||||
```bash
|
||||
docker run -it --rm --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/quantitative_validation.py
|
||||
```
|
||||
|
||||
### 4. Visualization
|
||||
Generate the final galleries and t-SNE maps.
|
||||
|
||||
**Generate t-SNE Maps:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/graficar_tsne_msi.py
|
||||
```
|
||||
|
||||
**Create Cluster Galleries:**
|
||||
```bash
|
||||
docker run -it --rm --shm-size=2gb --gpus all -v $(pwd):/app msi-hybrid-workflow \
|
||||
python3 scripts_python/visualize_clusters.py
|
||||
```
|
||||
|
||||
## Citation & Acknowledgments
|
||||
This implementation is based on the methodology proposed by:
|
||||
> Hu, H., Bindu, J. P., & Laskin, J. (2022). Self-supervised clustering of mass spectrometry imaging data using contrastive learning. *Chemical Science*, 13(1), 90-98. DOI: [10.1039/d1sc04077d](https://doi.org/10.1039/d1sc04077d)
|
||||
|
||||
## License
|
||||
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
|
||||
This project is licensed under the **MIT License**.
|
||||
|
||||
|
Before Width: | Height: | Size: 1.4 MiB |
@@ -1,11 +0,0 @@
|
||||
cluster_id,ion_count
|
||||
0,112
|
||||
1,20
|
||||
2,91
|
||||
3,118
|
||||
4,19
|
||||
5,27
|
||||
6,36
|
||||
7,33
|
||||
8,16
|
||||
9,116
|
||||
|
|
Before Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 256 KiB After Width: | Height: | Size: 256 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,73 @@
|
||||
# Technical Documentation & Experimental Rationale
|
||||
|
||||
This document provides a detailed technical overview of the computational choices, hyperparameter tuning, and validation strategies implemented in the hybrid Julia-Python MSI workflow.
|
||||
|
||||
## Docker Maintenance & Disk Space
|
||||
If you encounter disk space issues due to failed builds or unused images, use these commands:
|
||||
|
||||
- **Safe Clean (Dangling layers only):** `docker image prune`
|
||||
- **Deep Clean (Everything unused):** `docker system prune -a --volumes`
|
||||
- **Clear Build Cache:** `docker builder prune`
|
||||
|
||||
## 1. Hyperparameter Tuning Rationale (SimCLR)
|
||||
|
||||
The training configuration in `scripts_python/CNN_proof_1.py` follows the standard SimCLR framework (Chen et al., 2020) while being optimized for the morphological characteristics of Mass Spectrometry Imaging (MSI) data.
|
||||
|
||||
| Hyperparameter | Value | Rationale |
|
||||
| :--- | :--- | :--- |
|
||||
| **Temperature ($\tau$)** | 0.5 | **Selected via grid search.** We tested $\tau \in \{0.1, 0.5, 1.0\}$. A value of 0.1 led to unstable gradients and collapsed representations, while 1.0 was too permissive. $\tau=0.5$ provided the most stable convergence and distinct cluster boundaries. |
|
||||
| **Projection Dim** | 128 | Standard for SimCLR. Reducing to 64 lost anatomical detail; increasing to 256 did not improve Silhouette scores but increased computational overhead. |
|
||||
| **Training Epochs** | 50 | Observed convergence of NT-Xent loss between epochs 40-50. Further training (tested up to 200 epochs) led to minor overfitting to instrumental artifacts. |
|
||||
| **Batch Size** | 32 | Optimized for the i5 CPU environment to balance memory usage and gradient stability. |
|
||||
|
||||
## 2. Advanced Validation Strategies
|
||||
|
||||
To satisfy rigorous peer review, we implemented three quantitative validation layers in `scripts_python/quantitative_validation.py`:
|
||||
|
||||
### 2.1 Baseline Comparison (PCA vs. SimCLR)
|
||||
* **Method:** We compared our self-supervised approach against a traditional baseline where PCA is applied directly to raw pixel vectors (flattened ion images).
|
||||
* **Result:** SimCLR consistently yields higher Silhouette scores and lower Davies-Bouldin indices. This proves that the neural network's non-linear feature extraction captures anatomical "shapes" better than linear variance-based methods.
|
||||
|
||||
### 2.2 Stability & Reproducibility Analysis
|
||||
* **Metric:** Adjusted Rand Index (ARI).
|
||||
* **Method:** We ran the clustering pipeline across 10 different random seeds. By computing the ARI between all pairs of runs, we demonstrate that the metabolic domains identified (Clusters 0-9) are stable and not artifacts of k-means initialization.
|
||||
|
||||
### 2.3 Isotope Co-localization (Natural Ground Truth)
|
||||
* **Scientific Anchor:** Isotopes ($[M+H]^+$ and $[M+H+1]^+$) must co-localize perfectly in tissue.
|
||||
* **Validation:** We measure the Euclidean distance of isotopic pairs in the latent manifold. A t-test confirms that these distances are significantly smaller than those of random ion pairs, providing objective evidence that the model has learned chemical-biological reality.
|
||||
|
||||
## 3. Biological & Mathematical Rationale for $k=10$
|
||||
|
||||
While mathematical metrics (Elbow method, Silhouette) often suggest $k=2$ or $k=3$ (tissue vs. background), we selected **$k=10$** based on:
|
||||
1. **Anatomical Fidelity:** This threshold is required to resolve the hierarchy between the primary midrib, secondary veins, and apical accumulation zones.
|
||||
2. **Stability:** Metric stabilization was observed in the $k=8$ to $k=12$ range.
|
||||
3. **Metabolic Heatmaps:** Average ion intensities per cluster for scopolamine ($m/z$ 304.1) and atropine ($m/z$ 290.1) show clear sequestration in Clusters 9 (Vascular) and 7 (Apical), validating the biological relevance of the segmentation.
|
||||
|
||||
## 4. Technical Specifications & Citations
|
||||
|
||||
### 4.1 Data Augmentations
|
||||
We implemented **Additive Gaussian Noise ($\sigma=0.01$)**. This is critical for MSI to simulate detector background noise.
|
||||
* *Citation:* DeepION (2024) and Hu et al. (2022, Table S1).
|
||||
|
||||
### 4.2 Model Backbone
|
||||
**EfficientNet-B0** with ImageNet weights was used for transfer learning. The MBConv blocks are highly efficient for CPU-based inference.
|
||||
* *Citation:* Tan & Le (2019).
|
||||
|
||||
### 4.3 Preprocessing (JuliaMSI)
|
||||
* **Spectral Averaging:** Done via `MSI_src.get_average_spectrum`.
|
||||
* **Tolerance:** $\pm 0.05$ Da window for mass slices. This is standard for low-resolution Ion Trap instruments (LCQ Fleet) to ensure all isotopic signal is captured.
|
||||
* *Citation:* Sierra-Álvarez et al. (2025).
|
||||
|
||||
### 4.4 Dimensionality Reduction
|
||||
PCA was used to reduce the 1280-dim (EfficientNet) or 128-dim (Projector) features to **50 components** before k-means. This heuristic stabilizes clustering by removing noise and redundant dimensions.
|
||||
* *Citation:* Jolliffe (2002).
|
||||
|
||||
|
||||
## Benchmarking & Hardware Realism
|
||||
The pipeline is optimized for efficiency on consumer-grade hardware.
|
||||
- **Julia Stage**: Uses `BenchmarkTools.jl` to profile binary parsing.
|
||||
- **Python Stage**: Uses `psutil` and `CUDA` monitoring to track hardware overhead.
|
||||
- **Determinism**: All stochastic steps are locked with `seed=42`.
|
||||
|
||||
## Julia-Python Bridge Details
|
||||
The "two-language problem" is solved by an intermediate file-system bridge. Julia performs binary MSI parsing and **Threshold Intensity Quantization (TrIQ)**. The resulting data is saved as high-contrast 224x224 grayscale PNG images, allowing the Python PyTorch pipeline to consume it efficiently.
|
||||
@@ -0,0 +1,49 @@
|
||||
[deps]
|
||||
Accessors = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
|
||||
Base64 = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
|
||||
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
|
||||
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
|
||||
CairoMakie = "13f3f980-e62b-5c42-98c6-ff1f3baf88f0"
|
||||
CodecBase = "6c391c72-fb7b-5838-ba82-7cfb1bcfecbf"
|
||||
ColorSchemes = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
|
||||
Colors = "5ae59095-9a9b-59fe-a467-6f913c188581"
|
||||
ContinuousWavelets = "96eb917e-2868-4417-9cb6-27e7ff17528f"
|
||||
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
|
||||
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
|
||||
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
|
||||
GLMakie = "e9467ef8-e4e7-5192-8a1a-b1aee30e663a"
|
||||
Genie = "c43c736e-a2d1-11e8-161f-af95117fbd1e"
|
||||
GenieFramework = "a59fdf5c-6bf0-4f5d-949c-a137c9e2f353"
|
||||
HistogramThresholding = "2c695a8d-9458-5d45-9878-1b8a99cf7853"
|
||||
ImageBinarization = "cbc4b850-ae4b-5111-9e64-df94c024a13d"
|
||||
ImageComponentAnalysis = "d9b9e9a0-1569-11e9-2cb5-bbca914b0e89"
|
||||
ImageContrastAdjustment = "f332f351-ec65-5f6a-b3d1-319c6670881a"
|
||||
ImageCore = "a09fc81d-aa75-5fe9-8630-4744c3626534"
|
||||
ImageFiltering = "6a3955dd-da59-5b1f-98d4-e7296123deb5"
|
||||
ImageMorphology = "787d08f9-d448-5407-9aad-5290dd7ab264"
|
||||
ImageSegmentation = "80713f31-8817-5129-9cf8-209ff8fb23e1"
|
||||
Images = "916415d5-f1e6-5110-898d-aaa5f9f070e0"
|
||||
Interpolations = "a98d9a8b-a2ab-59e6-89dd-64a1c18fca59"
|
||||
JLD2 = "033835bb-8acc-5ee8-8aae-3f567f8a3819"
|
||||
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
|
||||
Libz = "2ec943e9-cfe8-584d-b93d-64dcb6d567b7"
|
||||
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
|
||||
Loess = "4345ca2d-374a-55d4-8d30-97f9976e7612"
|
||||
Mmap = "a63ad114-7e13-5084-954f-fe012c677804"
|
||||
NativeFileDialog = "e1fe445b-aa65-4df4-81c1-2041507f0fd4"
|
||||
NaturalSort = "c020b1a1-e9b0-503a-9c33-f039bfc54a85"
|
||||
PackageCompiler = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d"
|
||||
Parameters = "d96e819e-fc66-5662-9728-84c9c7592b0a"
|
||||
PlotlyBase = "a03496cd-edff-5a9b-9e67-9cda94a718b5"
|
||||
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
|
||||
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
|
||||
ProgressMeter = "92933f4c-e287-5a05-a399-4b506db050ca"
|
||||
SavitzkyGolay = "c4bf5708-b6a6-4fbe-bcd0-6850ed671584"
|
||||
Serialization = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
|
||||
Setfield = "efcf1570-3423-57d1-acb7-fd33fddbac46"
|
||||
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
|
||||
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
|
||||
StatsBase = "2913bbd2-ae8a-5f71-8c99-4fb6c76f3a91"
|
||||
StipplePlotly = "ec984513-233d-481d-95b0-a3b58b97af2b"
|
||||
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
|
||||
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
|
||||
@@ -0,0 +1,10 @@
|
||||
torch>=2.0.0
|
||||
torchvision>=0.15.0
|
||||
Pillow>=9.0.0
|
||||
numpy>=1.21.0
|
||||
scikit-learn>=1.0.0
|
||||
matplotlib>=3.5.0
|
||||
pandas>=1.4.0
|
||||
scipy>=1.7.0
|
||||
psutil>=5.9.0
|
||||
plotly>=6.8.0
|
||||
|
After Width: | Height: | Size: 894 KiB |
|
After Width: | Height: | Size: 168 KiB |
|
After Width: | Height: | Size: 181 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 908 KiB |
|
After Width: | Height: | Size: 2.4 MiB |
|
Before Width: | Height: | Size: 425 KiB |
|
Before Width: | Height: | Size: 402 KiB |
|
Before Width: | Height: | Size: 439 KiB |
|
Before Width: | Height: | Size: 386 KiB |
|
Before Width: | Height: | Size: 436 KiB |
|
Before Width: | Height: | Size: 451 KiB |
|
Before Width: | Height: | Size: 444 KiB |
|
Before Width: | Height: | Size: 405 KiB |
|
Before Width: | Height: | Size: 420 KiB |
|
Before Width: | Height: | Size: 429 KiB |
|
After Width: | Height: | Size: 161 KiB |
|
After Width: | Height: | Size: 394 KiB |
|
After Width: | Height: | Size: 359 KiB |
|
After Width: | Height: | Size: 341 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 273 KiB |
|
After Width: | Height: | Size: 349 KiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 128 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 617 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 232 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 239 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 248 KiB |
|
After Width: | Height: | Size: 240 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 242 KiB |
|
After Width: | Height: | Size: 246 KiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 618 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
@@ -1,70 +0,0 @@
|
||||
using MSI_src
|
||||
using CSV, DataFrames
|
||||
using Plots
|
||||
using Statistics
|
||||
using Plots.Measures
|
||||
|
||||
# 1. Data loading
|
||||
data_path = "Leaf.imzML"
|
||||
mask_path = "region_of_interest.png"
|
||||
clusters_path = "msi_clusters_results.csv"
|
||||
|
||||
println("Loading data...")
|
||||
data = OpenMSIData(data_path)
|
||||
clusters_df = CSV.read(clusters_path, DataFrame)
|
||||
|
||||
# 2. Get Average Spectrum (Single reference)
|
||||
mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path)
|
||||
|
||||
# 3. Configure base plot (Thin, clean gray line)
|
||||
p = plot(mzs_avg, ints_avg,
|
||||
linecolor = :darkgray,
|
||||
linewidth = 0.8,
|
||||
label = "Average Spectrum (Reference)",
|
||||
xlabel = "m/z",
|
||||
ylabel = "Relative Intensity",
|
||||
title = "Cluster Mapping on Isotopic Pattern",
|
||||
size = (1200, 600),
|
||||
legend = :outerright,
|
||||
grid = false, # Clean article style
|
||||
framestyle = :box, # Full frame
|
||||
left_margin = 15mm,
|
||||
bottom_margin = 15mm
|
||||
)
|
||||
|
||||
# 4. Distinctive color palette
|
||||
cluster_colors = palette(:tab10)
|
||||
|
||||
# 5. Color specific peaks (Sticks)
|
||||
println("Highlighting chemical clusters...")
|
||||
for cluster_id in sort(unique(clusters_df.cluster))
|
||||
sub_df = filter(row -> row.cluster == cluster_id, clusters_df)
|
||||
|
||||
label_ready = false
|
||||
|
||||
for target_mz in sub_df.mz
|
||||
# Find the index of the real peak in the average spectrum
|
||||
idx = argmin(abs.(mzs_avg .- target_mz))
|
||||
|
||||
# Tolerance to center the color on the real peak
|
||||
if abs(mzs_avg[idx] - target_mz) < 0.1
|
||||
m = mzs_avg[idx]
|
||||
i = ints_avg[idx]
|
||||
|
||||
# Draw the cluster "stick" over the base spectrum
|
||||
plot!(p, [m, m], [0, i],
|
||||
linecolor = cluster_colors[cluster_id + 1],
|
||||
linewidth = 1.2,
|
||||
alpha = 1.0, # Fully opaque to stand out
|
||||
label = label_ready ? "" : "Cluster $cluster_id"
|
||||
)
|
||||
label_ready = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# 6. Save with high resolution
|
||||
savefig("espectro_msi_paper_style.png")
|
||||
println("Final plot saved as 'espectro_msi_paper_style.png'")
|
||||
savefig("espectro_msi_clusters_julia.png")
|
||||
println("Plot saved as 'espectro_msi_clusters_julia.png'")
|
||||
@@ -1,589 +0,0 @@
|
||||
ion_name,cluster_id,tsne_x,tsne_y
|
||||
ion_100.15.png,6,-40.932426,-10.908073
|
||||
ion_100.48.png,9,21.072824,-16.83617
|
||||
ion_100.8.png,6,-44.621838,-11.493084
|
||||
ion_101.45.png,9,34.47281,-16.28591
|
||||
ion_101.78.png,2,-13.818509,5.9901714
|
||||
ion_102.1.png,6,-39.913902,-7.6706624
|
||||
ion_102.75.png,0,3.711694,2.8761594
|
||||
ion_103.73.png,3,25.524195,5.0248933
|
||||
ion_104.7.png,0,6.3908186,3.1167102
|
||||
ion_105.03.png,5,-32.656612,1.0016607
|
||||
ion_105.68.png,0,4.476362,4.953501
|
||||
ion_106.0.png,0,-3.9591544,5.814191
|
||||
ion_106.65.png,2,-23.629314,13.045395
|
||||
ion_106.98.png,6,-41.06501,-11.841768
|
||||
ion_107.3.png,3,26.141336,5.6587133
|
||||
ion_107.63.png,2,-11.70391,8.273663
|
||||
ion_107.95.png,2,-10.682738,12.293447
|
||||
ion_108.28.png,0,5.4774737,4.7060905
|
||||
ion_108.61.png,3,19.261587,3.6005502
|
||||
ion_108.93.png,7,-33.09098,7.1473045
|
||||
ion_109.26.png,0,2.448873,4.068846
|
||||
ion_109.58.png,3,26.700348,-1.6223453
|
||||
ion_109.91.png,5,-34.37336,5.7190495
|
||||
ion_110.23.png,2,-13.548649,12.304782
|
||||
ion_110.56.png,0,8.171888,6.2068224
|
||||
ion_110.88.png,4,-42.90921,-14.561416
|
||||
ion_111.21.png,7,-32.069893,6.121762
|
||||
ion_111.53.png,9,17.032578,-14.9836
|
||||
ion_111.86.png,6,-41.86804,-12.264283
|
||||
ion_112.18.png,6,-39.195858,-6.9346743
|
||||
ion_112.51.png,9,28.834616,-21.248415
|
||||
ion_112.83.png,4,-45.280384,-14.686986
|
||||
ion_113.16.png,1,-38.0473,-4.6447887
|
||||
ion_113.48.png,9,30.0885,-19.64369
|
||||
ion_113.81.png,6,-39.76301,-10.167555
|
||||
ion_114.13.png,6,-39.21211,-12.458875
|
||||
ion_114.46.png,3,24.479866,-2.5599716
|
||||
ion_114.78.png,6,-41.411972,-8.484517
|
||||
ion_115.11.png,4,-44.946033,-12.730046
|
||||
ion_115.43.png,9,27.25728,-22.379305
|
||||
ion_115.76.png,5,-31.31854,3.8297124
|
||||
ion_116.08.png,6,-41.640984,-11.303868
|
||||
ion_116.73.png,2,-14.471555,5.2624044
|
||||
ion_117.06.png,6,-43.930084,-11.334628
|
||||
ion_117.71.png,0,-0.99251306,12.130675
|
||||
ion_118.03.png,0,-1.974164,14.835406
|
||||
ion_118.68.png,0,5.701814,5.353048
|
||||
ion_119.01.png,7,-30.339453,8.254847
|
||||
ion_119.66.png,0,7.0023146,6.2532473
|
||||
ion_119.98.png,2,-17.69502,10.212994
|
||||
ion_120.31.png,3,25.333418,-2.47145
|
||||
ion_120.63.png,2,-21.46605,14.790991
|
||||
ion_120.96.png,5,-35.361584,3.6481993
|
||||
ion_121.28.png,2,-19.833818,7.7952666
|
||||
ion_121.61.png,9,29.773712,-11.878464
|
||||
ion_121.94.png,7,-30.860514,8.846124
|
||||
ion_122.26.png,2,-12.871035,10.980335
|
||||
ion_122.59.png,3,20.165756,0.8244692
|
||||
ion_122.91.png,1,-37.685265,-1.6078014
|
||||
ion_123.24.png,0,-3.8681993,6.9443965
|
||||
ion_123.56.png,9,31.087072,-19.9912
|
||||
ion_123.89.png,2,-20.36767,12.96694
|
||||
ion_124.21.png,2,-16.67268,10.083388
|
||||
ion_124.54.png,0,0.5643915,11.15306
|
||||
ion_124.86.png,6,-39.107998,-10.219036
|
||||
ion_125.19.png,7,-32.009422,9.557379
|
||||
ion_125.51.png,8,11.884864,-13.311716
|
||||
ion_125.84.png,1,-37.684673,-3.4273758
|
||||
ion_126.16.png,1,-36.814728,-2.23065
|
||||
ion_126.49.png,9,31.721008,-19.458025
|
||||
ion_126.81.png,6,-43.756336,-11.9929285
|
||||
ion_127.14.png,5,-34.404408,4.2661257
|
||||
ion_127.46.png,9,16.890953,-15.761453
|
||||
ion_127.79.png,1,-37.11607,-3.4930828
|
||||
ion_128.11.png,1,-38.135204,-3.4246678
|
||||
ion_128.44.png,9,27.918097,-12.72148
|
||||
ion_128.76.png,1,-36.798344,-4.142718
|
||||
ion_129.09.png,4,-45.294636,-13.309718
|
||||
ion_129.41.png,9,27.155005,-20.287508
|
||||
ion_129.74.png,0,9.277016,2.169231
|
||||
ion_130.06.png,8,12.751752,-11.503576
|
||||
ion_130.39.png,9,27.945795,-23.77022
|
||||
ion_130.71.png,2,-15.9459305,14.688283
|
||||
ion_131.04.png,5,-33.40034,4.365237
|
||||
ion_131.69.png,3,20.051266,5.4822
|
||||
ion_132.01.png,0,-2.6060483,14.521514
|
||||
ion_132.66.png,0,6.651698,5.3709097
|
||||
ion_132.99.png,7,-30.735043,7.1117187
|
||||
ion_133.64.png,0,8.923789,7.2876906
|
||||
ion_133.96.png,2,-17.921602,12.313286
|
||||
ion_134.29.png,0,-8.982729,11.345206
|
||||
ion_134.61.png,0,6.684335,3.9621217
|
||||
ion_134.94.png,6,-39.647675,-9.488616
|
||||
ion_135.27.png,0,-7.147459,11.077727
|
||||
ion_135.59.png,9,31.931988,-11.242002
|
||||
ion_135.92.png,6,-38.679104,-8.646229
|
||||
ion_136.24.png,2,-21.387281,13.0522175
|
||||
ion_136.57.png,9,26.215488,-8.447047
|
||||
ion_136.89.png,6,-39.423294,-11.103563
|
||||
ion_137.22.png,2,-18.702082,11.593917
|
||||
ion_137.54.png,0,4.5336566,9.587065
|
||||
ion_137.87.png,2,-20.39063,8.51847
|
||||
ion_138.19.png,0,-3.517939,7.195597
|
||||
ion_138.52.png,8,10.112699,-13.610569
|
||||
ion_138.84.png,6,-39.930943,-11.200036
|
||||
ion_139.17.png,2,-21.219393,9.426966
|
||||
ion_139.49.png,8,10.493626,-14.211387
|
||||
ion_139.82.png,1,-37.167812,-1.3658186
|
||||
ion_140.14.png,7,-28.534073,9.305264
|
||||
ion_140.47.png,9,27.554335,-23.885014
|
||||
ion_140.79.png,6,-43.277565,-12.250897
|
||||
ion_141.12.png,7,-33.104458,7.699927
|
||||
ion_141.44.png,9,17.903873,-16.033558
|
||||
ion_141.77.png,0,-5.5243983,13.699684
|
||||
ion_142.09.png,2,-18.984343,14.215493
|
||||
ion_142.74.png,7,-27.618898,4.4566145
|
||||
ion_143.07.png,4,-46.344624,-14.81412
|
||||
ion_143.72.png,0,-5.9816747,13.293046
|
||||
ion_144.04.png,2,-11.155265,14.170109
|
||||
ion_144.37.png,3,19.259422,1.1916993
|
||||
ion_144.69.png,3,27.138573,5.7115173
|
||||
ion_145.02.png,1,-37.03697,-2.6906428
|
||||
ion_145.67.png,3,27.36732,-0.38681844
|
||||
ion_145.99.png,2,-20.595125,10.809723
|
||||
ion_146.32.png,3,20.659002,0.8583992
|
||||
ion_146.64.png,0,0.5069913,12.077325
|
||||
ion_146.97.png,5,-34.340405,2.3559327
|
||||
ion_147.29.png,2,-11.517773,8.150197
|
||||
ion_147.62.png,3,18.983427,4.159373
|
||||
ion_147.94.png,7,-32.49874,8.392821
|
||||
ion_148.27.png,2,-14.248463,10.451742
|
||||
ion_148.59.png,3,24.674915,-6.1475773
|
||||
ion_148.92.png,6,-40.50674,-10.018055
|
||||
ion_149.25.png,2,-19.732456,14.968335
|
||||
ion_149.57.png,9,28.265984,-21.08255
|
||||
ion_149.9.png,1,-37.801445,-2.135665
|
||||
ion_150.22.png,2,-18.528763,8.687745
|
||||
ion_150.55.png,9,26.87205,-8.916402
|
||||
ion_150.87.png,6,-38.87418,-9.531368
|
||||
ion_151.2.png,2,-21.394608,12.821622
|
||||
ion_151.52.png,9,17.998955,-15.572056
|
||||
ion_151.85.png,5,-31.658724,1.8839927
|
||||
ion_152.17.png,7,-27.798784,9.632678
|
||||
ion_152.5.png,9,26.860607,-22.968582
|
||||
ion_152.82.png,1,-36.320477,-2.7099292
|
||||
ion_153.15.png,7,-27.550566,9.645868
|
||||
ion_153.47.png,9,27.603357,-23.536224
|
||||
ion_153.8.png,7,-31.640509,6.528484
|
||||
ion_154.12.png,7,-31.38128,8.300594
|
||||
ion_154.45.png,3,23.81995,0.47742814
|
||||
ion_154.77.png,5,-31.340246,2.6841404
|
||||
ion_155.1.png,6,-38.985897,-7.9012914
|
||||
ion_155.75.png,3,23.791573,-7.5370507
|
||||
ion_156.07.png,9,23.335367,-9.456169
|
||||
ion_156.4.png,9,32.113476,-20.326483
|
||||
ion_156.72.png,7,-26.680313,5.8982115
|
||||
ion_157.05.png,6,-41.05461,-9.774933
|
||||
ion_157.7.png,9,32.16658,-7.1336193
|
||||
ion_158.02.png,2,-11.812407,14.297634
|
||||
ion_158.67.png,3,24.569906,4.6746826
|
||||
ion_159.0.png,5,-33.735867,2.712962
|
||||
ion_159.65.png,3,22.141064,8.087676
|
||||
ion_159.97.png,2,-18.856886,13.17376
|
||||
ion_160.3.png,2,-14.948667,10.354482
|
||||
ion_160.62.png,3,20.122013,3.8841648
|
||||
ion_160.95.png,7,-30.790535,5.913171
|
||||
ion_161.27.png,0,-4.1914387,12.365071
|
||||
ion_161.6.png,8,10.7571,-13.120692
|
||||
ion_161.92.png,2,-21.266256,8.730152
|
||||
ion_162.25.png,0,-2.8663845,7.336084
|
||||
ion_162.58.png,9,27.714441,-12.068402
|
||||
ion_162.9.png,1,-36.017006,-2.4591231
|
||||
ion_163.23.png,2,-17.248466,6.9128537
|
||||
ion_163.55.png,9,26.516489,-14.088811
|
||||
ion_163.88.png,1,-37.00385,-1.8382791
|
||||
ion_164.2.png,2,-19.261747,10.5906105
|
||||
ion_164.53.png,8,11.775578,-13.3859415
|
||||
ion_164.85.png,5,-33.099106,2.5399122
|
||||
ion_165.18.png,2,-10.854196,11.623945
|
||||
ion_165.5.png,8,10.943736,-14.005076
|
||||
ion_165.83.png,7,-27.53292,8.744625
|
||||
ion_166.15.png,2,-17.272701,11.286682
|
||||
ion_166.48.png,8,14.226561,-14.4455385
|
||||
ion_166.8.png,5,-31.635275,1.0225788
|
||||
ion_167.13.png,1,-36.78637,-0.8704057
|
||||
ion_167.45.png,3,27.44686,-1.43741
|
||||
ion_167.78.png,3,16.833252,4.725952
|
||||
ion_168.1.png,5,-33.255524,3.2703094
|
||||
ion_168.43.png,3,29.844877,-5.1431966
|
||||
ion_168.75.png,5,-30.86539,2.9853792
|
||||
ion_169.08.png,2,-18.081688,8.909306
|
||||
ion_169.73.png,0,-4.49475,9.887941
|
||||
ion_170.05.png,2,-20.052332,14.501295
|
||||
ion_170.7.png,2,-18.27792,17.12719
|
||||
ion_171.03.png,6,-41.992714,-10.252468
|
||||
ion_171.68.png,9,31.992657,-6.449951
|
||||
ion_172.0.png,7,-31.901983,8.909973
|
||||
ion_172.65.png,3,28.201687,1.7387993
|
||||
ion_172.98.png,1,-35.71287,-1.633639
|
||||
ion_173.63.png,3,29.567598,-2.1647427
|
||||
ion_173.95.png,0,2.6752598,9.273825
|
||||
ion_174.28.png,0,-1.4785752,15.294363
|
||||
ion_174.6.png,8,10.788745,-13.70675
|
||||
ion_174.93.png,7,-27.343237,6.6634164
|
||||
ion_175.25.png,2,-16.242544,9.454839
|
||||
ion_175.58.png,8,13.58418,-13.084291
|
||||
ion_175.91.png,2,-19.902641,16.263332
|
||||
ion_176.23.png,0,5.8883977,7.5633116
|
||||
ion_176.56.png,3,26.058708,-0.33804464
|
||||
ion_176.88.png,4,-45.82347,-14.564874
|
||||
ion_177.21.png,5,-33.769085,1.0597107
|
||||
ion_177.53.png,9,28.158157,-22.620466
|
||||
ion_177.86.png,2,-23.884726,12.815301
|
||||
ion_178.18.png,2,-14.489526,9.718306
|
||||
ion_178.83.png,7,-25.836714,9.320589
|
||||
ion_179.16.png,2,-15.42384,11.252816
|
||||
ion_179.81.png,2,-15.41136,15.422945
|
||||
ion_180.13.png,2,-19.366283,8.451141
|
||||
ion_180.46.png,9,27.730162,-7.8079157
|
||||
ion_180.78.png,0,-7.172285,13.136606
|
||||
ion_181.11.png,7,-29.788584,8.512648
|
||||
ion_181.43.png,3,23.71532,-5.6585317
|
||||
ion_181.76.png,3,27.179075,5.278677
|
||||
ion_182.08.png,2,-19.475264,14.344315
|
||||
ion_182.73.png,0,-8.101207,8.876574
|
||||
ion_183.06.png,2,-17.989485,11.640276
|
||||
ion_183.71.png,3,18.50558,4.8625207
|
||||
ion_184.03.png,2,-20.027864,9.215963
|
||||
ion_184.68.png,3,26.700153,4.8592734
|
||||
ion_185.01.png,1,-38.56908,-5.026004
|
||||
ion_185.66.png,9,29.439285,-13.884041
|
||||
ion_185.98.png,2,-20.049011,15.177003
|
||||
ion_186.31.png,0,-2.2016842,10.762651
|
||||
ion_186.63.png,3,29.112328,0.8230599
|
||||
ion_186.96.png,7,-27.437508,6.7763624
|
||||
ion_187.61.png,8,14.746,-15.561341
|
||||
ion_187.93.png,2,-24.653465,11.311923
|
||||
ion_188.58.png,9,26.924181,-16.26996
|
||||
ion_188.91.png,2,-23.250217,12.80303
|
||||
ion_189.24.png,0,-3.1196318,10.865817
|
||||
ion_189.56.png,9,17.892994,-14.850101
|
||||
ion_189.89.png,2,-15.080282,14.058813
|
||||
ion_190.21.png,2,-14.918471,12.226166
|
||||
ion_190.54.png,9,26.066849,-8.028413
|
||||
ion_190.86.png,2,-16.36275,16.187475
|
||||
ion_191.19.png,2,-18.617264,14.443393
|
||||
ion_191.51.png,9,15.985019,-15.161865
|
||||
ion_191.84.png,0,0.07637024,6.4175425
|
||||
ion_192.16.png,7,-29.96435,6.764731
|
||||
ion_192.81.png,2,-24.450735,12.3053665
|
||||
ion_193.14.png,2,-14.9156885,12.590401
|
||||
ion_193.79.png,0,6.8999925,6.922773
|
||||
ion_194.11.png,2,-16.894192,9.066876
|
||||
ion_194.76.png,2,-9.240621,15.130415
|
||||
ion_195.09.png,7,-31.992617,8.856382
|
||||
ion_195.74.png,3,25.191437,-0.08246486
|
||||
ion_196.06.png,2,-19.416407,9.060027
|
||||
ion_196.71.png,0,1.2136008,4.672844
|
||||
ion_197.04.png,7,-28.425535,8.977524
|
||||
ion_197.69.png,9,27.999023,-19.508387
|
||||
ion_198.01.png,0,-8.079587,11.449043
|
||||
ion_198.66.png,0,4.744716,2.964314
|
||||
ion_198.99.png,6,-40.550262,-7.840601
|
||||
ion_199.31.png,0,-6.043486,12.333179
|
||||
ion_199.64.png,9,29.09711,-15.459312
|
||||
ion_199.96.png,2,-20.972567,15.738652
|
||||
ion_200.29.png,2,-13.509321,11.575929
|
||||
ion_200.61.png,9,27.025208,-21.31873
|
||||
ion_200.94.png,2,-16.386883,15.327882
|
||||
ion_201.26.png,2,-13.90451,9.776584
|
||||
ion_201.59.png,9,27.768497,-21.380787
|
||||
ion_201.91.png,0,-1.0409251,13.911233
|
||||
ion_202.24.png,0,1.139871,5.342685
|
||||
ion_202.57.png,9,32.10026,-16.520195
|
||||
ion_202.89.png,2,-18.145033,6.5922
|
||||
ion_203.22.png,0,-5.0403314,12.270527
|
||||
ion_203.87.png,3,18.17732,3.943971
|
||||
ion_204.19.png,0,2.0714018,5.8082066
|
||||
ion_204.52.png,3,9.449215,4.8136754
|
||||
ion_204.84.png,1,-38.05102,-5.3855333
|
||||
ion_205.17.png,2,-15.323726,14.87177
|
||||
ion_205.82.png,3,21.14677,3.581677
|
||||
ion_206.14.png,0,-1.1087127,9.537847
|
||||
ion_206.79.png,2,-14.900894,15.599931
|
||||
ion_207.12.png,5,-34.12811,1.4008504
|
||||
ion_207.77.png,3,34.465927,-9.905594
|
||||
ion_208.09.png,0,5.6138525,8.248161
|
||||
ion_208.74.png,0,7.5379066,4.3042154
|
||||
ion_209.07.png,7,-31.906462,7.4224014
|
||||
ion_209.72.png,3,30.367035,-3.2509553
|
||||
ion_210.04.png,2,-20.77343,14.54681
|
||||
ion_210.69.png,9,30.188074,-9.307119
|
||||
ion_211.02.png,7,-29.426338,7.0815706
|
||||
ion_211.67.png,9,33.281834,-17.332632
|
||||
ion_211.99.png,0,-5.434221,10.356245
|
||||
ion_212.64.png,9,34.94895,-10.69858
|
||||
ion_212.97.png,2,-14.627183,14.259659
|
||||
ion_213.62.png,9,35.294746,-13.719771
|
||||
ion_213.94.png,0,7.8965335,7.9705496
|
||||
ion_214.27.png,3,17.790344,1.8371335
|
||||
ion_214.59.png,3,26.038671,5.301521
|
||||
ion_214.92.png,5,-30.914831,1.2200598
|
||||
ion_215.24.png,0,-7.1221085,11.834678
|
||||
ion_215.57.png,9,31.794752,-17.835423
|
||||
ion_215.89.png,0,-3.2855515,13.961797
|
||||
ion_216.22.png,0,-0.6859162,9.586189
|
||||
ion_216.55.png,7,-26.259516,8.475644
|
||||
ion_216.87.png,6,-43.11727,-10.622378
|
||||
ion_217.2.png,7,-25.998281,9.529986
|
||||
ion_217.52.png,9,34.34466,-17.174564
|
||||
ion_217.85.png,0,-0.25917205,6.3075128
|
||||
ion_218.17.png,0,2.7875588,7.1370487
|
||||
ion_218.82.png,0,3.3789108,5.3887396
|
||||
ion_219.15.png,0,4.9419,8.125323
|
||||
ion_219.8.png,3,23.570993,2.7602973
|
||||
ion_220.12.png,0,-7.2615247,9.177098
|
||||
ion_220.77.png,3,32.593887,-5.763114
|
||||
ion_221.1.png,0,-6.712871,11.301274
|
||||
ion_221.75.png,9,30.484035,-9.331975
|
||||
ion_222.07.png,0,-2.938413,12.682396
|
||||
ion_222.72.png,0,5.9590015,3.8290143
|
||||
ion_223.05.png,5,-33.04995,0.4847193
|
||||
ion_223.7.png,9,30.453188,-16.514444
|
||||
ion_224.02.png,0,1.7316281,5.1408854
|
||||
ion_224.67.png,3,33.902676,-9.881889
|
||||
ion_225.0.png,2,-13.303643,7.322489
|
||||
ion_225.65.png,9,28.50149,-19.001616
|
||||
ion_225.97.png,0,3.9495807,8.52111
|
||||
ion_226.62.png,3,17.701633,6.6655583
|
||||
ion_226.95.png,2,-24.95157,12.440863
|
||||
ion_227.6.png,8,15.005958,-14.606815
|
||||
ion_227.92.png,0,-5.9959893,9.723175
|
||||
ion_228.25.png,0,4.7219896,10.262852
|
||||
ion_228.9.png,2,-17.233511,16.979364
|
||||
ion_229.22.png,0,-4.9454846,11.388046
|
||||
ion_229.88.png,3,21.72242,2.5592306
|
||||
ion_230.2.png,0,3.0545614,8.768679
|
||||
ion_230.85.png,0,3.5411508,4.9265428
|
||||
ion_231.18.png,0,5.736937,6.2244816
|
||||
ion_231.83.png,3,22.28968,3.1365538
|
||||
ion_232.15.png,0,5.1185856,9.96256
|
||||
ion_232.8.png,3,28.587622,-3.1082885
|
||||
ion_233.13.png,0,-6.356156,10.779369
|
||||
ion_233.78.png,9,33.08437,-8.988923
|
||||
ion_234.1.png,0,-5.092869,11.342078
|
||||
ion_234.75.png,3,30.446781,0.8939183
|
||||
ion_235.08.png,2,-23.331598,13.555416
|
||||
ion_235.73.png,9,26.594164,-18.618465
|
||||
ion_236.05.png,2,-17.068436,8.41498
|
||||
ion_236.7.png,3,28.35997,-2.046046
|
||||
ion_237.03.png,3,15.8622055,6.6107087
|
||||
ion_237.68.png,9,17.181717,-15.99207
|
||||
ion_238.0.png,0,8.263369,8.6873
|
||||
ion_238.65.png,9,28.135519,-15.045629
|
||||
ion_238.98.png,0,1.7897984,10.504221
|
||||
ion_239.95.png,3,26.174,-3.077104
|
||||
ion_240.6.png,9,15.474228,-15.669998
|
||||
ion_240.93.png,0,6.4458795,5.3719096
|
||||
ion_241.9.png,3,27.38608,0.54914427
|
||||
ion_242.23.png,3,18.723701,1.9100204
|
||||
ion_242.88.png,0,5.1718507,7.6415257
|
||||
ion_243.21.png,2,-13.767222,10.946924
|
||||
ion_243.86.png,3,28.45869,-0.33844206
|
||||
ion_244.18.png,0,8.380079,4.4239235
|
||||
ion_244.83.png,3,23.159258,0.100792
|
||||
ion_245.16.png,0,3.64497,8.144562
|
||||
ion_245.81.png,3,25.525908,-4.2612433
|
||||
ion_246.13.png,0,-3.549516,12.331077
|
||||
ion_246.78.png,9,31.131891,-12.253968
|
||||
ion_247.11.png,0,0.8747157,11.044132
|
||||
ion_247.76.png,9,34.884518,-15.607239
|
||||
ion_248.08.png,3,26.72761,4.3562646
|
||||
ion_248.73.png,9,28.246988,-10.076125
|
||||
ion_249.06.png,0,-3.017238,11.757186
|
||||
ion_249.71.png,8,14.475118,-15.140657
|
||||
ion_250.03.png,3,25.359653,-3.5558565
|
||||
ion_250.68.png,9,26.263126,-20.95294
|
||||
ion_251.01.png,0,9.693218,7.141149
|
||||
ion_251.98.png,3,25.197989,-3.0150151
|
||||
ion_252.63.png,9,34.998253,-14.195647
|
||||
ion_252.96.png,0,7.398285,9.583776
|
||||
ion_253.93.png,3,24.647907,-4.957775
|
||||
ion_254.91.png,3,20.270203,6.8519335
|
||||
ion_255.23.png,0,3.0325668,8.183513
|
||||
ion_255.88.png,3,25.278559,-5.496368
|
||||
ion_256.21.png,3,22.577757,-4.6108294
|
||||
ion_256.86.png,3,30.956982,-3.893138
|
||||
ion_257.19.png,0,8.345898,7.157985
|
||||
ion_257.84.png,9,32.548405,-10.303978
|
||||
ion_258.16.png,3,30.508417,-4.707207
|
||||
ion_258.81.png,3,19.469334,5.1611023
|
||||
ion_259.14.png,2,-8.376543,13.943265
|
||||
ion_259.79.png,3,30.419836,-8.039713
|
||||
ion_260.11.png,9,33.020374,-7.0337534
|
||||
ion_260.76.png,9,28.17402,-18.515789
|
||||
ion_261.09.png,0,6.6859336,8.302815
|
||||
ion_261.74.png,9,34.7219,-15.372783
|
||||
ion_262.06.png,3,20.93358,3.3292527
|
||||
ion_262.71.png,9,35.46796,-12.1922
|
||||
ion_263.04.png,0,-5.995883,11.587837
|
||||
ion_263.69.png,9,16.308891,-15.314592
|
||||
ion_264.01.png,9,32.272972,-13.530391
|
||||
ion_264.99.png,3,26.751202,-5.154515
|
||||
ion_265.96.png,3,24.902645,-0.7530937
|
||||
ion_266.94.png,3,25.701172,3.553615
|
||||
ion_267.91.png,9,34.188293,-10.638313
|
||||
ion_268.89.png,3,30.478693,-1.8946239
|
||||
ion_269.21.png,2,-13.981171,8.046158
|
||||
ion_269.87.png,9,29.998203,-15.938599
|
||||
ion_270.19.png,3,25.72741,1.5884147
|
||||
ion_270.84.png,3,36.868366,-9.9761715
|
||||
ion_271.17.png,3,19.93252,6.0084004
|
||||
ion_271.82.png,9,33.174046,-16.580727
|
||||
ion_272.14.png,9,26.206633,-7.955533
|
||||
ion_272.79.png,3,28.905403,-7.9051175
|
||||
ion_273.12.png,0,8.056266,5.3453474
|
||||
ion_273.77.png,9,33.81305,-19.9639
|
||||
ion_274.09.png,9,31.556974,-22.127022
|
||||
ion_274.74.png,9,33.679058,-18.526842
|
||||
ion_275.07.png,9,28.535221,-7.1477456
|
||||
ion_276.04.png,3,14.807062,5.5181775
|
||||
ion_277.02.png,3,28.40732,-3.9556458
|
||||
ion_277.99.png,3,26.6683,-4.0368953
|
||||
ion_278.32.png,3,23.75582,1.7946953
|
||||
ion_278.64.png,2,-13.898659,5.659099
|
||||
ion_278.97.png,6,-41.740196,-9.413981
|
||||
ion_279.29.png,5,-29.076683,3.008845
|
||||
ion_279.62.png,3,29.266857,-0.6369429
|
||||
ion_279.94.png,0,0.4989599,12.061284
|
||||
ion_280.92.png,3,32.446533,-4.107399
|
||||
ion_281.89.png,9,31.876614,-15.746353
|
||||
ion_282.87.png,3,28.560238,-1.0499889
|
||||
ion_283.85.png,9,26.621946,-20.67594
|
||||
ion_284.82.png,9,33.796124,-12.506761
|
||||
ion_285.15.png,3,21.241554,5.1587663
|
||||
ion_285.8.png,9,26.547033,-18.30967
|
||||
ion_286.12.png,9,32.822624,-20.686197
|
||||
ion_286.77.png,3,30.250584,0.55641127
|
||||
ion_287.1.png,3,21.9872,2.1390061
|
||||
ion_287.75.png,9,37.12438,-13.494064
|
||||
ion_288.07.png,3,30.606201,-2.640319
|
||||
ion_289.05.png,3,22.890013,3.9677382
|
||||
ion_290.02.png,9,32.2399,-12.798281
|
||||
ion_291.0.png,9,28.448782,-14.007974
|
||||
ion_291.97.png,9,31.225016,-12.040639
|
||||
ion_292.95.png,9,34.69593,-11.920377
|
||||
ion_293.92.png,9,33.119762,-11.329056
|
||||
ion_294.9.png,3,36.564575,-9.625822
|
||||
ion_295.87.png,3,28.584211,-1.8474163
|
||||
ion_296.85.png,3,20.620918,7.438985
|
||||
ion_297.83.png,9,36.039566,-11.209591
|
||||
ion_298.15.png,3,25.659477,-1.8728
|
||||
ion_298.8.png,3,35.617268,-10.148742
|
||||
ion_299.13.png,3,21.799765,7.968525
|
||||
ion_301.08.png,9,27.44734,-13.561337
|
||||
ion_302.05.png,9,30.053375,-14.549845
|
||||
ion_303.03.png,9,29.068108,-14.753645
|
||||
ion_303.68.png,9,28.479387,-21.916006
|
||||
ion_304.0.png,9,29.201258,-23.598558
|
||||
ion_304.33.png,8,13.122702,-12.554004
|
||||
ion_304.98.png,9,24.650152,-7.1270638
|
||||
ion_305.95.png,3,29.059801,-8.600534
|
||||
ion_306.28.png,8,10.460474,-12.517865
|
||||
ion_306.93.png,9,31.42041,-17.013552
|
||||
ion_307.9.png,9,32.330303,-13.718061
|
||||
ion_308.88.png,3,31.862032,-5.8857284
|
||||
ion_309.85.png,9,29.141745,-18.15918
|
||||
ion_310.83.png,9,36.09488,-12.799859
|
||||
ion_311.16.png,3,28.080969,-6.667759
|
||||
ion_312.78.png,3,29.836946,0.27934504
|
||||
ion_313.11.png,2,-8.627648,12.400691
|
||||
ion_314.08.png,3,20.629183,5.6328382
|
||||
ion_315.06.png,3,26.503016,-2.5715907
|
||||
ion_318.96.png,9,31.351917,-11.315838
|
||||
ion_326.76.png,3,32.09507,0.18656318
|
||||
ion_328.71.png,3,18.54395,7.1383853
|
||||
ion_329.04.png,0,-7.3291235,14.529308
|
||||
ion_329.69.png,9,34.27189,-15.177913
|
||||
ion_330.01.png,3,26.687662,1.431783
|
||||
ion_330.99.png,3,31.18035,-0.7660054
|
||||
ion_334.89.png,9,30.313026,-9.015304
|
||||
ion_335.21.png,0,8.570336,5.221153
|
||||
ion_336.84.png,9,31.535072,-16.199507
|
||||
ion_337.17.png,3,21.336227,6.6063633
|
||||
ion_338.14.png,3,26.978844,-5.2260184
|
||||
ion_339.12.png,9,27.873163,-20.949478
|
||||
ion_351.8.png,9,31.467436,-10.136445
|
||||
ion_352.12.png,3,28.709461,0.9844084
|
||||
ion_353.75.png,9,16.17768,-16.142302
|
||||
ion_354.07.png,0,10.21724,8.987664
|
||||
ion_355.05.png,2,-8.144377,15.491125
|
||||
ion_370.33.png,3,29.735342,2.3608685
|
||||
ion_370.65.png,7,-28.00135,5.0777225
|
||||
ion_370.98.png,1,-38.86183,-6.1244082
|
||||
ion_371.3.png,2,-14.572228,4.9324327
|
||||
ion_371.63.png,2,-21.988415,16.459906
|
||||
ion_371.95.png,1,-35.610634,-3.5852711
|
||||
ion_372.6.png,3,32.483067,1.3230696
|
||||
ion_372.93.png,7,-27.402096,5.2922916
|
||||
ion_384.63.png,3,30.532621,2.4404614
|
||||
ion_387.56.png,3,22.448105,8.419394
|
||||
ion_390.81.png,0,-0.39847365,13.831687
|
||||
ion_391.14.png,2,-7.6635137,15.491304
|
||||
ion_401.54.png,3,31.95286,-0.16999035
|
||||
ion_401.86.png,3,17.869164,6.7715282
|
||||
ion_461.69.png,3,31.942822,0.51566416
|
||||
ion_59.51.png,9,35.17394,-13.068886
|
||||
ion_59.84.png,2,-20.054785,12.566305
|
||||
ion_60.16.png,2,-13.147553,13.29442
|
||||
ion_60.81.png,2,-22.018095,16.838892
|
||||
ion_64.71.png,3,30.316786,-0.84601045
|
||||
ion_66.66.png,3,18.554628,6.6652193
|
||||
ion_66.99.png,6,-42.332752,-10.112175
|
||||
ion_67.64.png,3,17.628195,4.6080613
|
||||
ion_67.96.png,5,-32.32362,1.8389728
|
||||
ion_68.62.png,0,5.661518,2.3490248
|
||||
ion_68.94.png,6,-39.790955,-10.437897
|
||||
ion_69.27.png,0,1.6724036,4.168741
|
||||
ion_69.59.png,2,-23.649536,11.986989
|
||||
ion_69.92.png,4,-43.299904,-15.888535
|
||||
ion_70.24.png,0,-0.06470341,8.682315
|
||||
ion_70.57.png,9,29.347612,-20.504143
|
||||
ion_70.89.png,6,-42.5278,-11.181254
|
||||
ion_71.54.png,0,-0.9896617,12.607591
|
||||
ion_71.87.png,6,-39.048397,-8.880032
|
||||
ion_72.19.png,5,-32.476727,1.5677394
|
||||
ion_72.52.png,8,10.250291,-13.858199
|
||||
ion_72.84.png,5,-30.629602,1.8604381
|
||||
ion_73.49.png,9,36.719025,-11.857051
|
||||
ion_73.82.png,4,-45.17158,-16.50476
|
||||
ion_74.14.png,4,-45.596066,-13.342802
|
||||
ion_74.79.png,2,-17.46527,16.901453
|
||||
ion_76.74.png,0,-6.216439,15.702544
|
||||
ion_77.72.png,0,-6.6433234,14.540961
|
||||
ion_78.69.png,0,6.182824,2.9642966
|
||||
ion_79.02.png,4,-46.21426,-15.078558
|
||||
ion_79.34.png,9,28.354658,-15.809483
|
||||
ion_79.67.png,7,-28.589724,7.147096
|
||||
ion_79.99.png,5,-35.044357,0.942713
|
||||
ion_80.32.png,9,31.341908,-17.860785
|
||||
ion_80.64.png,2,-19.469915,16.784105
|
||||
ion_80.97.png,4,-45.72406,-15.982423
|
||||
ion_81.62.png,0,5.452961,5.6512375
|
||||
ion_81.95.png,1,-37.81082,-2.6366253
|
||||
ion_82.27.png,3,22.566402,4.0558753
|
||||
ion_82.6.png,0,-7.4663644,10.1609125
|
||||
ion_82.92.png,2,-17.679209,12.253551
|
||||
ion_83.25.png,0,2.373072,3.9440634
|
||||
ion_83.57.png,5,-31.87277,0.8549705
|
||||
ion_83.9.png,4,-43.896214,-16.96346
|
||||
ion_84.22.png,2,-14.043374,12.942986
|
||||
ion_84.55.png,9,32.700012,-19.502073
|
||||
ion_84.87.png,6,-42.983273,-11.961578
|
||||
ion_85.52.png,9,28.50589,-18.010765
|
||||
ion_85.85.png,4,-42.999424,-14.644611
|
||||
ion_86.17.png,4,-44.66821,-16.437698
|
||||
ion_86.5.png,9,27.44913,-24.501375
|
||||
ion_86.82.png,6,-43.99355,-10.41811
|
||||
ion_87.47.png,9,18.174158,-15.126801
|
||||
ion_87.8.png,6,-40.46243,-9.185634
|
||||
ion_88.12.png,6,-39.640736,-8.055685
|
||||
ion_88.77.png,0,3.8780096,2.591604
|
||||
ion_89.75.png,0,10.09258,6.4302506
|
||||
ion_90.07.png,0,3.625766,9.283005
|
||||
ion_90.72.png,5,-31.266928,4.554381
|
||||
ion_91.05.png,4,-45.765697,-14.986678
|
||||
ion_91.7.png,9,29.559906,-13.975161
|
||||
ion_92.67.png,0,7.893663,5.9997163
|
||||
ion_93.0.png,4,-45.56015,-15.572192
|
||||
ion_93.32.png,9,34.741074,-12.338461
|
||||
ion_93.65.png,0,-5.853657,6.404585
|
||||
ion_93.97.png,2,-17.645025,10.471852
|
||||
ion_94.3.png,0,-3.9838848,6.2626543
|
||||
ion_94.62.png,7,-25.971523,9.763064
|
||||
ion_94.95.png,6,-38.702198,-10.900641
|
||||
ion_95.28.png,0,-7.582129,12.356361
|
||||
ion_95.6.png,0,-0.56754535,11.996512
|
||||
ion_95.93.png,4,-43.824963,-16.213938
|
||||
ion_96.58.png,0,-1.5130029,12.203467
|
||||
ion_96.9.png,5,-35.778248,2.471955
|
||||
ion_97.23.png,3,16.597586,6.1397967
|
||||
ion_97.55.png,3,21.361723,4.0301137
|
||||
ion_97.88.png,4,-44.037876,-16.904804
|
||||
ion_98.2.png,5,-33.773403,2.9667366
|
||||
ion_98.53.png,9,18.12225,-16.086273
|
||||
ion_98.85.png,6,-43.389095,-11.146669
|
||||
ion_99.5.png,9,28.50092,-20.264837
|
||||
ion_99.83.png,4,-44.475746,-16.098194
|
||||
|
@@ -0,0 +1,95 @@
|
||||
using Pkg
|
||||
Pkg.activate("/app/environment")
|
||||
|
||||
# Handle dynamic environment fallback
|
||||
if !haskey(Pkg.project().dependencies, "Plots")
|
||||
Pkg.add("Plots")
|
||||
end
|
||||
|
||||
ENV["GKSwstype"] = "100" # Headless rendering for Docker container
|
||||
using Plots
|
||||
|
||||
# Load framework core dependencies smoothly
|
||||
juliamsi_path = "/app/JuliaMSI"
|
||||
push!(LOAD_PATH, joinpath(juliamsi_path, "src"))
|
||||
include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
|
||||
using .MSI_src
|
||||
|
||||
using CSV, DataFrames
|
||||
using Statistics
|
||||
using Plots.Measures
|
||||
|
||||
# 1. PATH CONFIGURATIONS
|
||||
data_path = "/app/data/Leaf.imzML"
|
||||
mask_path = "/app/data/region_of_interest.png"
|
||||
clusters_path = "/app/msi_clusters_results.csv"
|
||||
|
||||
println("Loading data arrays...")
|
||||
data = OpenMSIData(data_path)
|
||||
clusters_df = CSV.read(clusters_path, DataFrame)
|
||||
|
||||
# 2. RUN FRAMEWORK ANALYTICS TO DISCOVER PHYSICAL BOUNDARIES
|
||||
println("Syncing Dataset Precomputed Boundaries...")
|
||||
MSI_src.precompute_analytics(data)
|
||||
|
||||
# Extract binned spectrum arrays
|
||||
mzs_avg, ints_avg = MSI_src.get_average_spectrum(data, mask_path=mask_path)
|
||||
|
||||
# --- DYNAMIC AXIS SAFEGUARD ---
|
||||
# Query the atomic fields populated by precompute_analytics
|
||||
# fallback to standard values if the fields return uninitialized values
|
||||
min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
|
||||
max_vis_mz = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 700.0
|
||||
|
||||
println(" Detected Dynamic Min m/z Limit: ", round(min_vis_mz, digits=2))
|
||||
println(" Detected Dynamic Max m/z Limit: ", round(max_vis_mz, digits=2))
|
||||
|
||||
# 3. Configure Base Plot Layer with Dynamic X-limits
|
||||
p = plot(mzs_avg, ints_avg,
|
||||
linecolor = :lightgray, # Light base so cluster sticks pop out visually
|
||||
linewidth = 0.7,
|
||||
label = "Average Spectrum (Reference)",
|
||||
xlabel = "m/z",
|
||||
ylabel = "Relative Intensity",
|
||||
title = "Cluster Mapping on Isotopic Pattern",
|
||||
size = (1200, 600),
|
||||
legend = :outerright,
|
||||
grid = false,
|
||||
framestyle = :box,
|
||||
xlims = (min_vis_mz, max_vis_mz), # Dynamically locks view strictly to valid mass range
|
||||
left_margin = 15mm,
|
||||
bottom_margin = 15mm
|
||||
)
|
||||
|
||||
# 4. Use the exact qualitative 10-color palette seen in your image
|
||||
cluster_colors = palette(:tab10)
|
||||
|
||||
# 5. Map Cluster Vectors to Binned Positions
|
||||
println("Mapping chemical clusters onto binned coordinates...")
|
||||
for cluster_id in sort(unique(clusters_df.cluster))
|
||||
sub_df = filter(row -> row.cluster == cluster_id, clusters_df)
|
||||
label_ready = false
|
||||
|
||||
for target_mz in sub_df.mz
|
||||
# Find the closest matching bin channel index in the 2000-bin array
|
||||
idx = argmin(abs.(mzs_avg .- target_mz))
|
||||
|
||||
m = mzs_avg[idx]
|
||||
i = ints_avg[idx]
|
||||
|
||||
# Draw the vertical peak highlighter over the base spectrum
|
||||
plot!(p, [m, m], [0, i],
|
||||
linecolor = cluster_colors[cluster_id + 1],
|
||||
linewidth = 1.2,
|
||||
alpha = 0.9,
|
||||
label = label_ready ? "" : "Cluster $cluster_id"
|
||||
)
|
||||
label_ready = true
|
||||
end
|
||||
end
|
||||
|
||||
# 6. Save assets to shared folder mount
|
||||
savefig("/app/espectro_msi_paper_style.png")
|
||||
println("Saved publication-ready plot: /app/espectro_msi_paper_style.png")
|
||||
savefig("/app/espectro_msi_clusters_julia.png")
|
||||
println("Saved backup copy: /app/espectro_msi_clusters_julia.png")
|
||||
@@ -0,0 +1,119 @@
|
||||
# BRIDGE SCRIPT: Connects JuliaMSI framework to the CNN Preprocessing pipeline.
|
||||
# VERSION (V3): Relying directly on precomputed analytics and multiple mz slices for max throughtput
|
||||
|
||||
using Pkg
|
||||
juliamsi_path = "/app/JuliaMSI"
|
||||
push!(LOAD_PATH, joinpath(juliamsi_path, "src"))
|
||||
|
||||
# Load JuliaMSI core
|
||||
include(joinpath(juliamsi_path, "src", "MSI_src.jl"))
|
||||
|
||||
using .MSI_src
|
||||
using Statistics, Images, Interpolations, BenchmarkTools
|
||||
|
||||
# CONFIGURATION
|
||||
data_path = "/app/data/Leaf.imzML"
|
||||
mask_path = "/app/data/region_of_interest.png"
|
||||
output_folder = "/app/datos_para_ai"
|
||||
img_size = (256, 256)
|
||||
tolerance = 0.05
|
||||
mkpath(output_folder)
|
||||
|
||||
println("--- JULIA BATCH ENGINE ---")
|
||||
|
||||
function run_production_pipeline()
|
||||
# 1. LOAD DATA
|
||||
println("Step 1: Ingesting Data...")
|
||||
data = OpenMSIData(data_path)
|
||||
|
||||
orig_height = data.image_dims[2]
|
||||
orig_width = data.image_dims[1]
|
||||
if orig_height < 256 || orig_width < 256
|
||||
final_img_size = (orig_height, orig_width)
|
||||
println(" [Notice] Original image is smaller than 256x256. Keeping original size: ", final_img_size)
|
||||
else
|
||||
final_img_size = (256, 256)
|
||||
println(" [Notice] Resizing down to target size: ", final_img_size)
|
||||
end
|
||||
|
||||
# 2. RUN FRAMEWORK ANALYTICS
|
||||
println("Step 2: Checking Dataset Precomputed Boundaries...")
|
||||
# This matches the framework's internal logic to safely discover the true boundaries.
|
||||
# It populates global_min_mz and global_max_mz by reading the binary headers properly.
|
||||
MSI_src.precompute_analytics(data)
|
||||
|
||||
# 3. EXTRACT AVERAGE SPECTRUM
|
||||
println("Step 3: Calculating ROI Average Spectrum...")
|
||||
mzs, avg_ints = MSI_src.get_average_spectrum(data, mask_path=mask_path)
|
||||
|
||||
println(" True Dataset Min m/z: ", round(minimum(mzs), digits=2))
|
||||
println(" True Dataset Max m/z: ", round(maximum(mzs), digits=2))
|
||||
|
||||
# 4. PEAK PICKING USING TRUE SPECTRA LIMITS
|
||||
# Identify relevant ion channels above a 2% intensity base peak threshold
|
||||
threshold = maximum(avg_ints) * 0.02
|
||||
peak_indices = findall(x -> x > threshold, avg_ints)
|
||||
|
||||
min_vis_mz = data.global_min_mz[] > 0.0 ? data.global_min_mz[] : 50.0
|
||||
max_vis_mz = data.global_max_mz[] > 0.0 ? data.global_max_mz[] : 1000.0
|
||||
|
||||
# Isolate targets that fall strictly within the standard CNN metabolic training window
|
||||
target_masses = Float64[]
|
||||
for idx in peak_indices
|
||||
mz_val = mzs[idx]
|
||||
if mz_val >= min_vis_mz && mz_val <= max_vis_mz
|
||||
push!(target_masses, mz_val)
|
||||
end
|
||||
end
|
||||
|
||||
total_ions = length(target_masses)
|
||||
println("Found $total_ions ions within training range ($(min_vis_mz) to $(max_vis_mz) m/z) above threshold.")
|
||||
if total_ions == 0
|
||||
println("Warning: No peaks met the criteria. Check your threshold or mask alignment.")
|
||||
return
|
||||
end
|
||||
|
||||
# 5. MULTI-CHANNEL BATCH EXTRACTION (Single pass over binary data)
|
||||
println("Step 4: Multi-channel Batch Extraction (Optimized I/O)...")
|
||||
slice_dict = MSI_src.get_multiple_mz_slices(data, target_masses, tolerance, mask_path=mask_path)
|
||||
|
||||
# 6. THREADED PROCESSING & EXPORT
|
||||
println("Step 5: Threaded TrIQ Normalization & Safe 256x256 Zero-Padding...")
|
||||
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
|
||||
exported_count = Threads.Atomic{Int}(0)
|
||||
|
||||
# Fixed target dimensions for the CNN
|
||||
target_size = (256, 256)
|
||||
|
||||
Threads.@threads for mz_val in target_masses
|
||||
slice = get(slice_dict, mz_val, nothing)
|
||||
if slice === nothing || all(iszero, slice) continue end
|
||||
|
||||
# 1. Framework-Native TrIQ (0.0 to 255.0 Scaling)
|
||||
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
|
||||
|
||||
# 2. Allocate an empty 256x256 background matrix
|
||||
padded_matrix = zeros(Float32, target_size)
|
||||
|
||||
# 3. Compute structural centering offsets based on true resolution (161x106)
|
||||
h_orig, w_orig = size(slice_quant, 1), size(slice_quant, 2)
|
||||
offset_y = div(target_size[1] - h_orig, 2) + 1
|
||||
offset_x = div(target_size[2] - w_orig, 2) + 1
|
||||
|
||||
# 4. Map the pristine, raw pixels directly into the center
|
||||
padded_matrix[offset_y:offset_y+h_orig-1, offset_x:offset_x+w_orig-1] .= slice_quant
|
||||
|
||||
# 5. Convert safely to 0.0 - 1.0 float mapping for Gray image export
|
||||
normalized_gray = padded_matrix ./ 255.0
|
||||
|
||||
# 6. Save the unblurred, structurally perfect map
|
||||
filename = "ion_$(round(mz_val, digits=2)).png"
|
||||
save(joinpath(output_folder, filename), Gray.(normalized_gray))
|
||||
|
||||
Threads.atomic_add!(exported_count, 1)
|
||||
end
|
||||
|
||||
println("\nSuccess: $(exported_count[]) target image maps exported to $output_folder.")
|
||||
end
|
||||
|
||||
@time run_production_pipeline()
|
||||
@@ -0,0 +1,203 @@
|
||||
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
|
||||
|
||||
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, "..", "datos_para_ai")
|
||||
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
|
||||
# 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
|
||||
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
|
||||
self.spatial_transform = transforms.Compose([
|
||||
transforms.Resize((size, size)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
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)
|
||||
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):
|
||||
def __init__(self, img_dir, transform=None):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = [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("L")
|
||||
if self.transform:
|
||||
xi, xj = self.transform(image)
|
||||
return xi, xj
|
||||
|
||||
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.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
|
||||
)
|
||||
|
||||
self.projector = nn.Sequential(
|
||||
nn.Linear(256, 128),
|
||||
nn.ReLU(),
|
||||
nn.Linear(128, projection_dim)
|
||||
)
|
||||
|
||||
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
|
||||
z = self.projector(h_norm)
|
||||
return h, z
|
||||
|
||||
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"Launching VRAM-Optimized Contrastive Pipeline on: {DEVICE}")
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
model = MSI_Structural_Encoder().to(DEVICE)
|
||||
optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=1e-4)
|
||||
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()
|
||||
|
||||
for epoch in range(EPOCHS):
|
||||
model.train()
|
||||
total_loss = 0
|
||||
epoch_start = time.time()
|
||||
|
||||
optimizer.zero_grad() # Initialize gradients outside the accumulation loop
|
||||
|
||||
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}")
|
||||
torch.save(model.features.state_dict(), MODEL_SAVE_PATH)
|
||||
print(f"Model saved to: {MODEL_SAVE_PATH}")
|
||||
@@ -4,42 +4,85 @@ 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
|
||||
|
||||
# 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
|
||||
IMG_DIR = "datos_para_ai"
|
||||
MODEL_PATH = "Model/msi_encoder_trained.pth"
|
||||
DEVICE = torch.device("cpu") # Forced to CPU
|
||||
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")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
||||
|
||||
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)
|
||||
|
||||
# 1. LOAD MODEL AND EXTRACT FEATURES
|
||||
def extract_features():
|
||||
# Load the trained encoder
|
||||
model = models.efficientnet_b0()
|
||||
model.classifier = nn.Identity()
|
||||
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model = MSI_Structural_Encoder()
|
||||
if not os.path.exists(MODEL_PATH):
|
||||
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.Resize((256, 256)),
|
||||
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...")
|
||||
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 = Image.open(img_path).convert("L")
|
||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||
feat = model(img_t).cpu().numpy().flatten()
|
||||
features.append(feat)
|
||||
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)
|
||||
|
||||
@@ -47,9 +90,10 @@ def extract_features():
|
||||
if __name__ == "__main__":
|
||||
X = extract_features()
|
||||
|
||||
# Dimensionality reduction (PCA) for stability
|
||||
pca = PCA(n_components=50)
|
||||
pca = PCA(n_components=min(50, X.shape[1]), 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)
|
||||
|
||||
inertias = []
|
||||
silhouettes = []
|
||||
@@ -63,35 +107,31 @@ if __name__ == "__main__":
|
||||
labels = kmeans.fit_predict(X_pca)
|
||||
|
||||
inertias.append(kmeans.inertia_)
|
||||
silhouettes.append(silhouette_score(X_pca, labels))
|
||||
# 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))
|
||||
|
||||
# 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)')
|
||||
@@ -99,17 +139,17 @@ if __name__ == "__main__":
|
||||
ax4.grid(True)
|
||||
|
||||
plt.tight_layout()
|
||||
plt.savefig('cluster_validation_detailed_plot.png')
|
||||
print("Plot saved as 'cluster_validation_detailed_plot.png'")
|
||||
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)]}")
|
||||
@@ -0,0 +1,182 @@
|
||||
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.decomposition import PCA
|
||||
from sklearn.manifold import TSNE
|
||||
from sklearn.cluster import KMeans
|
||||
import matplotlib.pyplot as plt
|
||||
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)
|
||||
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, "..", "datos_para_ai")
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
TARGET_K = 10 # Enforce your target 10 metabolic domains
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
# Matches the high-fidelity GroupNorm architecture
|
||||
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()
|
||||
# Loading only the feature extractor weights
|
||||
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("Loading specialized custom MSI Structural Encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetInference(IMG_DIR)
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
|
||||
features = []
|
||||
ion_names = []
|
||||
|
||||
print("Extracting and L2-normalizing features from custom manifold...")
|
||||
with torch.no_grad():
|
||||
for img, name in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
# Re-enforce unit hypersphere mapping
|
||||
feat = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat.cpu().numpy().flatten())
|
||||
ion_names.append(name[0])
|
||||
|
||||
features = np.array(features)
|
||||
|
||||
# Dimensionality Reduction Optimization
|
||||
pca_km = PCA(n_components=min(50, len(features)), random_state=42)
|
||||
features_pca_all = pca_km.fit_transform(features)
|
||||
|
||||
# FIX: Slice out the first principal component (index 0)
|
||||
# if it continues to hold the global brightness/intensity bias
|
||||
features_pca_km = features_pca_all[:, 1:]
|
||||
|
||||
# CRITICAL FIX: Re-normalize strictly for K-Means to ensure objective Cosine geometry
|
||||
features_pca_km_norm = features_pca_km / np.linalg.norm(features_pca_km, axis=1, keepdims=True)
|
||||
|
||||
# ENFORCE EXACTLY 10 METABOLIC DOMAINS
|
||||
print(f"Executing K-Means clustering 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_km_norm)
|
||||
|
||||
print("Projecting t-SNE map...")
|
||||
tsne = TSNE(
|
||||
n_components=2,
|
||||
perplexity=15,
|
||||
early_exaggeration=24.0, # Boosted significantly to force tighter, more definitive visual clusters
|
||||
learning_rate='auto',
|
||||
init='pca',
|
||||
random_state=42
|
||||
)
|
||||
# Feed the unnormalized PCA vectors to t-SNE to allow intensity variance to separate the visual blobs
|
||||
embeddings_2d = tsne.fit_transform(features_pca_km)
|
||||
|
||||
# Plotting
|
||||
plt.figure(figsize=(10, 8))
|
||||
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.9, edgecolors='none', s=45)
|
||||
cbar = plt.colorbar(scatter, ticks=range(TARGET_K))
|
||||
cbar.set_label('Metabolic Domain ID (K=10)')
|
||||
|
||||
plt.title("Objectively Segmented Leaf Manifold (Custom Encoder)")
|
||||
plt.xlabel("t-SNE Dimension 1")
|
||||
plt.ylabel("t-SNE Dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.3)
|
||||
|
||||
plt.savefig(os.path.join(BASE_DIR, "..", "msi_tsne_corregido.png"), dpi=300, bbox_inches='tight')
|
||||
plt.close()
|
||||
|
||||
# INTERACTIVE PLOTLY EXPORT
|
||||
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="Interactive Segmented Leaf Manifold (Custom Encoder)",
|
||||
category_orders={"Cluster": [str(i) for i in range(TARGET_K)]}
|
||||
)
|
||||
|
||||
plotly_out = os.path.join(BASE_DIR, "..", "figures", "msi_tsne_interactive.html")
|
||||
os.makedirs(os.path.dirname(plotly_out), exist_ok=True)
|
||||
fig.write_html(plotly_out)
|
||||
print(f"Interactive t-SNE saved to: {plotly_out}")
|
||||
|
||||
# Save outputs
|
||||
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(BASE_DIR, "..", "msi_clusters_results.csv"), index=False)
|
||||
|
||||
print("Process complete.")
|
||||
@@ -0,0 +1,195 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, transforms
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import torch.nn.functional as F
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 1. CONFIGURATION
|
||||
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")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "guided_validation")
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
# FIX: Restore the full list of verified vascular landmarks to build a robust structural vector
|
||||
ANCHOR_MZS = [155.75, 156.07, 156.40, 273.77, 274.09, 275.07, 286.12, 304.00, 304.33]
|
||||
SIMI_THRESHOLD = 0.85 # Calibrated to capture true negative space co-exclusions down to 0.85
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
"""
|
||||
The exact high-fidelity custom architecture used during your successful
|
||||
zero-padded 256x256 contrastive training run.
|
||||
"""
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
|
||||
self.features = nn.Sequential(
|
||||
# Layer 1: Input 256x256x1 (Standardized size)
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 2
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 3
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
|
||||
# Layer 4
|
||||
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()
|
||||
# Load only the feature extractor weights to match the save format in CNN_proof_1.py
|
||||
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||
print(f"Successfully synchronized weights with custom encoder architecture: {path}")
|
||||
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
if __name__ == "__main__":
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)), # Standardized size matching training
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
# 3. SCAN ALL IMAGE MAPS
|
||||
all_files = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||
print(f"Discovered {len(all_files)} total ion slices in data pool.")
|
||||
|
||||
ion_registry = []
|
||||
for f in all_files:
|
||||
try:
|
||||
mz_extracted = float(f.replace("ion_", "").replace(".png", ""))
|
||||
ion_registry.append({"filename": f, "mz": mz_extracted})
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
df_ions = pd.DataFrame(ion_registry)
|
||||
|
||||
# 4. EXTRACT VECTORS
|
||||
print("Extracting L2-normalized latent fingerprints...")
|
||||
latent_vectors = {}
|
||||
|
||||
with torch.no_grad():
|
||||
for _, row in df_ions.iterrows():
|
||||
fpath = os.path.join(IMG_DIR, row['filename'])
|
||||
img_tensor = transform(Image.open(fpath).convert("L")).unsqueeze(0).to(DEVICE)
|
||||
feat = encoder(img_tensor)
|
||||
feat_norm = F.normalize(feat, p=2, dim=1) # Project onto unit hypersphere
|
||||
latent_vectors[row['filename']] = feat_norm.squeeze(0).cpu().numpy()
|
||||
|
||||
# 5. CONSTRUCT SEED
|
||||
anchor_features = []
|
||||
found_anchors = []
|
||||
|
||||
for anchor in ANCHOR_MZS:
|
||||
match = df_ions[np.isclose(df_ions['mz'], anchor, atol=0.05)]
|
||||
if not match.empty:
|
||||
fname = match.iloc[0]['filename']
|
||||
anchor_features.append(latent_vectors[fname])
|
||||
found_anchors.append(fname)
|
||||
|
||||
if len(anchor_features) == 0:
|
||||
print("Error: None of your specified anchor vein images were located.")
|
||||
exit()
|
||||
|
||||
vascular_profile_centroid = np.mean(anchor_features, axis=0)
|
||||
vascular_profile_centroid /= np.linalg.norm(vascular_profile_centroid)
|
||||
|
||||
print(f"Generated unified vascular profile from {len(found_anchors)} anchor ions.")
|
||||
|
||||
# 6. EVALUATE SIMILARITY
|
||||
guided_matches = []
|
||||
for fname, vector in latent_vectors.items():
|
||||
similarity = np.dot(vector, vascular_profile_centroid)
|
||||
if similarity >= SIMI_THRESHOLD:
|
||||
mz_val = df_ions[df_ions['filename'] == fname]['mz'].values[0]
|
||||
guided_matches.append({"filename": fname, "mz": mz_val, "similarity": similarity})
|
||||
|
||||
df_guided = pd.DataFrame(guided_matches).sort_values(by="similarity", ascending=False)
|
||||
print(f"\nFound {len(df_guided)} ions displaying vascular alignment (Cosine Sim >= {SIMI_THRESHOLD})")
|
||||
|
||||
csv_out = os.path.join(OUTPUT_DIR, "guided_vascular_ions.csv")
|
||||
df_guided.to_csv(csv_out, index=False)
|
||||
|
||||
# 7. GENERATE GALLERIES
|
||||
max_per_page = 12
|
||||
chunks = [df_guided[i:i + max_per_page] for i in range(0, len(df_guided), max_per_page)]
|
||||
|
||||
for page_idx, chunk in enumerate(chunks):
|
||||
num_plots = len(chunk)
|
||||
rows = int(np.ceil(num_plots / 4))
|
||||
cols = min(num_plots, 4)
|
||||
|
||||
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 4))
|
||||
fig.suptitle(f"Guided Vascular Affinity Grouping - Tier {page_idx + 1}", fontsize=16, y=0.98)
|
||||
|
||||
flat_axes = axes.flatten() if isinstance(axes, np.ndarray) else [axes]
|
||||
|
||||
for idx, (_, row) in enumerate(chunk.iterrows()):
|
||||
ax = flat_axes[idx]
|
||||
img_path = os.path.join(IMG_DIR, row['filename'])
|
||||
img = Image.open(img_path)
|
||||
# Use 'viridis' for improved structural visibility
|
||||
ax.imshow(img, cmap='viridis')
|
||||
ax.set_title(f"m/z {row['mz']:.2f}\nSim: {row['similarity']:.4f}", fontsize=10)
|
||||
ax.axis('off')
|
||||
|
||||
for empty_idx in range(num_plots, len(flat_axes)):
|
||||
flat_axes[empty_idx].axis('off')
|
||||
|
||||
plt.tight_layout()
|
||||
gallery_out = os.path.join(OUTPUT_DIR, f"Guided_Vascular_Gallery_Page_{page_idx + 1}.png")
|
||||
plt.savefig(gallery_out, dpi=200, bbox_inches='tight')
|
||||
plt.close()
|
||||
|
||||
print("\nGuided extraction validation cycle complete.")
|
||||
|
||||
print("\n--- RUNNING ISOTOPIC FUNCTIONAL VALIDATION ---")
|
||||
verified_biological_count = 0
|
||||
|
||||
for idx, row in df_guided.iterrows():
|
||||
target_mz = row['mz']
|
||||
isotope_mz = target_mz + 1.0033
|
||||
|
||||
# Check if the expected isotope exists within your parsed data pool
|
||||
isotope_match = df_ions[np.isclose(df_ions['mz'], isotope_mz, atol=0.02)]
|
||||
|
||||
if not isotope_match.empty:
|
||||
iso_fname = isotope_match.iloc[0]['filename']
|
||||
iso_vector = latent_vectors[iso_fname]
|
||||
|
||||
# Calculate similarity of the isotope to your core vascular vector
|
||||
iso_sim = np.dot(iso_vector, vascular_profile_centroid)
|
||||
|
||||
if iso_sim >= 0.80:
|
||||
print(f"Verified Structural Pair: Base m/z {target_mz:.2f} (Sim: {row['similarity']:.4f}) -> Isotope m/z {isotope_mz:.2f} (Sim: {iso_sim:.4f})")
|
||||
verified_biological_count += 1
|
||||
|
||||
print(f"Validation complete. Confirmed {verified_biological_count} true isotopic structural pairs.")
|
||||
@@ -0,0 +1,116 @@
|
||||
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.decomposition import PCA
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.manifold import TSNE
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# 1. CONFIGURACIÓN
|
||||
IMG_DIR = "datos_para_ai"
|
||||
OUTPUT_DIR = "pruebas_clusters"
|
||||
N_CLUSTERS = 10
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
# 2. CARGAR MODELO PRE-ENTRENADO (Directo de PyTorch)
|
||||
def get_pretrained_extractor():
|
||||
# Usamos los pesos por defecto de ImageNet
|
||||
model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
|
||||
model.classifier = nn.Identity() # Quitamos la capa de clasificación
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# 3. DATASET CON NORMALIZACIÓN ESTÁNDAR
|
||||
class MSIDatasetDirect(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(),
|
||||
# Normalización obligatoria para modelos pre-entrenados
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
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]
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"Extrayendo características con red pre-entrenada en {DEVICE}...")
|
||||
model = get_pretrained_extractor()
|
||||
dataset = MSIDatasetDirect(IMG_DIR)
|
||||
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 = model(img)
|
||||
# Aplanar el vector de características (1280 dimensiones para EffNet-B0)
|
||||
features.append(feat.cpu().numpy().flatten())
|
||||
ion_names.append(name[0])
|
||||
|
||||
features = np.array(features)
|
||||
print(f"Características extraídas: {features.shape}")
|
||||
|
||||
# 4. REDUCCIÓN DE DIMENSIONALIDAD (PCA)
|
||||
# Esto ayuda a que el clustering no se pierda en dimensiones irrelevantes
|
||||
print("Reduciendo ruido con PCA...")
|
||||
features_scaled = StandardScaler().fit_transform(features)
|
||||
pca = PCA(n_components=0.95) # Mantenemos el 95% de la varianza
|
||||
features_pca = pca.fit_transform(features_scaled)
|
||||
print(f"Dimensiones tras PCA: {features_pca.shape[1]}")
|
||||
|
||||
# 5. CLUSTERING K-MEANS
|
||||
print(f"Agrupando en {N_CLUSTERS} clusters...")
|
||||
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
|
||||
labels = km.fit_predict(features_pca)
|
||||
|
||||
# 6. VISUALIZACIÓN (t-SNE)
|
||||
print("Generando visualización t-SNE para verificar consistencia...")
|
||||
tsne = TSNE(n_components=2, random_state=42)
|
||||
features_tsne = tsne.fit_transform(features_pca)
|
||||
|
||||
plt.figure(figsize=(10, 8))
|
||||
scatter = plt.scatter(features_tsne[:, 0], features_tsne[:, 1], c=labels, cmap='tab10', alpha=0.7)
|
||||
plt.colorbar(scatter, ticks=range(N_CLUSTERS), label='Cluster ID')
|
||||
plt.title(f"Visualización de Clusters (K={N_CLUSTERS}) - Directo")
|
||||
plt.xlabel("t-SNE 1")
|
||||
plt.ylabel("t-SNE 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.5)
|
||||
plt.savefig(os.path.join(OUTPUT_DIR, "msi_clusters_direct_plot.png"))
|
||||
print(f"Gráfico de consistencia guardado en '{OUTPUT_DIR}/msi_clusters_direct_plot.png'.")
|
||||
|
||||
# 7. GUARDAR Y REPORTAR
|
||||
df = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||
df['mz'] = df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_results.csv"), index=False)
|
||||
|
||||
# Crear un resumen de cuántos iones hay por cluster
|
||||
print("\nResumen de Clusters (Consistente con el CSV y el Gráfico):")
|
||||
counts = df['cluster'].value_counts().sort_index()
|
||||
print(counts)
|
||||
|
||||
# Guardar también el resumen para evitar confusiones con otros archivos
|
||||
summary_df = counts.reset_index()
|
||||
summary_df.columns = ['Cluster_ID', 'Ion_Count']
|
||||
summary_df.to_csv(os.path.join(OUTPUT_DIR, "msi_clusters_direct_summary.csv"), index=False)
|
||||
|
||||
print(f"\nResultados guardados en '{OUTPUT_DIR}/msi_clusters_direct_results.csv' y '{OUTPUT_DIR}/msi_clusters_direct_summary.csv'.")
|
||||
print(f"Usa '{OUTPUT_DIR}/msi_clusters_direct_plot.png' para validar visualmente los puntos.")
|
||||
@@ -11,8 +11,9 @@ 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"
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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.manifold import TSNE
|
||||
import pandas as pd
|
||||
import plotly.express as px
|
||||
|
||||
# 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"
|
||||
CSV_PATH = "msi_clusters_results.csv" # Fuente de verdad
|
||||
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 BASADO EN EL CSV
|
||||
class MSIDatasetFromCSV(Dataset):
|
||||
def __init__(self, img_dir, img_names):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = img_names
|
||||
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)
|
||||
|
||||
# --- PROCESO ---
|
||||
if __name__ == "__main__":
|
||||
# 4. CARGAR EL CSV DE RESULTADOS
|
||||
print(f"Cargando datos desde {CSV_PATH}...")
|
||||
df = pd.read_csv(CSV_PATH)
|
||||
ion_names = df['ion_image'].tolist()
|
||||
|
||||
# Asegurarnos de que cluster sea categórico para Plotly
|
||||
df['cluster'] = df['cluster'].astype(str)
|
||||
|
||||
print("Extrayendo características con el encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetFromCSV(IMG_DIR, ion_names)
|
||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||
|
||||
features = []
|
||||
with torch.no_grad():
|
||||
for i, img in enumerate(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())
|
||||
if (i+1) % 100 == 0:
|
||||
print(f"Iones procesados: {i+1}/{len(ion_names)}")
|
||||
|
||||
features = np.array(features)
|
||||
|
||||
# 5. t-SNE
|
||||
print("Calculando t-SNE...")
|
||||
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
|
||||
embeddings_2d = tsne.fit_transform(features)
|
||||
|
||||
# Agregar coordenadas t-SNE al DataFrame original
|
||||
df['tsne_1'] = embeddings_2d[:, 0]
|
||||
df['tsne_2'] = embeddings_2d[:, 1]
|
||||
|
||||
# 6. VISUALIZACIÓN INTERACTIVA CON PLOTLY
|
||||
print("Generando gráfica interactiva con Plotly...")
|
||||
|
||||
# Usar escala de colores similar a tab10 o cualitativa estándar
|
||||
fig = px.scatter(
|
||||
df,
|
||||
x='tsne_1',
|
||||
y='tsne_2',
|
||||
color='cluster',
|
||||
hover_data={'ion_image': True, 'mz': True, 'cluster': True, 'tsne_1': False, 'tsne_2': False},
|
||||
title=f"t-SNE Interactivo de Iones MSI (Consistente con {CSV_PATH})",
|
||||
labels={'tsne_1': 't-SNE 1', 'tsne_2': 't-SNE 2'},
|
||||
category_orders={"cluster": [str(i) for i in range(N_CLUSTERS)]},
|
||||
color_discrete_sequence=px.colors.qualitative.Plotly # O T10 si está disponible
|
||||
)
|
||||
|
||||
# Mejorar el diseño
|
||||
fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color='DarkSlateGrey')))
|
||||
fig.update_layout(
|
||||
legend_title_text='Cluster ID',
|
||||
font=dict(size=14),
|
||||
hoverlabel=dict(bgcolor="white", font_size=16)
|
||||
)
|
||||
|
||||
# Guardar como HTML
|
||||
output_html = "msi_tsne_interactivo.html"
|
||||
fig.write_html(output_html)
|
||||
|
||||
print(f"\n¡Éxito! Gráfica interactiva guardada en '{output_html}'.")
|
||||
print("Puedes abrir este archivo en cualquier navegador para explorar los clusters.")
|
||||
@@ -0,0 +1,197 @@
|
||||
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
|
||||
|
||||
# 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")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
K = 10
|
||||
|
||||
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)
|
||||
|
||||
# 1. DATA LOADING
|
||||
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)
|
||||
# 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)
|
||||
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)
|
||||
|
||||
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))
|
||||
|
||||
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 ---")
|
||||
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)")
|
||||
|
||||
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.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)
|
||||
@@ -0,0 +1,73 @@
|
||||
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
|
||||
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")
|
||||
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):
|
||||
return self.features(x).squeeze(-1).squeeze(-1)
|
||||
|
||||
def load_encoder_diagnostic(path):
|
||||
model = MSI_Structural_Encoder()
|
||||
if os.path.exists(path):
|
||||
state_dict = torch.load(path, map_location=DEVICE)
|
||||
model.features.load_state_dict(state_dict)
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
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")
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
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)
|
||||
|
||||
with torch.no_grad():
|
||||
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.")
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
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
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super().__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)
|
||||
|
||||
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.")
|
||||
exit()
|
||||
|
||||
model = MSI_Structural_Encoder()
|
||||
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||
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))
|
||||
closest_mz = mzs[idx]
|
||||
|
||||
if abs(closest_mz - mz_target) > 0.1:
|
||||
return None, closest_mz
|
||||
|
||||
img_path = os.path.join(IMG_DIR, files[idx])
|
||||
img = Image.open(img_path).convert("L")
|
||||
tensor = transform(img).unsqueeze(0)
|
||||
|
||||
with torch.no_grad():
|
||||
feat = model(tensor)
|
||||
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||
return feat_norm.numpy().flatten(), closest_mz
|
||||
|
||||
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)
|
||||
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}")
|
||||
@@ -0,0 +1,55 @@
|
||||
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")
|
||||
|
||||
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}...")
|
||||
# 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)
|
||||
|
||||
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:
|
||||
ax.text(0.5, 0.5, 'Image Not Found', ha='center', va='center', fontsize=6)
|
||||
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}")
|
||||
else:
|
||||
print(f"Error: Missing required results file: {CSV_PATH}")
|
||||
print("Please run 'python scripts_python/graficar_tsne_msi.py' first to generate results.")
|
||||
@@ -1,33 +0,0 @@
|
||||
import pandas as pd
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
from PIL import Image
|
||||
|
||||
# Configuration
|
||||
# CSV_PATH = "msi_clusters_results.csv"
|
||||
CSV_PATH = "msi_clusters_direct_results.csv"
|
||||
IMG_DIR = "datos_para_ai"
|
||||
OUTPUT_DIR = "cluster_results"
|
||||
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} - Ion Examples", 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}/cluster_gallery_{cluster_id}.png")
|
||||
plt.close()
|
||||
|
||||
print(f"Galleries saved in {OUTPUT_DIR}. Review these images to identify which structure each cluster represents.")
|
||||