Subir archivos a "scripts_python"
This commit is contained in:
@@ -0,0 +1,172 @@
|
||||
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)
|
||||
|
||||
set_seed(42)
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images")
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth")
|
||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
TARGET_K = 5
|
||||
|
||||
class MSI_Structural_Encoder(nn.Module):
|
||||
def __init__(self):
|
||||
super(MSI_Structural_Encoder, self).__init__()
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||
nn.GroupNorm(4, 32),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(8, 64),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(16, 128),
|
||||
nn.ReLU(),
|
||||
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||
nn.GroupNorm(32, 256),
|
||||
nn.ReLU(),
|
||||
nn.AdaptiveAvgPool2d((1, 1))
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||
return h
|
||||
|
||||
def load_trained_encoder(path):
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||
model = MSI_Structural_Encoder()
|
||||
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||
model.to(DEVICE)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
class MSIDatasetInference(Dataset):
|
||||
def __init__(self, img_dir):
|
||||
self.img_dir = img_dir
|
||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||
self.transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)),
|
||||
transforms.ToTensor()
|
||||
])
|
||||
|
||||
def __len__(self):
|
||||
return len(self.img_names)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||
image = Image.open(img_path).convert("L")
|
||||
return self.transform(image), self.img_names[idx]
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Loading specialized custom MSI Structural Encoder...")
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
dataset = MSIDatasetInference(IMG_DIR)
|
||||
loader = DataLoader(dataset, batch_size=64, shuffle=False, num_workers=2)
|
||||
|
||||
features = []
|
||||
ion_names = []
|
||||
|
||||
print("Extracting and L2-normalizing features from custom manifold...")
|
||||
with torch.no_grad():
|
||||
for img, names in loader:
|
||||
img = img.to(DEVICE)
|
||||
feat = encoder(img)
|
||||
feat = F.normalize(feat, p=2, dim=1)
|
||||
features.append(feat.cpu().numpy())
|
||||
ion_names.extend(names)
|
||||
|
||||
features = np.concatenate(features, axis=0)
|
||||
print(f" Feature matrix: {features.shape}")
|
||||
|
||||
# PCA for denoising (retain 95% variance)
|
||||
pca = PCA(n_components=min(50, features.shape[0]), random_state=42)
|
||||
features_pca = pca.fit_transform(features)
|
||||
# Re-normalize after PCA to restore unit hypersphere geometry for Spherical K-Means
|
||||
features_pca = features_pca / np.linalg.norm(features_pca, axis=1, keepdims=True)
|
||||
print(f" PCA components: {features_pca.shape[1]} (explained variance: {pca.explained_variance_ratio_.sum():.3f})")
|
||||
|
||||
print(f"Executing Spherical K-Means (via re-normalized PCA) strictly constrained to K={TARGET_K}...")
|
||||
clusterer = KMeans(n_clusters=TARGET_K, init='k-means++', n_init=20, random_state=42)
|
||||
labels = clusterer.fit_predict(features_pca)
|
||||
|
||||
print("Projecting t-SNE map...")
|
||||
tsne = TSNE(
|
||||
n_components=2,
|
||||
perplexity=30,
|
||||
learning_rate='auto',
|
||||
init='pca',
|
||||
random_state=42
|
||||
)
|
||||
embeddings_2d = tsne.fit_transform(features_pca)
|
||||
|
||||
output_dir = os.path.join(BASE_DIR, "..", "..", "outputs_k5")
|
||||
figures_dir = os.path.join(output_dir, "figures")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
|
||||
plt.figure(figsize=(10, 8))
|
||||
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(f'Metabolic Domain ID (K={TARGET_K})')
|
||||
|
||||
plt.title(f"t-SNE Visualization of MSI Ions (K={TARGET_K})")
|
||||
plt.xlabel("t-SNE Dimension 1")
|
||||
plt.ylabel("t-SNE Dimension 2")
|
||||
plt.grid(True, linestyle='--', alpha=0.3)
|
||||
|
||||
plt.savefig(os.path.join(output_dir, "msi_tsne_plot.png"), dpi=300, bbox_inches='tight')
|
||||
plt.close()
|
||||
print(f" Static t-SNE saved to: outputs_k5/msi_tsne_plot.png")
|
||||
|
||||
print("Exporting Interactive Plotly t-SNE...")
|
||||
mz_values = [float(n.replace("ion_", "").replace(".png", "")) for n in ion_names]
|
||||
df_plot = pd.DataFrame({
|
||||
't-SNE Dimension 1': embeddings_2d[:, 0],
|
||||
't-SNE Dimension 2': embeddings_2d[:, 1],
|
||||
'Cluster': [str(lbl) for lbl in labels],
|
||||
'm/z': mz_values,
|
||||
'Filename': ion_names
|
||||
})
|
||||
|
||||
fig = px.scatter(
|
||||
df_plot,
|
||||
x='t-SNE Dimension 1',
|
||||
y='t-SNE Dimension 2',
|
||||
color='Cluster',
|
||||
hover_data=['m/z', 'Filename'],
|
||||
title=f"Interactive t-SNE of MSI Ions (K={TARGET_K})",
|
||||
category_orders={"Cluster": [str(i) for i in range(TARGET_K)]}
|
||||
)
|
||||
|
||||
plotly_out = os.path.join(figures_dir, "msi_tsne_interactive.html")
|
||||
fig.write_html(plotly_out)
|
||||
print(f" Interactive t-SNE saved to: {plotly_out}")
|
||||
|
||||
print("Exporting synchronized cluster assignments...")
|
||||
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||
df_results['mz'] = df_results['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
df_results.to_csv(os.path.join(output_dir, "msi_clusters_results.csv"), index=False)
|
||||
|
||||
print("Process complete.")
|
||||
@@ -8,48 +8,33 @@ 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")
|
||||
IMG_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "ion_images")
|
||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "..", "outputs", "models", "msi_encoder_trained.pth")
|
||||
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "..", "outputs", "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
|
||||
SIMI_THRESHOLD = 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))
|
||||
)
|
||||
|
||||
@@ -62,7 +47,6 @@ def load_trained_encoder(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}")
|
||||
|
||||
@@ -74,11 +58,10 @@ if __name__ == "__main__":
|
||||
encoder = load_trained_encoder(ENCODER_PATH)
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((256, 256)), # Standardized size matching training
|
||||
transforms.Resize((256, 256)),
|
||||
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.")
|
||||
|
||||
@@ -92,7 +75,6 @@ if __name__ == "__main__":
|
||||
|
||||
df_ions = pd.DataFrame(ion_registry)
|
||||
|
||||
# 4. EXTRACT VECTORS
|
||||
print("Extracting L2-normalized latent fingerprints...")
|
||||
latent_vectors = {}
|
||||
|
||||
@@ -101,10 +83,9 @@ if __name__ == "__main__":
|
||||
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
|
||||
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||
latent_vectors[row['filename']] = feat_norm.squeeze(0).cpu().numpy()
|
||||
|
||||
# 5. CONSTRUCT SEED
|
||||
anchor_features = []
|
||||
found_anchors = []
|
||||
|
||||
@@ -124,7 +105,6 @@ if __name__ == "__main__":
|
||||
|
||||
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)
|
||||
@@ -138,7 +118,6 @@ if __name__ == "__main__":
|
||||
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)]
|
||||
|
||||
@@ -156,7 +135,6 @@ if __name__ == "__main__":
|
||||
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')
|
||||
@@ -178,14 +156,12 @@ if __name__ == "__main__":
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Standalone ion-carpet exporter.
|
||||
|
||||
Assembles the per-ion viridis corpus exported by Stage 1 (outputs/ion_images_viridis/)
|
||||
into (i) a full-dataset mosaic sorted by m/z and (ii) per-cluster mosaics using the
|
||||
Stage-3/4 cluster assignment, for manual exploration and publication figures.
|
||||
|
||||
Usage:
|
||||
python3 make_ion_carpet.py DATASET [--tile-size N]
|
||||
|
||||
Requires the pipeline to have exported a viridis corpus for the dataset.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import math
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
sys.exit("Pillow is required (pip install pillow)")
|
||||
|
||||
try:
|
||||
import tqdm
|
||||
except ImportError:
|
||||
tqdm = None
|
||||
|
||||
|
||||
def load_ions(viridis_dir, tile_size, dataset):
|
||||
viridis_dir = os.path.join(viridis_dir)
|
||||
if not os.path.isdir(viridis_dir):
|
||||
sys.exit(f"viridis corpus not found: {viridis_dir}")
|
||||
|
||||
files = glob.glob(os.path.join(viridis_dir, "ion_*.png"))
|
||||
if not files:
|
||||
sys.exit(f"no ion tiles found in {viridis_dir}")
|
||||
|
||||
ions = []
|
||||
for f in files:
|
||||
try:
|
||||
mz = float(os.path.basename(f)[len("ion_"):-len(".png")])
|
||||
except ValueError:
|
||||
continue
|
||||
ions.append((mz, f))
|
||||
ions.sort(key=lambda t: t[0])
|
||||
return ions
|
||||
|
||||
|
||||
def mosaic(ions, tile_size, out_path, label=None):
|
||||
n = len(ions)
|
||||
cols = int(math.ceil(math.sqrt(n)))
|
||||
rows = int(math.ceil(n / cols))
|
||||
|
||||
canvas_w = cols * tile_size
|
||||
pad = max(2, tile_size // 16)
|
||||
label_h = pad * 2 + tile_size if label else 0
|
||||
|
||||
canvas = Image.new("RGB", (canvas_w, rows * tile_size + label_h), (255, 255, 255))
|
||||
draw = None
|
||||
if label:
|
||||
from PIL import ImageDraw
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
draw.text((pad, 0), label, fill=(0, 0, 0))
|
||||
|
||||
iterator = tqdm.tqdm(ions, desc=os.path.basename(out_path)) if tqdm else ions
|
||||
for idx, (mz, f) in enumerate(iterator):
|
||||
try:
|
||||
im = Image.open(f).convert("RGB")
|
||||
except OSError:
|
||||
continue
|
||||
im = im.resize((tile_size, tile_size), Image.LANCZOS)
|
||||
r = idx // cols
|
||||
c = idx % cols
|
||||
x = c * tile_size
|
||||
y = label_h + r * tile_size
|
||||
canvas.paste(im, (x, y))
|
||||
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
canvas.save(out_path)
|
||||
return rows, cols
|
||||
|
||||
|
||||
def cluster_assignments(root, dataset):
|
||||
csv_path = os.path.join(root, "outputs", dataset, "msi_clusters_results.csv")
|
||||
if not os.path.isfile(csv_path):
|
||||
return None
|
||||
assign = {}
|
||||
with open(csv_path) as f:
|
||||
header = f.readline().strip().split(",")
|
||||
for line in f:
|
||||
parts = line.strip().split(",")
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
assign[parts[0]] = int(parts[1])
|
||||
return assign
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument("dataset")
|
||||
ap.add_argument("--tile-size", type=int, default=96)
|
||||
ap.add_argument("--clusters", action="store_true", help="also emit per-cluster mosaics")
|
||||
args = ap.parse_args()
|
||||
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
dataset_dir = os.path.join(root, "datasets", args.dataset)
|
||||
viridis_dir = os.path.join(root, "outputs", "ion_images_viridis", args.dataset)
|
||||
ions = load_ions(viridis_dir, args.tile_size, args.dataset)
|
||||
out_dir = os.path.join(root, "outputs", args.dataset, "figures")
|
||||
full_path = os.path.join(out_dir, "ion_carpet_full.png")
|
||||
cols = int(math.ceil(math.sqrt(len(ions))))
|
||||
rows = int(math.ceil(len(ions) / cols))
|
||||
rows, cols = mosaic(ions, args.tile_size, full_path,
|
||||
label=f"{args.dataset}: {len(ions)} ions (grid {cols}x{rows}, m/z ascending row-major)")
|
||||
|
||||
manifest_path = os.path.join(out_dir, "ion_carpet_manifest.csv")
|
||||
with open(manifest_path, "w") as f:
|
||||
f.write("grid_index,row,col,mz,tile\n")
|
||||
for idx, (mz, tile) in enumerate(ions):
|
||||
f.write(f"{idx},{idx // cols},{idx % cols},{mz},{os.path.basename(tile)}\n")
|
||||
print(f"[carpet] full mosaic: {full_path} ({rows}x{cols} tiles)")
|
||||
print(f"[carpet] manifest: {manifest_path}")
|
||||
|
||||
if args.clusters:
|
||||
assign = cluster_assignments(root, args.dataset)
|
||||
if assign is None:
|
||||
print("[carpet] no cluster assignments; skipping per-cluster mosaics")
|
||||
return
|
||||
by_cluster = {}
|
||||
for mz, tile in ions:
|
||||
base = os.path.basename(tile)
|
||||
cl = assign.get(base)
|
||||
if cl is not None:
|
||||
by_cluster.setdefault(cl, []).append((mz, tile))
|
||||
for cl in sorted(by_cluster):
|
||||
cpath = os.path.join(out_dir, f"ion_carpet_cluster_{cl}.png")
|
||||
r2, c2 = mosaic(by_cluster[cl], args.tile_size, cpath,
|
||||
label=f"cluster {cl}: {len(by_cluster[cl])} ions")
|
||||
print(f"[carpet] cluster {cl} mosaic: {cpath} ({r2}x{c2} tiles)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,248 @@
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
import struct
|
||||
import xml.etree.ElementTree as ET
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
|
||||
TOLERANCE = 0.05
|
||||
TARGET_SIZE = (256, 256)
|
||||
TRIG_QUANTILE = 0.98
|
||||
THRESHOLD_FRACTION = 0.02
|
||||
|
||||
NS = "{http://psi.hupo.org/ms/mzml}"
|
||||
|
||||
def configure(data_dir, dataset_name):
|
||||
imzml_files = [f for f in os.listdir(data_dir) if f.lower().endswith(".imzml")]
|
||||
if not imzml_files:
|
||||
sys.exit(f"No .imzML file found in {data_dir}")
|
||||
imzml_path = os.path.join(data_dir, imzml_files[0])
|
||||
ibd_path = imzml_path[:-6] + ".ibd"
|
||||
if not os.path.isfile(ibd_path):
|
||||
ibd_path = imzml_path[:-5] + "ibd"
|
||||
output_dir = os.path.join(PROJECT_ROOT, "outputs", "ion_images", dataset_name)
|
||||
viridis_dir = os.path.join(PROJECT_ROOT, "outputs", "ion_images_viridis", dataset_name)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
os.makedirs(viridis_dir, exist_ok=True)
|
||||
return imzml_path, ibd_path, output_dir, viridis_dir
|
||||
|
||||
def parse_imzml(path):
|
||||
tree = ET.parse(path)
|
||||
root = tree.getroot()
|
||||
spectra = root.findall(f".//{NS}spectrum")
|
||||
scan_settings = root.findall(f".//{NS}scanSettings")
|
||||
max_x = 0
|
||||
max_y = 0
|
||||
for ss in scan_settings:
|
||||
for cv in ss.findall(f"{NS}cvParam"):
|
||||
acc = cv.get("accession")
|
||||
if acc == "IMS:1000042":
|
||||
max_x = int(cv.get("value"))
|
||||
elif acc == "IMS:1000043":
|
||||
max_y = int(cv.get("value"))
|
||||
groups = root.findall(f".//{NS}referenceableParamGroup")
|
||||
mz_format = np.float64
|
||||
int_format = np.float32
|
||||
for g in groups:
|
||||
gid = g.get("id")
|
||||
for cv in g.findall(f"{NS}cvParam"):
|
||||
acc = cv.get("accession")
|
||||
if acc == "MS:1000523" and gid == "mzArray":
|
||||
mz_format = np.float64
|
||||
elif acc == "MS:1000521" and gid == "intensityArray":
|
||||
int_format = np.float32
|
||||
coord_list = []
|
||||
for s in spectra:
|
||||
bdas = s.findall(f".//{NS}binaryDataArray")
|
||||
if not bdas:
|
||||
continue
|
||||
params = {cv.get("accession"): cv.get("value")
|
||||
for cv in s.findall(f".//{NS}cvParam")}
|
||||
x = int(params.get("IMS:1000050", 0))
|
||||
y = int(params.get("IMS:1000051", 0))
|
||||
x = max(x, 1)
|
||||
y = max(y, 1)
|
||||
for bda in s.findall(f".//{NS}binaryDataArray"):
|
||||
ref = bda.find(f"{NS}referenceableParamGroupRef")
|
||||
if ref is None:
|
||||
continue
|
||||
bda_params = {cv.get("accession"): cv.get("value")
|
||||
for cv in bda.findall(f"{NS}cvParam")}
|
||||
offset = int(bda_params.get("IMS:1000102", 0))
|
||||
length = int(bda_params.get("IMS:1000103", 0))
|
||||
coord_list.append({
|
||||
"x": x - 1, "y": y - 1,
|
||||
"offset": offset, "length": length,
|
||||
"ref": ref.get("ref")
|
||||
})
|
||||
spectra_info = []
|
||||
i = 0
|
||||
while i < len(coord_list):
|
||||
if i + 1 < len(coord_list) and coord_list[i]["x"] == coord_list[i+1]["x"] and coord_list[i]["y"] == coord_list[i+1]["y"]:
|
||||
mz_info = coord_list[i] if coord_list[i]["ref"] == "mzArray" else coord_list[i+1]
|
||||
int_info = coord_list[i+1] if coord_list[i]["ref"] == "mzArray" else coord_list[i]
|
||||
spectra_info.append({
|
||||
"x": mz_info["x"], "y": mz_info["y"],
|
||||
"mz_offset": mz_info["offset"], "mz_length": mz_info["length"],
|
||||
"int_offset": int_info["offset"], "int_length": int_info["length"]
|
||||
})
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
return spectra_info, max_x, max_y, mz_format, int_format
|
||||
|
||||
def find_mask_path(data_dir):
|
||||
"""Auto-detect the ROI mask PNG for a dataset.
|
||||
|
||||
Prefers the canonical `region_of_interest.png`, then falls back to any PNG
|
||||
whose name matches roi/mask/region (e.g. Datura_root's Mask_Datura_root.png).
|
||||
Mirrors the Julia bridge's detection so every stage agrees on the mask.
|
||||
"""
|
||||
if not os.path.isdir(data_dir):
|
||||
return None
|
||||
canonical = os.path.join(data_dir, "region_of_interest.png")
|
||||
if os.path.isfile(canonical):
|
||||
return canonical
|
||||
for f in sorted(os.listdir(data_dir)):
|
||||
if f.lower().endswith(".png") and re.search(r"roi|mask|region", f.lower()):
|
||||
return os.path.join(data_dir, f)
|
||||
return None
|
||||
|
||||
|
||||
def load_mask(path, dims):
|
||||
if path is None or not os.path.isfile(path):
|
||||
return None
|
||||
img = Image.open(path).convert("L")
|
||||
mask = np.array(img, dtype=np.float32)
|
||||
if mask.shape != (dims[1], dims[0]):
|
||||
from PIL.Image import Resampling
|
||||
mask = np.array(Image.fromarray(mask).resize((dims[0], dims[1]), Resampling.NEAREST))
|
||||
return (mask > 128).astype(np.float32)
|
||||
|
||||
def trig_normalize(slice_2d, mask=None, quantile=0.98):
|
||||
if mask is not None:
|
||||
vals = slice_2d[mask > 0]
|
||||
if len(vals) == 0:
|
||||
vals = slice_2d[slice_2d > 0]
|
||||
else:
|
||||
vals = slice_2d[slice_2d > 0]
|
||||
if len(vals) == 0:
|
||||
return slice_2d
|
||||
threshold = np.percentile(vals, quantile * 100)
|
||||
if threshold == 0:
|
||||
threshold = vals.max()
|
||||
if threshold == 0:
|
||||
return slice_2d
|
||||
normalized = np.clip(slice_2d / threshold, 0, 1)
|
||||
if mask is not None:
|
||||
normalized = normalized * mask
|
||||
return normalized
|
||||
|
||||
def zero_pad(slice_2d, target_size=(256, 256)):
|
||||
h, w = slice_2d.shape
|
||||
padded = np.zeros(target_size, dtype=np.float32)
|
||||
if h > target_size[0] or w > target_size[1]:
|
||||
sh = min(h, target_size[0])
|
||||
sw = min(w, target_size[1])
|
||||
padded[:sh, :sw] = slice_2d[:sh, :sw]
|
||||
else:
|
||||
offset_y = (target_size[0] - h) // 2
|
||||
offset_x = (target_size[1] - w) // 2
|
||||
padded[offset_y:offset_y+h, offset_x:offset_x+w] = slice_2d
|
||||
return padded
|
||||
|
||||
def compute_average_spectrum(spectra_info, ibd_path, mz_format, int_format, mask=None):
|
||||
ibd_size = os.path.getsize(ibd_path)
|
||||
intensity_dict = {}
|
||||
with open(ibd_path, "rb") as f:
|
||||
for spec in spectra_info:
|
||||
if mask is not None and mask[spec["y"], spec["x"]] == 0:
|
||||
continue
|
||||
if spec["mz_offset"] + spec["mz_length"] * mz_format().itemsize > ibd_size:
|
||||
continue
|
||||
if spec["int_offset"] + spec["int_length"] * int_format().itemsize > ibd_size:
|
||||
continue
|
||||
f.seek(spec["int_offset"])
|
||||
ints = np.frombuffer(f.read(spec["int_length"] * int_format().itemsize), dtype=int_format)
|
||||
f.seek(spec["mz_offset"])
|
||||
mzs = np.frombuffer(f.read(spec["mz_length"] * mz_format().itemsize), dtype=mz_format)
|
||||
for i in range(len(mzs)):
|
||||
mz_key = round(mzs[i], 2)
|
||||
intensity_dict[mz_key] = intensity_dict.get(mz_key, 0) + ints[i]
|
||||
sorted_mzs = np.sort(list(intensity_dict.keys()))
|
||||
avg_ints = np.array([intensity_dict[m] for m in sorted_mzs])
|
||||
return sorted_mzs, avg_ints
|
||||
|
||||
def extract_ion_images(spectra_info, ibd_path, target_mzs, tolerance, mz_format, int_format,
|
||||
max_x, max_y, output_dir, viridis_dir=None, mask=None):
|
||||
ion_images = {mz: np.zeros((max_y, max_x), dtype=np.float64) for mz in target_mzs}
|
||||
ibd_size = os.path.getsize(ibd_path)
|
||||
with open(ibd_path, "rb") as f:
|
||||
for spec in spectra_info:
|
||||
if spec["mz_offset"] + spec["mz_length"] * mz_format().itemsize > ibd_size:
|
||||
continue
|
||||
f.seek(spec["int_offset"])
|
||||
ints = np.frombuffer(f.read(spec["int_length"] * int_format().itemsize), dtype=int_format)
|
||||
f.seek(spec["mz_offset"])
|
||||
mzs = np.frombuffer(f.read(spec["mz_length"] * mz_format().itemsize), dtype=mz_format)
|
||||
for target_mz in target_mzs:
|
||||
mz_match = np.abs(mzs - target_mz) <= tolerance
|
||||
if mz_match.any():
|
||||
ion_images[target_mz][spec["y"], spec["x"]] = ints[mz_match].sum()
|
||||
if viridis_dir:
|
||||
import matplotlib
|
||||
cmap = matplotlib.colormaps["viridis"]
|
||||
exported = 0
|
||||
for mz_val in target_mzs:
|
||||
slice_2d = ion_images[mz_val]
|
||||
if np.all(slice_2d == 0):
|
||||
continue
|
||||
if mask is not None:
|
||||
slice_2d = slice_2d * mask
|
||||
slice_norm = trig_normalize(slice_2d, mask=mask, quantile=TRIG_QUANTILE)
|
||||
padded = zero_pad(slice_norm, TARGET_SIZE)
|
||||
img = (padded * 255).astype(np.uint8)
|
||||
filename = f"ion_{mz_val:.5f}.png"
|
||||
Image.fromarray(img, mode="L").save(os.path.join(output_dir, filename))
|
||||
if viridis_dir:
|
||||
rgb = (cmap(padded)[:, :, :3] * 255).astype(np.uint8)
|
||||
Image.fromarray(rgb, mode="RGB").save(os.path.join(viridis_dir, filename))
|
||||
exported += 1
|
||||
return exported
|
||||
|
||||
if __name__ == "__main__":
|
||||
data_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.join(PROJECT_ROOT, "datasets", "Datura_leaf")
|
||||
dataset_name = sys.argv[2] if len(sys.argv) > 2 else "Datura_leaf"
|
||||
imzml_path, ibd_path, output_dir, viridis_dir = configure(data_dir, dataset_name)
|
||||
|
||||
print(f"--- PYTHON PREPROCESSOR: {dataset_name} ---")
|
||||
print(f"Data: {imzml_path}")
|
||||
print(f"Output: {output_dir}")
|
||||
print("Step 1: Parsing imzML...")
|
||||
spectra_info, max_x, max_y, mz_format, int_format = parse_imzml(imzml_path)
|
||||
print(f" Dims: {max_x}x{max_y}, Spectra with data: {len(spectra_info)}")
|
||||
print(f" mz format: {mz_format.__name__}, intensity format: {int_format.__name__}")
|
||||
mask = load_mask(find_mask_path(data_dir), (max_x, max_y))
|
||||
if mask is not None:
|
||||
nz = int(np.count_nonzero(mask))
|
||||
print(f" Using ROI mask ({nz}/{mask.size} pixels)")
|
||||
else:
|
||||
print(" Note: No ROI mask provided. Using full tissue area.")
|
||||
print("Step 2: Computing average spectrum...")
|
||||
mzs, avg_ints = compute_average_spectrum(spectra_info, ibd_path, mz_format, int_format, mask=mask)
|
||||
print(f" m/z range: {mzs[0]:.2f} - {mzs[-1]:.2f}")
|
||||
print("Step 3: Peak picking (2% threshold)...")
|
||||
threshold = avg_ints.max() * THRESHOLD_FRACTION
|
||||
target_mzs = mzs[avg_ints > threshold]
|
||||
print(f" Found {len(target_mzs)} peaks above threshold")
|
||||
if len(target_mzs) == 0:
|
||||
sys.exit(" No peaks found!")
|
||||
print("Step 4: Extracting ion images...")
|
||||
exported = extract_ion_images(spectra_info, ibd_path, target_mzs, TOLERANCE,
|
||||
mz_format, int_format, max_x, max_y, output_dir,
|
||||
viridis_dir=viridis_dir, mask=mask)
|
||||
print(f"\nSuccess: {exported} ion images exported to {output_dir}")
|
||||
print(f"Success: {exported} viridis maps exported to {viridis_dir}")
|
||||
@@ -0,0 +1,102 @@
|
||||
import os
|
||||
import sys
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
from PIL import Image
|
||||
|
||||
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from msi_preprocess_python import parse_imzml, compute_average_spectrum, load_mask, configure, find_mask_path
|
||||
|
||||
dataset_name = sys.argv[1] if len(sys.argv) > 1 else "Datura_leaf"
|
||||
data_dir = os.path.join(PROJECT_ROOT, "datasets", dataset_name)
|
||||
output_dir = os.path.join(PROJECT_ROOT, "outputs", dataset_name)
|
||||
figures_dir = os.path.join(output_dir, "figures")
|
||||
cluster_csv = os.path.join(output_dir, "msi_clusters_results.csv")
|
||||
os.makedirs(figures_dir, exist_ok=True)
|
||||
|
||||
imzml_path, ibd_path, _, _ = configure(data_dir, dataset_name)
|
||||
|
||||
print(f"Parsing imzML: {imzml_path}")
|
||||
spectra_info, max_x, max_y, mz_format, int_format = parse_imzml(imzml_path)
|
||||
mask = load_mask(find_mask_path(data_dir), (max_x, max_y))
|
||||
print(f" Dims: {max_x}x{max_y}, Spectra: {len(spectra_info)}")
|
||||
|
||||
print("Computing average spectrum...")
|
||||
mzs_avg, ints_avg = compute_average_spectrum(spectra_info, ibd_path, mz_format, int_format, mask=mask)
|
||||
|
||||
min_vis_mz = float(mzs_avg[0]) if mzs_avg[0] > 0 else 50.0
|
||||
max_vis_mz = float(mzs_avg[-1]) if mzs_avg[-1] > 0 else 1000.0
|
||||
|
||||
cluster_colors = plt.cm.tab10(np.linspace(0, 1, 10))
|
||||
|
||||
# ---- 1. mean_spectrum_full.png ----
|
||||
plt.figure(figsize=(14, 4))
|
||||
plt.plot(mzs_avg, ints_avg, color='black', linewidth=1.0)
|
||||
plt.xlabel("m/z")
|
||||
plt.ylabel("Relative Intensity")
|
||||
plt.title(f"Full Average Spectrum ({dataset_name})")
|
||||
plt.xlim(min_vis_mz, max_vis_mz)
|
||||
plt.grid(False)
|
||||
plt.box(True)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(figures_dir, "mean_spectrum_full.png"), dpi=200)
|
||||
plt.close()
|
||||
print(" Saved: mean_spectrum_full.png")
|
||||
|
||||
# ---- Cluster annotations ----
|
||||
if os.path.isfile(cluster_csv):
|
||||
clusters_df = pd.read_csv(cluster_csv)
|
||||
clusters_df['mz'] = clusters_df['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||
|
||||
# ---- 2. spectrum_cluster_annotated.png ----
|
||||
plt.figure(figsize=(14, 6))
|
||||
plt.plot(mzs_avg, ints_avg, color='lightgray', linewidth=0.7, label="Average Spectrum")
|
||||
for cluster_id in sorted(clusters_df['cluster'].unique()):
|
||||
sub = clusters_df[clusters_df['cluster'] == cluster_id]
|
||||
color = cluster_colors[int(cluster_id) % 10]
|
||||
for target_mz in sub['mz']:
|
||||
idx = np.argmin(np.abs(mzs_avg - target_mz))
|
||||
m, i = mzs_avg[idx], ints_avg[idx]
|
||||
plt.vlines(m, 0, i, color=color, linewidth=1.2, alpha=0.9,
|
||||
label=f"Cluster {cluster_id}" if m == sub['mz'].iloc[0] else "")
|
||||
plt.xlabel("m/z")
|
||||
plt.ylabel("Relative Intensity")
|
||||
plt.title(f"Cluster-Annotated Spectrum ({dataset_name})")
|
||||
plt.xlim(min_vis_mz, max_vis_mz)
|
||||
plt.legend(loc='upper right', fontsize=8)
|
||||
plt.box(True)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(figures_dir, "spectrum_cluster_annotated.png"), dpi=200)
|
||||
plt.close()
|
||||
print(" Saved: spectrum_cluster_annotated.png")
|
||||
|
||||
# ---- 3. spectrum per cluster (one PDF per cluster) ----
|
||||
for cluster_id in sorted(clusters_df['cluster'].unique()):
|
||||
sub = clusters_df[clusters_df['cluster'] == cluster_id]
|
||||
color = cluster_colors[int(cluster_id) % 10]
|
||||
mz_set = set(sub['mz'])
|
||||
cluster_ints = np.where([m in mz_set for m in mzs_avg], ints_avg, 0.0)
|
||||
fig, ax = plt.subplots(figsize=(14, 4))
|
||||
ax.plot(mzs_avg, ints_avg, color='lightgray', linewidth=0.5)
|
||||
ax.plot(mzs_avg, cluster_ints, color=color, linewidth=1.5)
|
||||
for target_mz in sub['mz']:
|
||||
idx = np.argmin(np.abs(mzs_avg - target_mz))
|
||||
mi, ii = mzs_avg[idx], ints_avg[idx]
|
||||
ax.vlines(mi, 0, ii, color=color, linewidth=1.0, alpha=0.6)
|
||||
ax.set_title(f"Cluster {cluster_id} (n={len(sub)})", fontsize=12)
|
||||
ax.set_xlabel("m/z")
|
||||
ax.set_ylabel("Relative Intensity")
|
||||
ax.set_xlim(min_vis_mz, max_vis_mz)
|
||||
ax.box(True)
|
||||
fig.tight_layout()
|
||||
fig.savefig(os.path.join(figures_dir, f"spectrum_cluster_{cluster_id}.pdf"))
|
||||
plt.close(fig)
|
||||
print(f" Saved: spectrum_cluster_{cluster_id}.pdf")
|
||||
else:
|
||||
print(f" No cluster CSV found at {cluster_csv} — skipping per-cluster plots")
|
||||
|
||||
print(f"Done: {dataset_name} spectrum plots -> {figures_dir}")
|
||||
Reference in New Issue
Block a user