Spaces:
Running on Zero
Running on Zero
Condensate Titration: input-only panel, row/column comparison in the scan, ZeroGPU duration 120 s
Browse filesFiles changed (4)
- README.md+14-14
- app.py+108-72
- cell_fm/apps/condenseq/page.py+25-89
- cell_fm/apps/condenseq/substitution.py+133-12
58 unmodified lines596061626362636465666768697071727369707172735 unmodified lines7980818586878889828384858687888966 unmodified lines15615715816216315916016116216316416516658 unmodified linesBoth are normalised by the width of the log-intensity range, so both lie in [0, 1]and are directly comparable between sequences.
Also reported: **c_sat**, the first intensity at which the smoothed curve reachesprobability 0.8, and the raw per-image calls as a downloadable CSV.The curve also marks **c_sat**, the first intensity at which it reaches probability 0.8,and the raw per-image calls download as a 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.- **Left** — the input alone, any 66-aa IDR sequence and **Run analysis**; then the run's AUC and AAC, 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 evenly5 unmodified lines
### Default sequence
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.The box is pre-filled with the **NUP98 IDP**, wild type, unnamed in the UI. Its F→Spanel — the wild type and 91 random F→S mutants, ten draws for each of 1 to 9substitutions and the one way to replace all ten F — ships in`assets/nup98_mutation_seqs.csv`; pasting a mutant in and comparing its AUC against WT isthe quickest way to see the model respond to sequence grammar, as in the paper's Fig. 5b.
### Amino acid substitution scan
66 unmodified linesscales linearly in both, so a section that needs to be faster should lower them in`pipeline.py` (`NUM_IMAGES`, `NUM_STEPS`).
On ZeroGPU the per-call budget is set by `ZEROGPU_DURATION` (default 300 s), whichcovers the defaults with room to spare.On ZeroGPU the per-call budget is set by `ZEROGPU_DURATION` (default 120 s). Keep itclose to what a run needs: `spaces` requests 1.5× it on the default GPU size, and ZeroGPUrefuses any request above the visitor's allowance before running anything — at 300 s(450 s requested) every visitor without PRO was turned away with "The requested GPUduration (450s) is larger than the maximum allowed".
---
14 unmodified lines1516171819202124 unmodified lines464748495051485253545556575855565759606162636465666768691 unmodified line717273656667686974757630 unmodified lines10710810910610710811011111211311411510 unmodified lines1261271281251291301311323 unmodified lines1361371381351361371381391401411421431441451461471391401415 unmodified lines14714814915916016116215015115216615315416816917015515615715815917316016116216344 unmodified lines2082092102242252262272282112122137 unmodified lines22122222324224322422522622722822923023123225025125225325425525625725825926026126226326426523323423523626726826927027123723823924027327424124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229315 unmodified lines30931031129629729829930030130231231331431531631731831932032132232332432532632732832933033133233333433533633733833934034114 unmodified linesimport matplotlibmatplotlib.use("Agg")import numpy as npimport pandas as pd
from cell_fm.apps.condenseq import page, pipeline, substitutionfrom cell_fm.apps.virtual_opencell import viewer24 unmodified linestry: import spaces
# What a run needs, not a safe-looking maximum: spaces requests 1.5x this (the 'large' GPU # size), and ZeroGPU refuses outright any request above the visitor's allowance -- at 300 s # (450 s requested) every visitor without PRO got "larger than the maximum allowed". GPU_DECORATOR = spaces.GPU(duration=int(os.environ.get("ZEROGPU_DURATION", "300"))) GPU_DECORATOR = spaces.GPU(duration=int(os.environ.get("ZEROGPU_DURATION", "120")))except Exception: # running locally or on a dedicated GPU def GPU_DECORATOR(fn): return fn
HERE = os.path.dirname(os.path.abspath(__file__))
# 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()}
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 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"))1 unmodified lineLADDER = (pipeline.MIN_INTENSITY, pipeline.MAX_INTENSITY)
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 reference_nucleus(): """The nucleus every image is generated in, (H, W) in [0, 1]; None if it cannot be fetched.""" try:30 unmodified lines
def build_condensate_titration_section(): """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.""" """Laid out like the Virtual OpenCell tab: a navbar; the sequence box, 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):10 unmodified lines 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.metrics_html(result), page.curve_figure(result, LADDER), image, caption,3 unmodified lines gr.DownloadButton(value=path, interactive=True), )
def info(name, sequence): return page.info_html(name, sequence, pipeline.NUM_IMAGES, pipeline.DEFAULT_SEED)
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()5 unmodified lines 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", )
with gr.Row(): with gr.Column(scale=4): info_panel = gr.HTML(info(page.DEFAULT_PRESET, PRESETS[page.DEFAULT_PRESET])) # just the input: any IDR of the library's length, checked when the analysis runs 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"), value=DEFAULT_SEQUENCE, lines=3, max_lines=6, show_label=False, label=f"IDR sequence ({pipeline.SEQUENCE_LENGTH} aa)", placeholder=f"Any {pipeline.SEQUENCE_LENGTH}-aa IDR sequence", elem_classes="cs-sequence", ) run_button = gr.Button("Run titration", elem_classes="cs-run") run_button = gr.Button("Run analysis", 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)44 unmodified lines 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=[result_state, curve_plot, image]).success( show_result, inputs=[result_state] + settings, outputs=[metrics_panel, curve_plot, image, caption, position, samples_box, samples, download],7 unmodified lines
def build_substitution_scan_section(): """The paper's substitution matrices, mean change in AUC and AAC side by side; a click on any FROM -> TO cell shows the per-IDP changes that cell averages. Precomputed, so CPU only.""" """The paper's substitution matrices, mean change in AUC and AAC side by side. A click on a FROM -> TO cell shows the per-IDP changes that cell averages; a click on a residue on either axis adds its row (Mutate FROM) or column (Mutate TO) to a comparison. Precomputed, CPU only.""" try: scan = substitution.load_scan() except Exception as exc: # the scan is an extra; the titration above works without it print(f"[startup] substitution scan unavailable: {exc}") return
def view(i, j): maps = [substitution.heatmap(scan, metric, (i, j))[0] for metric in substitution.METRICS] 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 selection extents = {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 margin return [gr.skip()] * 5 if cell[0] == cell[1]: gr.Info("The diagonal is a residue replaced by itself — pick a cell off it.") return [gr.skip()] * 5 return view(*cell) def maps(cell, axis, colours): compared = (axis, [(scan.index(r), c) for r, c in colours.items()]) return [substitution.heatmap(scan, metric, cell, compared)[0] for metric in substitution.METRICS]
def select_auc(evt: gr.SelectData): return select("auc", evt)
def select_aac(evt: gr.SelectData): return select("aac", evt) def cell_view(i, j): return (page.substitution_html(scan, i, j), substitution.distribution(scan, i, j), substitution.idp_table(scan, i, j))
auc0, aac0, selection0, distribution0, table0 = view( *(scan.index(residue) for residue in substitution.DEFAULT_SELECTION)) def compare_view(axis, colours): return substitution.comparison(scan, axis, colours), substitution.comparison_table(scan, axis, colours)
# where each matrix and its axis labels sit in its image; the same in every render layouts = {metric: substitution.heatmap(scan, metric)[1] for metric in substitution.METRICS} skip5 = [gr.skip()] * 5
def select(metric, cell, axis, colours, evt): target = substitution.hit(layouts[metric], *evt.index) if target is None: # the colour bar, a title, the margin return [gr.skip()] * 11 if target[0] == "cell": i, j = target[1:] if i == j: gr.Info("The diagonal is a residue replaced by itself — pick a cell off it.") return [gr.skip()] * 11 return (*maps((i, j), axis, colours), *cell_view(i, j), (i, j), *skip5)
# a residue label: add it to the comparison, or take it out; the other axis starts afresh clicked = "row" if target[0] == "row" else "col" residue = scan.amino_acids[target[1]] residues = list(colours) if clicked == axis else [] if residue in residues: residues.remove(residue) elif len(residues) < len(substitution.SERIES): residues.append(residue) else: gr.Info(f"Compare up to {len(substitution.SERIES)} at once — click one to take it out first.") return [gr.skip()] * 11 colours = substitution.assign_colours(residues, colours if clicked == axis else {}) return (*maps(cell, clicked, colours), *[gr.skip()] * 4, clicked, list(colours), *compare_view(clicked, colours), colours)
def select_auc(cell, axis, colours, evt: gr.SelectData): return select("auc", cell, axis, colours, evt)
def select_aac(cell, axis, colours, evt: gr.SelectData): return select("aac", cell, axis, colours, evt)
def compare(cell, axis, residues, colours): """The switch or the picker changed: same residues keep their colours.""" colours = substitution.assign_colours(residues or [], colours) return (*maps(cell, axis, colours), *compare_view(axis, colours), colours)
cell0 = tuple(scan.index(residue) for residue in substitution.DEFAULT_SELECTION) axis0, residues0 = substitution.DEFAULT_COMPARISON colours0 = substitution.assign_colours(residues0, {}) auc0, aac0 = maps(cell0, axis0, colours0) selection0, distribution0, table0 = cell_view(*cell0) comparison0, values0 = compare_view(axis0, colours0)
gr.HTML(page.scan_header_html(scan), padding=False)
15 unmodified lines with gr.Column(scale=7): distribution = gr.Plot(value=distribution0, label="Per-IDP changes behind the selected cell", show_label=False)
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") aac_map.select(select_aac, outputs=outputs, show_progress="hidden") with gr.Accordion("Per-IDP values", open=False): 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)
gr.HTML(page.COMPARE_HTML, padding=False) with gr.Row(equal_height=True): compare_axis = gr.Radio([("Rows (Mutate FROM)", "row"), ("Columns (Mutate TO)", "col")], value=axis0, label="Compare", scale=0, min_width=440, elem_classes="vo-buttons") compare_residues = gr.Dropdown(list(scan.amino_acids), value=list(colours0), multiselect=True, max_choices=len(substitution.SERIES), label="Residues", scale=1) comparison = gr.Plot(value=comparison0, show_label=False, elem_id="cs-comparison") with gr.Accordion("Compared values", open=False): comparison_values = gr.Dataframe(value=values0, wrap=True, max_height=380, show_label=False)
cell_state = gr.State(cell0) colours_state = gr.State(colours0)
outputs = [auc_map, aac_map, selection, distribution, idp_table, cell_state, compare_axis, compare_residues, comparison, comparison_values, colours_state] inputs = [cell_state, compare_axis, colours_state] auc_map.select(select_auc, inputs=inputs, outputs=outputs, show_progress="hidden") aac_map.select(select_aac, inputs=inputs, outputs=outputs, show_progress="hidden") # .input: only a visitor's own changes; a label click sets both itself without re-running this for control in (compare_axis, compare_residues): control.input(compare, inputs=[cell_state, compare_axis, compare_residues, colours_state], outputs=[auc_map, aac_map, comparison, comparison_values, colours_state], show_progress="hidden", trigger_mode="always_last")
def build_virtual_opencell_section():123456456789101112131412131415 unmodified lines3031323637383933343536374546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510638394041111112113114115116117118119120121424344454647481254950127128515253545531 unmodified lines8788891669091929359 unmodified lines15315415523215615715815923 unmodified lines18318418526218618718818919019 unmodified lines210211212213214215216217218219220221222223224225226"""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 draw-- a navbar, the input and the plot on the left, a black image viewer with a sample strip andcontrast settings on the right -- and the same channel colours, the nucleus blue and the proteingrey. 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 Figure15 unmodified lines# 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"]def metrics_html(result=None) -> str: """AUC and AAC as OpenCell metadata; dashes before any run.""" values = ["—", "—"] if result is None else [f"{result.auc:.4f}", f"{result.aac:.4f}"] before = "Run the analysis to measure them. " if result is None else "" 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 <div class="vo-section-caption">{before}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> to [0, 1].</div> <div class="vo-metadata">{''.join(_item(l, v) for l, v in zip(["AUC", "AAC"], values))}</div></div>"""
31 unmodified lines _style(ax)
if result is None: ax.text(0.5, 0.5, "Run the titration to draw the curve", transform=ax.transAxes, ax.text(0.5, 0.5, "Run the analysis to draw the curve", transform=ax.transAxes, ha="center", va="center", fontsize=11, color=MUTED) else: x, y, curve = result.intensities, result.predictions, result.curve59 unmodified linesdef 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>') 'Run the analysis 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)} · '23 unmodified lines <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> (AUC), right its Supplementary Fig. 5c (AAC). Click any cell for the distribution behind it, or a residue on either axis to compare whole rows (Mutate FROM) or columns (Mutate TO) below.</div></div>"""
19 unmodified lines"""
COMPARE_HTML = """<div class="vo-target"> <div class="vo-section-header">Compare rows or columns</div> <div class="vo-section-caption">A row is everything one residue becomes (Mutate FROM), a column everything that becomes one residue (Mutate TO). Click residues on a matrix's axis to add or remove them, up to eight; clicking on the other axis starts a comparison there. Each point is a matrix cell, with its 95% confidence interval over the IDPs; hover for the numbers.</div></div>"""
def per_idp_html(repo: str, filename: str) -> str: return f"""<div class="vo-target">41 unmodified lines4243444546474849505152535441 unmodified lines969798929394991001011029610310410510610710815 unmodified lines1241251261181271281291301311321331341351361371381391401411423 unmodified lines14614714812814913015015115215315415515615715815916016113313413513616216316416516613816716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126241 unmodified lines
# Shown before any click: F -> S, the substitution the paper's NUP98 validation makes one F at a timeDEFAULT_SELECTION = ("F", "S")# and compared: the rows of the residues the paper finds drive condensation, aromatics and arginineDEFAULT_COMPARISON = ("row", ("F", "Y", "W", "R"))
# Series colours for compared rows or columns: the categorical palette's eight slots in fixed order# (validated on white with the dataviz checks; three are under 3:1 against it, hence the direct# labels and the table view that go with the plot)SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"]
def mean_matrix(delta: np.ndarray) -> np.ndarray:41 unmodified lines )
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.def heatmap(scan: Scan, metric: str, selected=None, compared=None): """(image, layout): the matrix drawn as in the paper, as an RGB array, and where its parts sit in that image, so a click maps back to what it landed on (see hit).
selected, a (from, to) index pair, is outlined. selected, a (from, to) index pair, is outlined. compared is ("row" | "col", [(index, colour)]): rows or columns being compared, each outlined, with its residue in bold and a mark in its series colour beside it -- the colour is the series', the text stays ink. """ matrix = scan.mean[metric] n = len(scan.amino_acids)15 unmodified lines 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 # Everything below is drawn after the layout, so the matrix sits at the same pixels in every # render and a click always maps the same way. Marks go just outside it: rows beside the # right edge, before the colour bar; columns under the bottom edge, where no labels are. axis, marks = compared if compared is not None else ("row", []) for k, colour in marks: if axis == "row": ax.add_patch(Rectangle((-0.5, k - 0.5), n, 1, fill=False, edgecolor=INK, linewidth=1.6, clip_on=False)) ax.add_patch(Rectangle((n - 0.38, k - 0.4), 0.34, 0.8, color=colour, clip_on=False)) ax.get_yticklabels()[k].set_fontweight("bold") else: ax.add_patch(Rectangle((k - 0.5, -0.5), 1, n, fill=False, edgecolor=INK, linewidth=1.6, clip_on=False)) ax.add_patch(Rectangle((k - 0.4, n - 0.38), 0.8, 0.34, color=colour, clip_on=False)) ax.get_xticklabels()[k].set_fontweight("bold") if selected is not None: i, j = selected ax.add_patch(Rectangle((j - 0.5, i - 0.5), 1, 1, fill=False, edgecolor=INK,3 unmodified lines 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) box = ax.get_window_extent() renderer = canvas.get_renderer() rows = [t.get_window_extent(renderer) for t in ax.get_yticklabels()] cols = [t.get_window_extent(renderer) for t in ax.get_xticklabels()] layout = { "matrix": (box.x0, height - box.y1, box.x1, height - box.y0), # left, top, right, bottom "row_labels": min(b.x0 for b in rows) - 6, # left edge of the FROM labels "col_labels": height - max(b.y1 for b in cols) - 6, # top edge of the TO labels } return image, layout
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))def hit(layout, x: float, y: float, n: int = 20): """What pixel (x, y) of a heatmap image is on: ("cell", i, j) in the matrix, ("row", i) on a Mutate FROM label, ("col", j) on a Mutate TO label, or None anywhere else.""" left, top, right, bottom = layout["matrix"] i = int(np.floor((y - top) / (bottom - top) * n)) return (i, j) if 0 <= i < n and 0 <= j < n else None j = int(np.floor((x - left) / (right - left) * n)) on_row, on_col = 0 <= i < n, 0 <= j < n if on_row and on_col: return ("cell", i, j) if on_row and layout["row_labels"] <= x < left: return ("row", i) if on_col and layout["col_labels"] <= y < top: return ("col", j) return None
def assign_colours(residues, previous: dict) -> dict: """residue -> series colour for the compared residues. A residue keeps the colour it had, and a new one takes the first free slot, so adding or removing one never repaints the others.""" colours = {r: c for r, c in previous.items() if r in residues} for residue in residues: if residue not in colours: colours[residue] = next(c for c in SERIES if c not in colours.values()) return colours
def _profile(scan: Scan, metric: str, axis: str, k: int): """Mean change and its 95% confidence half-width along compared row/column k, NaN on the diagonal.""" delta = scan.delta[metric][k] if axis == "row" else scan.delta[metric][:, k] # (other, idp) scored = np.isfinite(delta) n = scored.sum(axis=1) mean = (scan.mean[metric][k] if axis == "row" else scan.mean[metric][:, k]).astype(float).copy() sd = np.array([np.std(d[s], ddof=1) if c > 1 else np.nan for d, s, c in zip(delta, scored, n)]) half = 1.96 * sd / np.sqrt(np.maximum(n, 1)) mean[k] = half[k] = np.nan return mean, half, n
def comparison(scan: Scan, axis: str, colours: dict): """The compared rows ("row": Mutate FROM) or columns ("col": Mutate TO) side by side: each one's mean change along the other axis, with 95% confidence intervals over the IDPs, AUC left and AAC right. Plotly, for the hover; a figure with a note when nothing is compared.""" import plotly.graph_objects as go from plotly.subplots import make_subplots
aa = list(scan.amino_acids) other = "Mutate TO" if axis == "row" else "Mutate FROM" fig = make_subplots(rows=1, cols=2, horizontal_spacing=0.09, subplot_titles=[f"Mean Δ {LABELS[m]}" for m in METRICS])
for col, metric in enumerate(METRICS, start=1): fig.add_hline(y=0, line=dict(color=MUTED, width=1, dash="dot"), row=1, col=col) for residue, colour in colours.items(): k = scan.index(residue) mean, half, n = _profile(scan, metric, axis, k) name = f"FROM {residue}" if axis == "row" else f"TO {residue}" pairs = [f"{residue} → {a}" if axis == "row" else f"{a} → {residue}" for a in aa] fig.add_trace(go.Scatter( x=aa, y=mean, mode="lines+markers", name=name, legendgroup=name, showlegend=col == 1, line=dict(color=colour, width=2), marker=dict(color=colour, size=8, line=dict(color=SURFACE, width=2)), error_y=dict(type="data", array=half, color=colour, thickness=1, width=0), customdata=np.stack([pairs, half, n], axis=1), hovertemplate=(f"<b>%{{customdata[0]}}</b><br>mean Δ {LABELS[metric]} %{{y:+.4f}}" " ± %{customdata[1]:.4f} (95% CI)<br>%{customdata[2]} IDPs<extra></extra>"), ), row=1, col=col) if len(colours) <= 4: # a few series are named where they end, as well as in the legend last = int(np.flatnonzero(np.isfinite(mean))[-1]) fig.add_annotation(x=aa[last], y=mean[last], text=residue, showarrow=False, xshift=12, font=dict(size=12, color=INK), row=1, col=col) fig.update_xaxes(title_text=other, categoryorder="array", categoryarray=aa, showgrid=False, row=1, col=col) fig.update_yaxes(title_text=f"Mean Δ {LABELS[metric]} (mutant − wild type)", zeroline=False, gridcolor="rgba(82,81,78,0.15)", row=1, col=col)
if not colours: fig.add_annotation(text="Click a residue on either axis of a matrix, or pick some above", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False, font=dict(size=13, color=MUTED)) fig.update_layout( height=430, margin=dict(l=10, r=10, t=40, b=10), paper_bgcolor=SURFACE, plot_bgcolor=SURFACE, font=dict(color=INK, size=12), legend=dict(orientation="h", y=1.14, x=0, font=dict(size=12)), hovermode="closest", ) return fig
def comparison_table(scan: Scan, axis: str, colours: dict) -> pd.DataFrame: """The numbers the comparison plots: one row per residue of the other axis, a mean change and its confidence half-width per compared residue and metric.""" table = {("Mutate TO" if axis == "row" else "Mutate FROM"): list(scan.amino_acids)} for residue in colours: k = scan.index(residue) name = f"FROM {residue}" if axis == "row" else f"TO {residue}" for metric in METRICS: mean, half, _ = _profile(scan, metric, axis, k) table[f"{name} Δ {LABELS[metric]}"] = mean table[f"{name} ± 95% CI ({LABELS[metric]})"] = half return pd.DataFrame(table).round(4)
def distribution(scan: Scan, i: int, j: int) -> Figure:README.md+14-14
app.py+108-72
cell_fm/apps/condenseq/page.py+25-89
cell_fm/apps/condenseq/substitution.py+133-12