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, "datos_para_ai", "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}")