Tengo Gzirishvili Claude Opus 4.8 commited on
Commit
eeea851
·
1 Parent(s): 73c780f

Primer Picker: full in-silico PCR specificity — no more "go to NCBI Primer-BLAST"

Browse files

The footer used to send users to NCBI Primer-BLAST to finish the job, which
defeats the point of an in-house tool. The reason was v1 only counted
per-primer matches, not the paired off-target AMPLICONS that Primer-BLAST
uniquely finds. Now we do that check ourselves so the workflow is complete
here and the user never leaves.

- core/primers.py: insilico_pcr() pairs every forward-oriented priming site
with every downstream reverse-oriented site on the same subject within
MAX_PRODUCT (4 kb) → predicted PCR products, exactly like Primer-BLAST's
specificity step. rank() now folds off-target *product* counts (not raw
match counts) into fitness + reasoning and surfaces the product list.
- server.py: _hsp_to_event() converts a BLAST HSP to a 3'-anchored priming
event (strand from sbjct_start/end; rejects 5'-only / low-identity hits);
_run_primer_blast() builds events across ALL primers, runs in-silico PCR,
and attributes products per primer. Adds organism targeting (entrez_query)
so off-target = "would mis-prime in THIS genome" — human/mouse/rat/zebrafish/
yeast/E.coli/all. /api/primers/analyze accepts `organism`.
- Frontend: organism selector (shown when the scan is on), a "Predicted
off-target products" section (pair + size + subject, or a green "no
off-target products — specific" banner), per-primer chips now read
"specific · 0 off-target products" / "N off-target products". Footer
rewritten: the scan IS the Primer-BLAST-equivalent check, done here;
validate critical results at the bench. No third-party redirect.

Tests: +4 insilico_pcr (core) +3 HSP/event/product (server), network mocked.
160 pytest pass. Verified in-app: organism toggle, products render (populated
+ clean), spec chips, footer copy, mobile no-overflow at 375px.
(Live NCBI can't run from this sandbox's TLS proxy; logic is fully unit-tested
and reuses the proven NCBIWWW path.) Cache-buster → v=20260603-insilicopcr.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

dee/core/primers.py CHANGED
@@ -15,14 +15,14 @@ that in one shot:
15
  * combine everything into a transparent fitness score in [0, 1] and a
16
  plain-English recommendation.
17
 
18
- The **NCBI specificity scan** (blastn-short against nt, to catch off-target
19
- priming genome-wide) is a network job and lives in ``server.py``; this module
20
- stays pure and unit-testable. ``rank()`` accepts the specificity result and
21
- folds it into the final score when it's available.
22
-
23
- Honesty: this is primer triage, not a full in-silico PCR. The specificity scan
24
- flags how many strong genomic matches each primer has; it does not enumerate
25
- every possible spurious amplicon the way NCBI Primer-BLAST's paired search does.
26
  """
27
  from __future__ import annotations
28
 
@@ -39,6 +39,7 @@ MAX_PRIMERS = 50
39
  MIN_LEN = 10
40
  MAX_LEN = 60
41
  MAX_TEMPLATE = 60_000 # bp; longer → ask the user to trim to the region
 
42
  _SEED = 10 # 3'-anchor seed length used to find priming sites
43
  _DNA_RE = re.compile(r"^[ACGTN]+$")
44
  _COMP = str.maketrans("ACGTN", "TGCAN")
@@ -338,6 +339,45 @@ def score_amplicon(fwd: Dict[str, Any], rev: Dict[str, Any],
338
  return res
339
 
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  # ── fitness rubric + recommendation ──────────────────────────────────────────
342
  def _primer_fitness(p: Dict[str, Any], spec: Optional[Dict[str, Any]],
343
  has_template: bool) -> Tuple[float, List[str]]:
@@ -391,22 +431,37 @@ def _primer_fitness(p: Dict[str, Any], spec: Optional[Dict[str, Any]],
391
  why.append("No strong 3'-anchored match on your template — may not amplify it.")
392
 
393
  if spec is not None:
394
- n = spec.get("strong_offtargets")
395
- if n is None:
396
- why.append("Specificity scan returned nothing usable.")
397
- elif n <= 1:
398
- score += 0.20; why.append("NCBI scan: no off-target priming matches — specific.")
399
- elif n <= 5:
400
- score += 0.10; why.append(f"NCBI scan: {n} strong matches — mostly specific.")
 
 
 
 
401
  else:
402
- why.append(f"NCBI scan: {n} strong genomic matches — risk of mis-priming.")
 
 
 
 
 
 
 
 
403
  return round(min(score, 1.0), 3), why
404
 
405
 
406
  def rank(primers: List[Dict[str, Any]], template: str = "",
407
- specificity: Optional[Dict[str, Dict[str, Any]]] = None) -> Dict[str, Any]:
 
408
  """Attach fitness + reasoning to each primer, score amplicons, and pick the
409
- best. ``specificity`` maps primer id → {strong_offtargets, top_hits}."""
 
 
410
  has_template = bool(template)
411
  for p in primers:
412
  spec = (specificity or {}).get(p["id"]) if specificity else None
@@ -430,6 +485,7 @@ def rank(primers: List[Dict[str, Any]], template: str = "",
430
  return {
431
  "primers": ranked,
432
  "amplicons": amplicons,
 
433
  "best_primer_id": best_id,
434
  "best_pair": amplicons[0] if amplicons else None,
435
  "has_template": has_template,
 
15
  * combine everything into a transparent fitness score in [0, 1] and a
16
  plain-English recommendation.
17
 
18
+ The **NCBI specificity scan** is a network job and lives in ``server.py``: it
19
+ BLASTs every primer against a chosen organism, then runs full **in-silico PCR**
20
+ here (``insilico_pcr``) — pairing any forward-oriented priming site with any
21
+ downstream reverse-oriented site within a sane product size, exactly like NCBI
22
+ Primer-BLAST's specificity check. The result is the set of predicted PCR
23
+ products (intended + unintended), computed entirely on our side so the user
24
+ never has to leave for a third-party tool. ``rank()`` folds the off-target
25
+ product counts into the final score.
26
  """
27
  from __future__ import annotations
28
 
 
39
  MIN_LEN = 10
40
  MAX_LEN = 60
41
  MAX_TEMPLATE = 60_000 # bp; longer → ask the user to trim to the region
42
+ MAX_PRODUCT = 4000 # bp; products bigger than this won't amplify in a std PCR
43
  _SEED = 10 # 3'-anchor seed length used to find priming sites
44
  _DNA_RE = re.compile(r"^[ACGTN]+$")
45
  _COMP = str.maketrans("ACGTN", "TGCAN")
 
339
  return res
340
 
341
 
342
+ # ── in-silico PCR (the Primer-BLAST specificity check, in-house) ────────────
343
+ # A "priming event" is one BLAST hit good enough to extend: it carries the
344
+ # subject it landed on, the 5'/3' subject coordinates, and the direction the
345
+ # polymerase would run ("+" = toward higher coords, "-" = toward lower). Any
346
+ # "+" event upstream of a "-" event on the SAME subject, within MAX_PRODUCT bp,
347
+ # is a predicted PCR product — exactly how Primer-BLAST flags off-target
348
+ # amplicons. We pair across ALL submitted primers (not just declared F/R), so a
349
+ # forward primer mis-pairing with another forward's reverse-complement site is
350
+ # caught too.
351
+ def insilico_pcr(events_by_subject: Dict[str, List[Dict[str, Any]]],
352
+ max_product: int = MAX_PRODUCT,
353
+ cap: int = 60) -> List[Dict[str, Any]]:
354
+ products: List[Dict[str, Any]] = []
355
+ for subj, events in events_by_subject.items():
356
+ plus = [e for e in events if e["dir"] == "+"]
357
+ minus = [e for e in events if e["dir"] == "-"]
358
+ for f in plus:
359
+ for r in minus:
360
+ # convergent: the forward site sits to the left of the reverse
361
+ # site and they point toward each other.
362
+ if f["pos5"] < r["pos5"] and f["pos3"] < r["pos3"]:
363
+ size = r["pos5"] - f["pos5"] + 1
364
+ if 1 <= size <= max_product:
365
+ products.append({
366
+ "subject": subj,
367
+ "title": f.get("title") or r.get("title") or subj,
368
+ "organism": f.get("organism") or r.get("organism") or "",
369
+ "fwd": f["primer_id"], "rev": r["primer_id"],
370
+ "fwd_name": f.get("name", f["primer_id"]),
371
+ "rev_name": r.get("name", r["primer_id"]),
372
+ "size": size,
373
+ })
374
+ if len(products) >= cap:
375
+ products.sort(key=lambda p: p["size"])
376
+ return products
377
+ products.sort(key=lambda p: p["size"])
378
+ return products
379
+
380
+
381
  # ── fitness rubric + recommendation ──────────────────────────────────────────
382
  def _primer_fitness(p: Dict[str, Any], spec: Optional[Dict[str, Any]],
383
  has_template: bool) -> Tuple[float, List[str]]:
 
431
  why.append("No strong 3'-anchored match on your template — may not amplify it.")
432
 
433
  if spec is not None:
434
+ # Off-target PRODUCTS (full in-silico PCR) are the real signal — a primer
435
+ # can match many places yet still amplify nothing spurious. Fall back to
436
+ # raw match count only if product info is absent.
437
+ prod = spec.get("offtarget_products")
438
+ if prod is not None:
439
+ if prod == 0:
440
+ score += 0.20; why.append("In-silico PCR: no off-target products — specific.")
441
+ elif prod <= 2:
442
+ score += 0.08; why.append(f"In-silico PCR: {prod} possible off-target product(s) — mostly specific.")
443
+ else:
444
+ why.append(f"In-silico PCR: {prod} predicted off-target products — risk of mis-priming.")
445
  else:
446
+ n = spec.get("strong_offtargets")
447
+ if n is None:
448
+ why.append("Specificity scan returned nothing usable.")
449
+ elif n <= 1:
450
+ score += 0.20; why.append("NCBI scan: no off-target priming matches — specific.")
451
+ elif n <= 5:
452
+ score += 0.10; why.append(f"NCBI scan: {n} strong matches — mostly specific.")
453
+ else:
454
+ why.append(f"NCBI scan: {n} strong genomic matches — risk of mis-priming.")
455
  return round(min(score, 1.0), 3), why
456
 
457
 
458
  def rank(primers: List[Dict[str, Any]], template: str = "",
459
+ specificity: Optional[Dict[str, Dict[str, Any]]] = None,
460
+ products: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
461
  """Attach fitness + reasoning to each primer, score amplicons, and pick the
462
+ best. ``specificity`` maps primer id → {offtarget_products, strong_offtargets,
463
+ top_hits}; ``products`` is the in-silico PCR product list (intended +
464
+ unintended) surfaced to the UI."""
465
  has_template = bool(template)
466
  for p in primers:
467
  spec = (specificity or {}).get(p["id"]) if specificity else None
 
485
  return {
486
  "primers": ranked,
487
  "amplicons": amplicons,
488
+ "offtarget_products": products or [],
489
  "best_primer_id": best_id,
490
  "best_pair": amplicons[0] if amplicons else None,
491
  "has_template": has_template,
dee/server.py CHANGED
@@ -446,6 +446,20 @@ def _run_blast(job: BlastJob, protein: str) -> None:
446
  # blastn-short submission (a multi-FASTA query) — literally "blast them all
447
  # together" — and NCBIXML yields one record per primer, in query order.
448
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  @dataclass
450
  class PrimerJob:
451
  job_id: str
@@ -455,8 +469,10 @@ class PrimerJob:
455
  finished_at: Optional[float] = None
456
  primers: List[Dict[str, Any]] = field(default_factory=list) # scored, pre-spec
457
  template: str = ""
 
458
  warnings: List[str] = field(default_factory=list)
459
  specificity: Optional[Dict[str, Dict[str, Any]]] = None # id -> {...}
 
460
  error: Optional[str] = None
461
 
462
  def elapsed(self) -> float:
@@ -465,7 +481,9 @@ class PrimerJob:
465
 
466
  def result(self) -> Dict[str, Any]:
467
  from .core import primers as _P
468
- return _P.rank(self.primers, self.template, self.specificity)
 
 
469
 
470
  def public(self) -> Dict[str, Any]:
471
  return {
@@ -484,35 +502,46 @@ _PRIMER_BY_ID: Dict[str, PrimerJob] = {}
484
  _PRIMER_LOCK = threading.Lock()
485
 
486
 
487
- def _primer_specificity_from_record(alignment_iter, primer_len: int) -> Dict[str, Any]:
488
- """Count 'strong' off-target matches for one primer's BLAST record: hits
489
- that align over (nearly) the full primer with high identity — the ones that
490
- could actually prime. Returns a count + a few example subjects."""
491
- strong = 0
492
- top: List[Dict[str, Any]] = []
493
- for alignment in alignment_iter:
494
- for hsp in alignment.hsps:
495
- ident = hsp.identities / max(1, hsp.align_length)
496
- if hsp.align_length >= primer_len - 2 and ident >= 0.90:
497
- strong += 1
498
- if len(top) < 5:
499
- top.append({
500
- "title": _trim_description(getattr(alignment, "hit_def", ""))[:80],
501
- "identity_pct": round(100.0 * ident, 1),
502
- "organism": _extract_organism(getattr(alignment, "hit_def", "")),
503
- })
504
- break # count each subject once
505
- return {"strong_offtargets": strong, "top_hits": top}
 
 
 
 
 
506
 
507
 
508
  def _run_primer_blast(job: PrimerJob) -> None:
509
- """One blastn-short submission for ALL primers; map records back by order."""
 
 
 
 
 
 
510
  try:
511
  from Bio.Blast import NCBIWWW, NCBIXML
512
 
513
  job.status = "scanning"
514
  fasta = "\n".join(f">{p['id']}\n{p['seq']}" for p in job.primers)
515
- handle = NCBIWWW.qblast(
516
  program="blastn",
517
  database="nt",
518
  sequence=fasta,
@@ -523,17 +552,45 @@ def _run_primer_blast(job: PrimerJob) -> None:
523
  nucl_penalty=-3,
524
  hitlist_size=50,
525
  )
 
 
 
 
 
526
  spec: Dict[str, Dict[str, Any]] = {}
 
527
  records = list(NCBIXML.parse(handle))
528
  # Records come back in query order; align them to job.primers.
529
  for i, record in enumerate(records):
530
  if i >= len(job.primers):
531
  break
532
  p = job.primers[i]
533
- spec[p["id"]] = _primer_specificity_from_record(record.alignments, len(p["seq"]))
534
- # Any primer NCBI dropped (no hits at all) → explicitly clean.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535
  for p in job.primers:
536
- spec.setdefault(p["id"], {"strong_offtargets": 0, "top_hits": []})
 
 
 
 
537
  job.specificity = spec
538
  job.status = "done"
539
  except Exception as exc: # noqa: BLE001
@@ -1071,6 +1128,9 @@ def create_app() -> Flask:
1071
  primers_text = (body.get("primers") or "").strip()
1072
  template = re.sub(r"\s+", "", (body.get("template") or "")).upper()
1073
  scan_ncbi = bool(body.get("scan_ncbi"))
 
 
 
1074
  if not primers_text:
1075
  return jsonify({"error": "Paste at least one primer."}), 400
1076
  if template and not re.fullmatch(r"[ACGTN]+", template):
@@ -1102,7 +1162,8 @@ def create_app() -> Flask:
1102
  "kind": "consent_required",
1103
  }), 403
1104
 
1105
- seq_hash = _hash_sequence("|".join(p["seq"] for p in parsed) + "::" + template)
 
1106
  with _PRIMER_LOCK:
1107
  cached = _PRIMER_CACHE.get(seq_hash)
1108
  if cached and cached.status in {"done", "scanning", "pending"}:
@@ -1113,7 +1174,8 @@ def create_app() -> Flask:
1113
  "warnings": cached.warnings,
1114
  })
