Download static/index.html from udgamlabs/biocell: direct link, hf CLI and curl.
- Browser
- Download file 77.7 kB
-
https://huggingface.co/spaces/udgamlabs/biocell/resolve/main/static/index.html
- Command line
-
hf download hf://spaces/udgamlabs/biocell/static/index.html
-
curl -L -o index.html https://huggingface.co/spaces/udgamlabs/biocell/resolve/main/static/index.html
77.7 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{MODEL_NAME}}: switch a gene, watch the cell</title>
<meta name="description" content="{{MODEL_NAME}} by Udgam Labs predicts how a human cell's genes respond when one or two genes are switched off or on.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&family=Newsreader:opsz,wght@6..72,500&display=swap" rel="stylesheet">
<style>
:root{
--paper:#FAF6EE; --ink:#1C1B18; --ink2:#5E5A51; --line:#E6DFD2; --white:#FFFFFF;
--sage-deep:#3F6B4C; --sage:#9CC2A1; --sage-light:#C5DDC7; --sage-tint:#DFEDDD;
--peach-deep:#8A4F2A; --peach:#F5C3A5; --peach-light:#F8D6C1; --peach-tint:#FBE4D6;
--lift:0 8px 0 rgb(28 27 24 / 0.06);
--serif:"Newsreader",Georgia,serif; --sans:"Figtree",system-ui,-apple-system,"Segoe UI",sans-serif;
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
--sym:var(--sans);
color-scheme:light;
}
body[data-mode="researcher"]{--sym:var(--mono)}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--paper);color:var(--ink);font:400 16px/1.5 var(--sans);}
a{color:var(--ink);text-underline-offset:3px}
button{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--ink);outline-offset:3px}
.wrap{max-width:1200px;margin:0 auto;padding:0 28px}
.sym{font-family:var(--sym);font-weight:600;letter-spacing:.01em}
.mono{font-family:var(--mono)}
.r-only{display:none!important}
body[data-mode="researcher"] .r-only{display:revert!important}
body[data-mode="researcher"] .s-only{display:none!important}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
/* Header */
header.top{display:flex;align-items:center;gap:18px;padding:20px 0 14px}
.lockup{height:22px;width:auto;color:var(--ink);display:block}
.divider{width:1px;height:26px;background:var(--line)}
.mname{font:500 24px/1 var(--serif);letter-spacing:-.01em}
.spacer{flex:1}
.linkbtn{background:none;border:0;padding:10px 6px;cursor:pointer;font-weight:600;text-decoration:underline;text-underline-offset:4px;text-decoration-thickness:1px}
.tabs{display:inline-flex;background:var(--white);border:1px solid var(--line);border-radius:999px;padding:4px;box-shadow:var(--lift)}
.tabs button{border:0;background:none;border-radius:999px;padding:8px 16px;cursor:pointer;font-weight:600;font-size:14px;color:var(--ink2)}
.tabs button[aria-pressed="true"]{background:var(--sage-tint);color:var(--ink)}
/* Hero */
.hero{padding:10px 0 14px;display:flex;align-items:flex-end;justify-content:space-between;gap:24px;flex-wrap:wrap}
.hero h1{font:500 clamp(32px,4.2vw,50px)/1.06 var(--serif);letter-spacing:-.02em;margin:0}
.hero p.lede{margin:8px 0 0;font-size:18px;color:var(--ink2);max-width:none}
.fixed-note{margin:10px 0 0;font-size:14px;color:var(--ink2)}
.fixed-note a{font-weight:600;color:var(--ink);margin-left:6px}
/* Gene cards */
.cards-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin:30px 0 12px}
.cards-head h2,.sec-h{font:500 22px/1.2 var(--serif);margin:0}
.hint{font-size:14px;color:var(--ink2)}
.cards{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
.card{position:relative;text-align:left;background:var(--white);border:2px solid transparent;border-radius:28px;box-shadow:var(--lift);padding:18px 18px 16px;cursor:pointer;display:flex;flex-direction:column;gap:6px;min-height:138px;transition:transform .18s ease,border-color .18s ease}
.card:hover{transform:translateY(-2px)}
.card[aria-pressed="true"]{border-color:var(--ink)}
.card .cname{font:500 20px/1.15 var(--serif);letter-spacing:-.005em}
.card .cline{font-size:14px;color:var(--ink2);line-height:1.35}
.card .cfoot{margin-top:auto;display:flex;align-items:center;justify-content:space-between;gap:8px;padding-top:8px}
.card .csym{font-size:12px;color:var(--ink2)}
.card .cact{font-size:13px;font-weight:600;color:var(--sage-deep)}
.card .cact{border-radius:999px;padding:6px 12px;margin:-6px 0}
/* the one ink pill marks the card the cell is showing; before any run it marks the first card as the place to start */
.card[aria-pressed="true"] .cact,body:not(.ran) .cards:not(:has(.card[aria-pressed="true"])) .card:first-child .cact{background:var(--ink);color:var(--paper)}
.card .check{position:absolute;top:14px;right:14px;width:24px;height:24px;border-radius:999px;border:2px solid var(--ink);display:none;align-items:center;justify-content:center;font-size:13px;font-weight:700}
body.mixing .card .check{display:flex}
body.mixing .card[aria-pressed="true"] .check{background:var(--ink);color:var(--paper)}
body.mixing .card .cact{visibility:hidden}
body.mixing .card .cname{padding-right:30px}
/* Controls */
.controls{display:flex;flex-wrap:wrap;align-items:center;gap:10px 12px;margin:0;padding:14px 16px;background:var(--white);border-radius:28px;box-shadow:var(--lift)}
.group{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.glabel{font-size:13px;color:var(--ink2);font-weight:600;margin-right:2px}
.pill{border:1px solid var(--line);background:var(--paper);border-radius:999px;padding:8px 14px;font-size:14px;font-weight:600;cursor:pointer;white-space:nowrap;min-height:38px}
.pill[aria-pressed="true"]{background:var(--sage-tint);border-color:var(--sage-deep)}
.pill.mixbtn[aria-pressed="true"]{background:var(--ink);color:var(--paper);border-color:var(--ink)}
.search{position:relative;flex:1;min-width:220px}
.search input{width:100%;border:1px solid var(--line);background:var(--paper);border-radius:999px;padding:10px 16px;font:500 15px var(--sans);color:var(--ink);min-height:40px}
.search input::placeholder{color:#8B8678}
.results{position:absolute;z-index:20;left:0;right:0;top:calc(100% + 6px);background:var(--white);border:1px solid var(--line);border-radius:22px;box-shadow:var(--lift);padding:6px;margin:0;list-style:none;max-height:320px;overflow:auto}
.results[hidden]{display:none}
.results li{padding:9px 12px;border-radius:14px;cursor:pointer;display:flex;gap:10px;align-items:baseline}
.results li[aria-selected="true"],.results li:hover{background:var(--sage-tint)}
.results .role{font-size:13px;color:var(--ink2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
/* Mix panel */
.mix{margin:0;background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:20px 22px}
.mix[hidden]{display:none}
.mix-top{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:baseline}
.mix-cells{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:14px}
.mini{background:var(--sage-tint);border-radius:24px;padding:8px 6px 10px;text-align:center}
.mini svg{width:100%;height:auto;display:block}
.mini .cst .stt{display:none}
.mini .cst{font-size:30px}
.mini .mlabel{font-weight:600;font-size:15px}
.mini .msize{font-size:13px;color:var(--ink2)}
.mix-chips{display:none;gap:8px;margin-top:10px}
.mixline{font:500 21px/1.3 var(--serif);margin:16px 0 6px}
.mixhow{font-size:13px;color:var(--ink2);margin:0}
.surprises{width:100%;border-collapse:collapse;margin-top:10px;font-size:14px}
.surprises th,.surprises td{text-align:left;padding:7px 8px;border-bottom:1px solid var(--line)}
.surprises th{font-weight:600;color:var(--ink2);font-size:13px}
.surprises td:nth-child(n+2),.surprises th:nth-child(n+2){white-space:nowrap}
.note{font-size:13px;color:var(--ink2);margin:10px 0 0}
/* Playground */
.play{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(0,1fr);gap:18px;margin:8px 0 0;align-items:start}
.colL{display:flex;flex-direction:column;gap:14px}
@media (min-width:901px) and (min-height:800px){body:not([data-mode="researcher"]) .colL{position:sticky;top:12px}}
@media (min-width:901px){body:not([data-mode="researcher"]) .syslist{display:grid;grid-template-columns:1fr 1fr;column-gap:6px}.sysrow{min-height:44px}.systems{padding:12px 12px}}
.colR{display:flex;flex-direction:column;gap:14px;min-width:0}
.cellpanel{position:relative;background:var(--sage-tint);border-radius:44px;padding:20px 18px 18px}
.story{background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:20px 24px;min-height:416px}
.systems{background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:16px 14px}
.cardsblock .cards-head{margin:4px 4px 10px}
.panel-top{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:0 6px 4px}
.panel-top .t{font-weight:600;font-size:14px;color:var(--ink2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
.cellpanel .panel-top{min-height:40px}
.cellpanel .pill{background:var(--white)}
#cell svg{width:100%;height:auto;display:block;overflow:visible}
/* Cell drawing */
.org{cursor:pointer;transform-box:fill-box;transform-origin:center}
.org:focus{outline:none}
.org:focus-visible .shp{stroke-width:3.5}
.shp{transition:fill .4s ease-out,stroke .4s ease-out}
.clbl{font:600 14px var(--sans);fill:var(--ink)}
.cst{font:500 13.5px var(--sans);fill:var(--ink)}
.cst .arr{font-weight:700}
.cst .arr.mid{font-size:1.2em}.cst .arr.big{font-size:1.45em}
.arw{font-weight:700;display:inline-block;line-height:1}
.arw.mid{font-size:1.25em}.arw.big{font-size:1.55em}
.lblg{cursor:pointer}
.lead{stroke:#1C1B18;stroke-opacity:.45;stroke-width:1}
.lead-dot{fill:#1C1B18}
#breath{transform-box:fill-box;transform-origin:center;animation:breathe 7s ease-in-out infinite alternate}
@keyframes breathe{from{transform:scale(1)}to{transform:scale(1.015)}}
.drift{animation:drift 11s ease-in-out infinite}
.drift.d1{animation-name:drift1;animation-duration:9s}
.drift.d2{animation-name:drift2;animation-duration:12s}
.drift.d3{animation-name:drift3;animation-duration:14s}
@keyframes drift1{0%,100%{transform:translate(0,0)}50%{transform:translate(3px,-2px)}}
@keyframes drift2{0%,100%{transform:translate(0,0)}50%{transform:translate(-2px,3px)}}
@keyframes drift3{0%,100%{transform:translate(0,0)}33%{transform:translate(2px,2px)}66%{transform:translate(-2px,1px)}}
body.calm #breath,body.calm .drift{animation:none}
body.calm .shp{transition:none}
@media (prefers-reduced-motion: reduce){#breath,.drift{animation:none}.shp{transition:none}.card{transition:none}}
/* System card */
.syscard{position:absolute;left:18px;right:18px;bottom:18px;background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:16px 18px;z-index:5;border:1px solid var(--line)}
.syscard[hidden]{display:none}
.syscard h3{margin:0 40px 4px 0;font:500 20px/1.2 var(--serif)}
.syscard p{margin:4px 0;font-size:14.5px}
.syscard .close{position:absolute;top:10px;right:10px;width:36px;height:36px;border-radius:999px;border:1px solid var(--line);background:var(--paper);cursor:pointer;font-size:18px;line-height:1}
.trainline{margin:-2px 4px 10px}
.sysrow .badge{width:108px;min-width:0}
#cardsHint{min-width:11.5em;text-align:right;white-space:nowrap}
.headright{display:inline-flex;align-items:center;gap:10px}
.cards-head h2{white-space:nowrap}
@media (max-width:600px){#cardsHint{display:none}}
.mixpill{min-height:34px;padding:6px 12px;font-size:13px;background:var(--white)}
.mixpill[aria-pressed="true"]{background:var(--ink);color:var(--paper);border-color:var(--ink)}
.searchbar{background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:8px}
.searchbar .search{min-width:0}
.unitline{font-size:13px;color:var(--ink2);margin:8px 10px 2px}
.story .idle{margin:0 0 10px}
.example{position:relative;border-top:1px dashed var(--line);padding-top:10px;opacity:.42;pointer-events:none;user-select:none}
.example .exlabel{display:inline-block;font-size:12px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;color:var(--ink2);margin-bottom:6px}
.example h2{font-size:20px!important;margin-bottom:6px!important}
.example .fam{display:none}
.mcol{background:var(--sage-tint);border-radius:24px;padding:14px 12px 12px;min-height:300px;min-width:0}
.mcol .mlabel{font-weight:600;font-size:15px}
.mcol .msize{font-size:13px;color:var(--ink2);margin-bottom:8px}
.mlist{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
.mlist li{display:flex;flex-wrap:wrap;align-items:center;gap:3px 8px;font-size:13.5px;line-height:1.2;min-height:26px}
.mlist .badge{min-width:68px;padding:3px 8px;font-size:12.5px}
.mlist .more,.mlist .none{color:var(--ink2);font-size:13px}
/* Story */
.story h2{font:500 26px/1.2 var(--serif);letter-spacing:-.01em;margin:0 0 12px}
.story p{margin:0 0 10px}
.story .size{font-size:19px;font-weight:600;margin-bottom:4px}
.story .scope{font-size:14px;color:var(--ink2);margin:0 0 12px}
.story .fam{font-size:14px;color:var(--ink2);border-top:1px solid var(--line);padding-top:10px;margin-top:12px}
.story .warn{font-size:14px;background:var(--peach-tint);border-radius:16px;padding:8px 12px}
.story .idle{font:500 24px/1.3 var(--serif);color:var(--ink2);margin-top:6px}
.story .err{background:var(--peach-tint);border-radius:16px;padding:10px 14px}
/* Systems list */
.syslist{list-style:none;margin:0;padding:0}
.sysrow{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;min-height:48px;padding:6px 10px;border:0;background:none;border-radius:16px;cursor:pointer;text-align:left}
.sysrow:hover{background:var(--paper)}
.sysrow .sn{font-weight:600;font-size:15px}
.sysrow .sx{font-size:12px;color:var(--ink2);font-family:var(--mono)}
.badge{flex:none;white-space:nowrap;display:inline-flex;align-items:center;gap:6px;border-radius:999px;padding:4px 11px;font-size:13.5px;font-weight:600;min-width:94px;justify-content:center;background:var(--paper);color:var(--ink2);border:1px solid var(--line)}
.badge.up{background:var(--sage-tint);color:var(--sage-deep);border-color:var(--sage)}
.badge.down{background:var(--peach-tint);color:var(--peach-deep);border-color:var(--peach)}
/* Genes */
.genes{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin:18px 0 0}
.gbox{background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:18px 20px}
.gbox h3{margin:0 0 8px;font:500 20px/1.2 var(--serif)}
.grow{display:grid;grid-template-columns:minmax(64px,auto) 1fr auto;gap:10px;align-items:center;min-height:42px;border-bottom:1px solid var(--line);font-size:14px}
.grow:last-child{border-bottom:0}
.grow .role{color:var(--ink2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.grow .fc{font-weight:600;white-space:nowrap}
.grow .bar{grid-column:2/4;height:6px;border-radius:999px;background:var(--paper);overflow:hidden;margin-top:-6px;margin-bottom:6px}
.grow .bar i{display:block;height:100%;border-radius:999px}
.up .bar i{background:var(--sage)} .down .bar i{background:var(--peach)}
.ph{color:#B9B2A3}
/* Researcher */
.rsec{margin:18px 0 0;background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:20px 22px}
.kv{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:10px 18px;margin-top:10px}
.kv div{font-size:13px;color:var(--ink2)}
.kv b{display:block;font:500 16px var(--mono);color:var(--ink)}
table.rt{width:100%;border-collapse:collapse;font-size:13.5px;margin-top:8px}
table.rt th,table.rt td{padding:6px 8px;border-bottom:1px solid var(--line);text-align:left}
table.rt th{color:var(--ink2);font-weight:600;font-size:12.5px}
table.rt td.n{font-family:var(--mono);text-align:right}
table.rt th.n{text-align:right}
.twocol{display:grid;grid-template-columns:1fr 1fr;gap:20px}
.btnrow{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px;align-items:center}
.btn{border:1px solid var(--ink);background:var(--white);border-radius:999px;padding:9px 16px;font-weight:600;font-size:14px;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;min-height:40px}
.btn.ink{background:var(--ink);color:var(--paper)}
.upload input[type=file]{font-size:14px}
.status{font-size:14px;color:var(--ink2)}
/* Gene map */
details.map{margin:18px 0 0;background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:16px 22px}
details.map summary{cursor:pointer;font-weight:600;min-height:40px;display:flex;align-items:center}
.mapwrap{position:relative;margin-top:8px}
#map{width:100%;height:340px;display:block}
.tip{position:absolute;pointer-events:none;background:var(--ink);color:var(--paper);border-radius:12px;padding:6px 10px;font-size:12.5px;white-space:nowrap}
.tip[hidden]{display:none}
footer{margin:40px 0 30px;font-size:13px;color:var(--ink2);display:flex;gap:16px;flex-wrap:wrap;justify-content:space-between;border-top:1px solid var(--line);padding-top:16px}
/* How it works */
dialog{border:0;border-radius:44px;padding:30px 34px;max-width:680px;width:calc(100% - 32px);background:var(--paper);color:var(--ink);box-shadow:var(--lift)}
dialog::backdrop{background:rgb(28 27 24 / .35)}
dialog h2{font:500 30px/1.15 var(--serif);margin:0 0 10px}
dialog h3{font:500 19px/1.2 var(--serif);margin:18px 0 4px}
dialog p,dialog li{font-size:15px}
dialog .close{position:absolute;top:18px;right:18px}
@media (max-width:900px){
.play{display:grid;grid-template-columns:minmax(0,1fr)}
.colL,.colR{display:contents}
.colL{position:static}
.searchbar{order:1}.cardsblock{order:1}.controls{order:2}.mix{order:3}.story{order:4}.cellpanel{order:5}.systems{order:6}
}
@media (max-width:600px){
.wrap{padding:0 16px}
header.top{gap:10px;flex-wrap:wrap;padding-top:14px}
.lockup{height:18px}
.mname{font-size:20px}
.linkbtn{padding:8px 2px;font-size:14px}
.tabs button{padding:7px 11px;font-size:13px}
.hero{padding-top:12px}
.hero p.lede{font-size:16px}
.cards{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;scroll-padding:0 16px;gap:12px;margin:0 -16px;padding:4px 16px 12px;scrollbar-width:none}
.cards::-webkit-scrollbar{display:none}
.card{flex:0 0 78%;scroll-snap-align:start;min-height:156px}
.controls{border-radius:28px;padding:12px}
.group.lines{flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;max-width:100%}
.clbl,.cst .stt{display:none}
.cst{font-size:24px}
.lblg.top .cst{transform:translateY(-11px)}
.story{min-height:480px;padding:18px}
.genes{grid-template-columns:1fr}
.twocol{grid-template-columns:1fr}
.mix-cells{grid-template-columns:1fr}
.cellpanel{border-radius:32px;padding:14px 10px 12px}
dialog{padding:24px 20px;border-radius:32px}
}
</style>
</head>
<body data-mode="simple">
<div class="wrap">
<header class="top">
{{LOCKUP}}
<span class="divider" aria-hidden="true"></span>
<span class="mname">{{MODEL_NAME}}</span>
<span class="spacer"></span>
<button class="linkbtn" id="howBtn" type="button">How it works</button>
<div class="tabs" role="group" aria-label="Mode">
<button type="button" id="modeSimple" aria-pressed="true">Simple</button>
<button type="button" id="modeResearch" aria-pressed="false">Researcher</button>
</div>
</header>
<section class="hero">
<div>
<h1>Switch a gene. Watch the cell answer.</h1>
<p class="lede">Pick a gene to switch off or on inside a human cell. {{MODEL_NAME}} predicts how the cell's other genes respond.</p>
<p class="fixed-note">A research tool. Predictions from a model, not measurements. Not medical advice.<a href="{{MODEL_PAGE}}" target="_blank" rel="noopener">Where it falls short</a></p>
</div>
</section>
<section class="play">
<div class="colL">
<div class="cellpanel">
<div class="panel-top">
<span class="t" id="cellCaption">A human cell</span>
<button type="button" class="pill" id="pauseBtn" aria-pressed="false">Pause motion</button>
</div>
<div id="cell"></div>
<div class="syscard" id="syscard" hidden role="dialog" aria-modal="false" aria-labelledby="scName">
<button type="button" class="close" id="scClose" aria-label="Close">×</button>
<h3 id="scName"></h3>
<div id="scBody"></div>
</div>
</div>
<div class="systems">
<div class="panel-top"><span class="t">Gene groups</span><span class="hint">Tap one to see more</span></div>
<ul class="syslist" id="syslist"></ul>
<p class="unitline r-only">Numbers show how strongly a gene group moved compared with the rest of the cell's genes (a z-score).</p>
<p class="unitline s-only">Bigger arrows mean bigger moves compared with the rest of the cell's genes.</p>
</div>
</div>
<div class="colR">
<div class="story" id="story" aria-live="polite">
<p class="idle">Tap a gene. Watch what the model predicts.</p>
<div class="example" id="example" aria-hidden="true"></div>
</div>
<div class="searchbar">
<div class="search">
<label class="sr" for="q">Find any gene</label>
<input id="q" type="text" autocomplete="off" spellcheck="false" placeholder="Find any gene, e.g. MYC or ribosome" role="combobox" aria-expanded="false" aria-controls="qres" aria-autocomplete="list">
<ul class="results" id="qres" role="listbox" hidden></ul>
</div>
</div>
<div class="cardsblock">
<div class="cards-head">
<h2 id="cardsTitle">Try a gene</h2>
<span class="headright"><span class="hint" id="cardsHint">Tap a card to run it</span><button type="button" class="pill mixpill" id="mixBtn2" aria-pressed="false">Mix two genes</button></span>
</div>
<p class="mixhow trainline">These examples use genes the model saw in training. Try any other gene to test it.</p>
<div class="cards" id="cards" role="group" aria-labelledby="cardsTitle"></div>
</div>
<div class="controls" role="group" aria-label="Settings">
<button type="button" class="pill mixbtn" id="mixBtn" aria-pressed="false">Mix two</button>
<div class="group lines" role="group" aria-label="Cell line" id="lines"></div>
<div class="group" role="group" aria-label="Off or on">
<button type="button" class="pill" data-mod="knockdown" aria-pressed="true">Switch off</button>
<button type="button" class="pill" data-mod="activate" aria-pressed="false">Switch on</button>
</div>
</div>
<section class="mix" id="mix" hidden aria-label="Mix two genes">
<div class="mix-top">
<h2 class="sec-h">Mix two genes</h2>
<span class="hint" id="mixHint">Pick two cards, or find genes in the search box.</span>
</div>
<div class="mix-cells" id="mixCells"></div>
<p class="mixline" id="mixLine"> </p>
<p class="mixhow">Our measure: the total change across the ten gene groups with both genes, divided by the two single-gene changes added up. <span class="r-only mono" id="mixR"></span></p>
<p class="mixhow">Tested: on 24 gene pairs switched on (Norman et al. 2019), the model's error was 28.5% lower than adding the two single effects, ahead on 18 of 24.</p>
<h3 class="sec-h" style="font-size:18px;margin-top:16px">Biggest surprises</h3>
<table class="surprises" id="surprises"><thead><tr><th>Gene</th><th>Two added up</th><th>Together</th></tr></thead><tbody></tbody></table>
<p class="note">Two genes at once was tested only for genes switched on (24 pairs). Changes are in activity on a log scale.</p>
</section>
</div>
</section>
<section class="genes">
<div class="gbox up"><h3>Rises most</h3><div id="gUp"></div></div>
<div class="gbox down"><h3>Falls most</h3><div id="gDown"></div></div>
</section>
<section class="rsec r-only" id="rNums" aria-label="Exact numbers">
<h2 class="sec-h">Exact numbers</h2>
<div class="kv" id="kv"></div>
</section>
<section class="rsec r-only" aria-label="Systems table">
<h2 class="sec-h">Gene groups, exact</h2>
<table class="rt" id="sysTable"><thead><tr><th>Gene group</th><th>Gene Ontology group</th><th class="n">z_score</th><th class="n">mean_delta</th><th class="n">n_genes</th><th>Moved most</th></tr></thead><tbody></tbody></table>
</section>
<section class="rsec r-only" aria-label="Gene Ontology enrichment">
<h2 class="sec-h">Gene Ontology processes</h2>
<div class="twocol">
<div><h3 class="sec-h" style="font-size:17px">Up</h3><table class="rt" id="goUp"><thead><tr><th>Term</th><th class="n">z</th><th class="n">mean_delta</th><th class="n">n</th></tr></thead><tbody></tbody></table></div>
<div><h3 class="sec-h" style="font-size:17px">Down</h3><table class="rt" id="goDown"><thead><tr><th>Term</th><th class="n">z</th><th class="n">mean_delta</th><th class="n">n</th></tr></thead><tbody></tbody></table></div>
</div>
</section>
<section class="rsec r-only" aria-label="Export and upload">
<h2 class="sec-h">Export, or bring your own cells</h2>
<div class="btnrow">
<a class="btn" id="csvBtn" href="#" download>Download all 3,000 genes (CSV)</a>
<button type="button" class="btn" id="jsonBtn">Download full result (JSON)</button>
</div>
<p class="status" style="margin-top:16px">Upload untreated cells as a CSV: one row per cell, one column per gene symbol (raw counts or log1p). The model predicts how switching the chosen gene changes their gene activity. Uses the gene(s) and off / on setting above.</p>
<div class="btnrow upload">
<a class="btn" href="/api/sample_csv" download>Download a sample CSV</a>
<label class="sr" for="csvFile">CSV file of cells</label>
<input type="file" id="csvFile" accept=".csv,text/csv">
<button type="button" class="btn ink" id="uploadBtn">Run on my cells</button>
<span class="status" id="upStatus"></span>
</div>
</section>
<details class="map" id="mapBox">
<summary>Show all 3,000 genes</summary>
<p class="hint" style="margin:4px 0 0">Each dot is a gene: across, how active it is before the change; up or down, how much the model predicts it moves. About 300 genes are drawn, including the 70 that move most each way. <a href="#" id="csvLink2">Download all 3,000 (CSV)</a></p>
<div class="mapwrap"><canvas id="map" aria-label="Gene map"></canvas><div class="tip" id="tip" hidden></div></div>
</details>
<footer>
<span>{{MODEL_NAME}} by Udgam Labs · AI research from first principles</span>
<span>Predictions from a model, not measurements. <a href="{{MODEL_PAGE}}" target="_blank" rel="noopener">Model page</a></span>
</footer>
</div>
<dialog id="how" aria-labelledby="howTitle">
<button type="button" class="pill close" id="howClose">Close</button>
<h2 id="howTitle">How it works</h2>
<p>{{MODEL_NAME}} is a model of human cells. You choose a gene and switch it off (the lab method is called CRISPR interference) or on (CRISPR activation). The model predicts how the activity of 3,000 other genes changes in response.</p>
<h3>What goes in</h3>
<p>64 real, untreated cells from the cell line you pick, and a numeric description of the gene you switch, built from public knowledge about genes. Five cell lines are available; the liver line (HepG2) was never in training, so it tests how the model copes with a cell type it has not seen.</p>
<h3>The model</h3>
<p>A transformer with 16.3M parameters per copy. Three copies were trained from different random starts; this page runs all three and averages their predictions. It runs on our server and takes about 20 to 40 ms per prediction.</p>
<h3>The cell picture</h3>
<p>The drawing is a map, not a microscope image. Each part stands for one of ten groups of genes from the Gene Ontology (for example, recycling or power plants). A part lights up only when its genes move clearly together compared with all 3,000 genes (a z-score of at least 1.6) and their average change goes the same way. Sage with an up arrow means those genes become more active; peach with a down arrow means less active. It shows gene activity, not what the cell does next: for example, cell-division genes going down does not by itself mean the cell divides less.</p>
<h3>Familiarity</h3>
<p>How close this gene and cell type are to what the model has seen. Higher familiarity went with better predictions in our tests; it is not a probability of being right. Several example cards use genes the model trained on, so they show what it learned rather than a prediction for a new gene.</p>
<h3>Where it falls short</h3>
<ul>
<li>It is a long way from a repeat lab experiment: 24 to 49% of the score that repeating the experiment gets, depending on the cell line.</li>
<li>On the liver line it is weaker, especially on the size of changes.</li>
<li>Two genes at once was tested only for genes switched on (24 pairs).</li>
<li>3,000 genes, not all 20,000; gene switches only, no drugs or doses.</li>
</ul>
<p><a href="{{MODEL_PAGE}}" target="_blank" rel="noopener">Read more on the model page</a></p>
</dialog>
<script>
"use strict";
const LINES = {
rpe1:{pill:"Retina (RPE1)", name:"Retina cell line (RPE1)", inn:"the retina cell line (RPE1)"},
k562:{pill:"Leukaemia (K562)", name:"Leukaemia cell line (K562)", inn:"the leukaemia cell line (K562)"},
jurkat:{pill:"T cell (Jurkat)", name:"T-cell line (Jurkat)", inn:"the T-cell line (Jurkat)"},
h1:{pill:"Stem cell (H1)", name:"Stem cell line (H1)", inn:"the stem cell line (H1)"},
hepg2:{pill:"Liver (HepG2), not in training", name:"Liver cell line (HepG2), not in training", inn:"the liver cell line (HepG2)"},
};
// Each "system" is a group of genes, not a behaviour of the cell: the names say so.
const SYS = {cell_skeleton:"Skeleton and shape genes", stress_alarm:"Stress-alarm genes", cell_division:"Cell-division genes",
protein_factory:"Protein-factory genes", power_plants:"Power-plant genes", trash_recycling:"Recycling genes",
message_editing:"Message-editing genes", fuel_metabolism:"Fuel genes", self_destruct:"Self-destruct genes", immune_signals:"Signalling genes"};
const SYS_DESC = {
cell_division:"Genes that help copy DNA and split the cell in two.",
trash_recycling:"Genes that help shred damaged proteins and recycle worn-out parts.",
protein_factory:"Genes that help build the proteins the cell needs.",
power_plants:"Genes that help make the cell's energy (ATP) in mitochondria.",
fuel_metabolism:"Genes that help process sugars, fats and other nutrients.",
message_editing:"Genes that help read DNA and trim RNA messages before proteins are made.",
self_destruct:"Genes that help a badly damaged cell shut itself down.",
immune_signals:"Genes that help send warning signals and coordinate immune defence.",
stress_alarm:"Genes that help the cell respond to damage and stress.",
cell_skeleton:"Genes that help hold the cell's shape and drive its movement."};
const SYS_ORDER = ["cell_division","protein_factory","trash_recycling","power_plants","fuel_metabolism","message_editing","self_destruct","immune_signals","stress_alarm","cell_skeleton"];
const CARDS = [
{g:"PSMA3", line:"rpe1", mod:"knockdown", name:"The protein shredder", text:"Part of the machine that breaks down most proteins."},
{g:"MYC", line:"h1", mod:"knockdown", name:"The growth engine", text:"Switches on growth-related genes."},
{g:"GATA1", line:"k562", mod:"knockdown", name:"The blood identity switch", text:"A general switch for how blood cells develop."},
{g:"RPL5", line:"hepg2", mod:"knockdown", name:"A protein-factory part, in liver", text:"Part of the ribosome, which builds proteins."},
{g:"CEBPE", line:"k562", mod:"activate", name:"A gene reader", text:"Turns other genes on."},
{g:"CNN1", line:"k562", mod:"activate", name:"A muscle-fibre helper", text:"Helps regulate smooth-muscle contraction."},
{g:"KIF11", line:"rpe1", mod:"knockdown", name:"The cell-splitting motor", text:"Sets up the spindle when a cell divides."},
{g:"ATP5F1B", line:"jurkat", mod:"knockdown", name:"A power-plant part", text:"Part of the mitochondrial machine that makes the cell's fuel."},
];
const ARROW_UP = "↑", ARROW_DOWN = "↓";
const $ = s => document.querySelector(s);
const esc = s => String(s == null ? "" : s).replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
const state = {line:"rpe1", mod:"knockdown", genes:null, mix:false, sel:[], last:null, mixRes:null, mode:"simple", paused:false, active:null};
const cache = new Map();
let runToken = 0; const animTokens = {};
const rmq = window.matchMedia("(prefers-reduced-motion: reduce)");
const motionOff = () => rmq.matches || state.paused;
/* ---------- The cell drawing ---------- */
/* ---- Cell drawing (round 3): organelles on an organic body; labels outside on leader lines ---- */
const CX = 300, CY = 190;
function wob(t, k){ return 1 + k * (0.030 * Math.sin(3*t + 0.6) + 0.018 * Math.sin(5*t + 2.1) + 0.010 * Math.sin(7*t + 0.3)); }
function blobPt(t, rx, ry, k, cx, cy){ const r = wob(t, k); return [(cx ?? CX) + rx * r * Math.cos(t), (cy ?? CY) + ry * r * Math.sin(t)]; }
function blobPath(rx, ry, k){
const n = 40, pts = [];
for (let i = 0; i < n; i++) pts.push(blobPt(i / n * Math.PI * 2, rx, ry, k));
const f = v => v.toFixed(1);
let d = `M${f(pts[0][0])} ${f(pts[0][1])}`;
for (let i = 0; i < n; i++){
const p0 = pts[(i-1+n)%n], p1 = pts[i], p2 = pts[(i+1)%n], p3 = pts[(i+2)%n];
d += ` C${f(p1[0]+(p2[0]-p0[0])/6)} ${f(p1[1]+(p2[1]-p0[1])/6)} ${f(p2[0]-(p3[0]-p1[0])/6)} ${f(p2[1]-(p3[1]-p1[1])/6)} ${f(p2[0])} ${f(p2[1])}`;
}
return d + "Z";
}
const deg = a => a * Math.PI / 180;
const NUC = {x:262, y:192, r:66};
function arcPath(cx, cy, r, a0, a1, wave, n){
// an open wavy arc (used for the folded ribbons of the protein factories)
let d = "";
for (let i = 0; i <= n; i++){
const t = deg(a0 + (a1 - a0) * i / n), rr = r + wave * Math.sin(i / n * Math.PI * 7);
d += (i ? " L" : "M") + (cx + rr*Math.cos(t)).toFixed(1) + " " + (cy + rr*Math.sin(t)).toFixed(1);
}
return d;
}
function bandPath(cx, cy, r0, r1, a0, a1){
// a closed crescent band on the nucleus edge (message editing)
const p = (r, a) => `${(cx + r*Math.cos(deg(a))).toFixed(1)} ${(cy + r*Math.sin(deg(a))).toFixed(1)}`;
return `M${p(r1,a0)} A${r1} ${r1} 0 0 1 ${p(r1,a1)} A${(r1-r0)/2} ${(r1-r0)/2} 0 0 1 ${p(r0,a1)} A${r0} ${r0} 0 0 0 ${p(r0,a0)} A${(r1-r0)/2} ${(r1-r0)/2} 0 0 1 ${p(r1,a0)}Z`;
}
function bean(cx, cy, w, h, rot){
// one mitochondrion outline (a capsule with a slight waist), in page coordinates
const a = w/2, b = h/2, c = Math.cos(deg(rot)), sn = Math.sin(deg(rot));
const P = (x, y) => `${(cx + x*c - y*sn).toFixed(1)} ${(cy + x*sn + y*c).toFixed(1)}`;
const d = `M${P(-a,0)} C${P(-a,-b*1.15)} ${P(-a*0.2,-b*1.05)} ${P(0,-b*0.8)} C${P(a*0.2,-b*1.05)} ${P(a,-b*1.15)} ${P(a,0)} C${P(a,b*1.15)} ${P(a*0.2,b*1.05)} ${P(0,b*0.8)} C${P(-a*0.2,b*1.05)} ${P(-a,b*1.15)} ${P(-a,0)}Z`;
return {d, t:`translate(${cx} ${cy}) rotate(${rot})`, w};
}
function drop(x, y, r){ return `M${x} ${y-r*1.35} C${x+r*0.9} ${y-r*0.4} ${x+r} ${y+r*0.2} ${x+r} ${y+r*0.35} A${r} ${r} 0 0 1 ${x-r} ${y+r*0.35} C${x-r} ${y+r*0.2} ${x-r*0.9} ${y-r*0.4} ${x} ${y-r*1.35}Z`; }
function circ(x, y, r){ return `M${x-r} ${y} a${r} ${r} 0 1 0 ${2*r} 0 a${r} ${r} 0 1 0 ${-2*r} 0Z`; }
function hexa(x, y, r){ let d = ""; for (let i = 0; i < 6; i++){ const a = deg(60*i - 90); d += (i ? " L" : "M") + (x + r*Math.cos(a)).toFixed(1) + " " + (y + r*Math.sin(a)).toFixed(1); } return d + "Z"; }
const BODY = {rx:190, ry:135, k:1};
const MITO = [bean(388, 266, 60, 26, -20), bean(438, 228, 48, 22, 32), bean(340, 300, 46, 20, -6)];
const VESICLES = [[398,122,16],[424,110,10],[416,146,9],[376,102,8],[440,134,6]];
const DROPS = [[456,168,8],[470,190,6],[450,192,5.5]];
const RECEPTOR_ANGLES = [150, 168, 186, 204];
const RIBO_FREE = [[160,140],[176,252],[340,150],[356,206],[330,240],[150,200],[200,96],[372,82],[300,282],[452,120],[408,192],[262,300],[138,170],[236,300],[392,236]];
function cellSVG(p){
const S = 'stroke="#1C1B18" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';
const T = 'stroke="#1C1B18" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"';
const o = (id, inner, drift) => `<g class="org" id="${p}org-${id}" data-sys="${id}" tabindex="0" role="button" aria-label="${SYS[id]}: steady"><g class="${drift || ""}">${inner}</g></g>`;
// Body: interior (rest colour) + membrane band (the reacting shape, two outline lines)
const outer = blobPath(BODY.rx, BODY.ry, 1), inner = blobPath(BODY.rx - 9, BODY.ry - 9, 1);
const halo = blobPath(BODY.rx + 22, BODY.ry + 20, 0.9);
// Protein factories: ribbons round the nucleus; the beads (ribosomes) are the reacting shape
const er = [arcPath(NUC.x, NUC.y, NUC.r + 20, 196, 338, 3.5, 70), arcPath(NUC.x, NUC.y, NUC.r + 34, 204, 330, 4, 70), arcPath(NUC.x, NUC.y, NUC.r + 48, 214, 318, 4, 60)];
// Signals: receptors on the membrane
const rec = RECEPTOR_ANGLES.map(a => {
const t = deg(a), [x, y] = blobPt(t, BODY.rx, BODY.ry, 1), ux = Math.cos(t), uy = Math.sin(t);
const sx = x + ux*12, sy = y + uy*12, px = -uy, py = ux;
return {stem:`M${(x-ux*2).toFixed(1)} ${(y-uy*2).toFixed(1)} L${sx.toFixed(1)} ${sy.toFixed(1)}`,
head:`M${(sx+px*7).toFixed(1)} ${(sy+py*7).toFixed(1)} Q${(sx+ux*12).toFixed(1)} ${(sy+uy*12).toFixed(1)} ${(sx-px*7).toFixed(1)} ${(sy-py*7).toFixed(1)} Q${(sx+ux*4).toFixed(1)} ${(sy+uy*4).toFixed(1)} ${(sx+px*7).toFixed(1)} ${(sy+py*7).toFixed(1)}Z`};
});
const ribo = RIBO_FREE.map(([x,y]) => `<circle cx="${x}" cy="${y}" r="1.9" fill="#1C1B18" fill-opacity=".5"/>`).join("");
const parts = [
o("stress_alarm", `<path class="shp" data-kind="stroke" id="${p}shape-stress_alarm" d="${halo}" fill="none" ${S} stroke-dasharray="1 9" stroke-width="3"/>`),
o("cell_skeleton", `<path d="${outer}" fill="#FFFFFF"/>
<path d="M150 150 Q220 120 300 140 M170 270 Q250 248 330 276 M360 76 Q410 110 470 150 M120 210 Q150 250 200 286" fill="none" stroke="#1C1B18" stroke-opacity=".12" stroke-width="1.3" stroke-linecap="round"/>
<g class="drift d3">${ribo}</g>
<path class="shp" data-kind="fill" id="${p}shape-cell_skeleton" d="${outer} ${inner}" fill-rule="evenodd" fill="#F3EFE6" stroke="#1C1B18" stroke-width="1.6" stroke-linejoin="round"/>`),
o("protein_factory", `${er.map(d => `<path d="${d}" fill="none" stroke="#1C1B18" stroke-width="11" stroke-linecap="round" stroke-linejoin="round"/><path d="${d}" fill="none" stroke="#F3EFE6" stroke-width="7.4" stroke-linecap="round" stroke-linejoin="round"/>`).join("")}
<path class="shp" data-kind="stroke" id="${p}shape-protein_factory" d="${er.join(" ")}" fill="none" stroke="#1C1B18" stroke-width="3.6" stroke-linecap="round" stroke-dasharray="0 9"/>`),
o("cell_division", `<circle class="shp" data-kind="fill" id="${p}shape-cell_division" cx="${NUC.x}" cy="${NUC.y}" r="${NUC.r}" fill="#FAF6EE" ${S}/>
<circle cx="${NUC.x}" cy="${NUC.y}" r="${NUC.r - 6}" fill="none" stroke="#1C1B18" stroke-opacity=".25" stroke-width="1.2" stroke-dasharray="3 5"/>
<path d="M228 170 C238 154, 258 160, 252 176 S270 190, 284 180 M236 212 C248 224, 266 220, 272 230 M286 156 C296 162, 300 172, 296 182" fill="none" stroke="#1C1B18" stroke-opacity=".4" stroke-width="1.6" stroke-linecap="round"/>
<circle cx="${NUC.x + 22}" cy="${NUC.y + 14}" r="14" fill="#EFE6D4" ${T}/><circle cx="${NUC.x + 18}" cy="${NUC.y + 10}" r="4" fill="#E2D5BC"/>`),
o("message_editing", `<path class="shp" data-kind="fill" id="${p}shape-message_editing" d="${bandPath(NUC.x, NUC.y, NUC.r + 1, NUC.r + 10, 112, 168)}" fill="#F3EFE6" ${S}/>
<path d="M188 262 q5 -6 10 0 t10 0 t10 0" fill="none" stroke="#1C1B18" stroke-opacity=".55" stroke-width="1.5" stroke-linecap="round"/>`, "drift d2"),
o("power_plants", `<path class="shp" data-kind="fill" id="${p}shape-power_plants" d="${MITO.map(m => m.d).join(" ")}" fill="#F3EFE6" ${S}/>` + MITO.map(m => `<g transform="${m.t}"><path d="M${(-0.36*m.w).toFixed(1)} -4 l${(0.12*m.w).toFixed(1)} 8 l${(0.12*m.w).toFixed(1)} -8 l${(0.12*m.w).toFixed(1)} 8 l${(0.12*m.w).toFixed(1)} -8 l${(0.12*m.w).toFixed(1)} 8 l${(0.12*m.w).toFixed(1)} -8" fill="none" stroke="#1C1B18" stroke-opacity=".55" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></g>`).join(""), "drift d1"),
o("trash_recycling", `<path class="shp" data-kind="fill" id="${p}shape-trash_recycling" d="${VESICLES.map(([x,y,r]) => circ(x,y,r)).join(" ")}" fill="#FFFFFF" ${S}/>
<circle cx="394" cy="118" r="3" fill="#1C1B18" fill-opacity=".35"/><circle cx="404" cy="128" r="2" fill="#1C1B18" fill-opacity=".35"/>`, "drift d2"),
o("fuel_metabolism", `<path class="shp" data-kind="fill" id="${p}shape-fuel_metabolism" d="${DROPS.map(([x,y,r]) => drop(x,y,r)).join(" ")}" fill="#FAF6EE" ${S}/>`, "drift d3"),
o("self_destruct", `<path class="shp" data-kind="fill" id="${p}shape-self_destruct" d="${hexa(344, 82, 11)}" fill="#F3EFE6" ${S}/><circle cx="344" cy="82" r="3" fill="#1C1B18"/>`, "drift d1"),
o("immune_signals", `${rec.map(r => `<path d="${r.stem}" fill="none" ${S}/>`).join("")}<path class="shp" data-kind="fill" id="${p}shape-immune_signals" d="${rec.map(r => r.head).join(" ")}" fill="#FFFFFF" ${S}/>`),
];
// Labels outside the cell, joined by leader lines. Clicking a label opens its system too.
const L = [
["cell_skeleton", -34, 24, "start", blobPt(deg(222), BODY.rx, BODY.ry, 1), [70, 36]],
["protein_factory", 214, 24, "middle", [214, 118], [214, 55]],
["self_destruct", 394, 24, "middle", [346, 70], [378, 55]],
["trash_recycling", 512, 54, "start", [432, 104], [504, 50]],
["fuel_metabolism", 512, 150, "start", [476, 178], [508, 154]],
["power_plants", 512, 262, "start", [458, 234], [508, 266]],
["stress_alarm", 634, 342, "end", blobPt(deg(42), BODY.rx + 22, BODY.ry + 20, 0.9), [520, 340]],
["immune_signals", -34, 214, "start", blobPt(deg(186), BODY.rx + 14, BODY.ry + 14, 1), [76, 210]],
["cell_division", -34, 128, "start", [NUC.x - 50, NUC.y - 40], [90, 124]],
["message_editing", -34, 314, "start", [204, 252], [112, 310]],
];
const labels = L.map(([id, x, y, anc, tip, from]) => `<g class="lblg${y < 40 ? " top" : ""}" data-sys="${id}">
<path class="lead" d="M${from[0].toFixed(1)} ${from[1].toFixed(1)} L${tip[0].toFixed(1)} ${tip[1].toFixed(1)}" fill="none"/>
<circle class="lead-dot" cx="${tip[0].toFixed(1)}" cy="${tip[1].toFixed(1)}" r="2.6"/>
<text class="clbl" x="${x}" y="${y}" text-anchor="${anc}">${SYS[id]}</text>
<text class="cst" id="${p}z-${id}" x="${x}" y="${y + 21}" text-anchor="${anc}"><tspan class="arr"></tspan><tspan class="stt"></tspan></text></g>`).join("");
return `<svg viewBox="-40 0 680 370" role="group" aria-label="The cell" xmlns="http://www.w3.org/2000/svg">
<g id="${p}breath">${parts.join("")}</g>
<g class="labels" aria-hidden="true">${labels}</g></svg>`;
}
const IDLE_FILL = {cell_skeleton:"#F3EFE6", cell_division:"#FAF6EE", power_plants:"#F3EFE6", trash_recycling:"#FFFFFF", fuel_metabolism:"#FAF6EE", self_destruct:"#F3EFE6", immune_signals:"#FFFFFF", message_editing:"#F3EFE6"};
function colorsFor(dir, strong, kind){
if (kind === "stroke") return dir === "up" ? "#3F6B4C" : "#8A4F2A";
return dir === "up" ? "#9CC2A1" : "#F5C3A5"; // a reacting part always takes the full base colour
}
function reacts(s){ return Math.abs(s.z_score) >= 1.6 && s.mean_delta !== 0 && Math.sign(s.mean_delta) === Math.sign(s.z_score); }
function dirOf(s){ return s.z_score > 0 ? "up" : "down"; }
function word(dir){ return dir === "up" ? "Up" : "Down"; }
function resetCell(p){
for (const id of Object.keys(SYS)){
const sh = document.getElementById(p+"shape-"+id); if (!sh) continue;
if (sh.dataset.kind === "stroke"){ sh.setAttribute("stroke","#1C1B18"); sh.setAttribute("stroke-width","3"); sh.setAttribute("stroke-dasharray","1 9"); }
else { sh.setAttribute("fill", IDLE_FILL[id] || "#FAF6EE"); sh.setAttribute("stroke","#1C1B18"); }
const g = document.getElementById(p+"org-"+id);
g.getAnimations && g.getAnimations().forEach(a => a.cancel());
g.style.transform = "";
setStatus(p, id, null, 0);
if (!p) g.setAttribute("aria-label", SYS[id] + ": steady");
}
}
/* Simple mode says how much in words; Researcher mode keeps the exact z-score. */
const simple = () => state.mode !== "researcher";
function amount(v){ return v >= 6 ? "a lot" : v >= 3 ? "clearly" : "a little"; }
function arrowSize(v){ return v >= 6 ? "big" : v >= 3 ? "mid" : "small"; }
function moveText(dir, v){ return simple() ? `${amount(v)}` : `${word(dir)} ${v.toFixed(1)}`; }
function moveHTML(dir, v){ return `<span class="arw ${simple() ? arrowSize(v) : ""}">${dir === "up" ? ARROW_UP : ARROW_DOWN}</span> ${moveText(dir, v)}`; }
function moveLabel(dir, v){ return simple() ? `${dir} ${amount(v)}` : `${dir}, ${v.toFixed(1)}`; }
function setStatus(p, id, dir, val, finalVal){
const t = document.getElementById(p+"z-"+id); if (!t) return;
const fv = finalVal == null ? val : finalVal;
t.children[0].textContent = dir ? (dir === "up" ? ARROW_UP : ARROW_DOWN) : "";
t.children[0].setAttribute("class", "arr " + (dir && simple() ? arrowSize(fv) : ""));
t.children[1].textContent = dir ? ` ${simple() ? amount(fv) : word(dir) + " " + val.toFixed(1)}` : (p ? "" : "Steady");
}
function paintCell(p, res, animate){
const my = animTokens[p] = (animTokens[p] || 0) + 1;
const live = () => animTokens[p] === my;
resetCell(p);
if (res && !p) document.body.classList.add("ran");
if (!res || (res.missing_priors && res.missing_priors.length)) return;
const calm = !animate || motionOff();
res.systems.forEach((s, i) => {
if (!SYS[s.id]) return;
const g = document.getElementById(p+"org-"+s.id);
if (!p) g.setAttribute("aria-label", `${SYS[s.id]}: ${reacts(s) ? moveLabel(dirOf(s), Math.abs(s.z_score)) : "steady"}`);
if (!reacts(s)) return;
const dir = dirOf(s), strong = Math.abs(s.z_score) >= 3.0, val = Math.abs(s.z_score);
const sh = document.getElementById(p+"shape-"+s.id);
const finalScale = dir === "up" ? 1.03 : 0.97;
const apply = () => {
if (sh.dataset.kind === "stroke"){
// the stress halo: a wider dotted line in the base colour, so it reads as sage or peach, not ink
sh.setAttribute("stroke", dir === "up" ? "#9CC2A1" : "#F5C3A5"); sh.setAttribute("stroke-width", "6"); sh.setAttribute("stroke-dasharray", "2 10");
} else if (s.id === "immune_signals"){
// small receptor heads: base fill and a deep outline, or the ink outline hides the colour
sh.setAttribute("fill", dir === "up" ? "#9CC2A1" : "#F5C3A5"); sh.setAttribute("stroke", colorsFor(dir, strong, "stroke"));
} else { sh.setAttribute("fill", colorsFor(dir, strong, "fill")); sh.setAttribute("stroke", colorsFor(dir, strong, "stroke")); }
g.style.transform = s.id === "cell_skeleton" || s.id === "stress_alarm" ? "" : `scale(${finalScale})`;
};
if (calm){ apply(); setStatus(p, s.id, dir, val); return; }
setTimeout(() => {
if (!live()) return;
apply();
let done = false;
const big = s.id === "cell_skeleton" || s.id === "stress_alarm";
const peak = big ? (dir === "up" ? 1.02 : 0.98) : (dir === "up" ? 1.06 : 0.94);
const end = big ? 1 : finalScale;
g.animate([{transform:"scale(1)"},{transform:`scale(${peak})`, offset:0.54},{transform:`scale(${end})`}],
{duration:650, easing:"cubic-bezier(.2,.8,.2,1)"});
// one ring pulse
const ring = sh.cloneNode(false);
ring.removeAttribute("id"); ring.setAttribute("fill","none");
ring.setAttribute("stroke", dir === "up" ? "#3F6B4C" : "#8A4F2A"); ring.setAttribute("stroke-width","3");
ring.removeAttribute("stroke-dasharray"); ring.style.transformBox = "fill-box"; ring.style.transformOrigin = "center"; ring.style.pointerEvents = "none";
sh.parentNode.insertBefore(ring, sh.nextSibling);
const an = ring.animate([{opacity:.95, transform:"scale(1)"},{opacity:0, transform:"scale(1.25)"}], {duration:700, easing:"ease-out"});
an.onfinish = an.oncancel = () => ring.remove();
// count-up
const t0 = performance.now();
const step = now => {
if (!live() || done) return;
const k = Math.max(0, Math.min(1, (now - t0) / 600)), e = 1 - Math.pow(1 - k, 3);
setStatus(p, s.id, dir, k < 1 ? val * e : val, val);
if (k < 1) requestAnimationFrame(step);
};
requestAnimationFrame(step);
setTimeout(() => { done = true; ring.remove(); if (live()) setStatus(p, s.id, dir, val); }, 760);
}, i * 80);
});
}
/* ---------- Data ---------- */
function key(line, genes, mod){ return `${line}|${genes.join(",")}|${mod}`; }
async function getResult(line, genes, mod){
const k = key(line, genes, mod);
if (!cache.has(k)){
const pr = fetch(`/api/perturb?line=${encodeURIComponent(line)}&genes=${encodeURIComponent(genes.join(","))}&modality=${encodeURIComponent(mod)}`)
.then(async r => { const j = await r.json(); if (!r.ok) throw new Error(j.error || "Request failed"); return j; });
cache.set(k, pr);
pr.catch(() => cache.delete(k));
}
return cache.get(k);
}
/* ---------- Story ---------- */
function sizeWords(rms){
if (rms >= 0.18) return "a large change";
if (rms >= 0.08) return "a clear change";
if (rms >= 0.035) return "a small change";
return "very little change";
}
function joinNames(a){ return a.length === 2 ? `${a[0]} and ${a[1]}` : a[0]; }
function sysSentenceMost(ups, downs){
const part = (list, dir) => !list.length ? "" : list.length === 1 ? `${SYS[list[0].id]} go ${dir} most` : `${SYS[list[0].id]} and ${SYS[list[1].id]} go ${dir} most`;
const t = [part(ups, "up"), part(downs, "down")].filter(Boolean).join("; ");
return t ? t + "." : "";
}
function sysSentence(list, dir){
// same words as the pills: "a lot" (|z| >= 6), "clearly" (3 to 6), "a little" (1.6 to 3); group names are plural
if (!list.length) return "";
const amt = list.map(s => amount(Math.abs(s.z_score))), names = list.map(s => SYS[s.id]);
if (list.length === 1) return `${names[0]} go ${dir} ${amt[0]}.`;
if (amt[0] === amt[1]) return `${names[0]} and ${names[1]} go ${dir} ${amt[0]}.`;
return `${names[0]} go ${dir} ${amt[0]}. ${names[1]} go ${dir} ${amt[1]}.`;
}
function genesHTML(genes){ return genes.map(g => `<span class="sym">${esc(g)}</span>`).join(" and "); }
function placeName(res){
if (res.cell_line === "custom") return "your uploaded cells";
return (LINES[res.cell_line] || {inn: res.cell_line}).inn;
}
function storyHTML(res){
const verb = res.modality === "activate" ? "on" : "off";
const head = `<h2>Switching ${verb} ${genesHTML(res.genes)} in ${esc(placeName(res))}</h2>`;
if (res.missing_priors && res.missing_priors.length){
return head + `<p class="size">The model has no knowledge of ${genesHTML(res.missing_priors)}, so it cannot predict this one.</p><p class="hint">Check the spelling, or find a gene with the search box.</p>`;
}
const sorted = res.systems.filter(reacts).sort((a,b) => Math.abs(b.z_score) - Math.abs(a.z_score));
const ups = sorted.filter(s => s.z_score > 0).slice(0,2), downs = sorted.filter(s => s.z_score < 0).slice(0,2);
const sw = sizeWords(res.effect_rms), quiet = sw === "a small change" || sw === "very little change";
const fewMoveALot = sorted.some(s => Math.abs(s.z_score) >= 3.0);
let h = head + `<p class="size">${quiet && fewMoveALot ? "A small change overall, but a few gene groups move a lot." : `The model predicts ${sw}.`}</p><p class="scope">This shows which groups of genes turn up or down, not what the cell does next.</p>`;
const ss = quiet ? sysSentenceMost(ups, downs) : [sysSentence(ups,"up"), sysSentence(downs,"down")].filter(Boolean).join(" ");
h += `<p>${ss || "No group of genes moves clearly."}</p>`;
const gs = [];
const u = res.top_up && res.top_up[0], d = res.top_down && res.top_down[0];
if (u && u.fold_change >= 1.5) gs.push(`<span class="sym">${esc(u.gene)}</span> rises about ${u.fold_change.toFixed(1)} times.`);
if (d && d.fold_change <= 0.67) gs.push(`<span class="sym">${esc(d.gene)}</span> falls to about ${Math.round(d.fold_change * 100)}% of its level.`);
if (gs.length) h += `<p>${gs.join(" ")}</p>`;
if (res.cell_line === "custom"){
h += `<p class="warn">These are your own cells, which the model never saw in training. Expect larger errors in the size of changes.</p>`;
} else if (res.zero_shot_cell_line){
h += `<p class="warn">This cell type was never in training. Expect larger errors in the size of changes.</p>`;
} else {
h += `<p class="fam"><b>Familiarity: ${esc(String(res.confidence.tier).toLowerCase())}.</b> How close this gene and cell type are to what the model has seen. Higher familiarity went with better predictions in our tests; it is not a probability of being right.</p>`;
}
if (res.custom_upload){
const c = res.custom_upload;
h += `<p class="hint">${c.n_uploaded_cells} cells uploaded; ${c.matched_hvgs} of the model's 3,000 genes matched (${c.coverage_pct}%). ${esc(c.normalization || "")}</p>`;
}
return h;
}
/* ---------- Systems list and card ---------- */
function buildSysList(){
$("#syslist").innerHTML = SYS_ORDER.map(id => `<li><button type="button" class="sysrow" data-sys="${id}" id="row-${id}" aria-label="${SYS[id]}: steady">
<span><span class="sn">${SYS[id]}</span><br class="r-only"><span class="sx r-only" id="rx-${id}"></span></span>
<span class="badge" id="b-${id}">Steady</span></button></li>`).join("");
}
function paintSysList(res){
const by = {};
if (res && !(res.missing_priors && res.missing_priors.length)) res.systems.forEach(s => by[s.id] = s);
for (const id of SYS_ORDER){
const s = by[id], b = $("#b-"+id), row = $("#row-"+id), rx = $("#rx-"+id);
if (s && reacts(s)){
const dir = dirOf(s), v = Math.abs(s.z_score).toFixed(1);
b.className = "badge " + dir; b.innerHTML = moveHTML(dir, Math.abs(s.z_score));
row.setAttribute("aria-label", `${SYS[id]}: ${moveLabel(dir, Math.abs(s.z_score))}`);
} else {
b.className = "badge"; b.textContent = "Steady"; row.setAttribute("aria-label", `${SYS[id]}: steady`);
}
rx.textContent = s && by[id] ? `z ${s.z_score.toFixed(2)} · mean_delta ${s.mean_delta.toFixed(4)}` : "";
}
}
let cardReturn = null;
function openSys(id, from){
const res = state.last; const card = $("#syscard");
const s = res && !(res.missing_priors && res.missing_priors.length) ? res.systems.find(x => x.id === id) : null;
$("#scName").textContent = SYS[id];
let h = "";
if (!s){ h = `<p>Run a gene to see how these genes respond.</p>`; }
else {
const dirTxt = reacts(s) ? `<b>${moveHTML(dirOf(s), Math.abs(s.z_score))}</b>` : "<b>Steady</b>: its genes do not move clearly together.";
h += `<p>${esc(SYS_DESC[id] || "")}</p><p>${dirTxt}</p><p class="hint">The arrow shows whether these genes become more or less active, not whether the cell does more or less of this.</p>`;
h += `<p>Moved most: ${s.drivers.map(d => `<span class="sym">${esc(d.gene)}</span>`).join(", ")}</p>`;
h += `<p class="r-only mono" style="font-size:13px">${esc(s.sci_name)} · z_score ${s.z_score} · mean_delta ${s.mean_delta} · n_genes ${s.n_genes}</p>`;
}
$("#scBody").innerHTML = h;
card.hidden = false; cardReturn = from || null;
$("#scClose").focus();
}
function closeSys(){ $("#syscard").hidden = true; if (cardReturn) { cardReturn.focus(); cardReturn = null; } }
/* ---------- Top genes ---------- */
function geneRows(list, dir, n){
const out = [];
const maxAbs = Math.max(0.0001, ...list.slice(0,n).map(x => Math.abs(x.delta)));
for (let i = 0; i < n; i++){
const g = list[i];
if (!g){ out.push(`<div class="grow"><span class="ph"> </span><span></span><span></span></div>`); continue; }
const fcTxt = dir === "up" ? `${ARROW_UP} ${g.fold_change.toFixed(1)}×` : `${ARROW_DOWN} ${Math.round(g.fold_change*100)}%`;
const rTxt = `<span class="r-only mono" style="font-size:12px;color:var(--ink2)">${g.ctrl.toFixed(2)} → ${g.pred.toFixed(2)} (${g.delta > 0 ? "+" : ""}${g.delta.toFixed(3)})</span>`;
out.push(`<div class="grow"><span class="sym">${esc(g.gene)}</span><span class="role">${esc(g.role || "")}</span><span class="fc">${fcTxt} ${rTxt}</span>
<span class="bar"><i style="width:${(100*Math.abs(g.delta)/maxAbs).toFixed(1)}%"></i></span></div>`);
}
return out.join("");
}
function paintGenes(res){
const n = state.mode === "researcher" ? 12 : 5;
const ok = res && !(res.missing_priors && res.missing_priors.length);
$("#gUp").innerHTML = geneRows(ok ? res.top_up : [], "up", n);
$("#gDown").innerHTML = geneRows(ok ? res.top_down : [], "down", n);
}
/* ---------- Researcher ---------- */
function paintResearcher(res){
const ok = res && !(res.missing_priors && res.missing_priors.length);
const c = res ? res.confidence : null;
const unseenLine = res && (res.zero_shot_cell_line || res.cell_line === "custom");
const kv = !res ? [["effect_rms","–"]] : !ok ? [["missing_priors", res.missing_priors.join(", ")], ["result", "not shown: the model has no knowledge of this gene"]] : [
["effect_rms", res.effect_rms], ...(unseenLine ? [] : [["familiarity score", c.score], ["tier", c.tier]]), ["prior_familiarity", c.prior_familiarity],
["ensemble_spread", c.ensemble_spread], ["cell_line_similarity", res.cell_line_similarity], ["ctx_scale_used", res.ctx_scale_used],
["n_cells", res.n_cells], ["nearest training genes", (c.nearest_train_genes||[]).map(x => `${x.gene} ${x.sim}`).join(", ")],
["missing_priors", "none"],
];
$("#kv").innerHTML = kv.map(([k,v]) => `<div>${esc(k)}<b>${esc(v)}</b></div>`).join("");
$("#sysTable tbody").innerHTML = ok ? res.systems.map(s => `<tr><td>${esc(SYS[s.id] || s.name)}</td><td>${esc(s.sci_name)}</td><td class="n">${s.z_score.toFixed(2)}</td><td class="n">${s.mean_delta.toFixed(4)}</td><td class="n">${s.n_genes}</td><td class="mono">${s.drivers.map(d => esc(d.gene)).join(", ")}</td></tr>`).join("") : "";
const go = (arr) => (arr||[]).map(t => `<tr><td>${esc(t.name)} <span class="mono" style="color:var(--ink2);font-size:11.5px">${esc(t.go_id)}</span></td><td class="n">${t.z_score.toFixed(2)}</td><td class="n">${t.mean_delta.toFixed(4)}</td><td class="n">${t.n_genes}</td></tr>`).join("") || `<tr><td colspan="4" class="hint">None past z 1.5</td></tr>`;
$("#goUp tbody").innerHTML = ok ? go(res.go_enrichment.up) : "";
$("#goDown tbody").innerHTML = ok ? go(res.go_enrichment.down) : "";
const href = res && res.cell_line !== "custom" ? `/api/export_csv?line=${encodeURIComponent(res.cell_line)}&genes=${encodeURIComponent(res.genes.join(","))}&modality=${encodeURIComponent(res.modality)}` : "#";
$("#csvBtn").href = href; $("#csvLink2").href = href;
}
/* ---------- Gene map ---------- */
let mapPts = [];
function drawMap(){
const cv = $("#map"), res = state.last;
if (!$("#mapBox").open) return;
const dpr = window.devicePixelRatio || 1, W = cv.clientWidth, H = cv.clientHeight;
cv.width = W * dpr; cv.height = H * dpr;
const ctx = cv.getContext("2d"); ctx.setTransform(dpr,0,0,dpr,0,0); ctx.clearRect(0,0,W,H);
mapPts = [];
const pts = res && !(res.missing_priors && res.missing_priors.length) ? res.spectrum || [] : [];
const padL = 44, padR = 14, padT = 14, padB = 34;
ctx.font = "12px Figtree, sans-serif"; ctx.fillStyle = "#5E5A51";
if (!pts.length){ ctx.fillText("Run a gene to fill the map.", padL, H/2); return; }
const xs = pts.map(p => p.c), ys = pts.map(p => p.d);
const xMax = Math.max(...xs) * 1.04 || 1, yAbs = Math.max(0.05, ...ys.map(Math.abs)) * 1.1;
const X = v => padL + (v / xMax) * (W - padL - padR), Y = v => padT + (1 - (v + yAbs) / (2*yAbs)) * (H - padT - padB);
ctx.strokeStyle = "#E6DFD2"; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(padL, Y(0)); ctx.lineTo(W - padR, Y(0)); ctx.stroke();
ctx.beginPath(); ctx.moveTo(padL, padT); ctx.lineTo(padL, H - padB); ctx.stroke();
ctx.fillText("Activity before the change →", padL, H - 10);
ctx.save(); ctx.translate(14, padT + 70); ctx.rotate(-Math.PI/2); ctx.fillText("Change →", -40, 0); ctx.restore();
ctx.fillText(`${ARROW_UP} up`, padL + 6, padT + 12); ctx.fillText(`${ARROW_DOWN} down`, padL + 6, H - padB - 6);
const thr = yAbs / 1.1 * 0.12;
for (const p of pts){
const x = X(p.c), y = Y(p.d), up = p.d > thr, dn = p.d < -thr;
ctx.beginPath();
if (up){ ctx.fillStyle = "#3F6B4C"; ctx.moveTo(x, y-4); ctx.lineTo(x+4, y+3); ctx.lineTo(x-4, y+3); ctx.closePath(); }
else if (dn){ ctx.fillStyle = "#8A4F2A"; ctx.moveTo(x, y+4); ctx.lineTo(x+4, y-3); ctx.lineTo(x-4, y-3); ctx.closePath(); }
else { ctx.fillStyle = "#C9C2B3"; ctx.arc(x, y, 2.4, 0, Math.PI*2); }
ctx.fill();
mapPts.push({x, y, p});
}
}
function mapHover(ev){
const r = $("#map").getBoundingClientRect(), mx = ev.clientX - r.left, my = ev.clientY - r.top;
let best = null, bd = 144;
for (const m of mapPts){ const d = (m.x-mx)**2 + (m.y-my)**2; if (d < bd){ bd = d; best = m; } }
const tip = $("#tip");
if (!best){ tip.hidden = true; return; }
tip.hidden = false;
tip.textContent = `${best.p.g}${best.p.r ? " · " + best.p.r : ""} · ${best.p.d > 0 ? "+" : ""}${best.p.d}`;
tip.style.left = Math.min(best.x + 10, r.width - tip.offsetWidth - 4) + "px"; tip.style.top = (best.y - 34) + "px";
}
/* ---------- Render ---------- */
function render(res, animate){
state.last = res;
closeSys();
$("#story").innerHTML = storyHTML(res);
$("#cellCaption").textContent = res.cell_line === "custom" ? "Your uploaded cells" : (LINES[res.cell_line] || {name: res.cell_line}).name;
paintCell("", res, animate);
if (animate && !motionOff() && !(res.missing_priors && res.missing_priors.length)){
const cp = document.querySelector(".cellpanel");
cp.animate && cp.animate([{backgroundColor:"#EFF7EC"},{backgroundColor:"#DFEDDD"}], {duration:600, easing:"ease-out"});
}
paintSysList(res);
paintGenes(res);
paintResearcher(res);
drawMap();
}
function showError(msg){
$("#story").innerHTML = `<p class="err">${esc(msg)}</p>`;
}
function askParentToShow(el, smooth){
// Embedded on udgamlabs.com: the frame has no scrollbar of its own, so the page around it does the scrolling.
const y = window.scrollY + el.getBoundingClientRect().top - 12;
window.parent.postMessage({type: "biocell-reveal", y: Math.round(y), smooth: !!smooth}, "*");
}
function revealResult(){
const beh = motionOff() ? "auto" : "smooth", vh = window.innerHeight;
const story = $("#story"), head = story.querySelector("h2") || story, cell = document.querySelector(".cellpanel");
if (window.parent !== window){
const first = window.innerWidth > 900 && cell.getBoundingClientRect().top < story.getBoundingClientRect().top ? cell : story;
askParentToShow(first, beh === "smooth"); return;
}
const sr = story.getBoundingClientRect(), hr = head.getBoundingClientRect(), cr = cell.getBoundingClientRect();
if (window.innerWidth > 900){
const top = Math.min(sr.top, cr.top), bottom = Math.max(hr.bottom, cr.bottom);
if (top >= 0 && bottom <= vh) return;
window.scrollTo({top: window.scrollY + top - 12, behavior: beh});
} else {
if (sr.top >= 0 && hr.bottom <= vh) return;
window.scrollTo({top: window.scrollY + sr.top - 12, behavior: beh});
}
}
async function run(genes, reveal){
state.genes = genes;
const my = ++runToken;
try {
const res = await getResult(state.line, genes, state.mod);
if (my !== runToken) return;
render(res, true);
if (reveal) revealResult();
} catch(e){ if (my === runToken) showError(e.message); }
}
/* ---------- Mix two ---------- */
function mixSummary(a, b, ab){
const by = r => Object.fromEntries(r.systems.map(s => [s.id, s.mean_delta]));
const A = by(a), B = by(b), T = by(ab);
let sAdd = 0, sTog = 0;
for (const id of Object.keys(SYS)){ sAdd += Math.abs((A[id]||0) + (B[id]||0)); sTog += Math.abs(T[id]||0); }
const R = sAdd > 0 ? sTog / sAdd : 0;
let line;
if (sAdd < 0.05) line = "Neither gene moves the cell's genes much here.";
else if (R > 1.25) line = "Together they move the cell's genes more than the two added up.";
else if (R < 0.75) line = "Together they move the cell's genes less than the two added up.";
else line = "Together they move the cell's genes about the same as the two added up.";
return {R, line, sAdd, sTog};
}
function buildMixCells(a, b){
const col = (p, lab) => `<div class="mcol"><div class="mlabel">${lab}</div><div class="msize" id="${p}size"> </div><ul class="mlist" id="${p}list"></ul></div>`;
$("#mixCells").innerHTML = col("ma-", `<span class="sym">${esc(a)}</span> alone`) + col("mb-", `<span class="sym">${esc(b)}</span> alone`) + col("mt-", "Together");
}
async function runMix(a, b){
const my = ++runToken;
state.genes = [a, b];
buildMixCells(a, b);
$("#mixLine").innerHTML = " ";
try {
const [ra, rb, rt] = await Promise.all([getResult(state.line,[a],state.mod), getResult(state.line,[b],state.mod), getResult(state.line,[a,b],state.mod)]);
if (my !== runToken) return;
state.mixRes = {ra, rb, rt};
render(rt, true);
const miss = rt.missing_priors && rt.missing_priors.length;
[["ma-",ra],["mb-",rb],["mt-",rt]].forEach(([p,r]) => { paintMini(p, r); });
if (miss){ $("#mixLine").textContent = "The model has no knowledge of " + rt.missing_priors.join(" and ") + ", so it cannot predict this mix."; $("#surprises tbody").innerHTML = ""; $("#mixR").textContent = ""; return; }
const m = mixSummary(ra, rb, rt);
$("#mixLine").textContent = m.line;
$("#mixR").textContent = `R = Σ|together| ÷ Σ|added| = ${m.sTog.toFixed(4)} ÷ ${m.sAdd.toFixed(4)} = ${m.R.toFixed(2)}`;
const syn = (rt.synergy && rt.synergy.top_synergy_genes) || [];
const f = v => `${v > 0 ? ARROW_UP + " +" : ARROW_DOWN + " "}${v.toFixed(3)}`;
$("#surprises tbody").innerHTML = syn.map(g => `<tr><td><span class="sym">${esc(g.gene)}</span> <span class="hint">${esc(g.role||"")}</span></td><td>${f(g.additive_delta)}</td><td><b>${f(g.predicted_delta)}</b></td></tr>`).join("");
} catch(e){ if (my === runToken) showError(e.message); }
}
function paintMini(p, r){
const size = document.getElementById(p+"size"), ul = document.getElementById(p+"list");
if (!size || !ul) return;
if (r.missing_priors && r.missing_priors.length){ size.textContent = "No knowledge of this gene"; ul.innerHTML = ""; return; }
size.textContent = `The model predicts ${sizeWords(r.effect_rms)}`;
const moved = r.systems.filter(reacts).sort((x, y) => Math.abs(y.z_score) - Math.abs(x.z_score));
const show = moved.slice(0, 4);
ul.innerHTML = show.map(s => { const d = dirOf(s); return `<li><span class="badge ${d}">${moveHTML(d, Math.abs(s.z_score))}</span><span>${SYS[s.id]}</span></li>`; }).join("")
+ (moved.length > 4 ? `<li class="more">and ${moved.length - 4} more</li>` : "")
+ (moved.length ? "" : `<li class="none">No group of genes moves clearly.</li>`);
}
function setMix(on){
state.mix = on;
document.body.classList.toggle("mixing", on);
$("#mixBtn").setAttribute("aria-pressed", String(on));
$("#mixBtn2").setAttribute("aria-pressed", String(on));
$("#mix").hidden = !on;
$("#cardsHint").textContent = on ? "Pick two cards to mix" : "Tap a card to run it";
if (on){
state.sel = ["CEBPE","CNN1"]; setLine("k562"); setMod("activate"); mixHintUpdate();
syncCards(); runMix("CEBPE","CNN1");
} else {
state.sel = []; syncCards(); mixHintUpdate();
const g = (state.genes || []).slice(0,1); if (g.length) run(g);
}
}
function mixHintUpdate(){
const n = state.sel.length;
$("#mixHint").textContent = n === 0 ? "Pick two cards, or find genes in the search box." : n === 1 ? "Pick one more." : `Mixing ${state.sel[0]} and ${state.sel[1]}.`;
}
function addToMix(g){
if (state.sel.includes(g)) state.sel = state.sel.filter(x => x !== g);
else { state.sel.push(g); if (state.sel.length > 2) state.sel.shift(); }
syncCards();
mixHintUpdate();
if (state.sel.length === 2) runMix(state.sel[0], state.sel[1]);
}
/* ---------- Controls ---------- */
function buildCards(){
$("#cards").innerHTML = CARDS.map((c, i) => `<button type="button" class="card" data-i="${i}" aria-pressed="false">
<span class="check" aria-hidden="true"><svg width="12" height="12" viewBox="0 0 12 12"><path d="M2.5 6.2 5 8.6 9.6 3.6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
<span class="cname">${esc(c.name)}</span><span class="cline">${esc(c.text)}</span>
<span class="cfoot"><span class="csym sym">${c.g} · ${esc(LINES[c.line].name.split(" (")[0].replace(" cell line","").replace(" line",""))}</span><span class="cact">${c.mod === "activate" ? "Switch it on" : "Switch it off"}</span></span></button>`).join("");
}
function syncCards(){
document.querySelectorAll(".card").forEach(el => {
const c = CARDS[+el.dataset.i];
const on = state.mix ? state.sel.includes(c.g) : (state.genes && state.genes.length === 1 && state.genes[0] === c.g && state.line === c.line && state.mod === c.mod);
el.setAttribute("aria-pressed", String(!!on));
});
}
function buildLines(){
$("#lines").innerHTML = Object.entries(LINES).map(([k,v]) => `<button type="button" class="pill" data-line="${k}" aria-pressed="${k === state.line}" aria-label="${esc(v.name)}" title="${esc(v.name)}">${esc(v.pill)}</button>`).join("");
}
function setLine(l){ state.line = l; document.querySelectorAll("[data-line]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.line === l))); }
function setMod(m){ state.mod = m; document.querySelectorAll("[data-mod]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.mod === m))); }
function rerun(){
if (state.mix){ if (state.sel.length === 2) runMix(state.sel[0], state.sel[1]); }
else if (state.genes) run(state.genes);
syncCards();
}
function setMode(m){
state.mode = m; document.body.dataset.mode = m;
$("#modeSimple").setAttribute("aria-pressed", String(m === "simple"));
$("#modeResearch").setAttribute("aria-pressed", String(m === "researcher"));
paintGenes(state.last);
if (state.last){ paintCell("", state.last, false); paintSysList(state.last); }
if (state.mix && state.mixRes){ paintMini("ma-", state.mixRes.ra); paintMini("mb-", state.mixRes.rb); paintMini("mt-", state.mixRes.rt); }
}
/* search */
let qTimer = null, qItems = [], qIdx = -1;
function showResults(items){
qItems = items; qIdx = -1;
const ul = $("#qres");
if (!items.length){ ul.hidden = true; $("#q").setAttribute("aria-expanded","false"); return; }
ul.innerHTML = items.map((it, i) => `<li role="option" id="qo${i}" data-g="${esc(it.gene)}" aria-selected="false"><span class="sym">${esc(it.gene)}</span><span class="role">${esc(it.role || "")}</span></li>`).join("");
ul.hidden = false; $("#q").setAttribute("aria-expanded","true");
}
function pickGene(g){
g = String(g || "").trim().toUpperCase(); if (!g) return;
showResults([]); $("#q").value = "";
if (state.mix) addToMix(g); else { syncCards(); run([g], true); syncCards(); }
}
/* ---------- Wire up ---------- */
function init(){
$("#cell").innerHTML = cellSVG("", false);
buildCards(); buildLines(); buildSysList(); paintGenes(null); paintResearcher(null);
$("#cards").addEventListener("click", e => {
const el = e.target.closest(".card"); if (!el) return;
const c = CARDS[+el.dataset.i];
if (state.mix){ addToMix(c.g); return; }
setLine(c.line); setMod(c.mod); state.genes = [c.g]; syncCards(); run([c.g], true);
});
$("#lines").addEventListener("click", e => { const b = e.target.closest("[data-line]"); if (!b) return; setLine(b.dataset.line); rerun(); });
document.querySelectorAll("[data-mod]").forEach(b => b.addEventListener("click", () => { setMod(b.dataset.mod); rerun(); }));
$("#mixBtn").addEventListener("click", () => setMix(!state.mix));
$("#mixBtn2").addEventListener("click", () => {
setMix(!state.mix);
if (state.mix){ if (window.parent !== window) askParentToShow($("#mix"), !motionOff()); else $("#mix").scrollIntoView({behavior: motionOff() ? "auto" : "smooth", block: "nearest"}); }
});
$("#modeSimple").addEventListener("click", () => setMode("simple"));
$("#modeResearch").addEventListener("click", () => setMode("researcher"));
$("#pauseBtn").addEventListener("click", () => {
state.paused = !state.paused; document.body.classList.toggle("calm", state.paused);
$("#pauseBtn").setAttribute("aria-pressed", String(state.paused));
$("#pauseBtn").textContent = state.paused ? "Play motion" : "Pause motion";
});
if (rmq.matches){ $("#pauseBtn").hidden = true; }
const how = $("#how");
$("#howBtn").addEventListener("click", () => how.showModal());
$("#howClose").addEventListener("click", () => how.close());
how.addEventListener("click", e => { if (e.target === how) how.close(); });
// systems: cell parts and list rows
const sysAct = e => {
const el = e.target.closest("[data-sys]"); if (!el) return;
if (e.type === "keydown" && e.key !== "Enter" && e.key !== " ") return;
if (e.type === "keydown") e.preventDefault();
openSys(el.dataset.sys, el);
};
$("#cell").addEventListener("click", sysAct); $("#cell").addEventListener("keydown", sysAct);
$("#syslist").addEventListener("click", sysAct);
$("#scClose").addEventListener("click", closeSys);
document.addEventListener("keydown", e => { if (e.key === "Escape" && !$("#syscard").hidden) closeSys(); });
// search
const q = $("#q");
q.addEventListener("input", () => {
clearTimeout(qTimer);
const v = q.value.trim(); if (!v){ showResults([]); return; }
qTimer = setTimeout(async () => {
try { const r = await fetch("/api/search?q=" + encodeURIComponent(v)); if (q.value.trim() === v) showResults(await r.json()); } catch(_){}
}, 120);
});
q.addEventListener("keydown", e => {
if (e.key === "ArrowDown" || e.key === "ArrowUp"){
if (!qItems.length) return; e.preventDefault();
qIdx = (qIdx + (e.key === "ArrowDown" ? 1 : -1) + qItems.length) % qItems.length;
document.querySelectorAll("#qres li").forEach((li, i) => li.setAttribute("aria-selected", String(i === qIdx)));
q.setAttribute("aria-activedescendant", "qo" + qIdx);
} else if (e.key === "Enter"){
e.preventDefault(); pickGene(qIdx >= 0 ? qItems[qIdx].gene : q.value);
} else if (e.key === "Escape"){ showResults([]); }
});
$("#qres").addEventListener("mousedown", e => { const li = e.target.closest("li"); if (li){ e.preventDefault(); pickGene(li.dataset.g); } });
q.addEventListener("blur", () => setTimeout(() => showResults([]), 150));
// researcher
$("#jsonBtn").addEventListener("click", () => {
if (!state.last) return;
const blob = new Blob([JSON.stringify(state.last, null, 2)], {type:"application/json"});
const a = document.createElement("a"); a.href = URL.createObjectURL(blob);
a.download = `{{NAME_SLUG}}_${state.last.cell_line}_${state.last.genes.join("_")}_${state.last.modality}.json`; a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 2000);
});
$("#uploadBtn").addEventListener("click", async () => {
const f = $("#csvFile").files[0], st = $("#upStatus");
if (!f){ st.textContent = "Choose a CSV file first."; return; }
const genes = (state.mix && state.sel.length === 2) ? state.sel : (state.genes || ["PSMA3"]);
st.textContent = "Running…";
try {
const text = await f.text();
const r = await fetch("/api/perturb_csv", {method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({csv:text, genes:genes.join(","), modality:state.mod, label:f.name})});
const j = await r.json(); if (!r.ok) throw new Error(j.error || "Upload failed");
st.textContent = `Done: ${j.custom_upload.matched_hvgs} of 3,000 genes matched.`;
++runToken; render(j, true);
document.getElementById("story").scrollIntoView({behavior: motionOff() ? "auto" : "smooth", block:"start"});
} catch(e){ st.textContent = e.message; }
});
["#csvBtn","#csvLink2"].forEach(sel => $(sel).addEventListener("click", e => { if ($(sel).getAttribute("href") === "#"){ e.preventDefault(); $("#jsonBtn").click(); } }));
$("#mapBox").addEventListener("toggle", drawMap);
$("#map").addEventListener("mousemove", mapHover);
$("#map").addEventListener("mouseleave", () => $("#tip").hidden = true);
window.addEventListener("resize", () => { clearTimeout(window.__rz); window.__rz = setTimeout(drawMap, 150); });
// Warm the first card so the first tap answers at once, then the rest.
getResult("rpe1",["PSMA3"],"knockdown").then(res => {
const ex = document.getElementById("example");
if (ex && !state.last) ex.innerHTML = `<span class="exlabel">Example result, real model output</span>` + storyHTML(res);
}).catch(()=>{});
setTimeout(() => CARDS.slice(1).forEach(c => getResult(c.line,[c.g],c.mod).catch(()=>{})), 800);
// Optional start state from the address: #try=line:GENE[,GENE2]:off|on, #play=mix, #mode=researcher (combine with &)
const h = decodeURIComponent(location.hash.slice(1));
if (/\bmode=researcher\b/.test(h)) setMode("researcher");
if (/\bplay=mix\b/.test(h)) setMix(true);
const m = h.match(/try=([a-z0-9]+):([A-Za-z0-9,\-]+):(off|on)/);
if (m && !state.mix){ setLine(m[1]); setMod(m[3] === "on" ? "activate" : "knockdown"); const g = m[2].toUpperCase().split(",").slice(0,2); state.genes = g; syncCards(); run(g); }
}
init();
</script>
<script>
/* When udgamlabs.com embeds this page, tell it our height so the frame fits with no inner scrollbar. */
(function(){
if (window.parent === window) return;
var last = 0;
function send(){ var h = document.documentElement.scrollHeight; if (Math.abs(h - last) > 2){ last = h; window.parent.postMessage({type: "biocell-height", h: h}, "*"); } }
window.addEventListener("load", send);
if (window.ResizeObserver) new ResizeObserver(send).observe(document.body);
setInterval(send, 1500);
})();
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{MODEL_NAME}}: switch a gene, watch the cell</title>
<meta name="description" content="{{MODEL_NAME}} by Udgam Labs predicts how a human cell's genes respond when one or two genes are switched off or on.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&family=Newsreader:opsz,wght@6..72,500&display=swap" rel="stylesheet">
<style>
:root{
--paper:#FAF6EE; --ink:#1C1B18; --ink2:#5E5A51; --line:#E6DFD2; --white:#FFFFFF;
--sage-deep:#3F6B4C; --sage:#9CC2A1; --sage-light:#C5DDC7; --sage-tint:#DFEDDD;
--peach-deep:#8A4F2A; --peach:#F5C3A5; --peach-light:#F8D6C1; --peach-tint:#FBE4D6;
--lift:0 8px 0 rgb(28 27 24 / 0.06);
--serif:"Newsreader",Georgia,serif; --sans:"Figtree",system-ui,-apple-system,"Segoe UI",sans-serif;
--mono:"IBM Plex Mono",ui-monospace,Menlo,monospace;
--sym:var(--sans);
color-scheme:light;
}
body[data-mode="researcher"]{--sym:var(--mono)}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--paper);color:var(--ink);font:400 16px/1.5 var(--sans);}
a{color:var(--ink);text-underline-offset:3px}
button{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--ink);outline-offset:3px}
.wrap{max-width:1200px;margin:0 auto;padding:0 28px}
.sym{font-family:var(--sym);font-weight:600;letter-spacing:.01em}
.mono{font-family:var(--mono)}
.r-only{display:none}
body[data-mode="researcher"] .r-only{display:revert}
body[data-mode="researcher"] .s-only{display:none}
.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
/* Header */
header.top{display:flex;align-items:center;gap:18px;padding:20px 0 14px}
.lockup{height:22px;width:auto;color:var(--ink);display:block}
.divider{width:1px;height:26px;background:var(--line)}
.mname{font:500 24px/1 var(--serif);letter-spacing:-.01em}
.spacer{flex:1}
.linkbtn{background:none;border:0;padding:10px 6px;cursor:pointer;font-weight:600;text-decoration:underline;text-underline-offset:4px;text-decoration-thickness:1px}
.tabs{display:inline-flex;background:var(--white);border:1px solid var(--line);border-radius:999px;padding:4px;box-shadow:var(--lift)}
.tabs button{border:0;background:none;border-radius:999px;padding:8px 16px;cursor:pointer;font-weight:600;font-size:14px;color:var(--ink2)}
.tabs button[aria-pressed="true"]{background:var(--sage-tint);color:var(--ink)}
/* Hero */
.hero{padding:10px 0 14px;display:flex;align-items:flex-end;justify-content:space-between;gap:24px;flex-wrap:wrap}
.hero h1{font:500 clamp(32px,4.2vw,50px)/1.06 var(--serif);letter-spacing:-.02em;margin:0}
.hero p.lede{margin:8px 0 0;font-size:18px;color:var(--ink2);max-width:none}
.fixed-note{margin:10px 0 0;font-size:14px;color:var(--ink2)}
.fixed-note a{font-weight:600;color:var(--ink);margin-left:6px}
/* Gene cards */
.cards-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin:30px 0 12px}
.cards-head h2,.sec-h{font:500 22px/1.2 var(--serif);margin:0}
.hint{font-size:14px;color:var(--ink2)}
.cards{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
.card{position:relative;text-align:left;background:var(--white);border:2px solid transparent;border-radius:28px;box-shadow:var(--lift);padding:18px 18px 16px;cursor:pointer;display:flex;flex-direction:column;gap:6px;min-height:138px;transition:transform .18s ease,border-color .18s ease}
.card:hover{transform:translateY(-2px)}
.card[aria-pressed="true"]{border-color:var(--ink)}
.card .cname{font:500 20px/1.15 var(--serif);letter-spacing:-.005em}
.card .cline{font-size:14px;color:var(--ink2);line-height:1.35}
.card .cfoot{margin-top:auto;display:flex;align-items:center;justify-content:space-between;gap:8px;padding-top:8px}
.card .csym{font-size:12px;color:var(--ink2)}
.card .cact{font-size:13px;font-weight:600;color:var(--sage-deep)}
.card .cact{border-radius:999px;padding:6px 12px;margin:-6px 0}
/* the one ink pill marks the card the cell is showing; before any run it marks the first card as the place to start */
.card[aria-pressed="true"] .cact,body:not(.ran) .cards:not(:has(.card[aria-pressed="true"])) .card:first-child .cact{background:var(--ink);color:var(--paper)}
.card .check{position:absolute;top:14px;right:14px;width:24px;height:24px;border-radius:999px;border:2px solid var(--ink);display:none;align-items:center;justify-content:center;font-size:13px;font-weight:700}
body.mixing .card .check{display:flex}
body.mixing .card[aria-pressed="true"] .check{background:var(--ink);color:var(--paper)}
body.mixing .card .cact{visibility:hidden}
body.mixing .card .cname{padding-right:30px}
/* Controls */
.controls{display:flex;flex-wrap:wrap;align-items:center;gap:10px 12px;margin:0;padding:14px 16px;background:var(--white);border-radius:28px;box-shadow:var(--lift)}
.group{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.glabel{font-size:13px;color:var(--ink2);font-weight:600;margin-right:2px}
.pill{border:1px solid var(--line);background:var(--paper);border-radius:999px;padding:8px 14px;font-size:14px;font-weight:600;cursor:pointer;white-space:nowrap;min-height:38px}
.pill[aria-pressed="true"]{background:var(--sage-tint);border-color:var(--sage-deep)}
.pill.mixbtn[aria-pressed="true"]{background:var(--ink);color:var(--paper);border-color:var(--ink)}
.search{position:relative;flex:1;min-width:220px}
.search input{width:100%;border:1px solid var(--line);background:var(--paper);border-radius:999px;padding:10px 16px;font:500 15px var(--sans);color:var(--ink);min-height:40px}
.search input::placeholder{color:#8B8678}
.results{position:absolute;z-index:20;left:0;right:0;top:calc(100% + 6px);background:var(--white);border:1px solid var(--line);border-radius:22px;box-shadow:var(--lift);padding:6px;margin:0;list-style:none;max-height:320px;overflow:auto}
.results[hidden]{display:none}
.results li{padding:9px 12px;border-radius:14px;cursor:pointer;display:flex;gap:10px;align-items:baseline}
.results li[aria-selected="true"],.results li:hover{background:var(--sage-tint)}
.results .role{font-size:13px;color:var(--ink2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
/* Mix panel */
.mix{margin:0;background:var(--white);border-radius:28px;box-shadow:var(--lift);padding:20px 22px}
.mix[hidden]{display:none}
.mix-top{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:baseline}
.mix-cells{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px;margin-top:14px}
.mini{background:var(--sage-tint);border-radius:24px;padding:8px 6px 10px;text-align:center}
.mini svg{width:100%;height:auto;display:block}
.mini .cst .stt{display:none}