Spaces:
Running on Zero
Running on Zero
Condensate Titration: Virtual OpenCell layout and style; GPU only generates and classifies
Browse filesFiles changed (5)
61 unmodified lines626364656667686970717273747576777879808182838467686970858687888990919261 unmodified linesAlso reported: **c_sat**, the first intensity at which the smoothed curve reachesprobability 0.8, and the raw per-image calls as a downloadable CSV.
### Layout
The tab is laid out like the Virtual OpenCell one, in the same OpenCell style:
- **Navbar** — a picker over the NUP98 panel below. Picking one fills the sequence box; typing a panel sequence selects it, and anything else is a custom sequence.- **Left** — the sequence's name and composition (aromatic, basic and acidic residue counts, net charge), the sequence box and **Run titration**, then the run's AUC, AAC, c_sat and condensed-image count, and the titration curve.- **Right** — the generated images in OpenCell's colours, nucleus blue and the IDP grey, with the same channel switch and per-channel intensity range and gamma. The slider steps through all 512 images along the ladder and the strip below holds 64 evenly spaced ones; the viewer opens on the image where condensation peaks, captioned with its expression level and call. Before a run it shows the reference nucleus alone.
Only generation and classification run on the GPU; the curve, viewer and strip aredrawn afterwards on the CPU, so none of that spends the ZeroGPU budget.
### Default sequence
The box is pre-filled with the **NUP98 IDP**, wild type. Its mutation panel — 92sequences of 66 aa covering F→S, F→Y, charge and spacer variants — ships in`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.The box is pre-filled with the **NUP98 IDP**, wild type. Its panel — the wild type and91 random F→S mutants, ten draws for each of 1 to 9 substitutions and the one way toreplace all ten F — ships in `assets/nup98_mutation_seqs.csv` and fills the navbarpicker; comparing a mutant's AUC against WT is the quickest way to see the model respondto sequence grammar, as in the paper's Fig. 5b.
### Amino acid substitution scan
2 unmodified lines34566789103 unmodified lines14151616171818201920212229 unmodified lines52535456575859606162636465666768697055565758596061626376777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113264656667681351361371381391401411421431441456914714814915015115215315470717273747576777879808182838485868788165166167168169170899091929394957 unmodified lines1031041051841851861871881891061071081091101111121131141151161171181191201211221231241251261271281291301311321331341911921931941951351361371971981992002012022032042051381391401411421431441451461471481491501511521531541551561571581591601611622071632092101641651661671681691701711721731741751761772122132142152161781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102182192202112122222232242252262272282292302132142152162172182192202212222232242252262272282322332342352292302312322332342352362372382392402412424 unmodified lines24724824924824925025125225325425525625025125925225325425517 unmodified lines2732742752832842852862872882892902912922932942762772782797 unmodified lines287288289290291292308309310293294295296312313314315316317318319320321322323324297298299300301123 unmodified lines42542642745445545645745842842943043143220 unmodified lines4534544554854564574582 unmodified linesEnter an IDP sequence; the app generates a concentration ladder of images withCELL-FM, classifies each as condensed or diffuse, smooths the calls into atitration curve, and integrates it into AUC (condensation propensity) and AAC(reentrant dissolution).(reentrant dissolution). Below it, the paper's amino acid substitution scan.Both tabs share the Virtual OpenCell look; see cell_fm/apps/condenseq/page.py."""
import os3 unmodified linesimport gradio as grimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
from cell_fm.apps.condenseq import metrics, pipeline, substitutionfrom cell_fm.apps.condenseq import page, pipeline, substitutionfrom cell_fm.apps.virtual_opencell import viewer
# gradio_client walks component API schemas to build /gradio_api/info. JSON Schema29 unmodified lines
HERE = os.path.dirname(os.path.abspath(__file__))
# palette: categorical slots 1 and 2 (validated, CVD dE 24.7 / normal dE 33.6)CURVE = "#2a78d6" # the titration curve and the area under itGAP = "#eb6834" # the area above the curveINK = "#0b0b0b"MUTED = "#52514e"SURFACE = "#fcfcfb"
def load_default_sequence() -> str: """The NUP98 IDP, wild type -- what the box is pre-filled with.""" df = pd.read_csv(os.path.join(HERE, "assets", "nup98_mutation_seqs.csv"), dtype=str) return df.loc[df.mutation == "WT", "sequence"].iloc[0]
DEFAULT_SEQUENCE = load_default_sequence()# The NUP98 panel the navbar picks from, and the name of each sequence in itPRESETS = page.load_presets(os.path.join(HERE, "assets", "nup98_mutation_seqs.csv"))PRESET_NAMES = {sequence: name for name, sequence in PRESETS.items()}
# The proteins with virtual staining, and OpenCell's annotations of their real cell linesPROTEINS = viewer.load_catalog(os.path.join(HERE, "assets", "virtual_opencell_proteins.csv"))
LADDER = (pipeline.MIN_INTENSITY, pipeline.MAX_INTENSITY)
def plot_curve(result: pipeline.Result): """The titration curve, with the two integrated areas drawn as the areas they are.""" x, y, curve = result.intensities, result.predictions, result.curve flat = metrics.no_reentrant_curve(curve)
fig, ax = plt.subplots(figsize=(8.5, 4.6), facecolor=SURFACE) ax.set_facecolor(SURFACE)
# the raw per-image calls, kept visible but recessive: the curve is a summary of these ax.scatter(x, y, s=7, alpha=0.16, color=MUTED, linewidths=0, zorder=1)
# AUC: what the sequence actually does ax.fill_between(x, 0, curve, color=CURVE, alpha=0.18, linewidth=0, zorder=2, label=f"AUC {result.auc:.3f}") # AAC: the condensation lost to reentrant dissolution at high concentration if result.aac > 1e-9: ax.fill_between(x, curve, flat, where=flat > curve, color=GAP, alpha=0.30, linewidth=0, zorder=3, label=f"AAC {result.aac:.3f}") ax.plot(x, flat, color=GAP, linewidth=1.2, linestyle="--", alpha=0.8, zorder=4)
ax.plot(x, curve, color=CURVE, linewidth=2.0, zorder=5)
ax.set_xscale("log") ax.set_xlim(x.min(), x.max()) ax.set_ylim(-0.02, 1.02) ax.set_xlabel("Protein intensity level (a.u., log scale)", fontsize=11, color=INK) ax.set_ylabel("Condensate probability", fontsize=11, color=INK) ax.tick_params(labelsize=10, colors=MUTED) ax.grid(True, 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)
if result.c_sat != float("inf"): ax.axvline(result.c_sat, color=MUTED, linewidth=1.0, linestyle=":", zorder=4) ax.annotate( f"$c_{{sat}}$ {result.c_sat:.0f}", xy=(result.c_sat, 1.0), xytext=(6, -13), textcoords="offset points", fontsize=9, color=MUTED, ha="left", va="top", )
ax.legend(loc="upper left", frameon=False, fontsize=10, labelcolor=INK) fig.tight_layout() return fig
def sample_gallery(result: pipeline.Result): """Every generated image along the ladder, captioned with its protein expression level, so the curve is checkable by eye.""" magma = matplotlib.colormaps["magma"] return [ ((magma(np.clip(img, 0, 1))[..., :3] * 255).astype(np.uint8), f"{level:.0f}") for img, level in zip(result.images, result.image_intensities) ]
def sequence_name(sequence: str) -> str: """A sequence's name in the NUP98 panel, or page.CUSTOM.""" return PRESET_NAMES.get(page.residues(sequence), page.CUSTOM)
def summary_markdown(result: pipeline.Result) -> str: return f"""| | ||---|---|| **AUC** — area under the curve, condensation propensity | **{result.auc:.4f}** || **AAC** — area above the curve, reentrant dissolution | **{result.aac:.4f}** || Sequence length | {len(result.sequence)} aa |
Both areas are normalised by the width of the log-intensity range, so they lie in[0, 1] and are comparable across sequences."""
def results_table(result: pipeline.Result) -> pd.DataFrame: """The numbers behind the plot, so the chart is never the only way to read them.""" return pd.DataFrame({ "protein_intensity_level": np.round(result.intensities, 4), "predicted_class": result.predictions, "condensate_probability_ma": np.round(result.curve, 6), })def reference_nucleus(): """The nucleus every image is generated in, (H, W) in [0, 1]; None if it cannot be fetched.""" try: return (np.asarray(pipeline.reference_nucleus()[0, 0], dtype=np.float32) + 1) / 2 except Exception as exc: # the viewer starts empty; a run reports the problem itself print(f"[startup] reference nucleus unavailable: {exc}") return None
@GPU_DECORATORdef analyse(sequence, progress=gr.Progress()): """Generate and classify, the only work that needs the GPU. Drawing the results happens in a follow-up step, so none of it spends the GPU budget.""" try: sequence = pipeline.clean_sequence(sequence) except ValueError as exc: raise gr.Error(str(exc)) from exc
result = pipeline.run(sequence, progress=progress)
table = results_table(result) csv_path = os.path.join("/tmp", "pred_vs_intensity.csv") table.to_csv(csv_path, index=False)
return plot_curve(result), sample_gallery(result), summary_markdown(result), table, csv_path # all the viewer needs, at half the bytes to hand back from the GPU worker result.images = result.images.astype(np.float16) # the two skipped outputs are there to carry the progress bar while this runs return result, gr.skip(), gr.skip()
# ---------------------------------------------------------------------------7 unmodified lines
def build_condensate_titration_section(): """Sequence in, condensate titration curve out, summarised as AUC and AAC.""" gr.Markdown( """ Predict how an Intrinsically Disordered Peptide (IDP) behaves as its concentration rises. """ ) """Laid out like the Virtual OpenCell tab: a navbar with a sequence picker; the sequence, its numbers and its titration curve on the left; the generated images on the right; then the paper's substitution scan, how a titration is computed, and a footer.""" nucleus = reference_nucleus()
def show(result, position, channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma): index = int(position) - 1 return (page.view(result, nucleus, index, channel, (n_min, n_max, n_gamma), (t_min, t_max, t_gamma)), page.caption_html(result, index))
def show_result(result, *settings): """Everything a finished run fills in, drawn on the CPU.""" index = int(np.argmax(result.curve)) # open on the image where condensation peaks image, caption = show(result, index + 1, *settings) # a directory per run, so two visitors' downloads cannot overwrite each other path = os.path.join(tempfile.mkdtemp(), "pred_vs_intensity.csv") page.results_table(result).to_csv(path, index=False) strip = page.thumbnail_indices(len(result.images)) return ( page.metrics_html(result, sequence_name(result.sequence)), page.curve_figure(result, LADDER), image, caption, gr.Slider(value=index + 1, maximum=len(result.images), interactive=True), gr.Column(visible=True), gr.Gallery(value=page.thumbnails(result, nucleus), selected_index=int(np.argmin(np.abs(strip - index)))), gr.DownloadButton(value=path, interactive=True), )
gr.Image( value=os.path.join(HERE, "images", "cellfm_flow_diagram.png"), show_label=False, show_download_button=False, container=False, interactive=False, ) def info(name, sequence): return page.info_html(name, sequence, pipeline.NUM_IMAGES, pipeline.DEFAULT_SEED)
with gr.Row(): with gr.Column(scale=2): sequence = gr.Textbox( value=DEFAULT_SEQUENCE, lines=4, label="IDP sequence", info=( f"Exactly {pipeline.SEQUENCE_LENGTH} single-letter amino acids — the whole " "CondenSeq library is 66-mers. FASTA headers are stripped." ), def pick_preset(name): if name not in PRESETS.index: return gr.skip(), gr.skip() return PRESETS[name], info(name, PRESETS[name])
def edit_sequence(text): """Name what is typed; the picker follows when it matches a panel sequence and clears when not.""" name = sequence_name(text) return gr.Dropdown(value=name if name in PRESETS.index else None), info(name, text)
def pick_sample(result, evt: gr.SelectData): if result is None: return gr.skip() return int(page.thumbnail_indices(len(result.images))[evt.index]) + 1
defaults = ("Both", 0, 100, 1.0, 0, 100, 1.0) image0, caption0 = show(None, 1, *defaults)
with gr.Column(elem_id="condensate-titration"): with gr.Row(elem_classes="vo-navbar", equal_height=True): gr.HTML(page.NAVBAR_HTML) preset = gr.Dropdown( choices=list(PRESETS.index), value=page.DEFAULT_PRESET, filterable=True, show_label=False, container=False, scale=0, min_width=260, elem_classes="vo-search", ) run_button = gr.Button("Run analysis", variant="primary")
with gr.Column(scale=3): summary = gr.Markdown() with gr.Row(): with gr.Column(scale=4): info_panel = gr.HTML(info(page.DEFAULT_PRESET, PRESETS[page.DEFAULT_PRESET])) sequence = gr.Textbox( value=PRESETS[page.DEFAULT_PRESET], lines=3, max_lines=6, label="IDP sequence", info=(f"Exactly {pipeline.SEQUENCE_LENGTH} single-letter amino acids, the length of " "the whole CondenSeq library; FASTA headers are stripped"), elem_classes="cs-sequence", ) run_button = gr.Button("Run titration", elem_classes="cs-run") metrics_panel = gr.HTML(page.metrics_html()) gr.HTML(page.CURVE_HTML, padding=False) curve_plot = gr.Plot(value=page.curve_figure(None, LADDER), show_label=False)
curve_plot = gr.Plot(label="Condensate titration curve") sample_plot = gr.Gallery( label="Generated images (protein channel), captioned with the protein expression level (a.u.)", columns=8, height=520, allow_preview=True, object_fit="contain", elem_classes="cs-gallery", ) with gr.Column(scale=6): with gr.Row(): channel = gr.Radio(page.CHANNELS, value=defaults[0], label="Channel", elem_classes="vo-buttons") download = gr.DownloadButton("Download CSV", value=None, interactive=False, size="sm", variant="secondary", scale=0, min_width=140, elem_classes="vo-download") image = gr.Image( value=image0, show_label=False, interactive=False, height=560, show_download_button=True, elem_classes="vo-viewer", ) caption = gr.HTML(caption0, padding=False) position = gr.Slider(1, pipeline.NUM_IMAGES, value=1, step=1, interactive=False, label="Image along the ladder, lowest expression first") # hidden until a run fills it: an empty strip is just a placeholder box with gr.Column(visible=False) as samples_box: gr.HTML('<div class="vo-settings-label">Samples</div>', padding=False) samples = gr.Gallery( show_label=False, columns=8, height=230, allow_preview=False, object_fit="contain", show_share_button=False, show_download_button=False, elem_classes="vo-thumbnails", ) with gr.Row(elem_classes="vo-settings"): with gr.Column(): gr.HTML('<div class="vo-settings-label">Nucleus image settings</div>', padding=False) n_min = gr.Slider(0, 100, value=defaults[1], step=1, label="Intensity min (%)") n_max = gr.Slider(1, 150, value=defaults[2], step=1, label="Intensity max (%)") n_gamma = gr.Slider(0.5, 1.5, value=defaults[3], step=0.05, label="Gamma") with gr.Column(): gr.HTML('<div class="vo-settings-label">IDP image settings</div>', padding=False) t_min = gr.Slider(0, 100, value=defaults[4], step=1, label="Intensity min (%)") t_max = gr.Slider(1, 150, value=defaults[5], step=1, label="Intensity max (%)") t_gamma = gr.Slider(0.5, 1.5, value=defaults[6], step=0.05, label="Gamma")
with gr.Accordion("Per-image results", open=False): table = gr.Dataframe(label="pred_vs_intensity", wrap=True) download = gr.File(label="Download CSV") build_substitution_scan_section()
gr.Markdown( """ --- Generation follows `evaluate_seq2img_dict.py`, classification `evaluate_single_img.py`, smoothing `ma_plot.py`, and the areas `analysis/ana_all_mutation_log_scale.py` from the CELL-FM repository. Every image is conditioned on one fixed reference nucleus, so curves are comparable across sequences. """ ) gr.HTML(page.HOW_HTML, padding=False) gr.Image( value=os.path.join(HERE, "images", "cellfm_flow_diagram.png"), show_label=False, show_download_button=False, container=False, interactive=False, elem_classes="cs-diagram", ) gr.HTML(page.FOOTER_HTML)
result_state = gr.State(None) settings = [channel, n_min, n_max, n_gamma, t_min, t_max, t_gamma]
# .input, not .change: only a visitor's own edits, so neither handler retriggers the other preset.input(pick_preset, inputs=preset, outputs=[sequence, info_panel], show_progress="hidden") sequence.input(edit_sequence, inputs=sequence, outputs=[preset, info_panel], show_progress="hidden", trigger_mode="always_last")
run_button.click( analyse, inputs=sequence, outputs=[curve_plot, sample_plot, summary, table, download], run_button.click(analyse, inputs=sequence, outputs=[result_state, curve_plot, image]).success( show_result, inputs=[result_state] + settings, outputs=[metrics_panel, curve_plot, image, caption, position, samples_box, samples, download], )
# Redraws take milliseconds: no progress overlay, and a dragged slider only renders its latest value samples.select(pick_sample, inputs=result_state, outputs=position, show_progress="hidden") for control in [position] + settings: control.change(show, inputs=[result_state, position] + settings, outputs=[image, caption], show_progress="hidden", trigger_mode="always_last")
def build_substitution_scan_section(): """The paper's substitution matrices, mean change in AUC and AAC side by side; a click on4 unmodified lines print(f"[startup] substitution scan unavailable: {exc}") return
def 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), return (*maps, page.substitution_html(scan, 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 selection17 unmodified lines auc0, aac0, selection0, distribution0, table0 = view( *(scan.index(residue) for residue in substitution.DEFAULT_SELECTION))
gr.Markdown( f""" --- ### Amino acid substitution scan
Every 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 the IDPs that contain the FROM residue: the left matrix is the paper's Fig. 5d, the right its Supplementary Fig. 5c. **Click any cell** to see the distribution behind it. """ ) gr.HTML(page.scan_header_html(scan), padding=False)
# 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.7 unmodified lines show_label=False, interactive=False, show_fullscreen_button=False, elem_id="cs-matrix-aac", )
with gr.Row(): with gr.Column(scale=3): selection = gr.HTML(selection0, elem_id="cs-selection") 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.Column(scale=7): 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 the offline 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`. """ ) gr.HTML(page.per_idp_html(substitution.MODEL_REPO, substitution.SCAN_FILE), padding=False) idp_table = gr.Dataframe(value=table0, wrap=True, max_height=380, show_label=False)
outputs = [auc_map, aac_map, selection, distribution, idp_table] auc_map.select(select_auc, outputs=outputs, show_progress="hidden")123 unmodified lines show_progress="hidden", trigger_mode="always_last")
# Gradio's gallery block clips at its height; make the grid scroll inside it insteadCSS = viewer.CSS + """.cs-gallery .gallery-container { height: 100%; }.cs-gallery .grid-wrap { height: 100%; overflow-y: auto; }"""# OpenCell's look for both tabs, each scoped to its own container, plus what only the titration needsCSS = viewer.CSS + viewer.scoped_css(page.SCOPE) + page.CSS
CITATION = """@article{zheng2026virtual, title = {Virtual experiments bridge sequence and microscopy with generative models},20 unmodified lines with gr.Tabs(): with gr.Tab("Condensate Titration"): build_condensate_titration_section() build_substitution_scan_section() with gr.Tab("Virtual OpenCell"): build_virtual_opencell_section()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348"""The Condensate Titration tab's panels, captions and figures, in the Virtual OpenCell tab's look.
The two tabs read as one site: the same flat OpenCell styling (viewer.scoped_css), the same layout-- a navbar with a picker, an information panel on the left with the plot under it, a black imageviewer with a sample strip and contrast settings on the right -- and the same channel colours, thenucleus blue and the protein grey. Generated images go through viewer.render, so both viewers drawalike.
Nothing here touches the models: the app hands in a pipeline.Result and the reference nucleus."""
import htmlimport re
import numpy as npimport pandas as pdfrom matplotlib.figure import Figure
from ..virtual_opencell import viewerfrom . import metrics
SCOPE = "#condensate-titration"
# the plot palette: categorical slots 1 and 2 (validated, CVD dE 24.7 / normal dE 33.6)CURVE = "#2a78d6" # the titration curve and the area under itGAP = "#eb6834" # the area above the curveINK = "#0b0b0b"MUTED = "#52514e"BACKGROUND = "#fff" # plots sit on white, like the Virtual OpenCell map
NUM_THUMBNAILS = 64 # the sample strip: evenly spaced along the ladder; the slider reaches the rest
# OpenCell's channel switch. viewer.render calls the protein channel the "target"; here it is the IDPCHANNELS = [("Nucleus", "Nucleus"), ("IDP", "Target"), ("Both", "Both")]
DEFAULT_PRESET = "NUP98 WT"CUSTOM = "Custom sequence"
def _item(label: str, value: str) -> str: return (f'<div class="vo-metadata-item"><div class="vo-metadata-label">{label}</div>' f'<div class="vo-metadata-value">{value}</div></div>')
# ---------------------------------------------------------------------------# The sequence picker# ---------------------------------------------------------------------------
def load_presets(path: str) -> pd.Series: """The NUP98 IDP panel shipped with the app, display name -> sequence, wild type first.
The wild type and random F -> S mutants of it: ten draws for each of 1 to 9 substitutions and the one way to make all ten, the virtual mutagenesis of the paper's Fig. 5b. """ table = pd.read_csv(path, dtype=str) return pd.Series(table["sequence"].to_numpy(), index=table["mutation"].map(_preset_name).to_numpy())
def _preset_name(mutation: str) -> str: if mutation == "WT": return DEFAULT_PRESET count, draw = re.fullmatch(r"(\d+)FtoS_(\d+)", mutation).groups() return f"NUP98 {count}F→S #{draw}"
def residues(text: str) -> str: """The sequence a box holds, the way pipeline.clean_sequence reads it, without its checks.""" lines = [ln for ln in str(text).splitlines() if not ln.startswith(">")] return "".join("".join(lines).split()).upper()
def describe(name: str) -> str: if name == DEFAULT_PRESET: return "The NUP98 FG-repeat IDP, wild type" match = re.fullmatch(r"NUP98 (\d+)F→S #(\d+)", name) if match: count, draw = match.groups() return f"NUP98 IDP with {count} of its 10 phenylalanines mutated to serine, draw {draw}" return "A sequence entered by hand"
def info_html(name: str, sequence: str, num_images: int, seed: int) -> str: """The left-hand panel, OpenCell's target header: which sequence this is and what it is made of.
The composition counts are the residues the substitution scan below finds matter most: aromatics and arginine drive condensation, acidic residues oppose it. """ seq = residues(sequence) aromatic, basic, acidic = (sum(seq.count(a) for a in letters) for letters in ("FYW", "RK", "DE")) items = [ _item("Length", f"{len(seq)} aa"), _item("Aromatic (F Y W)", str(aromatic)), _item("Basic (R K)", str(basic)), _item("Acidic (D E)", str(acidic)), _item("Net charge", f"{basic - acidic:+d}"), ] return f"""<div class="vo-target"> <div class="vo-target-name">{html.escape(name)}</div> <div class="vo-protein-description">{html.escape(describe(name))}</div> <div class="vo-status">CELL-FM condensate titration · {num_images} images · seed {seed}</div> <div class="vo-metadata">{''.join(items)}</div></div>"""
# ---------------------------------------------------------------------------# A run's numbers and curve# ---------------------------------------------------------------------------
def metrics_html(result=None, name: str = "") -> str: """AUC, AAC, c_sat and the condensed count, as OpenCell metadata; dashes before any run.""" if result is None: values = ["—"] * 4 measured = "Run the titration to measure them." else: c_sat = "not reached" if result.c_sat == float("inf") else f"{result.c_sat:.0f} a.u." values = [f"{result.auc:.4f}", f"{result.aac:.4f}", c_sat, f"{int(result.predictions.sum())} / {len(result.predictions)}"] measured = f"Measured for {html.escape(name)}." labels = ["AUC", "AAC", "c<sub>sat</sub>", "Condensed images"] return f"""<div class="vo-target cs-metrics"> <div class="vo-section-header">Titration</div> <div class="vo-section-caption">{measured} AUC is how much of the scanned range the IDP spends condensed; AAC how much of that it loses to re-dissolving at high expression. Both are normalised to [0, 1]. c<sub>sat</sub> is the first level at which the curve reaches 0.8.</div> <div class="vo-metadata">{''.join(_item(l, v) for l, v in zip(labels, values))}</div></div>"""
CURVE_HTML = """<div class="vo-target"> <div class="vo-section-header">Titration curve</div> <div class="vo-section-caption">One grey dot per generated image, called condensed (1) or diffuse (0) by the ViT; the line is their moving average, the condensate probability. Blue is the area under it (AUC), orange the condensation lost to re-dissolving past the peak (AAC).</div></div>"""
def _style(ax): ax.set_facecolor(BACKGROUND) ax.tick_params(labelsize=10, colors=MUTED) ax.grid(True, 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)
def curve_figure(result, ladder) -> Figure: """The titration curve, with the two integrated areas drawn as the areas they are.
ladder is the (lowest, highest) expression level; before any run the axes are drawn empty over it, so the panel has its final shape from the start. """ fig = Figure(figsize=(7.4, 4.4), dpi=100, facecolor=BACKGROUND) ax = fig.add_subplot() _style(ax)
if result is None: ax.text(0.5, 0.5, "Run the titration to draw the curve", transform=ax.transAxes, ha="center", va="center", fontsize=11, color=MUTED) else: x, y, curve = result.intensities, result.predictions, result.curve flat = metrics.no_reentrant_curve(curve)
# the raw per-image calls, kept visible but recessive: the curve is a summary of these ax.scatter(x, y, s=7, alpha=0.16, color=MUTED, linewidths=0, zorder=1) # AUC: what the sequence actually does ax.fill_between(x, 0, curve, color=CURVE, alpha=0.18, linewidth=0, zorder=2, label=f"AUC {result.auc:.3f}") # AAC: the condensation lost to reentrant dissolution at high concentration if result.aac > 1e-9: ax.fill_between(x, curve, flat, where=flat > curve, color=GAP, alpha=0.30, linewidth=0, zorder=3, label=f"AAC {result.aac:.3f}") ax.plot(x, flat, color=GAP, linewidth=1.2, linestyle="--", alpha=0.8, zorder=4) ax.plot(x, curve, color=CURVE, linewidth=2.0, zorder=5)
if result.c_sat != float("inf"): ax.axvline(result.c_sat, color=MUTED, linewidth=1.0, linestyle=":", zorder=4) ax.annotate(f"$c_{{sat}}$ {result.c_sat:.0f}", xy=(result.c_sat, 1.0), xytext=(6, -13), textcoords="offset points", fontsize=9, color=MUTED, ha="left", va="top") ax.legend(loc="upper left", frameon=False, fontsize=10, labelcolor=INK)
ax.set_xscale("log") ax.set_xlim(*ladder) ax.set_ylim(-0.02, 1.02) ax.set_xlabel("Protein expression level (a.u., log scale)", fontsize=11, color=INK) ax.set_ylabel("Condensate probability", fontsize=11, color=INK) fig.tight_layout() return fig
def results_table(result) -> pd.DataFrame: """The numbers behind the plot, so the chart is never the only way to read them.""" return pd.DataFrame({ "protein_intensity_level": np.round(result.intensities, 4), "predicted_class": result.predictions, "condensate_probability_ma": np.round(result.curve, 6), })
# ---------------------------------------------------------------------------# The image viewer and sample strip# ---------------------------------------------------------------------------
def _sample(result, nucleus: np.ndarray, index: int) -> np.ndarray: """One image as viewer.render takes it: (2, H, W), nucleus first, on the uint16 scale its auto-contrast expects. Before any run the IDP channel is empty.""" protein = np.zeros_like(nucleus) if result is None else result.images[index].astype(np.float32) return np.stack([nucleus, protein]) * 65535.0
def view(result, nucleus, index: int, channel: str = "Both", nucleus_settings=(0, 100, 1.0), target_settings=(0, 100, 1.0)): """Image `index` of the ladder as an RGB array; the reference nucleus alone before a run.""" if nucleus is None: return None if result is not None: index = int(np.clip(index, 0, len(result.images) - 1)) return viewer.render(_sample(result, nucleus, index), channel, nucleus_settings, target_settings)
def caption_html(result=None, index: int = 0) -> str: if result is None: return ('<div class="cs-viewer-caption">The reference nucleus every image is generated in. ' 'Run the titration to add the IDP.</div>') index = int(np.clip(index, 0, len(result.images) - 1)) call = "condensed" if result.predictions[index] else "diffuse" return (f'<div class="cs-viewer-caption">Image {index + 1} of {len(result.images)} · ' f'expression level <b>{result.image_intensities[index]:.0f}</b> a.u. · ' f'called <b>{call}</b> · condensate probability {result.curve[index]:.2f}</div>')
def thumbnail_indices(n: int) -> np.ndarray: """Which images of an n-image ladder the strip shows.""" return np.unique(np.linspace(0, n - 1, min(n, NUM_THUMBNAILS)).round().astype(int))
def thumbnails(result, nucleus) -> list: """(image, caption) per strip entry, both channels at default settings, captioned with the level.""" return [(view(result, nucleus, i), f"{result.image_intensities[i]:.0f}") for i in thumbnail_indices(len(result.images))]
# ---------------------------------------------------------------------------# The substitution scan# ---------------------------------------------------------------------------
def scan_header_html(scan) -> str: return f"""<div class="vo-target"> <div class="vo-section-header">Amino acid substitution scan</div> <div class="vo-section-caption">Every residue type in {len(scan.idr_index)} held-out IDPs replaced by each other type, each mutant titrated as above, and its AUC and AAC compared with the wild type's. A cell is the mean change over the IDPs that contain the FROM residue: left the paper's Fig. 5d (AUC), right its Supplementary Fig. 5c (AAC). Click any cell for the distribution behind it.</div></div>"""
def substitution_html(scan, i: int, j: int) -> str: """The selected substitution, named large like a target, with its summary statistics.""" source, target = scan.amino_acids[i], scan.amino_acids[j] items, n = [], 0 for metric in ("auc", "aac"): values = scan.delta[metric][i, j] values = values[np.isfinite(values)] n = len(values) label = metric.upper() items += [_item(f"Mean Δ {label}", f"{values.mean():+.4f}"), _item(f"Median Δ {label}", f"{np.median(values):+.4f}")] return f"""<div class="vo-target"> <div class="cs-substitution">{source} → {target}</div> <div class="vo-status">Every {source} in the IDP replaced by {target} · {n} of {len(scan.idr_index)} IDPs contain {source}</div> <div class="vo-metadata cs-metrics">{''.join(items)}</div></div>"""
def per_idp_html(repo: str, filename: str) -> str: return f"""<div class="vo-target"> <div class="vo-section-header">Per-IDP values</div> <div class="vo-section-caption">One row per IDP behind the selected cell; click a header to sort. Precomputed: the whole scan is <a href="https://huggingface.co/{repo}/blob/main/{filename}" target="_blank">{filename}</a> in the model repo, checked against the matrices the paper's figures were drawn from (<code>ana_all_mutation_log_scale.py</code>, AAC being <code>compute_area_if_no_reentrant_minus_auc</code>).</div></div>"""
# ---------------------------------------------------------------------------# Static text# ---------------------------------------------------------------------------
NAVBAR_HTML = """<div class="vo-navbar-brand"> <span class="vo-navbar-title">Condensate Titration</span> <span class="vo-navbar-menu">CELL-FM virtual CondenSeq experiments on 66-aa IDPs</span></div>"""
HOW_HTML = """<div class="vo-target"> <div class="vo-section-header">How a titration is computed</div> <div class="vo-section-caption">CELL-FM generates one image per expression level along a log-spaced ladder, a ViT classifier calls each image condensed or diffuse, a moving average over the calls is the titration curve, and the curve is integrated against log expression into AUC and AAC.</div></div>"""
FOOTER_HTML = """<div class="vo-footer"> Each image is CELL-FM's prediction from the IDP sequence and a protein expression level alone, drawn in one shared cell: the nucleus channel is the same real CondenSeq nucleus for every image, so differences come from the sequence and the level. Sampling is fixed at 512 levels from 20 to 2048 a.u., 100 ODE steps and seed 6, as in the offline runs. The IDP library and the condensate phenotypes the models learned from are CondenSeq's (Kappel et al., <i>Nat. Methods</i> 2025).</div>"""
# Additions to the OpenCell look for what the Virtual OpenCell tab does not haveCSS = """#condensate-titration .cs-sequence textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important; font-size: 15px !important; line-height: 1.55; background: #fff;}#condensate-titration .cs-run { background: var(--vo-blue) !important; color: #fff !important; border: none !important; border-radius: 5px !important; font-family: "Lato", sans-serif; font-size: 17px; letter-spacing: 0.5px;}#condensate-titration .cs-run:hover { background: #0189bd !important; }#condensate-titration .cs-metrics .vo-metadata-value { font-family: "Lato", sans-serif; font-size: 26px; font-weight: 300; }#condensate-titration .cs-viewer-caption { font-family: "Lato", sans-serif; font-size: 14px; color: #555; margin: 2px 0; }#condensate-titration .cs-viewer-caption b { color: #182026; font-weight: 600; }#condensate-titration .cs-substitution { font-family: "Lato", sans-serif; font-size: 44px; font-weight: 400; line-height: 1.1; }#condensate-titration .cs-diagram img { max-width: 1100px; margin: 0 auto; }"""37 unmodified lines383940414142434437 unmodified linesCOLORS = {"auc": "#2a78d6", "aac": "#eb6834"}INK = "#0b0b0b"MUTED = "#52514e"SURFACE = "#fcfcfb"SURFACE = "#fff" # white, like the tab's other plots and the Virtual OpenCell map
# Shown before any click: F -> S, the substitution the paper's NUP98 validation makes one F at a timeDEFAULT_SELECTION = ("F", "S")412 unmodified lines413414415416417418419420421412 unmodified lines background: #eee; border-radius: 6px; padding: 10px 16px; margin-top: 10px; font-size: 13px; color: #333;}"""
def scoped_css(scope: str) -> str: """The same look for another container: every rule above is written against #virtual-opencell, so re-pointing them gives a second tab OpenCell's style without touching this one's.""" return CSS.replace("#virtual-opencell", scope)README.md+23-4
app.py+159-189
cell_fm/apps/condenseq/page.pyAdded+348
cell_fm/apps/condenseq/substitution.py+1-1
cell_fm/apps/virtual_opencell/viewer.py+6