1115
  job = PrimerJob(job_id=uuid.uuid4().hex[:12], seq_hash=seq_hash,
1116
- primers=scored, template=template, warnings=warnings)
 
1117
  _PRIMER_CACHE[seq_hash] = job
1118
  _PRIMER_BY_ID[job.job_id] = job
1119
 
 
446
  # blastn-short submission (a multi-FASTA query) — literally "blast them all
447
  # together" — and NCBIXML yields one record per primer, in query order.
448
 
449
+ # Organism targeting for the specificity scan — mirrors Primer-BLAST's
450
+ # "Organism" field. Restricts the BLAST via an Entrez query so off-target =
451
+ # "would mis-prime in THIS genome", not "matches something, somewhere, in nt".
452
+ _PRIMER_ORGANISMS = {
453
+ "human": '"Homo sapiens"[Organism]',
454
+ "mouse": '"Mus musculus"[Organism]',
455
+ "ecoli": '"Escherichia coli"[Organism]',
456
+ "yeast": '"Saccharomyces cerevisiae"[Organism]',
457
+ "rat": '"Rattus norvegicus"[Organism]',
458
+ "zebrafish": '"Danio rerio"[Organism]',
459
+ "all": "", # whole nt — broad, noisier
460
+ }
461
+
462
+
463
  @dataclass
