Spaces:
Running on Zero
Running on Zero
Condensate Titration: the paper's ΔAUC and ΔAAC substitution matrices, click a cell for its distribution
Browse filesFiles changed (3)
- README.md+23-1
- app.py+94-1
- cell_fm/apps/condenseq/substitution.pyAdded+190
68 unmodified lines69707172737472 unmodified lines1471481491501511521531541556 unmodified lines16216316416516616768 unmodified lines`assets/nup98_mutation_seqs.csv`; paste one in to compare its AUC against WT, whichis the quickest way to see the model respond to sequence grammar.---## Virtual OpenCell72 unmodified lines| `condenseq/cellfm_seq2img.bin` | CELL-FM CS generator, ESM-C 600M encoder included || `condenseq/vae.bin` | 160×160 image VAE || `condenseq/vit_cls.bin` | Condensed/diffuse ViT classifier |To run against a local copy instead, set `CELLFM_LOCAL_WEIGHTS` to a **flat**directory holding the three `.bin` files — the prefix is stripped for local paths.`upload_weights.py` pushes them from the cluster.## Provenance6 unmodified lines| Classification | `cell_fm/tasks_local/vit_cls_condenseq_img/evaluate_single_img.py` || Moving average | `cell_fm/tasks_local/vit_cls_condenseq_img/ma_plot.py` || AUC / AAC | `cell_diff/tasks/analysis/{utils,ana_all_mutation_log_scale}.py` |Model hyperparameters mirror `scripts/cell_fm_cs/evaluate_seq2img.sh` and`scripts/vit_cls_condenseq_img/pretrain.sh`. The metric port in `metrics.py` was68 unmodified lines6970717273747576777879808182838485868788899091929372 unmodified lines1661671681691701711721731741751766 unmodified lines18318418518618718818968 unmodified lines`assets/nup98_mutation_seqs.csv`; paste one in to compare its AUC against WT, whichis the quickest way to see the model respond to sequence grammar.### Amino acid substitution scanBelow the titration, the tab shows the paper's two substitution matrices side by side:the mean change in **AUC** (Fig. 5d) and in **AAC** (Supplementary Fig. 5c) when everyresidue of one type (row, *Mutate FROM*) is replaced by another (column, *Mutate TO*).They come from an in silico scan of 100 held-out CondenSeq IDPs — 380 substitutions,512 images per sequence on the same ladder as above — and each cell averages over theIDPs that contain the FROM residue (58–95 of them, median 89). An IDP without it is leftout, not counted as a zero change.**Click any cell** to see the distribution behind its mean: a histogram of the per-IDPchange in AUC and in AAC, with mean and median, and a table of every IDP's wild-type andmutant values. The scan is far past a demo's GPU budget, so it is precomputed:`condenseq/substitution_scan.npz` in the weights repo, built by`notebooks/tools/build_substitution_scan_assets.py`, which recomputes every value from thestored per-image calls and checks the means against the matrices`ana_all_mutation_log_scale.py` wrote for the paper (they agree to 1e-16). This sectionruns on CPU.---## Virtual OpenCell72 unmodified lines| `condenseq/cellfm_seq2img.bin` | CELL-FM CS generator, ESM-C 600M encoder included || `condenseq/vae.bin` | 160×160 image VAE || `condenseq/vit_cls.bin` | Condensed/diffuse ViT classifier || `condenseq/substitution_scan.npz` | The precomputed substitution scan: per-IDP AUC and AAC, wild type and every mutant |To run against a local copy instead, set `CELLFM_LOCAL_WEIGHTS` to a **flat**directory holding the three `.bin` files and `substitution_scan.npz` — the prefix isstripped for local paths.`upload_weights.py` pushes them from the cluster.## Provenance6 unmodified lines| Classification | `cell_fm/tasks_local/vit_cls_condenseq_img/evaluate_single_img.py` || Moving average | `cell_fm/tasks_local/vit_cls_condenseq_img/ma_plot.py` || AUC / AAC | `cell_diff/tasks/analysis/{utils,ana_all_mutation_log_scale}.py` || Substitution scan | `cell_diff/tasks/analysis/ana_all_mutation_log_scale.py`, precomputed by `notebooks/tools/build_substitution_scan_assets.py` |Model hyperparameters mirror `scripts/cell_fm_cs/evaluate_seq2img.sh` and`scripts/vit_cls_condenseq_img/pretrain.sh`. The metric port in `metrics.py` was
16 unmodified lines17181920212223212 unmodified lines236237238239240241148 unmodified lines39039139239339439516 unmodified linesimport numpy as npimport pandas as pdfrom cell_fm.apps.condenseq import metrics, pipelinefrom cell_fm.apps.virtual_opencell import viewer# gradio_client walks component API schemas to build /gradio_api/info. JSON Schema212 unmodified lines)def build_virtual_opencell_section():"""Pick an OpenCell protein and browse CELL-FM's virtual staining of it, laid out like anOpenCell target page: the real cell line's annotations on the left, the images on the right."""148 unmodified lineswith gr.Tabs():with gr.Tab("Condensate Titration"):build_condensate_titration_section()with gr.Tab("Virtual OpenCell"):build_virtual_opencell_section()16 unmodified lines17181920212223212 unmodified lines236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333148 unmodified lines48248348448548648748816 unmodified linesimport numpy as npimport pandas as pdfrom cell_fm.apps.condenseq import metrics, pipeline, substitutionfrom cell_fm.apps.virtual_opencell import viewer# gradio_client walks component API schemas to build /gradio_api/info. JSON Schema212 unmodified lines)def build_substitution_scan_section():"""The paper's substitution matrices, mean change in AUC and AAC side by side; a click onany FROM -> TO cell shows the per-IDP changes that cell averages. Precomputed, so CPU only."""try:scan = substitution.load_scan()except Exception as exc: # the scan is an extra; the titration above works without itprint(f"[startup] substitution scan unavailable: {exc}")returndef selection_markdown(i, j):source, target = scan.amino_acids[i], scan.amino_acids[j]n = int(np.isfinite(scan.delta["auc"][i, j]).sum())return (f"**{source} → {target}** — every {source} in the IDP replaced by {target}. "f"Mean over the {n} of {len(scan.idr_index)} IDPs that contain {source}: "f"Δ AUC **{scan.mean['auc'][i, j]:+.4f}**, Δ AAC **{scan.mean['aac'][i, j]:+.4f}**.")def view(i, j):maps = [substitution.heatmap(scan, metric, (i, j))[0] for metric in substitution.METRICS]return (*maps, selection_markdown(i, j), substitution.distribution(scan, i, j),substitution.idp_table(scan, i, j))# where each matrix sits in its image; the layout does not depend on the selectionextents = {metric: substitution.heatmap(scan, metric)[1] for metric in substitution.METRICS}def select(metric, evt):cell = substitution.cell_at(extents[metric], *evt.index)if cell is None: # the colour bar, a label, the marginreturn [gr.skip()] * 5if cell[0] == cell[1]:gr.Info("The diagonal is a residue replaced by itself — pick a cell off it.")return [gr.skip()] * 5return view(*cell)def select_auc(evt: gr.SelectData):return select("auc", evt)def select_aac(evt: gr.SelectData):return select("aac", evt)auc0, aac0, selection0, distribution0, table0 = view(*(scan.index(residue) for residue in substitution.DEFAULT_SELECTION))gr.Markdown(f"""---### Amino acid substitution scanEvery residue type in {len(scan.idr_index)} held-out IDPs replaced by each other type,each mutant run through the pipeline above (512 images on the same log-spaced ladder),and its AUC and AAC compared with the wild type's. Each cell is the mean change over theIDPs that contain the FROM residue: the left matrix is the paper's Fig. 5d, the right itsSupplementary Fig. 5c. **Click any cell** to see the distribution behind it.""")# labels hidden: Gradio draws them over the image's top-left corner, where each matrix# carries its own title, as in the paper. They still name the components for the API.with gr.Row():auc_map = gr.Image(value=auc0, format="png", label=f"Mean Δ AUC ({substitution.PAPER_FIGURES['auc']})",show_label=False, interactive=False, show_fullscreen_button=False, elem_id="cs-matrix-auc",)aac_map = gr.Image(value=aac0, format="png", label=f"Mean Δ AAC ({substitution.PAPER_FIGURES['aac']})",show_label=False, interactive=False, show_fullscreen_button=False, elem_id="cs-matrix-aac",)selection = gr.Markdown(selection0, elem_id="cs-selection")distribution = gr.Plot(value=distribution0, label="Per-IDP changes behind the selected cell",show_label=False)with gr.Accordion("Per-IDP values", open=False):idp_table = gr.Dataframe(value=table0, wrap=True)gr.Markdown(f"""Precomputed, so this part needs no GPU: the per-IDP numbers are[`{substitution.SCAN_FILE}`](https://huggingface.co/{substitution.MODEL_REPO}/blob/main/{substitution.SCAN_FILE})in the model repo, built by `notebooks/tools/build_substitution_scan_assets.py` from theoffline scan and checked against the matrices of`analysis/ana_all_mutation_log_scale.py`, which drew the paper's figures. AAC there is`compute_area_if_no_reentrant_minus_auc`.""")outputs = [auc_map, aac_map, selection, distribution, idp_table]auc_map.select(select_auc, outputs=outputs, show_progress="hidden")aac_map.select(select_aac, outputs=outputs, show_progress="hidden")def build_virtual_opencell_section():"""Pick an OpenCell protein and browse CELL-FM's virtual staining of it, laid out like anOpenCell target page: the real cell line's annotations on the left, the images on the right."""148 unmodified lineswith gr.Tabs():with gr.Tab("Condensate Titration"):build_condensate_titration_section()build_substitution_scan_section()with gr.Tab("Virtual OpenCell"):build_virtual_opencell_section()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""The amino-acid substitution scan: mean change in AUC (Fig. 5d) and AAC (SupplementaryFig. 5c), and the per-IDP changes behind every cell of the two matrices.
The scan replaced every residue type by every other type in 100 held-out CondenSeq IDPs andran each mutant through the same generate -> classify -> integrate path as pipeline.py: 512images per sequence on a log-spaced expression ladder, integrated as in metrics.py. That ismillions of generated images, far past a demo's GPU budget, so the results are precomputed bynotebooks/tools/build_substitution_scan_assets.py and published in the model repo ascondenseq/substitution_scan.npz; this module only reads and draws them.
A matrix cell is the mean change over the IDPs that carry the FROM residue -- an IDP withoutit is left out rather than counted as a zero change, as the analysis script did. The heatmapsare drawn the way that script drew the paper's (CELL-Diff2-Devcell_diff/tasks/analysis/ana_all_mutation_log_scale.py): bwr, centred on zero over eachmatrix's own range, rows FROM and columns TO, in its residue order."""
import osfrom dataclasses import dataclassfrom functools import lru_cache
import numpy as npimport pandas as pdfrom matplotlib.backends.backend_agg import FigureCanvasAggfrom matplotlib.colors import TwoSlopeNormfrom matplotlib.figure import Figurefrom matplotlib.patches import Rectangle
MODEL_REPO = os.environ.get("CELLFM_MODEL_REPO", "BoHuangLab/CELL-FM")LOCAL_WEIGHTS = os.environ.get("CELLFM_LOCAL_WEIGHTS", "")SCAN_FILE = "condenseq/substitution_scan.npz"
METRICS = ("auc", "aac")LABELS = {"auc": "AUC", "aac": "AAC"}PAPER_FIGURES = {"auc": "Fig. 5d", "aac": "Supplementary Fig. 5c"}
# The app's palette: AUC in the titration curve's blue, AAC in the orange of the gap above itCOLORS = {"auc": "#2a78d6", "aac": "#eb6834"}INK = "#0b0b0b"MUTED = "#52514e"SURFACE = "#fcfcfb"
# Shown before any click: F -> S, the substitution the paper's NUP98 validation makes one F at a timeDEFAULT_SELECTION = ("F", "S")
def mean_matrix(delta: np.ndarray) -> np.ndarray: """(from, to, idp) changes -> (from, to) mean over the scored IDPs; 0 where none are scored, which is the diagonal.""" scored = np.isfinite(delta) total = np.where(scored, delta, 0.0).sum(axis=2) count = scored.sum(axis=2) return np.divide(total, count, out=np.zeros_like(total), where=count > 0)
@dataclass(frozen=True)class Scan: amino_acids: tuple # matrix order, R H K D E S T N Q G A V I L M C F Y W P idr_index: np.ndarray # (100,) CondenSeq index of each wild-type IDP wt_sequence: np.ndarray # (100,) its 66-aa sequence wt: dict # metric -> (100,) wild-type value delta: dict # metric -> (20, 20, 100) mutant minus wild type, NaN where not scored mean: dict # metric -> (20, 20) the matrix the paper plots
def index(self, residue: str) -> int: return self.amino_acids.index(residue)
@lru_cache(maxsize=1)def load_scan() -> Scan: """The precomputed scan: a flat local copy if CELLFM_LOCAL_WEIGHTS is set, else the model repo.""" if LOCAL_WEIGHTS: path = os.path.join(LOCAL_WEIGHTS, os.path.basename(SCAN_FILE)) else: from huggingface_hub import hf_hub_download
path = hf_hub_download(repo_id=MODEL_REPO, filename=SCAN_FILE)
saved = np.load(path) wt = {m: saved[f"wt_{m}"] for m in METRICS} delta = {m: saved[f"mut_{m}"] - wt[m] for m in METRICS} return Scan( amino_acids=tuple(str(a) for a in saved["amino_acids"]), idr_index=saved["idr_index"], wt_sequence=saved["wt_sequence"], wt=wt, delta=delta, mean={m: mean_matrix(delta[m]) for m in METRICS}, )
def heatmap(scan: Scan, metric: str, selected=None): """(image, extent): the matrix drawn as in the paper, as an RGB array, and where the matrix sits in that image -- (left, top, right, bottom) in pixels -- so a click maps back to a cell.
selected, a (from, to) index pair, is outlined. """ matrix = scan.mean[metric] n = len(scan.amino_acids)
fig = Figure(figsize=(8, 7), dpi=100, facecolor=SURFACE) canvas = FigureCanvasAgg(fig) ax = fig.add_subplot() im = ax.imshow(matrix, origin="upper", cmap="bwr", norm=TwoSlopeNorm(vcenter=0, vmin=matrix.min(), vmax=matrix.max())) cbar = fig.colorbar(im, ax=ax) cbar.ax.tick_params(labelsize=20) ax.set_xticks(np.arange(n), scan.amino_acids) ax.set_yticks(np.arange(n), scan.amino_acids) ax.tick_params(axis="x", labelsize=18, top=True, labeltop=True, bottom=False, labelbottom=False) ax.tick_params(axis="y", labelsize=18) ax.set_xlabel("Mutate TO", fontsize=18) ax.xaxis.set_label_position("top") ax.set_ylabel("Mutate FROM", fontsize=18) ax.set_title(f"Mean Δ {LABELS[metric]}", fontsize=20) fig.tight_layout()
# after the layout, so an outline on an edge cell cannot move the matrix between renders if selected is not None: i, j = selected ax.add_patch(Rectangle((j - 0.5, i - 0.5), 1, 1, fill=False, edgecolor=INK, linewidth=3, clip_on=False))
canvas.draw() image = np.asarray(canvas.buffer_rgba())[..., :3].copy()
# display coordinates count up from the bottom; image rows count down from the top box = ax.get_window_extent() height = image.shape[0] return image, (box.x0, height - box.y1, box.x1, height - box.y0)
def cell_at(extent, x: float, y: float, n: int = 20): """The (from, to) cell under pixel (x, y) of a heatmap image, or None off the matrix.""" left, top, right, bottom = extent j = int(np.floor((x - left) / (right - left) * n)) i = int(np.floor((y - top) / (bottom - top) * n)) return (i, j) if 0 <= i < n and 0 <= j < n else None
def distribution(scan: Scan, i: int, j: int) -> Figure: """The per-IDP changes behind cell (i, j) of both matrices, side by side.""" source, target = scan.amino_acids[i], scan.amino_acids[j]
fig = Figure(figsize=(11, 3.9), dpi=100, facecolor=SURFACE) for ax, metric in zip(fig.subplots(1, 2), METRICS): values = scan.delta[metric][i, j] values = values[np.isfinite(values)]
ax.set_facecolor(SURFACE) ax.hist(values, bins=20, color=COLORS[metric], alpha=0.8, edgecolor=SURFACE, linewidth=0.6) ax.axvline(0, color=MUTED, linewidth=1.0, linestyle=":") ax.axvline(values.mean(), color=INK, linewidth=1.8, label=f"mean {values.mean():+.4f} (matrix cell)") ax.axvline(np.median(values), color=INK, linewidth=1.2, linestyle="--", label=f"median {np.median(values):+.4f}")
ax.set_title(f"Δ {LABELS[metric]}, {source} → {target} ({len(values)} IDPs)", fontsize=12, color=INK) ax.set_xlabel(f"Δ normalized {LABELS[metric]} (mutant − wild type)", fontsize=10, color=INK) ax.set_ylabel("IDPs", fontsize=10, color=INK) ax.tick_params(labelsize=9, colors=MUTED) ax.grid(True, axis="y", alpha=0.18, linewidth=0.8) ax.set_axisbelow(True) for side in ("top", "right"): ax.spines[side].set_visible(False) for side in ("left", "bottom"): ax.spines[side].set_color(MUTED) ax.spines[side].set_linewidth(0.8) ax.legend(loc="upper left", frameon=False, fontsize=9, labelcolor=INK)
fig.tight_layout() return fig
def idp_table(scan: Scan, i: int, j: int) -> pd.DataFrame: """One row per IDP scored for FROM -> TO: wild-type and mutant values and the change.""" source, target = scan.amino_acids[i], scan.amino_acids[j] scored = np.isfinite(scan.delta["auc"][i, j]) table = { "CondenSeq index": scan.idr_index, f"{source} residues mutated": [s.count(source) for s in scan.wt_sequence], } for metric in METRICS: label = LABELS[metric] table[f"WT {label}"] = scan.wt[metric] table[f"{source}→{target} {label}"] = scan.wt[metric] + scan.delta[metric][i, j] table[f"Δ {label}"] = scan.delta[metric][i, j] table["wild-type sequence"] = scan.wt_sequence return pd.DataFrame(table)[scored].round(4).reset_index(drop=True)README.md+23-1
app.py+94-1
cell_fm/apps/condenseq/substitution.pyAdded+190