Spaces:
Sleeping
Learning flywheel v1: Directed-Evolution active-learning loop (DBTL)
Browse filesThe first durable-moat feature: TuringDNA learns from a researcher's wet-lab
results to design a smarter next round, on data no competitor has. Scoped to
Directed Evolution (the only tool with quantitative per-variant fitness).
Surrogate (dee/core/active_learning.py): additive ridge over single-site
effects with the ESM-2 ΔLL as the prior — y ≈ b + w_prior·ΣΔLL + Σβ_m. Fit
closed-form in numpy (no sklearn/scipy needed) on the user's measured variants;
β shrinks unseen mutations to the prior; an exploration bonus rewards
under-tested positions. Plugs straight into the existing additive SA: round 2
re-runs evolve() with per-mutation score = w_prior·ΔLL + β + κ·uncertainty.
Numpy-tested: measured data overrides a misleading prior (Spearman 0.77), 0
labels → pure prior, <4 → honest fallback.
Backend: migration 0007_de_outcomes.sql (USER RUNS IT); auth.py
save/list/cleanup_de_outcomes; /api/de/outcomes (POST/GET) + /api/de/round2
(score WT → fit surrogate → evolve adjusted pool → assemble like /api/run).
Sign-in gated; settings clamped (model/host whitelist; can't load arbitrary HF
ids); 500-aa sync cap; worked/partial/failed → 1.0/0.5/0.0. Run result now
carries library_id (deterministic save) so outcomes persist.
Frontend: a "Learn from results" panel on the DE results — log measured values
per variant, "Propose round 2 →" renders a data-conditioned library with a
"Round 2 · learned from N results" banner; the panel re-populates so you can
iterate to round 3. iOS-safe input (16px, no auto-zoom).
Verified: surrogate math (numpy); endpoints (gates, validation, settings
clamps, measurement mapping) via test-client; full UI loop in preview (request
shape, render, banner, re-iterate); zero console errors. ESM-dependent round-2
compute runs live (model can't download in the sandbox) and reuses the proven
round-1 path. Bump cache-busters to v=20260605-flywheel.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- dee/auth.py +129 -2
- dee/core/active_learning.py +176 -0
- dee/server.py +168 -0
- dee/static/app.css +33 -0
- dee/static/app.js +103 -0
- dee/static/index.html +25 -2
- supabase/migrations/0007_de_outcomes.sql +54 -0
|
@@ -573,12 +573,15 @@ def save_library_async(
|
|
| 573 |
host_organism: Optional[str],
|
| 574 |
n_variants: int,
|
| 575 |
top_fitness: Optional[float],
|
|
|
|
| 576 |
) -> None:
|
| 577 |
"""Fire-and-forget save of a generated library to Supabase Storage.
|
| 578 |
|
| 579 |
No-op for anonymous users — they have no user_id to bind to. Also
|
| 580 |
no-op if Supabase isn't configured. Spawns a daemon thread so the
|
| 581 |
-
/api/run response isn't held up by the upload.
|
|
|
|
|
|
|
| 582 |
"""
|
| 583 |
if not user_id:
|
| 584 |
return # anonymous run; nothing to attribute
|
|
@@ -598,6 +601,7 @@ def save_library_async(
|
|
| 598 |
"host_organism": host_organism,
|
| 599 |
"n_variants": n_variants,
|
| 600 |
"top_fitness": top_fitness,
|
|
|
|
| 601 |
},
|
| 602 |
daemon=True,
|
| 603 |
).start()
|
|
@@ -614,6 +618,7 @@ def _do_save_library(
|
|
| 614 |
host_organism: Optional[str],
|
| 615 |
n_variants: int,
|
| 616 |
top_fitness: Optional[float],
|
|
|
|
| 617 |
) -> None:
|
| 618 |
"""Worker for save_library_async. Two-step: upload CSV to Storage,
|
| 619 |
then insert metadata row. Both steps log on failure but don't raise
|
|
@@ -635,7 +640,7 @@ def _do_save_library(
|
|
| 635 |
return
|
| 636 |
|
| 637 |
csv_size = len(csv_bytes)
|
| 638 |
-
library_id = _uuid.uuid4().hex
|
| 639 |
# Path convention: <user_id>/<library_id>.csv
|
| 640 |
# The user_id prefix lets the storage RLS policy do a simple
|
| 641 |
# first-folder-segment check to gate access.
|
|
@@ -1313,6 +1318,128 @@ def _do_cleanup_expired_primer_analyses(user_id: str) -> None:
|
|
| 1313 |
logger.warning("primer_analyses cleanup failed for %s: %s", user_id, exc)
|
| 1314 |
|
| 1315 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
# ─── Directed-Evolution libraries: per-user list + signed download ────
|
| 1317 |
# DE runs already persist to public.libraries + the `libraries` Storage
|
| 1318 |
# bucket (see _do_save_library). These surface them in the unified hub —
|
|
|
|
| 573 |
host_organism: Optional[str],
|
| 574 |
n_variants: int,
|
| 575 |
top_fitness: Optional[float],
|
| 576 |
+
library_id: Optional[str] = None,
|
| 577 |
) -> None:
|
| 578 |
"""Fire-and-forget save of a generated library to Supabase Storage.
|
| 579 |
|
| 580 |
No-op for anonymous users — they have no user_id to bind to. Also
|
| 581 |
no-op if Supabase isn't configured. Spawns a daemon thread so the
|
| 582 |
+
/api/run response isn't held up by the upload. ``library_id`` lets the
|
| 583 |
+
caller pre-assign the id (so it can be returned to the client for the
|
| 584 |
+
learning-flywheel outcome logging); a fresh hex id is minted if omitted.
|
| 585 |
"""
|
| 586 |
if not user_id:
|
| 587 |
return # anonymous run; nothing to attribute
|
|
|
|
| 601 |
"host_organism": host_organism,
|
| 602 |
"n_variants": n_variants,
|
| 603 |
"top_fitness": top_fitness,
|
| 604 |
+
"library_id": library_id,
|
| 605 |
},
|
| 606 |
daemon=True,
|
| 607 |
).start()
|
|
|
|
| 618 |
host_organism: Optional[str],
|
| 619 |
n_variants: int,
|
| 620 |
top_fitness: Optional[float],
|
| 621 |
+
library_id: Optional[str] = None,
|
| 622 |
) -> None:
|
| 623 |
"""Worker for save_library_async. Two-step: upload CSV to Storage,
|
| 624 |
then insert metadata row. Both steps log on failure but don't raise
|
|
|
|
| 640 |
return
|
| 641 |
|
| 642 |
csv_size = len(csv_bytes)
|
| 643 |
+
library_id = library_id or _uuid.uuid4().hex
|
| 644 |
# Path convention: <user_id>/<library_id>.csv
|
| 645 |
# The user_id prefix lets the storage RLS policy do a simple
|
| 646 |
# first-folder-segment check to gate access.
|
|
|
|
| 1318 |
logger.warning("primer_analyses cleanup failed for %s: %s", user_id, exc)
|
| 1319 |
|
| 1320 |
|
| 1321 |
+
# ─── DE outcomes: per-library wet-lab results (the learning flywheel) ──
|
| 1322 |
+
# One row per measured variant; the surrogate fits on these for round 2.
|
| 1323 |
+
# Table: public.de_outcomes (migration 0007).
|
| 1324 |
+
|
| 1325 |
+
_DE_OUTCOMES_MAX = 2000 # max measured variants stored per library
|
| 1326 |
+
_UUIDISH = r"^[0-9a-fA-F-]{32,36}$" # accept 32-hex or dashed uuid (libraries.id form)
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
def save_de_outcomes(user_id: Optional[str], library_id: str, rows: list) -> Dict[str, Any]:
|
| 1330 |
+
"""Replace this user's logged outcomes for a library with `rows`
|
| 1331 |
+
(each {mutations, measured_value, outcome}). Returns {ok, n} or error."""
|
| 1332 |
+
import re as _re
|
| 1333 |
+
if not user_id:
|
| 1334 |
+
return {"ok": False, "error": "Sign in to log results."}
|
| 1335 |
+
if not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
|
| 1336 |
+
return {"ok": False, "error": "Saving isn't configured on this server."}
|
| 1337 |
+
if not _re.match(_UUIDISH, library_id or ""):
|
| 1338 |
+
return {"ok": False, "error": "Bad library id."}
|
| 1339 |
+
rows = (rows or [])[:_DE_OUTCOMES_MAX]
|
| 1340 |
+
from datetime import datetime, timezone, timedelta
|
| 1341 |
+
expires_at = (None if has_pro_plan(user_id) else
|
| 1342 |
+
(datetime.now(timezone.utc) + timedelta(days=FREE_LIBRARY_TTL_DAYS)).isoformat())
|
| 1343 |
+
payload = []
|
| 1344 |
+
for r in rows:
|
| 1345 |
+
if not isinstance(r, dict):
|
| 1346 |
+
continue
|
| 1347 |
+
outcome = str(r.get("outcome", "measured") or "measured")[:16]
|
| 1348 |
+
mv = r.get("measured_value")
|
| 1349 |
+
try:
|
| 1350 |
+
mv = float(mv) if mv is not None and mv != "" else None
|
| 1351 |
+
except (TypeError, ValueError):
|
| 1352 |
+
mv = None
|
| 1353 |
+
payload.append({
|
| 1354 |
+
"user_id": user_id,
|
| 1355 |
+
"library_id": library_id,
|
| 1356 |
+
"mutations": str(r.get("mutations", "") or "")[:300],
|
| 1357 |
+
"measured_value": mv,
|
| 1358 |
+
"outcome": outcome,
|
| 1359 |
+
"expires_at": expires_at,
|
| 1360 |
+
})
|
| 1361 |
+
import urllib.request
|
| 1362 |
+
import urllib.error
|
| 1363 |
+
# Replace semantics: clear this library's prior outcomes, then insert.
|
| 1364 |
+
try:
|
| 1365 |
+
url = (f"{SUPABASE_URL}/rest/v1/de_outcomes"
|
| 1366 |
+
f"?user_id=eq.{user_id}&library_id=eq.{library_id}")
|
| 1367 |
+
req = urllib.request.Request(url, method="DELETE",
|
| 1368 |
+
headers=_supabase_headers({"Prefer": "return=minimal"}))
|
| 1369 |
+
with urllib.request.urlopen(req, timeout=6.0):
|
| 1370 |
+
pass
|
| 1371 |
+
except Exception as exc: # noqa: BLE001
|
| 1372 |
+
logger.warning("de_outcomes clear failed: %s", exc)
|
| 1373 |
+
if not payload:
|
| 1374 |
+
return {"ok": True, "n": 0}
|
| 1375 |
+
try:
|
| 1376 |
+
req = urllib.request.Request(
|
| 1377 |
+
f"{SUPABASE_URL}/rest/v1/de_outcomes",
|
| 1378 |
+
data=json.dumps(payload).encode("utf-8"),
|
| 1379 |
+
method="POST",
|
| 1380 |
+
headers=_supabase_headers({"Content-Type": "application/json",
|
| 1381 |
+
"Prefer": "return=minimal"}),
|
| 1382 |
+
)
|
| 1383 |
+
with urllib.request.urlopen(req, timeout=8.0):
|
| 1384 |
+
return {"ok": True, "n": len(payload)}
|
| 1385 |
+
except urllib.error.HTTPError as exc:
|
| 1386 |
+
body = ""
|
| 1387 |
+
try:
|
| 1388 |
+
body = exc.read().decode("utf-8")[:200]
|
| 1389 |
+
except Exception: # noqa: BLE001
|
| 1390 |
+
pass
|
| 1391 |
+
logger.warning("de_outcomes insert HTTP %s: %s", exc.code, body)
|
| 1392 |
+
if exc.code in (404, 406) or "PGRST" in body:
|
| 1393 |
+
return {"ok": False, "error": "Result logging isn't enabled yet (database migration pending)."}
|
| 1394 |
+
return {"ok": False, "error": "Couldn't save your results. Please try again."}
|
| 1395 |
+
except Exception as exc: # noqa: BLE001
|
| 1396 |
+
logger.warning("de_outcomes insert failed: %s", exc)
|
| 1397 |
+
return {"ok": False, "error": "Couldn't save your results. Please try again."}
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
def list_de_outcomes(user_id: Optional[str], library_id: str) -> list:
|
| 1401 |
+
"""This user's logged outcomes for one library (newest first). [] on error."""
|
| 1402 |
+
import re as _re
|
| 1403 |
+
if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
|
| 1404 |
+
return []
|
| 1405 |
+
if not _re.match(_UUIDISH, library_id or ""):
|
| 1406 |
+
return []
|
| 1407 |
+
import urllib.request
|
| 1408 |
+
try:
|
| 1409 |
+
url = (f"{SUPABASE_URL}/rest/v1/de_outcomes"
|
| 1410 |
+
f"?user_id=eq.{user_id}&library_id=eq.{library_id}"
|
| 1411 |
+
f"&select=id,mutations,measured_value,outcome,created_at"
|
| 1412 |
+
f"&order=created_at.desc&limit={_DE_OUTCOMES_MAX}")
|
| 1413 |
+
req = urllib.request.Request(url, method="GET", headers=_supabase_headers())
|
| 1414 |
+
with urllib.request.urlopen(req, timeout=6.0) as resp:
|
| 1415 |
+
return json.loads(resp.read().decode("utf-8")) or []
|
| 1416 |
+
except Exception as exc: # noqa: BLE001
|
| 1417 |
+
logger.warning("de_outcomes list failed: %s", exc)
|
| 1418 |
+
return []
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
def cleanup_expired_de_outcomes_async(user_id: Optional[str]) -> None:
|
| 1422 |
+
"""Fire-and-forget delete of this user's expired outcome rows (lazy sweep)."""
|
| 1423 |
+
if not user_id or not (SUPABASE_URL and SUPABASE_SERVICE_KEY):
|
| 1424 |
+
return
|
| 1425 |
+
import threading
|
| 1426 |
+
threading.Thread(target=_do_cleanup_expired_de_outcomes,
|
| 1427 |
+
args=(user_id,), daemon=True).start()
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
def _do_cleanup_expired_de_outcomes(user_id: str) -> None:
|
| 1431 |
+
import urllib.request
|
| 1432 |
+
try:
|
| 1433 |
+
url = (f"{SUPABASE_URL}/rest/v1/de_outcomes"
|
| 1434 |
+
f"?user_id=eq.{user_id}&expires_at=lt.now()")
|
| 1435 |
+
req = urllib.request.Request(url, method="DELETE",
|
| 1436 |
+
headers=_supabase_headers({"Prefer": "return=minimal"}))
|
| 1437 |
+
with urllib.request.urlopen(req, timeout=4.0):
|
| 1438 |
+
pass
|
| 1439 |
+
except Exception as exc: # noqa: BLE001
|
| 1440 |
+
logger.warning("de_outcomes cleanup failed for %s: %s", user_id, exc)
|
| 1441 |
+
|
| 1442 |
+
|
| 1443 |
# ─── Directed-Evolution libraries: per-user list + signed download ────
|
| 1444 |
# DE runs already persist to public.libraries + the `libraries` Storage
|
| 1445 |
# bucket (see _do_save_library). These surface them in the unified hub —
|
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Active-learning surrogate for the Directed-Evolution loop (Design→Build→Test→Learn).
|
| 2 |
+
|
| 3 |
+
A user evolves a protein (round 1, zero-shot ESM-2 ΔLL), orders the top library,
|
| 4 |
+
measures variants on the bench, and logs the results. This module fits a light
|
| 5 |
+
surrogate on THEIR measurements and produces an *adjusted* per-mutation score
|
| 6 |
+
that the existing simulated-annealing search (`dee.optimizer.search.evolve`)
|
| 7 |
+
consumes unchanged — so round 2 is conditioned on real data, not just the prior.
|
| 8 |
+
|
| 9 |
+
Design (deliberately simple + honest, runs in milliseconds on CPU; numpy only,
|
| 10 |
+
no scikit-learn/scipy in the image):
|
| 11 |
+
|
| 12 |
+
* The SA objective is ADDITIVE over single-site effects:
|
| 13 |
+
fitness(variant) = Σ_{m∈variant} score(m)
|
| 14 |
+
In round 1, score(m) = ΔLL_m (the ESM-2 wild-type-marginal prior).
|
| 15 |
+
|
| 16 |
+
* We model the measured fitness as a ridge over single-site effects WITH the
|
| 17 |
+
ΔLL prior as a feature:
|
| 18 |
+
y_std ≈ b + w_prior · (Σ ΔLL of the variant) + Σ_{m} β_m · 1[m∈variant]
|
| 19 |
+
Fit [b, w_prior, β] by closed-form ridge (β strongly shrunk toward 0, so
|
| 20 |
+
mutations the user never measured fall back to the pure prior). y is
|
| 21 |
+
standardized so the (arbitrary) assay scale doesn't matter — ranking is
|
| 22 |
+
scale-invariant anyway.
|
| 23 |
+
|
| 24 |
+
* The round-2 per-mutation acquisition score (additive ⇒ plugs straight into
|
| 25 |
+
the SA) is:
|
| 26 |
+
score(m) = w_prior · ΔLL_m + β_m + κ · uncertainty_m
|
| 27 |
+
where uncertainty_m rewards under-measured mutations (exploration). Unseen
|
| 28 |
+
mutations get β_m = 0 and high uncertainty → the search explores them while
|
| 29 |
+
still respecting the ΔLL prior.
|
| 30 |
+
|
| 31 |
+
* Below a small floor of measurements we DON'T pretend to learn: we return the
|
| 32 |
+
pure prior with an honest note. No overclaiming.
|
| 33 |
+
|
| 34 |
+
Privacy: operates only on the data passed in (one user's own measurements).
|
| 35 |
+
"""
|
| 36 |
+
from __future__ import annotations
|
| 37 |
+
|
| 38 |
+
import re
|
| 39 |
+
from dataclasses import dataclass, replace
|
| 40 |
+
from typing import Dict, List, Optional, Sequence, Tuple
|
| 41 |
+
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
# Need at least this many measured variants before we trust a learned signal;
|
| 45 |
+
# below it, round 2 = re-search on the zero-shot prior (still a fresh library).
|
| 46 |
+
MIN_MEASUREMENTS = 4
|
| 47 |
+
|
| 48 |
+
_LABEL_RE = re.compile(r"^([A-Za-z])(\d+)([A-Za-z*])$") # e.g. "W58L"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def parse_label(label: str) -> Optional[Tuple[int, str]]:
|
| 52 |
+
"""'W58L' → (57, 'L') (0-indexed position, mutant AA). None if malformed."""
|
| 53 |
+
m = _LABEL_RE.match((label or "").strip())
|
| 54 |
+
if not m:
|
| 55 |
+
return None
|
| 56 |
+
pos = int(m.group(2)) - 1
|
| 57 |
+
if pos < 0:
|
| 58 |
+
return None
|
| 59 |
+
return (pos, m.group(3).upper())
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def parse_mutations(labels: str | Sequence[str]) -> List[Tuple[int, str]]:
|
| 63 |
+
"""Accept 'W58L,K204R' or ['W58L','K204R'] → [(57,'L'),(203,'R')]."""
|
| 64 |
+
if isinstance(labels, str):
|
| 65 |
+
parts = re.split(r"[,\s;]+", labels.strip())
|
| 66 |
+
else:
|
| 67 |
+
parts = list(labels)
|
| 68 |
+
out = []
|
| 69 |
+
for p in parts:
|
| 70 |
+
pm = parse_label(p)
|
| 71 |
+
if pm is not None:
|
| 72 |
+
out.append(pm)
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class Surrogate:
|
| 78 |
+
"""Result of fitting on a user's measurements."""
|
| 79 |
+
adjusted: Dict[Tuple[int, str], float] # (pos, mut_aa) → round-2 acquisition score
|
| 80 |
+
w_prior: float # learned weight on the ΔLL prior
|
| 81 |
+
n_train: int # measured variants used
|
| 82 |
+
n_effects: int # mutations that got a learned correction
|
| 83 |
+
learned: bool # False ⇒ fell back to the prior
|
| 84 |
+
note: str
|
| 85 |
+
|
| 86 |
+
def adjust_pool(self, pool: list) -> list:
|
| 87 |
+
"""Return a copy of a `search.Mutation` pool with delta_ll replaced by
|
| 88 |
+
the round-2 acquisition score (so `evolve()` runs unchanged)."""
|
| 89 |
+
return [replace(m, delta_ll=self.adjusted.get((m.position, m.mut_aa), m.delta_ll))
|
| 90 |
+
for m in pool]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def fit_surrogate(
|
| 94 |
+
pool: list,
|
| 95 |
+
measurements: List[Tuple[Sequence[str], float]],
|
| 96 |
+
*,
|
| 97 |
+
kappa: float = 0.4,
|
| 98 |
+
ridge_lambda: float = 1.0,
|
| 99 |
+
prior_lambda: float = 0.1,
|
| 100 |
+
) -> Surrogate:
|
| 101 |
+
"""Fit the additive surrogate.
|
| 102 |
+
|
| 103 |
+
pool: list of search.Mutation (round-1 single-site pool; each has
|
| 104 |
+
.position, .mut_aa, .delta_ll).
|
| 105 |
+
measurements: [(mutation_labels, measured_value), …] from the user's bench.
|
| 106 |
+
Returns a Surrogate whose `adjusted` maps (pos, mut_aa) → acquisition score.
|
| 107 |
+
"""
|
| 108 |
+
prior = {(m.position, m.mut_aa): float(m.delta_ll) for m in pool}
|
| 109 |
+
index = {key: i for i, key in enumerate(prior.keys())}
|
| 110 |
+
keys = list(prior.keys())
|
| 111 |
+
M = len(keys)
|
| 112 |
+
|
| 113 |
+
# Parse + keep only measurements with a numeric value and ≥1 in-pool mutation.
|
| 114 |
+
rows: List[Tuple[List[int], float, float]] = [] # (col_indices, prior_sum, y)
|
| 115 |
+
for labels, value in (measurements or []):
|
| 116 |
+
try:
|
| 117 |
+
y = float(value)
|
| 118 |
+
except (TypeError, ValueError):
|
| 119 |
+
continue
|
| 120 |
+
cols, psum = [], 0.0
|
| 121 |
+
for key in parse_mutations(labels):
|
| 122 |
+
if key in index:
|
| 123 |
+
cols.append(index[key]); psum += prior[key]
|
| 124 |
+
if cols:
|
| 125 |
+
rows.append((cols, psum, y))
|
| 126 |
+
|
| 127 |
+
n = len(rows)
|
| 128 |
+
counts = np.zeros(M)
|
| 129 |
+
for cols, _, _ in rows:
|
| 130 |
+
for c in cols:
|
| 131 |
+
counts[c] += 1
|
| 132 |
+
# Exploration bonus: under-measured mutations get a larger nudge.
|
| 133 |
+
unc = 1.0 / np.sqrt(1.0 + counts)
|
| 134 |
+
|
| 135 |
+
# Not enough signal → honest fallback to the pure ΔLL prior.
|
| 136 |
+
y_all = np.array([y for _, _, y in rows], dtype=float)
|
| 137 |
+
if n < MIN_MEASUREMENTS or M == 0 or (n and np.std(y_all) < 1e-9):
|
| 138 |
+
return Surrogate(
|
| 139 |
+
adjusted=dict(prior), w_prior=1.0, n_train=n, n_effects=0, learned=False,
|
| 140 |
+
note=(f"{n} measurement(s) logged — need ≥{MIN_MEASUREMENTS} with a spread of "
|
| 141 |
+
"values to learn; round 2 uses the ESM-2 prior."),
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# Standardize y (assay scale is arbitrary; ranking is scale-invariant).
|
| 145 |
+
y_std = (y_all - y_all.mean()) / (y_all.std() + 1e-9)
|
| 146 |
+
|
| 147 |
+
# Design matrix A = [intercept | prior_sum | incidence(M)].
|
| 148 |
+
A = np.zeros((n, 2 + M))
|
| 149 |
+
A[:, 0] = 1.0
|
| 150 |
+
for i, (cols, psum, _) in enumerate(rows):
|
| 151 |
+
A[i, 1] = psum
|
| 152 |
+
for c in cols:
|
| 153 |
+
A[i, 2 + c] = 1.0
|
| 154 |
+
|
| 155 |
+
# Ridge: don't regularize the intercept; lightly regularize the prior weight;
|
| 156 |
+
# strongly shrink the per-mutation β toward 0 (→ unseen muts default to prior).
|
| 157 |
+
reg = np.concatenate([[0.0], [prior_lambda], np.full(M, ridge_lambda)])
|
| 158 |
+
try:
|
| 159 |
+
w = np.linalg.solve(A.T @ A + np.diag(reg), A.T @ y_std)
|
| 160 |
+
except np.linalg.LinAlgError:
|
| 161 |
+
w = np.linalg.lstsq(A.T @ A + np.diag(reg), A.T @ y_std, rcond=None)[0]
|
| 162 |
+
|
| 163 |
+
w_prior = float(w[1])
|
| 164 |
+
beta = w[2:]
|
| 165 |
+
# Acquisition per pool mutation: prior (re-weighted) + learned correction + explore.
|
| 166 |
+
adjusted = {}
|
| 167 |
+
for key in keys:
|
| 168 |
+
c = index[key]
|
| 169 |
+
adjusted[key] = w_prior * prior[key] + float(beta[c]) + kappa * float(unc[c])
|
| 170 |
+
n_effects = int(np.sum(np.abs(beta) > 1e-6))
|
| 171 |
+
return Surrogate(
|
| 172 |
+
adjusted=adjusted, w_prior=w_prior, n_train=n, n_effects=n_effects, learned=True,
|
| 173 |
+
note=(f"Learned from {n} measured variants (prior weight {w_prior:.2f}; "
|
| 174 |
+
f"{n_effects} mutation effects corrected). Round 2 balances the "
|
| 175 |
+
"learned model with exploration of under-tested positions."),
|
| 176 |
+
)
|
|
@@ -119,6 +119,7 @@ class JobState:
|
|
| 119 |
csv_path: Optional[str] = None
|
| 120 |
desktop_path: Optional[str] = None
|
| 121 |
variants: Optional[List[Dict[str, Any]]] = None
|
|
|
|
| 122 |
error: Optional[str] = None
|
| 123 |
# Frozen copy of the user's settings + the parameters the engine actually
|
| 124 |
# used. Surfaces in the UI's metadata pills and the auto-generated
|
|
@@ -972,6 +973,7 @@ def create_app() -> Flask:
|
|
| 972 |
"wt_identifier": job.wt_identifier,
|
| 973 |
"wt_protein": job.wt_protein,
|
| 974 |
"variants": job.variants or [],
|
|
|
|
| 975 |
"settings_used": job.settings_used,
|
| 976 |
"started_at": job.started_at,
|
| 977 |
"elapsed_seconds": job.elapsed(),
|
|
@@ -1998,6 +2000,114 @@ def create_app() -> Flask:
|
|
| 1998 |
return jsonify({"ok": False, "error": "Library not found."}), 404
|
| 1999 |
return jsonify({"ok": True, "url": url})
|
| 2000 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2001 |
@app.post("/api/crispr/download")
|
| 2002 |
def crispr_download() -> Response:
|
| 2003 |
"""Return the CSV body for a fresh design. We re-design from the
|
|
@@ -2493,6 +2603,60 @@ def _summarize(path: Path, original_name: str) -> tuple[Dict[str, Any], Dict[str
|
|
| 2493 |
)
|
| 2494 |
|
| 2495 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2496 |
def _run_pipeline(
|
| 2497 |
job: JobState,
|
| 2498 |
input_path: Path,
|
|
@@ -2690,6 +2854,9 @@ def _run_pipeline(
|
|
| 2690 |
or record.identifier
|
| 2691 |
or "library"
|
| 2692 |
)[:120]
|
|
|
|
|
|
|
|
|
|
| 2693 |
_auth.save_library_async(
|
| 2694 |
user_id=job.user_id,
|
| 2695 |
job_id=job.job_id,
|
|
@@ -2700,6 +2867,7 @@ def _run_pipeline(
|
|
| 2700 |
host_organism=settings.get("host", "e_coli"),
|
| 2701 |
n_variants=len(variants),
|
| 2702 |
top_fitness=top_fitness,
|
|
|
|
| 2703 |
)
|
| 2704 |
except Exception as exc: # noqa: BLE001
|
| 2705 |
# save_library_async is itself fire-and-forget, but the kwargs
|
|
|
|
| 119 |
csv_path: Optional[str] = None
|
| 120 |
desktop_path: Optional[str] = None
|
| 121 |
variants: Optional[List[Dict[str, Any]]] = None
|
| 122 |
+
library_id: Optional[str] = None # set on save → lets the client log outcomes
|
| 123 |
error: Optional[str] = None
|
| 124 |
# Frozen copy of the user's settings + the parameters the engine actually
|
| 125 |
# used. Surfaces in the UI's metadata pills and the auto-generated
|
|
|
|
| 973 |
"wt_identifier": job.wt_identifier,
|
| 974 |
"wt_protein": job.wt_protein,
|
| 975 |
"variants": job.variants or [],
|
| 976 |
+
"library_id": job.library_id,
|
| 977 |
"settings_used": job.settings_used,
|
| 978 |
"started_at": job.started_at,
|
| 979 |
"elapsed_seconds": job.elapsed(),
|
|
|
|
| 2000 |
return jsonify({"ok": False, "error": "Library not found."}), 404
|
| 2001 |
return jsonify({"ok": True, "url": url})
|
| 2002 |
|
| 2003 |
+
# ── DE learning flywheel: log outcomes + active-learning round 2 ──
|
| 2004 |
+
@app.post("/api/de/outcomes")
|
| 2005 |
+
def de_outcomes_save() -> Response:
|
| 2006 |
+
"""Save this user's measured variants for a saved DE library."""
|
| 2007 |
+
auth = _auth.get_auth()
|
| 2008 |
+
if auth.anonymous:
|
| 2009 |
+
return jsonify({"ok": False, "error": "signin_required",
|
| 2010 |
+
"kind": "signin_required"}), 403
|
| 2011 |
+
body = request.get_json(force=True, silent=True) or {}
|
| 2012 |
+
library_id = str(body.get("library_id", "")).strip()
|
| 2013 |
+
outcomes = body.get("outcomes")
|
| 2014 |
+
if not isinstance(outcomes, list):
|
| 2015 |
+
return jsonify({"ok": False, "error": "No outcomes provided."}), 400
|
| 2016 |
+
result = _auth.save_de_outcomes(auth.user_id, library_id, outcomes)
|
| 2017 |
+
_auth.cleanup_expired_de_outcomes_async(auth.user_id) # lazy sweep
|
| 2018 |
+
return jsonify(result), (200 if result.get("ok") else 502)
|
| 2019 |
+
|
| 2020 |
+
@app.get("/api/de/outcomes/<library_id>")
|
| 2021 |
+
def de_outcomes_list(library_id: str) -> Response:
|
| 2022 |
+
auth = _auth.get_auth()
|
| 2023 |
+
if auth.anonymous:
|
| 2024 |
+
return jsonify({"ok": False, "error": "signin_required",
|
| 2025 |
+
"kind": "signin_required"}), 403
|
| 2026 |
+
return jsonify({"ok": True, "outcomes": _auth.list_de_outcomes(auth.user_id, library_id)})
|
| 2027 |
+
|
| 2028 |
+
@app.post("/api/de/round2")
|
| 2029 |
+
def de_round2() -> Response:
|
| 2030 |
+
"""Propose a round-2 library learned from this user's logged outcomes."""
|
| 2031 |
+
auth = _auth.get_auth()
|
| 2032 |
+
if auth.anonymous:
|
| 2033 |
+
return jsonify({"ok": False, "error": "signin_required",
|
| 2034 |
+
"kind": "signin_required",
|
| 2035 |
+
"signup_url": "https://turingdna.com/signin/?from=de"}), 403
|
| 2036 |
+
body = request.get_json(force=True, silent=True) or {}
|
| 2037 |
+
library_id = str(body.get("library_id", "")).strip()
|
| 2038 |
+
wt_protein = re.sub(r"\s+", "", str(body.get("wt_protein", ""))).upper()
|
| 2039 |
+
if not wt_protein or not re.match(r"^[ACDEFGHIKLMNPQRSTVWY*]+$", wt_protein):
|
| 2040 |
+
return jsonify({"ok": False, "error": "Missing or non-standard wild-type protein."}), 400
|
| 2041 |
+
if len(wt_protein) > _DE_ROUND2_MAX_AA:
|
| 2042 |
+
return jsonify({"ok": False, "error":
|
| 2043 |
+
f"Round 2 runs in real time for proteins up to {_DE_ROUND2_MAX_AA} aa on the "
|
| 2044 |
+
"free tier — yours is longer."}), 400
|
| 2045 |
+
|
| 2046 |
+
# Outcomes: DB is authoritative; allow inline only as a fallback.
|
| 2047 |
+
rows = _auth.list_de_outcomes(auth.user_id, library_id) if library_id else []
|
| 2048 |
+
if not rows and isinstance(body.get("measurements"), list):
|
| 2049 |
+
rows = body["measurements"]
|
| 2050 |
+
_OUT_VAL = {"worked": 1.0, "partial": 0.5, "failed": 0.0}
|
| 2051 |
+
measurements = []
|
| 2052 |
+
for r in rows:
|
| 2053 |
+
if not isinstance(r, dict):
|
| 2054 |
+
continue
|
| 2055 |
+
mv = r.get("measured_value")
|
| 2056 |
+
try:
|
| 2057 |
+
val = (float(mv) if mv is not None and mv != ""
|
| 2058 |
+
else _OUT_VAL.get(str(r.get("outcome", "")).lower()))
|
| 2059 |
+
except (TypeError, ValueError):
|
| 2060 |
+
val = None
|
| 2061 |
+
if val is None:
|
| 2062 |
+
continue
|
| 2063 |
+
measurements.append((r.get("mutations", ""), val))
|
| 2064 |
+
|
| 2065 |
+
# Sanitize settings — clamp model + host to known values (never load an
|
| 2066 |
+
# arbitrary HF model id from the client).
|
| 2067 |
+
s = body.get("settings") if isinstance(body.get("settings"), dict) else {}
|
| 2068 |
+
model = s.get("model", "small")
|
| 2069 |
+
if model not in ("small", "medium", "large"):
|
| 2070 |
+
model = "small"
|
| 2071 |
+
host = s.get("host", "e_coli")
|
| 2072 |
+
if host not in ("e_coli", "yeast", "human"):
|
| 2073 |
+
host = "e_coli"
|
| 2074 |
+
try:
|
| 2075 |
+
pct = float(s.get("percentile", 85.0))
|
| 2076 |
+
except (TypeError, ValueError):
|
| 2077 |
+
pct = 85.0
|
| 2078 |
+
pct = min(99.0, max(1.0, pct))
|
| 2079 |
+
|
| 2080 |
+
def _clampi(v, lo, hi, d):
|
| 2081 |
+
try:
|
| 2082 |
+
return max(lo, min(hi, int(v)))
|
| 2083 |
+
except (TypeError, ValueError):
|
| 2084 |
+
return d
|
| 2085 |
+
settings = {
|
| 2086 |
+
"model": model, "host": host, "percentile": pct,
|
| 2087 |
+
"k": _clampi(s.get("k", 30), 1, 200, 30),
|
| 2088 |
+
"min_mutations": _clampi(s.get("min_mutations", 2), 1, 10, 2),
|
| 2089 |
+
"max_mutations": _clampi(s.get("max_mutations", 5), 1, 12, 5),
|
| 2090 |
+
"restarts": _clampi(s.get("restarts", 8), 1, 24, 8),
|
| 2091 |
+
"steps": _clampi(s.get("steps", 1200), 100, 5000, 1200),
|
| 2092 |
+
"seed": s.get("seed"),
|
| 2093 |
+
}
|
| 2094 |
+
try:
|
| 2095 |
+
rows2, surrogate = _de_round2_library(wt_protein, settings, measurements)
|
| 2096 |
+
except Exception: # noqa: BLE001
|
| 2097 |
+
logger.exception("DE round-2 failed.")
|
| 2098 |
+
return jsonify({"ok": False, "error":
|
| 2099 |
+
"Couldn't compute round 2 — check the sequence and try again."}), 500
|
| 2100 |
+
_auth.cleanup_expired_de_outcomes_async(auth.user_id)
|
| 2101 |
+
return jsonify({
|
| 2102 |
+
"ok": True,
|
| 2103 |
+
"variants": rows2,
|
| 2104 |
+
"wt_protein": wt_protein,
|
| 2105 |
+
"wt_identifier": str(body.get("wt_identifier", "") or "round 2"),
|
| 2106 |
+
"settings_used": settings,
|
| 2107 |
+
"surrogate": surrogate,
|
| 2108 |
+
"round": 2,
|
| 2109 |
+
})
|
| 2110 |
+
|
| 2111 |
@app.post("/api/crispr/download")
|
| 2112 |
def crispr_download() -> Response:
|
| 2113 |
"""Return the CSV body for a fresh design. We re-design from the
|
|
|
|
| 2603 |
)
|
| 2604 |
|
| 2605 |
|
| 2606 |
+
_DE_ROUND2_MAX_AA = 500 # sync round-2 length cap (bounds ESM score time on free CPU)
|
| 2607 |
+
|
| 2608 |
+
|
| 2609 |
+
def _de_round2_library(wt_protein: str, settings: Dict[str, Any],
|
| 2610 |
+
measurements: list) -> tuple[list, Dict[str, Any]]:
|
| 2611 |
+
"""Active-learning round 2 (Design→Build→Test→Learn). Score the WT, fit the
|
| 2612 |
+
surrogate on the user's measured variants, re-rank the single-site pool by
|
| 2613 |
+
the learned acquisition score, evolve, and assemble the same variant table
|
| 2614 |
+
shape as a normal run. Returns (variant_rows, surrogate_info)."""
|
| 2615 |
+
from dee.core import active_learning as _al
|
| 2616 |
+
from dee.optimizer.search import Mutation as _Mut
|
| 2617 |
+
|
| 2618 |
+
scorer = ESM2Scorer(ScorerConfig(
|
| 2619 |
+
model_name=settings.get("model", "small"),
|
| 2620 |
+
device=settings.get("device"),
|
| 2621 |
+
quantization=settings.get("quantization"),
|
| 2622 |
+
))
|
| 2623 |
+
scores_df = scorer.score_all_substitutions(wt_protein)
|
| 2624 |
+
pool_df = top_percentile_pool(scores_df, percentile=float(settings.get("percentile", 85.0)))
|
| 2625 |
+
|
| 2626 |
+
# Fit the surrogate on the round-1 single-site pool + the user's results,
|
| 2627 |
+
# then overwrite the pool's per-mutation score with the learned acquisition
|
| 2628 |
+
# (additive ⇒ evolve() consumes it unchanged).
|
| 2629 |
+
muts = [_Mut(int(r.position), str(r.wt_aa), str(r.mut_aa), float(r.delta_ll))
|
| 2630 |
+
for r in pool_df.itertuples(index=False)]
|
| 2631 |
+
surrogate = _al.fit_surrogate(muts, measurements)
|
| 2632 |
+
adj_df = pool_df.copy()
|
| 2633 |
+
adj_df["delta_ll"] = [
|
| 2634 |
+
surrogate.adjusted.get((int(r.position), str(r.mut_aa)), float(r.delta_ll))
|
| 2635 |
+
for r in pool_df.itertuples(index=False)
|
| 2636 |
+
]
|
| 2637 |
+
|
| 2638 |
+
variants = evolve(adj_df, SearchConfig(
|
| 2639 |
+
k=int(settings.get("k", 30)),
|
| 2640 |
+
max_mutations=int(settings.get("max_mutations", 5)),
|
| 2641 |
+
min_mutations=int(settings.get("min_mutations", 2)),
|
| 2642 |
+
n_restarts=int(settings.get("restarts", 8)),
|
| 2643 |
+
steps_per_restart=int(settings.get("steps", 1200)),
|
| 2644 |
+
seed=settings.get("seed"),
|
| 2645 |
+
))
|
| 2646 |
+
df = variants_to_dataframe(
|
| 2647 |
+
wt_protein, variants,
|
| 2648 |
+
host=settings.get("host", "e_coli"),
|
| 2649 |
+
forbidden_sites=DEFAULT_FORBIDDEN_SITES,
|
| 2650 |
+
)
|
| 2651 |
+
return df.to_dict(orient="records"), {
|
| 2652 |
+
"learned": surrogate.learned,
|
| 2653 |
+
"n_train": surrogate.n_train,
|
| 2654 |
+
"w_prior": round(surrogate.w_prior, 3),
|
| 2655 |
+
"n_effects": surrogate.n_effects,
|
| 2656 |
+
"note": surrogate.note,
|
| 2657 |
+
}
|
| 2658 |
+
|
| 2659 |
+
|
| 2660 |
def _run_pipeline(
|
| 2661 |
job: JobState,
|
| 2662 |
input_path: Path,
|
|
|
|
| 2854 |
or record.identifier
|
| 2855 |
or "library"
|
| 2856 |
)[:120]
|
| 2857 |
+
# Pre-assign the library id so the client gets it in the result and
|
| 2858 |
+
# can log wet-lab outcomes against it (the learning flywheel).
|
| 2859 |
+
job.library_id = uuid.uuid4().hex
|
| 2860 |
_auth.save_library_async(
|
| 2861 |
user_id=job.user_id,
|
| 2862 |
job_id=job.job_id,
|
|
|
|
| 2867 |
host_organism=settings.get("host", "e_coli"),
|
| 2868 |
n_variants=len(variants),
|
| 2869 |
top_fitness=top_fitness,
|
| 2870 |
+
library_id=job.library_id,
|
| 2871 |
)
|
| 2872 |
except Exception as exc: # noqa: BLE001
|
| 2873 |
# save_library_async is itself fire-and-forget, but the kwargs
|
|
@@ -5855,3 +5855,36 @@ h3, h4 {
|
|
| 5855 |
|
| 5856 |
/* Primer results header actions (Export menu + Save) */
|
| 5857 |
.primer-results-actions { display: flex; align-items: center; gap: 10px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5855 |
|
| 5856 |
/* Primer results header actions (Export menu + Save) */
|
| 5857 |
.primer-results-actions { display: flex; align-items: center; gap: 10px; }
|
| 5858 |
+
|
| 5859 |
+
/* ── Learning flywheel: round-2 panel + banner ────────────────────────── */
|
| 5860 |
+
.round2-banner {
|
| 5861 |
+
margin: 0 0 14px; padding: 10px 14px;
|
| 5862 |
+
border: 1px solid var(--brand); border-radius: var(--r-2);
|
| 5863 |
+
background: var(--bg-hover); color: var(--ink); font-size: 13px; line-height: 1.5;
|
| 5864 |
+
}
|
| 5865 |
+
.round2-panel { margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--line); }
|
| 5866 |
+
.round2-list {
|
| 5867 |
+
display: flex; flex-direction: column; gap: 1px;
|
| 5868 |
+
background: var(--line); border: 1px solid var(--line); border-radius: var(--r-2);
|
| 5869 |
+
overflow: hidden; max-height: 320px; overflow-y: auto; margin: 6px 0 14px;
|
| 5870 |
+
}
|
| 5871 |
+
.round2-row {
|
| 5872 |
+
display: grid; grid-template-columns: 64px 1fr 110px; align-items: center;
|
| 5873 |
+
gap: 12px; padding: 9px 12px; background: var(--bg-card);
|
| 5874 |
+
}
|
| 5875 |
+
.r2-id { font-family: var(--font-mono); font-size: 12px; color: var(--ink-faint); }
|
| 5876 |
+
.r2-mut { font-family: var(--font-mono); font-size: 12.5px; color: var(--ink);
|
| 5877 |
+
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
| 5878 |
+
.r2-val {
|
| 5879 |
+
width: 100%; min-height: 40px; padding: 6px 8px;
|
| 5880 |
+
border: 1px solid var(--line); border-radius: var(--r-2);
|
| 5881 |
+
background: var(--bg-app); color: var(--ink);
|
| 5882 |
+
font-size: 16px; /* ≥16px so iOS Safari doesn't auto-zoom on focus */
|
| 5883 |
+
}
|
| 5884 |
+
.r2-val:focus { outline: none; border-color: var(--brand); }
|
| 5885 |
+
.round2-actions { display: flex; gap: 12px; justify-content: flex-end; align-items: center; }
|
| 5886 |
+
.round2-status { font-size: 12.5px; color: var(--ink-faint); margin: 4px 0 10px; }
|
| 5887 |
+
.round2-status-warn { color: var(--danger, #C0392B); }
|
| 5888 |
+
@media (max-width: 540px) {
|
| 5889 |
+
.round2-row { grid-template-columns: 50px 1fr 84px; gap: 8px; }
|
| 5890 |
+
}
|
|
@@ -1166,6 +1166,98 @@ const tableState = {
|
|
| 1166 |
wtProtein: '', // needed for the diff view
|
| 1167 |
};
|
| 1168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1169 |
function renderResults(data) {
|
| 1170 |
const card = $('#resultsCard');
|
| 1171 |
card.hidden = false;
|
|
@@ -1185,6 +1277,17 @@ function renderResults(data) {
|
|
| 1185 |
$('#resultSummary').innerHTML =
|
| 1186 |
`<strong>${evolvedCount}</strong> variants${hasWt ? ' + wild type' : ''} of <strong>${escapeHtml(data.wt_identifier)}</strong> · ${data.wt_protein.length} aa · ready to download`;
|
| 1187 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1188 |
renderStatsStrip(data);
|
| 1189 |
renderMutationMap(data);
|
| 1190 |
renderRunMeta(data);
|
|
|
|
| 1166 |
wtProtein: '', // needed for the diff view
|
| 1167 |
};
|
| 1168 |
|
| 1169 |
+
// ───────────────────────── LEARNING FLYWHEEL (round 2) ─────────────────────
|
| 1170 |
+
// Log measured fitness for the variants you tested → fit a surrogate on the
|
| 1171 |
+
// server → propose a data-conditioned round-2 library (Design→Build→Test→Learn).
|
| 1172 |
+
function _renderRound2Panel(data) {
|
| 1173 |
+
const panel = document.getElementById('round2Panel');
|
| 1174 |
+
const list = document.getElementById('round2List');
|
| 1175 |
+
if (!panel || !list) return;
|
| 1176 |
+
const evolved = (data.variants || []).filter((v) => v.Variant_ID !== 'WT').slice(0, 60);
|
| 1177 |
+
if (!evolved.length) { panel.hidden = true; return; }
|
| 1178 |
+
list.innerHTML = evolved.map((v) => {
|
| 1179 |
+
const mut = v.Mutations_AA || '';
|
| 1180 |
+
return `<label class="round2-row">
|
| 1181 |
+
<span class="r2-id">${escapeHtml(v.Variant_ID || '')}</span>
|
| 1182 |
+
<span class="r2-mut">${escapeHtml(mut || '(wild-type-like)')}</span>
|
| 1183 |
+
<input class="r2-val" type="number" step="any" inputmode="decimal"
|
| 1184 |
+
data-mut="${escapeHtml(mut)}" placeholder="measured"
|
| 1185 |
+
aria-label="measured value for ${escapeHtml(v.Variant_ID || '')}">
|
| 1186 |
+
</label>`;
|
| 1187 |
+
}).join('');
|
| 1188 |
+
const st = document.getElementById('round2Status');
|
| 1189 |
+
if (st) { st.hidden = true; st.textContent = ''; }
|
| 1190 |
+
panel.hidden = false;
|
| 1191 |
+
}
|
| 1192 |
+
|
| 1193 |
+
function _collectRound2Measurements() {
|
| 1194 |
+
const out = [];
|
| 1195 |
+
document.querySelectorAll('#round2List .r2-val').forEach((inp) => {
|
| 1196 |
+
const raw = (inp.value || '').trim();
|
| 1197 |
+
if (raw === '') return;
|
| 1198 |
+
const num = parseFloat(raw);
|
| 1199 |
+
if (!isFinite(num)) return;
|
| 1200 |
+
out.push({ mutations: inp.getAttribute('data-mut') || '', measured_value: num, outcome: 'measured' });
|
| 1201 |
+
});
|
| 1202 |
+
return out;
|
| 1203 |
+
}
|
| 1204 |
+
|
| 1205 |
+
function _round2Status(msg, kind) {
|
| 1206 |
+
const st = document.getElementById('round2Status');
|
| 1207 |
+
if (!st) return;
|
| 1208 |
+
st.hidden = false;
|
| 1209 |
+
st.textContent = msg;
|
| 1210 |
+
st.className = 'round2-status' + (kind ? ' round2-status-' + kind : '');
|
| 1211 |
+
}
|
| 1212 |
+
|
| 1213 |
+
(function initRound2() {
|
| 1214 |
+
const btn = document.getElementById('round2Btn');
|
| 1215 |
+
const saveBtn = document.getElementById('round2SaveBtn');
|
| 1216 |
+
if (btn) btn.addEventListener('click', async () => {
|
| 1217 |
+
const data = state.lastRun || {};
|
| 1218 |
+
const meas = _collectRound2Measurements();
|
| 1219 |
+
if (!meas.length) { _round2Status('Enter a measured value for at least one variant you tested.', 'warn'); return; }
|
| 1220 |
+
const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Designing round 2…';
|
| 1221 |
+
_round2Status(`Scoring and learning from your ${meas.length} result${meas.length === 1 ? '' : 's'}…`);
|
| 1222 |
+
try {
|
| 1223 |
+
const res = await fetch('/api/de/round2', {
|
| 1224 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 1225 |
+
body: JSON.stringify({
|
| 1226 |
+
library_id: data.library_id || '',
|
| 1227 |
+
wt_protein: data.wt_protein || '',
|
| 1228 |
+
wt_identifier: data.wt_identifier || '',
|
| 1229 |
+
settings: data.settings_used || {},
|
| 1230 |
+
measurements: meas,
|
| 1231 |
+
}),
|
| 1232 |
+
});
|
| 1233 |
+
const j = await res.json();
|
| 1234 |
+
if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); _round2Status('Sign in to use round 2.', 'warn'); return; }
|
| 1235 |
+
if (!j.ok) { _round2Status(j.error || 'Round 2 failed.', 'warn'); return; }
|
| 1236 |
+
renderResults(j); // renders the round-2 library + the "Round 2" banner
|
| 1237 |
+
const card = document.getElementById('resultsCard');
|
| 1238 |
+
if (card) card.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
| 1239 |
+
} catch (e) { _round2Status('Round 2 failed — please try again.', 'warn'); }
|
| 1240 |
+
finally { btn.disabled = false; if (btn.textContent === 'Designing round 2…') btn.textContent = orig; }
|
| 1241 |
+
});
|
| 1242 |
+
if (saveBtn) saveBtn.addEventListener('click', async () => {
|
| 1243 |
+
const data = state.lastRun || {};
|
| 1244 |
+
if (!data.library_id) { _round2Status('Results are saved against a library — sign in and run a design first.', 'warn'); return; }
|
| 1245 |
+
const meas = _collectRound2Measurements();
|
| 1246 |
+
const orig = saveBtn.textContent; saveBtn.disabled = true; saveBtn.textContent = 'Saving…';
|
| 1247 |
+
try {
|
| 1248 |
+
const res = await fetch('/api/de/outcomes', {
|
| 1249 |
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 1250 |
+
body: JSON.stringify({ library_id: data.library_id, outcomes: meas }),
|
| 1251 |
+
});
|
| 1252 |
+
const j = await res.json();
|
| 1253 |
+
if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); return; }
|
| 1254 |
+
if (j.ok) { saveBtn.textContent = 'Saved ✓'; setTimeout(() => { saveBtn.textContent = orig; }, 1500); }
|
| 1255 |
+
else { _round2Status(j.error || 'Could not save your results.', 'warn'); }
|
| 1256 |
+
} catch (e) { _round2Status('Could not save your results.', 'warn'); }
|
| 1257 |
+
finally { saveBtn.disabled = false; if (saveBtn.textContent === 'Saving…') saveBtn.textContent = orig; }
|
| 1258 |
+
});
|
| 1259 |
+
})();
|
| 1260 |
+
|
| 1261 |
function renderResults(data) {
|
| 1262 |
const card = $('#resultsCard');
|
| 1263 |
card.hidden = false;
|
|
|
|
| 1277 |
$('#resultSummary').innerHTML =
|
| 1278 |
`<strong>${evolvedCount}</strong> variants${hasWt ? ' + wild type' : ''} of <strong>${escapeHtml(data.wt_identifier)}</strong> · ${data.wt_protein.length} aa · ready to download`;
|
| 1279 |
|
| 1280 |
+
// Learning flywheel: remember this run + (re)build the round-2 panel.
|
| 1281 |
+
state.lastRun = data;
|
| 1282 |
+
_renderRound2Panel(data);
|
| 1283 |
+
const _r2b = $('#round2Banner');
|
| 1284 |
+
if (_r2b) {
|
| 1285 |
+
if (data.round === 2 && data.surrogate) {
|
| 1286 |
+
_r2b.hidden = false;
|
| 1287 |
+
_r2b.innerHTML = `<strong>Round 2.</strong> ${escapeHtml(data.surrogate.note || 'Designed from your logged bench results.')}`;
|
| 1288 |
+
} else { _r2b.hidden = true; _r2b.innerHTML = ''; }
|
| 1289 |
+
}
|
| 1290 |
+
|
| 1291 |
renderStatsStrip(data);
|
| 1292 |
renderMutationMap(data);
|
| 1293 |
renderRunMeta(data);
|
|
@@ -22,7 +22,7 @@
|
|
| 22 |
<!-- ?v= query bumps invalidate browser + iframe asset caches when app.css /
|
| 23 |
app.js change. Bump these numbers whenever you ship a frontend update —
|
| 24 |
without them, users keep getting the stale file for up to a week. -->
|
| 25 |
-
<link rel="stylesheet" href="/static/app.css?v=20260605-
|
| 26 |
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=2" />
|
| 27 |
<link rel="apple-touch-icon" href="/static/favicon.svg?v=2" />
|
| 28 |
<!-- Mol* (PDBe) viewer for AlphaFold structure embed. Loaded async; the
|
|
@@ -458,6 +458,8 @@
|
|
| 458 |
|
| 459 |
<!-- Run metadata + auto-generated methods text. Filled by JS. -->
|
| 460 |
<div class="run-meta" id="runMeta" hidden></div>
|
|
|
|
|
|
|
| 461 |
|
| 462 |
<!-- Mutation map (lollipop chart). Was carrying a chip-
|
| 463 |
legend (Low / Med / High dots) that read as
|
|
@@ -499,6 +501,27 @@
|
|
| 499 |
<tbody></tbody>
|
| 500 |
</table>
|
| 501 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
</section>
|
| 503 |
</section>
|
| 504 |
|
|
@@ -1641,6 +1664,6 @@
|
|
| 1641 |
<!-- Cloning reference data must load before app.js so the Designer
|
| 1642 |
can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
|
| 1643 |
<script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
|
| 1644 |
-
<script src="/static/app.js?v=20260605-
|
| 1645 |
</body>
|
| 1646 |
</html>
|
|
|
|
| 22 |
<!-- ?v= query bumps invalidate browser + iframe asset caches when app.css /
|
| 23 |
app.js change. Bump these numbers whenever you ship a frontend update —
|
| 24 |
without them, users keep getting the stale file for up to a week. -->
|
| 25 |
+
<link rel="stylesheet" href="/static/app.css?v=20260605-flywheel" />
|
| 26 |
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg?v=2" />
|
| 27 |
<link rel="apple-touch-icon" href="/static/favicon.svg?v=2" />
|
| 28 |
<!-- Mol* (PDBe) viewer for AlphaFold structure embed. Loaded async; the
|
|
|
|
| 458 |
|
| 459 |
<!-- Run metadata + auto-generated methods text. Filled by JS. -->
|
| 460 |
<div class="run-meta" id="runMeta" hidden></div>
|
| 461 |
+
<!-- Round-2 banner: set when a library was proposed from logged results. -->
|
| 462 |
+
<div class="round2-banner" id="round2Banner" hidden></div>
|
| 463 |
|
| 464 |
<!-- Mutation map (lollipop chart). Was carrying a chip-
|
| 465 |
legend (Low / Med / High dots) that read as
|
|
|
|
| 501 |
<tbody></tbody>
|
| 502 |
</table>
|
| 503 |
</div>
|
| 504 |
+
|
| 505 |
+
<!-- Learning flywheel: log wet-lab results → propose a
|
| 506 |
+
data-conditioned round 2 (Design→Build→Test→Learn). -->
|
| 507 |
+
<section class="round2-panel" id="round2Panel" hidden>
|
| 508 |
+
<header class="card-header">
|
| 509 |
+
<div class="card-header-left">
|
| 510 |
+
<p class="card-kicker">§ Learn from results</p>
|
| 511 |
+
<h3>Tested these on the bench? Teach the engine.</h3>
|
| 512 |
+
<p class="card-sub">Enter a measured value for the variants you assayed (any
|
| 513 |
+
number — activity, expression, stability; higher = better). Leave the
|
| 514 |
+
rest blank. TuringDNA fits a model on your results and proposes a smarter
|
| 515 |
+
round 2 — conditioned on your data, not just the prior.</p>
|
| 516 |
+
</div>
|
| 517 |
+
</header>
|
| 518 |
+
<div class="round2-list" id="round2List"></div>
|
| 519 |
+
<div class="round2-status" id="round2Status" hidden></div>
|
| 520 |
+
<div class="round2-actions">
|
| 521 |
+
<button class="ghost" type="button" id="round2SaveBtn">Save results</button>
|
| 522 |
+
<button class="primary" type="button" id="round2Btn">Propose round 2 →</button>
|
| 523 |
+
</div>
|
| 524 |
+
</section>
|
| 525 |
</section>
|
| 526 |
</section>
|
| 527 |
|
|
|
|
| 1664 |
<!-- Cloning reference data must load before app.js so the Designer
|
| 1665 |
can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
|
| 1666 |
<script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
|
| 1667 |
+
<script src="/static/app.js?v=20260605-flywheel" defer></script>
|
| 1668 |
</body>
|
| 1669 |
</html>
|
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-- 0007_de_outcomes.sql — per-user wet-lab outcomes for Directed-Evolution
|
| 2 |
+
-- libraries (the Design→Build→Test→Learn loop).
|
| 3 |
+
--
|
| 4 |
+
-- Run this in the Supabase SQL editor (Dashboard → SQL → New query → Run)
|
| 5 |
+
-- BEFORE the learning-flywheel feature. Idempotent: safe to run more than once.
|
| 6 |
+
--
|
| 7 |
+
-- One row per measured variant: which mutations it carried + the measured
|
| 8 |
+
-- value (or a coarse worked/partial/failed flag). The surrogate model fits on
|
| 9 |
+
-- these to propose a data-conditioned round-2 library. Mirrors the design of
|
| 10 |
+
-- public.crispr_designs / public.primer_analyses: owner-only RLS, 90-day TTL,
|
| 11 |
+
-- indexes for the per-library list query + the lazy expiry sweep. The backend
|
| 12 |
+
-- writes/reads with the service-role key and filters by user_id; the RLS
|
| 13 |
+
-- policies below are defense-in-depth for any direct anon-key access.
|
| 14 |
+
|
| 15 |
+
create table if not exists public.de_outcomes (
|
| 16 |
+
id uuid primary key default gen_random_uuid(),
|
| 17 |
+
user_id uuid not null references auth.users (id) on delete cascade,
|
| 18 |
+
library_id uuid not null, -- the public.libraries row this measures
|
| 19 |
+
created_at timestamptz not null default now(),
|
| 20 |
+
expires_at timestamptz, -- NULL = never expires
|
| 21 |
+
mutations text not null default '', -- e.g. "W58L,K204R" (self-contained for the surrogate)
|
| 22 |
+
measured_value double precision, -- nullable: a numeric assay readout
|
| 23 |
+
outcome text not null default 'measured' -- 'measured' | 'worked' | 'partial' | 'failed'
|
| 24 |
+
);
|
| 25 |
+
|
| 26 |
+
comment on table public.de_outcomes is
|
| 27 |
+
'User-logged wet-lab outcomes for directed-evolution variants. Feeds the '
|
| 28 |
+
'active-learning surrogate. 90-day TTL (expires_at); owner-only RLS.';
|
| 29 |
+
|
| 30 |
+
alter table public.de_outcomes enable row level security;
|
| 31 |
+
|
| 32 |
+
drop policy if exists "de_outcomes_select_own" on public.de_outcomes;
|
| 33 |
+
create policy "de_outcomes_select_own"
|
| 34 |
+
on public.de_outcomes for select
|
| 35 |
+
using (auth.uid() = user_id);
|
| 36 |
+
|
| 37 |
+
drop policy if exists "de_outcomes_insert_own" on public.de_outcomes;
|
| 38 |
+
create policy "de_outcomes_insert_own"
|
| 39 |
+
on public.de_outcomes for insert
|
| 40 |
+
with check (auth.uid() = user_id);
|
| 41 |
+
|
| 42 |
+
drop policy if exists "de_outcomes_delete_own" on public.de_outcomes;
|
| 43 |
+
create policy "de_outcomes_delete_own"
|
| 44 |
+
on public.de_outcomes for delete
|
| 45 |
+
using (auth.uid() = user_id);
|
| 46 |
+
|
| 47 |
+
-- List query: this user's outcomes for a given library.
|
| 48 |
+
create index if not exists de_outcomes_user_lib_idx
|
| 49 |
+
on public.de_outcomes (user_id, library_id, created_at desc);
|
| 50 |
+
|
| 51 |
+
-- Lazy expiry sweep target.
|
| 52 |
+
create index if not exists de_outcomes_expires_idx
|
| 53 |
+
on public.de_outcomes (expires_at)
|
| 54 |
+
where expires_at is not null;
|