464
  class PrimerJob:
465
  job_id: str
 
469
  finished_at: Optional[float] = None
470
  primers: List[Dict[str, Any]] = field(default_factory=list) # scored, pre-spec
471
  template: str = ""
472
+ organism: str = "human"
473
  warnings: List[str] = field(default_factory=list)
474
  specificity: Optional[Dict[str, Dict[str, Any]]] = None # id -> {...}
475
+ products: List[Dict[str, Any]] = field(default_factory=list) # in-silico PCR
476
  error: Optional[str] = None
477
 
478
  def elapsed(self) -> float:
 
481
 
482
  def result(self) -> Dict[str, Any]:
483
  from .core import primers as _P
484
+ out = _P.rank(self.primers, self.template, self.specificity, self.products)
485
+ out["organism"] = self.organism
486
+ return out
487
 
488
  def public(self) -> Dict[str, Any]:
489
  return {
 
502
  _PRIMER_LOCK = threading.Lock()
503
 
504
 
505
+ def _hsp_to_event(alignment, hsp, primer: Dict[str, Any]) -> Optional[Dict[str, Any]]:
506
+ """Turn one BLAST HSP into a 'priming event' for in-silico PCR — but only if
507
+ it's 3'-anchored enough to actually extend. Returns None otherwise.
508
+
509
+ Direction: the primer's 3' end maps to ``hsp.sbjct_end`` in both strand
510
+ cases; the polymerase runs toward higher coords when sbjct_end > sbjct_start
511
+ ('+') and toward lower coords otherwise ('-')."""
512
+ plen = len(primer["seq"])
513
+ ident = hsp.identities / max(1, hsp.align_length)
514
+ # Must cover the primer's 3' end and be a near-full, high-identity match.
515
+ if ident < 0.90 or hsp.align_length < plen - 3 or hsp.query_end < plen - 1:
516
+ return None
517
+ ss, se = hsp.sbjct_start, hsp.sbjct_end
518
+ direction = "+" if se >= ss else "-"
519
+ return {
520
+ "primer_id": primer["id"],
521
+ "name": primer.get("name", primer["id"]),
522
+ "pos5": ss, # 5' end of the primer on the subject
523
+ "pos3": se, # 3' end (where extension starts)
524
+ "dir": direction,
525
+ "title": _trim_description(getattr(alignment, "hit_def", ""))[:80],
526
+ "organism": _extract_organism(getattr(alignment, "hit_def", "")),
527
+ "identity_pct": round(100.0 * ident, 1),
528
+ }
529
 
530
 
531
  def _run_primer_blast(job: PrimerJob) -> None:
532
+ """One blastn-short submission for ALL primers, then in-silico PCR.
533
+
534
+ Pairs every forward-oriented priming site with every downstream reverse
535
+ site on the same subject (within MAX_PRODUCT bp) to predict the actual PCR
536
+ products — the same specificity check Primer-BLAST runs, done here so the
537
+ user never leaves the site."""
538
+ from .core import primers as _P
539
  try:
540
  from Bio.Blast import NCBIWWW, NCBIXML
541
 
542
  job.status = "scanning"
543
  fasta = "\n".join(f">{p['id']}\n{p['seq']}" for p in job.primers)
544
+ qblast_kw = dict(
545
  program="blastn",
546
  database="nt",
547
  sequence=fasta,
 
552
  nucl_penalty=-3,
553
  hitlist_size=50,
554
  )
555
+ entrez = _PRIMER_ORGANISMS.get(job.organism, "")
556
+ if entrez:
557
+ qblast_kw["entrez_query"] = entrez
558
+ handle = NCBIWWW.qblast(**qblast_kw)
559
+
560
  spec: Dict[str, Dict[str, Any]] = {}
561
+ events_by_subject: Dict[str, List[Dict[str, Any]]] = {}
562
  records = list(NCBIXML.parse(handle))
563
  # Records come back in query order; align them to job.primers.
564
  for i, record in enumerate(records):
565
  if i >= len(job.primers):
566
  break
567
  p = job.primers[i]
568
+ strong, top = 0, []
569
+ for alignment in record.alignments:
570
+ acc = getattr(alignment, "accession", "") or getattr(alignment, "hit_id", "")
571
+ hit_strong = False
572
+ for hsp in alignment.hsps:
573
+ ev = _hsp_to_event(alignment, hsp, p)
574
+ if ev:
575
+ events_by_subject.setdefault(acc, []).append(ev)
576
+ hit_strong = True
577
+ if hit_strong:
578
+ strong += 1
579
+ if len(top) < 5:
580
+ top.append({
581
+ "title": _trim_description(getattr(alignment, "hit_def", ""))[:80],
582
+ "organism": _extract_organism(getattr(alignment, "hit_def", "")),
583
+ })
584
+ spec[p["id"]] = {"strong_offtargets": strong, "top_hits": top}
585
+
586
+ # In-silico PCR across ALL primers, then attribute products per primer.
587
+ products = _P.insilico_pcr(events_by_subject)
588
  for p in job.primers:
589
+ pid = p["id"]
590
+ cnt = sum(1 for pr in products if pr["fwd"] == pid or pr["rev"] == pid)
591
+ spec.setdefault(pid, {"strong_offtargets": 0, "top_hits": []})
592
+ spec[pid]["offtarget_products"] = cnt
593
+ job.products = products
594
  job.specificity = spec
595
  job.status = "done"
596
  except Exception as exc: # noqa: BLE001
 
1128
  primers_text = (body.get("primers") or "").strip()
1129
  template = re.sub(r"\s+", "", (body.get("template") or "")).upper()
1130
  scan_ncbi = bool(body.get("scan_ncbi"))
1131
+ organism = (body.get("organism") or "human").lower()
1132
+ if organism not in _PRIMER_ORGANISMS:
1133
+ organism = "human"
1134
  if not primers_text:
1135
  return jsonify({"error": "Paste at least one primer."}), 400
1136
  if template and not re.fullmatch(r"[ACGTN]+", template):
 
1162
  "kind": "consent_required",
1163
  }), 403
