350 lines
13 KiB
Python
350 lines
13 KiB
Python
import os
|
|
import numpy as np
|
|
import pandas as pd
|
|
import matplotlib
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib.cm as cm
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
BENCH_CSV = os.path.join(ROOT, "Benchmark_recommendation", "results", "cross_language_benchmark.csv")
|
|
GAL = os.path.join(ROOT, "outputs")
|
|
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
|
|
FONT_B = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
|
|
FONT_I = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf"
|
|
FONT_BI = "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"
|
|
|
|
LIBRARIES = ["JuliaMSI", "MALDIquant", "Cardinal"]
|
|
DATASET_LABELS = {
|
|
"Datura_leaf": "Datura leaf (LD-LTP)",
|
|
"Datura_root": "Datura root (LD-LTP)",
|
|
"Human_colon": "Human colon (DESI)",
|
|
"Mouse_bladder": "Mouse bladder (AP-SMALDI)",
|
|
"Mouse_Liver": "Mouse liver (MALDI)",
|
|
"Mouse_Stomach": "Mouse stomach (MALDI)",
|
|
"San_pedro": "San Pedro (MALDI)",
|
|
}
|
|
RED = "#d62728"
|
|
FIG_DPI = 400
|
|
FIG_WIDTH_CM = 16.0
|
|
FIG_OUT = {
|
|
"figure1": "figure1.png",
|
|
"figure2": "figure2.png",
|
|
"figure3": "figure3.png",
|
|
}
|
|
|
|
|
|
def font(size, bold=False, italic=False):
|
|
if italic:
|
|
return ImageFont.truetype(FONT_BI if bold else FONT_I, size)
|
|
return ImageFont.truetype(FONT_B if bold else FONT, size)
|
|
|
|
|
|
def paste(img, canvas, x, y, bg=(255, 255, 255)):
|
|
if img.mode != "RGBA":
|
|
img = img.convert("RGBA")
|
|
canvas.paste(img, (int(x), int(y)), img)
|
|
|
|
|
|
def scale(img, height):
|
|
w, h = img.size
|
|
return img.resize((int(w * height / h), int(height)), Image.LANCZOS)
|
|
|
|
|
|
def _finalize(img, path, min_dpi=FIG_DPI, width_cm=FIG_WIDTH_CM):
|
|
"""Upscale to the pixel width of `width_cm` at `min_dpi` and save PNG metadata."""
|
|
target_w = int(round(width_cm / 2.54 * min_dpi))
|
|
if img.width < target_w:
|
|
img = img.resize((target_w, int(img.height * target_w / img.width)), Image.LANCZOS)
|
|
img.save(path, dpi=(min_dpi, min_dpi))
|
|
print(f"wrote {path}")
|
|
|
|
|
|
def _bench_dataset_order(df):
|
|
size_map = df.groupby("Dataset")["FileSize_MB"].first()
|
|
return list(size_map.sort_values().index)
|
|
|
|
|
|
def _bench_panel(df, datasets, y_col, title, ylabel, out, failed_notes):
|
|
viridis = cm.viridis(np.linspace(0.15, 0.85, len(LIBRARIES)))
|
|
pal = dict(zip(LIBRARIES, viridis))
|
|
gb = lambda mb: f"{mb/1024:.2f}" if mb / 1024 < 10 else f"{mb/1024:.1f}"
|
|
xlabels = [f"{d.replace('_', ' ')}\n{gb(df[df['Dataset']==d]['FileSize_MB'].iloc[0])} GB" for d in datasets]
|
|
|
|
fig, ax = plt.subplots(figsize=(9, 5), dpi=300)
|
|
x = np.arange(len(datasets))
|
|
width = 0.25
|
|
for idx, lib in enumerate(LIBRARIES):
|
|
lib_df = df[df["Library"] == lib].set_index("Dataset").reindex(datasets).reset_index()
|
|
vals = lib_df[y_col].astype(float)
|
|
ax.bar(x + (idx - 1) * width, vals, width, label=lib, color=pal[lib], linewidth=0)
|
|
for xi, v in zip(x, vals):
|
|
if np.isnan(v) and lib == "MALDIquant":
|
|
ax.plot(xi, ax.get_ylim()[1] * 0.45, "X", color=RED, ms=16, mec=RED, mew=3)
|
|
ax.set_yscale("log")
|
|
ax.set_title(title, fontsize=12, fontweight="bold", pad=10)
|
|
ax.set_ylabel(ylabel, fontsize=11, fontweight="bold")
|
|
ax.set_xticks(x)
|
|
ax.set_xticklabels(xlabels, fontsize=9, fontweight="bold", rotation=15)
|
|
ax.spines["top"].set_visible(False)
|
|
ax.spines["right"].set_visible(False)
|
|
ax.legend(title="Library", frameon=True, facecolor="white", loc="upper left")
|
|
if failed_notes:
|
|
ax.annotate(failed_notes, xy=(0.98, 0.04), xycoords="axes fraction",
|
|
ha="right", va="bottom", fontsize=8, color=RED, style="italic")
|
|
plt.tight_layout()
|
|
plt.savefig(out, dpi=300, bbox_inches="tight")
|
|
plt.close()
|
|
print(f"wrote {out}")
|
|
|
|
|
|
def build_fig1():
|
|
df = pd.read_csv(BENCH_CSV)
|
|
datasets = _bench_dataset_order(df)
|
|
tmp_through = os.path.join(ROOT, "outputs", "_tmp_through.png")
|
|
tmp_mem = os.path.join(ROOT, "outputs", "_tmp_mem.png")
|
|
_bench_panel(df, datasets, "Throughput_SPS",
|
|
"Slice Generation Throughput",
|
|
"Throughput (Slices Per Second) - Log Scale",
|
|
tmp_through,
|
|
None)
|
|
_bench_panel(df, datasets, "LoadMem_MB",
|
|
"Memory Consumption during Load",
|
|
"Memory (MB) - Log Scale",
|
|
tmp_mem,
|
|
None)
|
|
|
|
tp = Image.open(tmp_through).convert("RGBA")
|
|
mem = Image.open(tmp_mem).convert("RGBA")
|
|
h = 900
|
|
tp = scale(tp, h)
|
|
mem = scale(mem, h)
|
|
gap = 40
|
|
W = tp.width + mem.width + gap + 160
|
|
H = h + 120
|
|
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
|
paste(tp, canvas, 60, 70)
|
|
paste(mem, canvas, 60 + tp.width + gap, 70)
|
|
d = ImageDraw.Draw(canvas)
|
|
f = font(42, bold=True)
|
|
d.text((60, 10), "A Slice-generation throughput (slices/s, log scale)", font=f, fill="black")
|
|
d.text((60 + tp.width + gap, 10), "B Peak load memory (MB, log scale)", font=f, fill="black")
|
|
out = os.path.join(ROOT, FIG_OUT["figure1"])
|
|
_finalize(canvas, out)
|
|
os.remove(tmp_through)
|
|
os.remove(tmp_mem)
|
|
print(f"wrote {out}")
|
|
|
|
|
|
ION_TARGETS = [
|
|
("Scopolamine", 304.17),
|
|
("Atropine/Hyoscyamine", 290.08),
|
|
("6-Hydroxyhyoscyamine", 306.25),
|
|
("Tropinone", 140.17),
|
|
("Tropine", 142.08),
|
|
("Cuscohygrine", 225.92),
|
|
]
|
|
|
|
|
|
def _find_ions(ds, tol=0.12):
|
|
"""Find tropane-related ions in the feature matrix by target m/z."""
|
|
csvp = os.path.join(GAL, ds, "msi_clusters_results.csv")
|
|
df = pd.read_csv(csvp)
|
|
found = []
|
|
for name, mz in ION_TARGETS:
|
|
sub = df[(df["mz"] - mz).abs() <= tol]
|
|
if sub.empty:
|
|
continue
|
|
row = sub.loc[(sub["mz"] - mz).abs().idxmin()]
|
|
found.append((name, row["ion_image"], row["mz"], row["cluster"]))
|
|
return found
|
|
|
|
|
|
def _ion_grid(ds, n_cols, ion_h=230, cap_h=78, gap=24):
|
|
"""Return an annotated grid (n_cols x n_rows) of viridis tropane ion images."""
|
|
ions = _find_ions(ds)
|
|
imgs = []
|
|
for name, ion, mz, cluster in ions:
|
|
p = os.path.join(GAL, "ion_images_viridis", ds, ion)
|
|
if not os.path.exists(p):
|
|
p = os.path.join(GAL, "ion_images", ds, ion)
|
|
im = Image.open(p).convert("RGBA")
|
|
iw = int(im.width * ion_h / im.height)
|
|
imgs.append((im.resize((iw, ion_h), Image.LANCZOS), name, mz, cluster))
|
|
if not imgs:
|
|
return None, 0, 0
|
|
n_rows = (len(imgs) + n_cols - 1) // n_cols
|
|
cell_w = ion_h # square ion images
|
|
grid_w = n_cols * cell_w + (n_cols - 1) * gap
|
|
grid_h = n_rows * (ion_h + cap_h) + (n_rows - 1) * gap
|
|
grid = Image.new("RGBA", (grid_w, grid_h), (255, 255, 255))
|
|
d = ImageDraw.Draw(grid)
|
|
fl_name = font(22)
|
|
fl_mz = font(20)
|
|
fl_mz_i = font(20, italic=True)
|
|
for i, (im, name, mz, cluster) in enumerate(imgs):
|
|
r, c = divmod(i, n_cols)
|
|
x = c * (cell_w + gap)
|
|
y = r * (ion_h + cap_h + gap)
|
|
paste(im, grid, x, y)
|
|
cx = x + im.width // 2
|
|
d.text((cx - d.textlength(name, font=fl_name) / 2, y + ion_h + 6), name, font=fl_name, fill="black")
|
|
t1 = "m/z"
|
|
t2 = f" {mz:.2f} · Cluster {cluster}"
|
|
w1 = d.textlength(t1, font=fl_mz_i)
|
|
w2 = d.textlength(t2, font=fl_mz)
|
|
tx = cx - (w1 + w2) / 2
|
|
d.text((tx, y + ion_h + 34), t1, font=fl_mz_i, fill="black")
|
|
d.text((tx + w1, y + ion_h + 34), t2, font=fl_mz, fill="black")
|
|
return grid, grid_w, grid_h
|
|
|
|
|
|
def build_fig2():
|
|
ds_list = ["Datura_leaf", "Datura_root"]
|
|
n_cols = {"Datura_leaf": 3, "Datura_root": 2}
|
|
plot_h = 980
|
|
ion_h = 430
|
|
sep = 30
|
|
panels = []
|
|
for ds in ds_list:
|
|
p = os.path.join(GAL, ds, "figures", "cluster_validation_detailed_plot.png")
|
|
img = Image.open(p).convert("RGBA")
|
|
w = int(img.width * plot_h / img.height)
|
|
plot = img.resize((w, plot_h), Image.LANCZOS)
|
|
grid, gw, gh = _ion_grid(ds, n_cols[ds], ion_h=ion_h)
|
|
if grid is None:
|
|
panel_w, panel_h = plot.width, plot_h
|
|
panel = Image.new("RGBA", (panel_w, panel_h), (255, 255, 255))
|
|
paste(plot, panel, 0, 0)
|
|
else:
|
|
panel_w = plot.width + sep + gw
|
|
panel_h = max(plot_h, gh)
|
|
panel = Image.new("RGBA", (panel_w, panel_h), (255, 255, 255))
|
|
paste(plot, panel, 0, (panel_h - plot_h) // 2)
|
|
paste(grid, panel, plot.width + sep, (panel_h - gh) // 2)
|
|
panels.append((panel, ds))
|
|
maxw = max(p[0].width for p in panels)
|
|
cell_h = max(p[0].height for p in panels) + 70
|
|
W = maxw + 80
|
|
H = len(panels) * cell_h + 10
|
|
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
|
d = ImageDraw.Draw(canvas)
|
|
f = font(32)
|
|
for i, (panel, ds) in enumerate(panels):
|
|
x = 40 + (maxw - panel.width) // 2
|
|
y = 10 + i * cell_h
|
|
paste(panel, canvas, x, y)
|
|
d.text((x, y + panel.height + 10), DATASET_LABELS[ds], font=f, fill="black")
|
|
out = os.path.join(ROOT, FIG_OUT["figure2"])
|
|
_finalize(canvas, out)
|
|
|
|
|
|
def _bio_ions(ds):
|
|
"""Curated biologically interpretable ions per dataset: (target_mz, compound, adduct)."""
|
|
curated = {
|
|
"Mouse_bladder": [
|
|
(703.58, "Sphingomyelin (SM 34:1, d18:1/16:0)", "[M+H]+"),
|
|
(760.58, "Phosphatidylcholine (PC 34:1)", "[M+H]+"),
|
|
(725.54, "Sphingomyelin (SM 34:1, d18:1/16:0)", "[M+Na]+"),
|
|
(716.05, "Reference phospholipid", ""),
|
|
],
|
|
"Human_colon": [
|
|
(885.55, "Phosphatidylinositol (PI 38:4, 18:0/20:4)", "[M-H]-"),
|
|
(861.55, "Phosphatidylinositol (PI 36:2)", "[M-H]-"),
|
|
(747.52, "Phosphatidylglycerol (PG 34:1)", "[M-H]-"),
|
|
(788.54, "Phosphatidylserine (PS 36:1, 18:0/18:1)", "[M-H]-"),
|
|
],
|
|
}
|
|
csvp = os.path.join(GAL, ds, "msi_clusters_results.csv")
|
|
df = pd.read_csv(csvp)
|
|
found = []
|
|
for mz, compound, adduct in curated.get(ds, []):
|
|
sub = df[(df["mz"] - mz).abs() <= 0.12]
|
|
if sub.empty:
|
|
continue
|
|
row = sub.loc[(sub["mz"] - mz).abs().idxmin()]
|
|
found.append((row["ion_image"], row["mz"], row["cluster"], compound, adduct))
|
|
return found
|
|
|
|
|
|
def _wrap(draw, text, font, max_w):
|
|
"""Greedy word-wrap `text` into lines each fitting within `max_w` px."""
|
|
lines = []
|
|
for word in text.split():
|
|
if not lines:
|
|
lines.append(word)
|
|
elif draw.textlength(lines[-1] + " " + word, font=font) <= max_w:
|
|
lines[-1] += " " + word
|
|
else:
|
|
lines.append(word)
|
|
return lines
|
|
|
|
|
|
def build_fig3():
|
|
ds_list = ["Mouse_bladder", "Human_colon"]
|
|
tsne_h = 980
|
|
ion_h = 330
|
|
cap_h = 92
|
|
per_row = 2
|
|
rows = []
|
|
for ds in ds_list:
|
|
tsne = Image.open(os.path.join(GAL, ds, "msi_tsne_plot.png")).convert("RGBA")
|
|
tsne = scale(tsne, tsne_h)
|
|
reps = []
|
|
for ion, mz, c, compound, adduct in _bio_ions(ds):
|
|
p = os.path.join(GAL, "ion_images_viridis", ds, ion)
|
|
if not os.path.exists(p):
|
|
p = os.path.join(GAL, "ion_images", ds, ion)
|
|
im = Image.open(p).convert("RGBA")
|
|
w = int(im.width * ion_h / im.height)
|
|
reps.append((im.resize((w, ion_h), Image.LANCZOS), c, mz, compound, adduct))
|
|
n = len(reps)
|
|
nrows = (n + per_row - 1) // per_row
|
|
gapx = 18
|
|
gapy = 30
|
|
strip_w = max((r[0].width for r in reps), default=0)
|
|
strip_h = nrows * (ion_h + cap_h) + (nrows - 1) * gapy
|
|
panel = Image.new("RGBA", (tsne.width + 36 + strip_w, max(tsne_h, strip_h)), (255, 255, 255))
|
|
paste(tsne, panel, 0, (panel.height - tsne_h) // 2)
|
|
d = ImageDraw.Draw(panel)
|
|
fm = font(20, italic=True)
|
|
fmz = font(20)
|
|
flab = font(18)
|
|
x0 = tsne.width + 36
|
|
for i, (im, c, mz, compound, adduct) in enumerate(reps):
|
|
r, col = divmod(i, per_row)
|
|
x = x0 + col * (strip_w + gapx)
|
|
y = r * (ion_h + cap_h + gapy)
|
|
paste(im, panel, x, y)
|
|
t1 = f"m/z"
|
|
t2 = f" {mz:.2f} · Cluster {c}"
|
|
w1 = d.textlength(t1, font=fm)
|
|
w2 = d.textlength(t2, font=fmz)
|
|
d.text((x, y + ion_h + 4), t1, font=fm, fill="black")
|
|
d.text((x + w1, y + ion_h + 4), t2, font=fmz, fill="black")
|
|
lbl = f"Putative: {compound}" + (f" {adduct}" if adduct else "")
|
|
for j, line in enumerate(_wrap(d, lbl, flab, strip_w)):
|
|
d.text((x, y + ion_h + 34 + j * 22), line, font=flab, fill="black")
|
|
rows.append((panel, ds))
|
|
maxw = max(p[0].width for p in rows)
|
|
cell_h = max(p[0].height for p in rows) + 70
|
|
W = maxw + 80
|
|
H = len(rows) * cell_h + 10
|
|
canvas = Image.new("RGBA", (W, H), (255, 255, 255))
|
|
d = ImageDraw.Draw(canvas)
|
|
f = font(32)
|
|
for i, (panel, ds) in enumerate(rows):
|
|
x = 40
|
|
y = 10 + i * cell_h
|
|
paste(panel, canvas, x, y)
|
|
d.text((x, y + panel.height + 10), DATASET_LABELS[ds], font=f, fill="black")
|
|
out = os.path.join(ROOT, FIG_OUT["figure3"])
|
|
_finalize(canvas, out)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
build_fig1()
|
|
build_fig2()
|
|
build_fig3()
|