Subir archivos a "scripts_python"
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user