1164
 
1165
+ seq_hash = _hash_sequence("|".join(p["seq"] for p in parsed)
1166
+ + "::" + template + "::" + organism)
1167
  with _PRIMER_LOCK:
1168
  cached = _PRIMER_CACHE.get(seq_hash)
1169
  if cached and cached.status in {"done", "scanning", "pending"}:
 
1174
  "warnings": cached.warnings,
1175
  })
1176
  job = PrimerJob(job_id=uuid.uuid4().hex[:12], seq_hash=seq_hash,
1177
+ primers=scored, template=template, organism=organism,
1178
+ warnings=warnings)
1179
  _PRIMER_CACHE[seq_hash] = job
1180
  _PRIMER_BY_ID[job.job_id] = job
1181
 
dee/static/app.css CHANGED
@@ -5382,3 +5382,36 @@ h3, h4 {
5382
  .primer-card-head { flex-direction: column; align-items: flex-start; gap: 8px; }
5383
  .amp-row { flex-direction: column; }
5384
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5382
  .primer-card-head { flex-direction: column; align-items: flex-start; gap: 8px; }
5383
  .amp-row { flex-direction: column; }
5384
  }
5385
+
5386
+ /* ── Primer Picker: organism selector + in-silico PCR products ─────────── */
5387
+ .primer-organism-row { display: flex; flex-direction: column; gap: 4px; margin-top: 6px; }
5388
+ .primer-select {
5389
+ font-size: 13px; padding: 9px 12px; border: 1px solid var(--line-strong);
5390
+ border-radius: var(--r-3); background: var(--gray-0); color: var(--ink);
5391
+ max-width: 360px;
5392
+ }
5393
+ .primer-select:focus { outline: none; border-color: var(--brand); }
5394
+
5395
+ .primer-products { display: flex; flex-direction: column; gap: 6px; }
5396
+ .primer-clean {
5397
+ font-size: 13px; color: var(--success); background: color-mix(in srgb, var(--success) 12%, transparent);
5398
+ border-left: 3px solid var(--success); border-radius: var(--r-2); padding: 11px 14px;
5399
+ }
5400
+ .primer-clean strong { color: var(--success); }
5401
+ .primer-prod-note { font-size: 12.5px; color: var(--ink-soft); margin-bottom: 4px; }
5402
+ .prod-row {
5403
+ display: flex; flex-wrap: wrap; justify-content: space-between; gap: 6px 12px;
5404
+ padding: 9px 14px; border: 1px solid var(--line); border-left: 3px solid var(--danger);
5405
+ border-radius: var(--r-2); background: var(--gray-0);
5406
+ }
5407
+ .prod-pair { font-weight: 600; font-size: 12.5px; }
5408
+ .prod-info { display: flex; gap: 12px; align-items: center; font-size: 12px; color: var(--ink-soft); }
5409
+ .prod-size { font-family: var(--font-mono); color: var(--danger); }
5410
+ .prod-subj { color: var(--ink-faint); max-width: 48ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
5411
+ .primer-prod-more { font-size: 11.5px; color: var(--ink-faint); margin-top: 4px; }
5412
+
5413
+ @media (max-width: 640px) {
5414
+ .primer-select { max-width: 100%; }
5415
+ .prod-row { flex-direction: column; }
5416
+ .prod-subj { max-width: 100%; white-space: normal; }
5417
+ }
dee/static/app.js CHANGED
@@ -5836,6 +5836,8 @@ function runOracle(opts){
5836
  const inputEl = document.getElementById('primerInput');
5837
  const templateEl = document.getElementById('primerTemplate');
5838
  const scanEl = document.getElementById('primerScanNcbi');
 
 
5839
  const exampleBtn = document.getElementById('primerExample');
5840
  const errEl = document.getElementById('primerError');
5841
  const warnEl = document.getElementById('primerWarnings');
@@ -5843,9 +5845,20 @@ function runOracle(opts){
5843
  const statusEl = document.getElementById('primerScanStatus');
5844
  const bestEl = document.getElementById('primerBest');
5845
  const ampEl = document.getElementById('primerAmplicons');
 
5846
  const listEl = document.getElementById('primerList');
5847
  let pollHandle = null;
5848
 
 
 
 
 
 
 
 
 
 
 
5849
  const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
5850
  const pct = (f) => Math.round((Number(f) || 0) * 100);
5851
 
@@ -5870,10 +5883,11 @@ function runOracle(opts){
5870
  function specBadge(p) {
5871
  const s = p.specificity;
5872
  if (!s) return '';
5873
- const n = s.strong_offtargets;
5874
- if (n <= 1) return '<span class="pchip pchip-good">NCBI: specific</span>';
5875
- if (n <= 5) return `<span class="pchip pchip-warn">NCBI: ${n} matches</span>`;
5876
- return `<span class="pchip pchip-bad">NCBI: ${n} off-target</span>`;
 
5877
  }
5878
 
5879
  function renderPrimerCard(p, isBest) {
@@ -5932,6 +5946,31 @@ function runOracle(opts){
5932
  </div>`).join('');
5933
  } else { ampEl.hidden = true; ampEl.innerHTML = ''; }
5934
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5935
  // Ranked list
5936
  listEl.innerHTML = '<h3 class="primer-sec-title">All primers · ranked</h3>' +
5937
  (r.primers || []).map((p, i) => renderPrimerCard(p, i === 0)).join('');
@@ -5942,11 +5981,11 @@ function runOracle(opts){
5942
  if (state === 'scanning') {
5943
  statusEl.hidden = false;
5944
  statusEl.innerHTML = `<span class="ip-radar-spinner" aria-hidden="true"></span> `
5945
- + `Scanning NCBI for off-target priming…${elapsed != null ? ' · ' + elapsed + 's' : ''} `
5946
- + `<span class="primer-scan-note">(template scores are shown now; specificity will update)</span>`;
5947
  } else if (state === 'done') {
5948
  statusEl.hidden = false;
5949
- statusEl.innerHTML = '<span class="primer-scan-done">✓ NCBI specificity scan complete</span>';
5950
  setTimeout(() => { if (statusEl) statusEl.hidden = true; }, 4000);
5951
  } else if (state === 'error') {
5952
  statusEl.hidden = false;
@@ -5977,6 +6016,7 @@ function runOracle(opts){
5977
  if (!primers) { showErr('Paste at least one primer.'); return; }
5978
  const template = (templateEl.value || '').trim();
5979
  const scan = !!(scanEl && scanEl.checked);
 
5980
  const orig = analyzeBtn.textContent;
5981
  analyzeBtn.disabled = true;
5982
  analyzeBtn.textContent = 'Analysing…';
@@ -5984,7 +6024,7 @@ function runOracle(opts){
5984
  try {
5985
  const res = await fetch('/api/primers/analyze', {
5986
  method: 'POST', headers: { 'Content-Type': 'application/json' },
5987
- body: JSON.stringify({ primers, template, scan_ncbi: scan, blast_consent: scan }),
5988
  });
5989
  const data = await res.json();
5990
  if (res.status === 403 && data.kind === 'signin_required') {
 
5836
  const inputEl = document.getElementById('primerInput');
5837
  const templateEl = document.getElementById('primerTemplate');
5838
  const scanEl = document.getElementById('primerScanNcbi');
5839
+ const orgRow = document.getElementById('primerOrganismRow');
5840
+ const orgEl = document.getElementById('primerOrganism');
5841
  const exampleBtn = document.getElementById('primerExample');
5842
  const errEl = document.getElementById('primerError');
5843
  const warnEl = document.getElementById('primerWarnings');
 
5845
  const statusEl = document.getElementById('primerScanStatus');
5846
  const bestEl = document.getElementById('primerBest');
5847
  const ampEl = document.getElementById('primerAmplicons');
5848
+ const prodEl = document.getElementById('primerProducts');
5849
  const listEl = document.getElementById('primerList');
5850
  let pollHandle = null;
5851
 
5852
+ // The organism selector only matters when the specificity scan is on.
5853
+ if (scanEl && orgRow) {
5854
+ const syncOrg = () => { orgRow.hidden = !scanEl.checked; };
5855
+ scanEl.addEventListener('change', syncOrg);
5856
+ syncOrg();
5857
+ }
5858
+ const ORG_LABEL = { human: 'Homo sapiens', mouse: 'Mus musculus', rat: 'Rattus norvegicus',
5859
+ zebrafish: 'Danio rerio', yeast: 'S. cerevisiae', ecoli: 'E. coli',
5860
+ all: 'all sequences (nt)' };
5861
+
5862
  const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
5863
  const pct = (f) => Math.round((Number(f) || 0) * 100);
5864
 
 
5883
  function specBadge(p) {
5884
  const s = p.specificity;
5885
  if (!s) return '';
5886
+ // Off-target PRODUCTS (in-silico PCR) are the real signal.
5887
+ const n = (s.offtarget_products != null) ? s.offtarget_products : s.strong_offtargets;
5888
+ if (n === 0) return '<span class="pchip pchip-good">specific · 0 off-target products</span>';
5889
+ if (n <= 2) return `<span class="pchip pchip-warn">${n} off-target product${n === 1 ? '' : 's'}</span>`;
5890
+ return `<span class="pchip pchip-bad">${n} off-target products</span>`;
5891
  }
5892
 
5893
  function renderPrimerCard(p, isBest) {
 
5946
  </div>`).join('');
5947
  } else { ampEl.hidden = true; ampEl.innerHTML = ''; }
5948
 
5949
+ // Predicted PCR products from the in-silico PCR specificity scan.
5950
+ if (r.specificity_done) {
5951
+ const prods = r.offtarget_products || [];
5952
+ const org = ORG_LABEL[r.organism] || r.organism || 'the selected genome';
5953
+ if (!prods.length) {
5954
+ prodEl.hidden = false;
5955
+ prodEl.innerHTML = '<h3 class="primer-sec-title">In-silico PCR · specificity</h3>' +
5956
+ `<div class="primer-clean">✓ No off-target products predicted in <strong>${esc(org)}</strong>. ` +
5957
+ `These primers look specific.</div>`;
5958
+ } else {
5959
+ prodEl.hidden = false;
5960
+ prodEl.innerHTML = '<h3 class="primer-sec-title">Predicted off-target products · ' +
5961
+ esc(org) + '</h3>' +
5962
+ `<div class="primer-prod-note">${prods.length} unintended product${prods.length === 1 ? '' : 's'} ` +
5963
+ `your primers could amplify in this genome:</div>` +
5964
+ prods.slice(0, 12).map(pr => `
5965
+ <div class="prod-row">
5966
+ <div class="prod-pair">${esc(pr.fwd_name || pr.fwd)} <span class="amp-x">+</span> ${esc(pr.rev_name || pr.rev)}</div>
5967
+ <div class="prod-info"><span class="prod-size">${pr.size.toLocaleString()} bp</span>
5968
+ <span class="prod-subj">${esc(pr.title || pr.subject)}</span></div>
5969
+ </div>`).join('') +
5970
+ (prods.length > 12 ? `<div class="primer-prod-more">+ ${prods.length - 12} more</div>` : '');
5971
+ }
5972
+ } else { prodEl.hidden = true; prodEl.innerHTML = ''; }
5973
+
5974
  // Ranked list
5975
  listEl.innerHTML = '<h3 class="primer-sec-title">All primers · ranked</h3>' +
5976
  (r.primers || []).map((p, i) => renderPrimerCard(p, i === 0)).join('');
 
5981
  if (state === 'scanning') {
5982
  statusEl.hidden = false;
5983
  statusEl.innerHTML = `<span class="ip-radar-spinner" aria-hidden="true"></span> `
5984
+ + `Running in-silico PCR — searching the genome for off-target products…${elapsed != null ? ' · ' + elapsed + 's' : ''} `
5985
+ + `<span class="primer-scan-note">(template scores show now; specificity updates when it finishes)</span>`;
5986
  } else if (state === 'done') {
5987
  statusEl.hidden = false;
5988
+ statusEl.innerHTML = '<span class="primer-scan-done">✓ In-silico PCR specificity check complete</span>';
5989
  setTimeout(() => { if (statusEl) statusEl.hidden = true; }, 4000);
5990
  } else if (state === 'error') {
5991
  statusEl.hidden = false;
 
6016
  if (!primers) { showErr('Paste at least one primer.'); return; }
6017
  const template = (templateEl.value || '').trim();
6018
  const scan = !!(scanEl && scanEl.checked);
6019
+ const organism = (orgEl && orgEl.value) || 'human';
6020
  const orig = analyzeBtn.textContent;
6021
  analyzeBtn.disabled = true;
6022
  analyzeBtn.textContent = 'Analysing…';
 
6024
  try {
6025
  const res = await fetch('/api/primers/analyze', {
6026
  method: 'POST', headers: { 'Content-Type': 'application/json' },
6027
+ body: JSON.stringify({ primers, template, scan_ncbi: scan, blast_consent: scan, organism }),
6028
  });
6029
  const data = await res.json();
6030
  if (res.status === 403 && data.kind === 'signin_required') {
dee/static/index.html CHANGED
@@ -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=20260603-primersgate" />
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
@@ -860,12 +860,25 @@
860
  <label class="primer-toggle">
861
  <input type="checkbox" id="primerScanNcbi" />
862
  <span class="primer-toggle-text">
863
- <strong>Run NCBI specificity scan</strong>
864
- <span class="field-hint">Sends your primers to <code>blast.ncbi.nlm.nih.gov</code>
865
- (~1–3 min) to flag genome-wide off-target priming. Leave off if your primers are
866
- confidential.</span>
 
867
  </span>
868
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
869
 
870
  <div class="primer-actions">
871
  <button class="ghost" type="button" id="primerExample">Load example</button>
@@ -879,10 +892,11 @@
879
  <div class="primer-scan-status" id="primerScanStatus" hidden></div>
880
  <div class="primer-best" id="primerBest"></div>
881
  <div class="primer-amplicons" id="primerAmplicons"></div>
 
882
  <div class="primer-list" id="primerList"></div>
883
- <p class="primer-foot">Triage, not full in-silico PCR — the NCBI scan flags how many strong
884
- genomic matches each primer has, but doesn't enumerate every spurious amplicon. Confirm
885
- your final pair in NCBI Primer-BLAST before ordering.</p>
886
  </section>
887
  </section>
888
 
@@ -1246,6 +1260,6 @@
1246
  <!-- Cloning reference data must load before app.js so the Designer
1247
  can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
1248
  <script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
1249
- <script src="/static/app.js?v=20260603-primersgate" defer></script>
1250
  </body>
1251
  </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=20260603-insilicopcr" />
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
 
860
  <label class="primer-toggle">
861
  <input type="checkbox" id="primerScanNcbi" />
862
  <span class="primer-toggle-text">
863
+ <strong>Run specificity scan (in-silico PCR)</strong>
864
+ <span class="field-hint">Searches the chosen genome and runs in-silico PCR to
865
+ predict every product your primers would make — intended <em>and</em> off-target —
866
+ right here, so you don't need a separate tool. Sequences go to NCBI BLAST
867
+ (~1–3 min); leave off if your primers are confidential.</span>
868
  </span>
869
  </label>
870
+ <div class="primer-organism-row" id="primerOrganismRow" hidden>
871
+ <label class="field-label" for="primerOrganism">Check specificity against</label>
872
+ <select id="primerOrganism" class="primer-select">
873
+ <option value="human" selected>Human — Homo sapiens</option>
874
+ <option value="mouse">Mouse — Mus musculus</option>
875
+ <option value="rat">Rat — Rattus norvegicus</option>
876
+ <option value="zebrafish">Zebrafish — Danio rerio</option>
877
+ <option value="yeast">Yeast — S. cerevisiae</option>
878
+ <option value="ecoli">E. coli</option>
879
+ <option value="all">All sequences (nt) — broad, noisier</option>
880
+ </select>
881
+ </div>
882
 
883
  <div class="primer-actions">
884
  <button class="ghost" type="button" id="primerExample">Load example</button>
 
892
  <div class="primer-scan-status" id="primerScanStatus" hidden></div>
893
  <div class="primer-best" id="primerBest"></div>
894
  <div class="primer-amplicons" id="primerAmplicons"></div>
895
+ <div class="primer-products" id="primerProducts"></div>
896
  <div class="primer-list" id="primerList"></div>
897
+ <p class="primer-foot">The specificity scan runs full in-silico PCR against your chosen
898
+ genome — the same check NCBI Primer-BLAST performs — so the result is complete here.
899
+ Predictions are a strong guide; as always, validate critical results at the bench.</p>
900
  </section>
901
  </section>
902
 
 
1260
  <!-- Cloning reference data must load before app.js so the Designer
1261
  can read VECTORS / ENZYMES / CLONING_METHODS / TAGS / LINKERS. -->
1262
  <script src="/static/cloning_db.js?v=20260530-ui-polish" defer></script>
1263
+ <script src="/static/app.js?v=20260603-insilicopcr" defer></script>
1264
  </body>
1265
  </html>
tests/test_primer_scan.py CHANGED
@@ -1,6 +1,7 @@
1
- """Server-layer tests for the Primer Picker's NCBI specificity scan.
2
- Network mocked — verifies the strong-off-target count, the per-query record →
3
- primer mapping, and that the merged result carries specificity into ranking."""
 
4
  import sys
5
  import types
6
 
@@ -9,29 +10,46 @@ from dee.core import primers as P
9
 
10
 
11
  class _Hsp:
12
- def __init__(self, identities, align_length):
13
  self.identities = identities
14
  self.align_length = align_length
 
 
 
15
 
16
 
17
  class _Aln:
18
- def __init__(self, hit_def, hsps):
19
  self.hit_def = hit_def
20
  self.hsps = hsps
 
21
 
22
 
23
- def test_specificity_counts_only_strong_full_length_hits():
24
- prim_len = 20
25
- alns = [
26
- _Aln("Exact match [Homo sapiens]", [_Hsp(20, 20)]), # strong
27
- _Aln("Near match [Mus musculus]", [_Hsp(19, 20)]), # strong (95%)
28
- _Aln("Half match [E. coli]", [_Hsp(10, 20)]), # weak ident
29
- _Aln("Short partial [X]", [_Hsp(12, 12)]), # too short
30
- ]
31
- out = server._primer_specificity_from_record(alns, prim_len)
32
- assert out["strong_offtargets"] == 2
33
- assert len(out["top_hits"]) == 2
34
- assert out["top_hits"][0]["identity_pct"] == 100.0
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
 
37
  def _mock_blast(monkeypatch, records):
@@ -41,37 +59,50 @@ def _mock_blast(monkeypatch, records):
41
  monkeypatch.setitem(sys.modules, "Bio.Blast", fake)
42
 
43
 
44
- def test_run_primer_blast_maps_records_to_primers_in_order(monkeypatch):
45
- prims, _ = P.parse_primers("AAAAAAAAAAAAAAAAAAAA\nCCCCCCCCCCCCCCCCCCCC")
 
 
46
  scored = [P.score_primer(p) for p in prims]
47
- job = server.PrimerJob(job_id="j", seq_hash="h", primers=scored)
48
- # record 0 → many strong hits; record 1 → none
49
- rec0 = types.SimpleNamespace(alignments=[_Aln("hit [A]", [_Hsp(20, 20)]),
50
- _Aln("hit [B]", [_Hsp(20, 20)])])
51
- rec1 = types.SimpleNamespace(alignments=[])
52
- _mock_blast(monkeypatch, [rec0, rec1])
53
 
54
  server._run_primer_blast(job)
55
  assert job.status == "done"
56
- assert job.specificity[scored[0]["id"]]["strong_offtargets"] == 2
57
- assert job.specificity[scored[1]["id"]]["strong_offtargets"] == 0
 
 
58
 
59
 
60
- def test_job_result_merges_specificity_into_ranking(monkeypatch):
61
- prims, _ = P.parse_primers("ACAGTGACCTGAAGTCCATGC\nATATATATATATATATAT")
62
  scored = [P.score_primer(p) for p in prims]
63
  job = server.PrimerJob(job_id="j", seq_hash="h", primers=scored)
64
- # primer 0 clean, primer 1 noisy
65
- rec0 = types.SimpleNamespace(alignments=[])
66
- rec1 = types.SimpleNamespace(alignments=[_Aln(f"h{i} [X]", [_Hsp(18, 18)]) for i in range(30)])
67
- _mock_blast(monkeypatch, [rec0, rec1])
68
  server._run_primer_blast(job)
 
 
 
69
 
 
 
 
 
 
 
 
 
70
  res = job.result()
 
 
71
  assert res["specificity_done"] is True
72
- # the clean, well-formed primer should rank first
73
- assert res["primers"][0]["name"] == prims[0]["name"]
74
- assert "specificity" in res["primers"][0]
75
 
76
 
77
  def test_run_primer_blast_error_sets_status(monkeypatch):
 
1
+ """Server-layer tests for the Primer Picker's specificity scan + in-silico PCR.
2
+ Network mocked — verifies HSP→priming-event conversion (strand/3'-anchor),
3
+ record→primer mapping, and that predicted off-target PRODUCTS are counted and
4
+ folded into ranking."""
5
  import sys
6
  import types
7
 
 
10
 
11
 
12
  class _Hsp:
13
+ def __init__(self, identities, align_length, query_end, sbjct_start, sbjct_end):
14
  self.identities = identities
15
  self.align_length = align_length
16
+ self.query_end = query_end
17
+ self.sbjct_start = sbjct_start
18
+ self.sbjct_end = sbjct_end
19
 
20
 
21
  class _Aln:
22
+ def __init__(self, hit_def, hsps, accession="NC_1"):
23
  self.hit_def = hit_def
24
  self.hsps = hsps
25
+ self.accession = accession
26
 
27
 
28
+ # ── HSP → priming event ─────────────────────────────────────────────────────
29
+ def _primer(seq="ACGTACGTACGTACGTACGT"):
30
+ return {"id": "q0", "name": "p", "seq": seq}
31
+
32
+
33
+ def test_hsp_event_plus_strand():
34
+ p = _primer()
35
+ ev = server._hsp_to_event(_Aln("x [Homo sapiens]", []),
36
+ _Hsp(20, 20, 20, 100, 119), p)
37
+ assert ev["dir"] == "+" and ev["pos5"] == 100 and ev["pos3"] == 119
38
+
39
+
40
+ def test_hsp_event_minus_strand():
41
+ p = _primer()
42
+ ev = server._hsp_to_event(_Aln("x [Homo sapiens]", []),
43
+ _Hsp(20, 20, 20, 200, 181), p)
44
+ assert ev["dir"] == "-" and ev["pos5"] == 200 and ev["pos3"] == 181
45
+
46
+
47
+ def test_hsp_event_rejects_unanchored_or_weak():
48
+ p = _primer()
49
+ # 3' end not aligned (query_end far short of primer length) → None
50
+ assert server._hsp_to_event(_Aln("x", []), _Hsp(15, 15, 15, 100, 114), p) is None
51
+ # low identity → None
52
+ assert server._hsp_to_event(_Aln("x", []), _Hsp(14, 20, 20, 100, 119), p) is None
53
 
54
 
55
  def _mock_blast(monkeypatch, records):
 
59
  monkeypatch.setitem(sys.modules, "Bio.Blast", fake)
60
 
61
 
62
+ def test_run_primer_blast_predicts_offtarget_product(monkeypatch):
63
+ # F primer hits NC_1 at 100-119 (+), R primer hits NC_1 at 600-581 (-)
64
+ # → convergent, 501 bp → one predicted off-target product.
65
+ prims, _ = P.parse_primers(">F\nACGTACGTACGTACGTACGT\n>R\nTTGGCCAATTGGCCAATTGG")
66
  scored = [P.score_primer(p) for p in prims]
67
+ job = server.PrimerJob(job_id="j", seq_hash="h", primers=scored, organism="human")
68
+ recF = types.SimpleNamespace(alignments=[_Aln("chr1 [Homo sapiens]",
69
+ [_Hsp(20, 20, 20, 100, 119)], "NC_1")])
70
+ recR = types.SimpleNamespace(alignments=[_Aln("chr1 [Homo sapiens]",
71
+ [_Hsp(20, 20, 20, 600, 581)], "NC_1")])
72
+ _mock_blast(monkeypatch, [recF, recR])
73
 
74
  server._run_primer_blast(job)
75
  assert job.status == "done"
76
+ assert len(job.products) == 1
77
+ assert job.products[0]["size"] == 501
78
+ assert job.specificity[scored[0]["id"]]["offtarget_products"] == 1
79
+ assert job.specificity[scored[1]["id"]]["offtarget_products"] == 1
80
 
81
 
82
+ def test_run_primer_blast_clean_when_sites_on_different_subjects(monkeypatch):
83
+ prims, _ = P.parse_primers(">F\nACGTACGTACGTACGTACGT\n>R\nTTGGCCAATTGGCCAATTGG")
84
  scored = [P.score_primer(p) for p in prims]
85
  job = server.PrimerJob(job_id="j", seq_hash="h", primers=scored)
86
+ recF = types.SimpleNamespace(alignments=[_Aln("a", [_Hsp(20, 20, 20, 100, 119)], "NC_1")])
87
+ recR = types.SimpleNamespace(alignments=[_Aln("b", [_Hsp(20, 20, 20, 600, 581)], "NC_2")])
88
+ _mock_blast(monkeypatch, [recF, recR])
 
89
  server._run_primer_blast(job)
90
+ assert job.products == []
91
+ assert job.specificity[scored[0]["id"]]["offtarget_products"] == 0
92
+
93
 
94
+ def test_job_result_carries_products_and_organism(monkeypatch):
95
+ prims, _ = P.parse_primers(">F\nACGTACGTACGTACGTACGT\n>R\nTTGGCCAATTGGCCAATTGG")
96
+ scored = [P.score_primer(p) for p in prims]
97
+ job = server.PrimerJob(job_id="j", seq_hash="h", primers=scored, organism="mouse")
98
+ recF = types.SimpleNamespace(alignments=[_Aln("c [Mus musculus]", [_Hsp(20, 20, 20, 100, 119)], "NC_9")])
99
+ recR = types.SimpleNamespace(alignments=[_Aln("c [Mus musculus]", [_Hsp(20, 20, 20, 700, 681)], "NC_9")])
100
+ _mock_blast(monkeypatch, [recF, recR])
101
+ server._run_primer_blast(job)
102
  res = job.result()
103
+ assert res["organism"] == "mouse"
104
+ assert len(res["offtarget_products"]) == 1
105
  assert res["specificity_done"] is True
 
 
 
106
 
107
 
108
  def test_run_primer_blast_error_sets_status(monkeypatch):
tests/test_primers.py CHANGED
@@ -131,7 +131,41 @@ def test_rank_orders_by_fitness_and_picks_best():
131
 
132
  def test_rank_folds_in_specificity():
133
  p = P.score_primer({"id": "q0", "name": "x", "seq": "ACAGTGACCTGAAGTCCATGC", "role": ""})
134
- clean = P.rank([dict(p)], specificity={"q0": {"strong_offtargets": 0, "top_hits": []}})
135
- noisy = P.rank([dict(p)], specificity={"q0": {"strong_offtargets": 40, "top_hits": []}})
136
  assert clean["primers"][0]["fitness"] > noisy["primers"][0]["fitness"]
137
  assert clean["specificity_done"] is True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  def test_rank_folds_in_specificity():
133
  p = P.score_primer({"id": "q0", "name": "x", "seq": "ACAGTGACCTGAAGTCCATGC", "role": ""})
134
+ clean = P.rank([dict(p)], specificity={"q0": {"offtarget_products": 0, "top_hits": []}})
135
+ noisy = P.rank([dict(p)], specificity={"q0": {"offtarget_products": 8, "top_hits": []}})
136
  assert clean["primers"][0]["fitness"] > noisy["primers"][0]["fitness"]
137
  assert clean["specificity_done"] is True
138
+
139
+
140
+ # ── in-silico PCR ───────────────────────────────────────────────────────────
141
+ def _ev(pid, pos5, pos3, d, subj="NC_1"):
142
+ return {"primer_id": pid, "name": pid, "pos5": pos5, "pos3": pos3, "dir": d,
143
+ "title": "chr1", "organism": "Homo sapiens"}
144
+
145
+
146
+ def test_insilico_pcr_pairs_convergent_within_range():
147
+ events = {"NC_1": [_ev("F", 100, 119, "+"), _ev("R", 600, 581, "-")]}
148
+ prods = P.insilico_pcr(events)
149
+ assert len(prods) == 1
150
+ assert prods[0]["size"] == 501
151
+ assert prods[0]["fwd"] == "F" and prods[0]["rev"] == "R"
152
+
153
+
154
+ def test_insilico_pcr_skips_too_far_apart():
155
+ events = {"NC_1": [_ev("F", 100, 119, "+"), _ev("R", 9000, 8981, "-")]}
156
+ assert P.insilico_pcr(events, max_product=4000) == []
157
+
158
+
159
+ def test_insilico_pcr_skips_divergent_or_same_direction():
160
+ # reverse site upstream of the forward site → primers point away → no product
161
+ div = {"NC_1": [_ev("F", 600, 619, "+"), _ev("R", 100, 81, "-")]}
162
+ assert P.insilico_pcr(div) == []
163
+ # two forward sites, no reverse → no product
164
+ same = {"NC_1": [_ev("F1", 100, 119, "+"), _ev("F2", 300, 319, "+")]}
165
+ assert P.insilico_pcr(same) == []
166
+
167
+
168
+ def test_insilico_pcr_only_pairs_within_same_subject():
169
+ events = {"NC_1": [_ev("F", 100, 119, "+")],
170
+ "NC_2": [_ev("R", 600, 581, "-")]}
171
+ assert P.insilico_pcr(events) == [] # F and R on different subjects