Spaces:
Running
Running
feat(seq-tools): add sequence utilities, motif scanner and dot plot tools with frontend pages
Browse files- bioai-platform/backend/app/main.py +2 -1
- bioai-platform/backend/app/routers/seq_tools.py +163 -0
- bioai-platform/backend/app/tools/dotplot.py +110 -0
- bioai-platform/backend/app/tools/motif_scanner.py +201 -0
- bioai-platform/backend/app/tools/sequence_utilities.py +234 -0
- bioai-platform/backend/tests/test_seq_tools.py +269 -0
- bioai-platform/frontend/src/app/(dashboard)/analyze/dotplot/page.tsx +230 -0
- bioai-platform/frontend/src/app/(dashboard)/analyze/motif/page.tsx +228 -0
- bioai-platform/frontend/src/app/(dashboard)/analyze/page.tsx +4 -1
- bioai-platform/frontend/src/app/(dashboard)/analyze/sequences/page.tsx +121 -0
- bioai-platform/frontend/src/components/motifs/MotifTrack.tsx +86 -0
- bioai-platform/frontend/src/components/sequences/SequenceUtilitiesView.tsx +174 -0
- bioai-platform/frontend/src/lib/api.ts +40 -1
- bioai-platform/frontend/src/types/pipeline.ts +94 -0
bioai-platform/backend/app/main.py
CHANGED
|
@@ -14,7 +14,7 @@ from slowapi.errors import RateLimitExceeded
|
|
| 14 |
from app.config import settings
|
| 15 |
from app.logging_config import setup_logging
|
| 16 |
from app.middleware import RequestIDMiddleware
|
| 17 |
-
from app.routers import pipelines, pipeline_v2, ai, jobs, share, profile, sequences, uniprot, alignment, structures, pathways, domains, interactions, primers, structure_analysis, phylo, export, api_keys, cache_stats, docking, sequencing, audit, admet, md, function_predict
|
| 18 |
from app.services.cache import init_redis
|
| 19 |
|
| 20 |
setup_logging()
|
|
@@ -67,6 +67,7 @@ app.include_router(audit.router)
|
|
| 67 |
app.include_router(admet.router)
|
| 68 |
app.include_router(md.router)
|
| 69 |
app.include_router(function_predict.router)
|
|
|
|
| 70 |
|
| 71 |
TERMINAL_STATUSES = {"complete", "failed"}
|
| 72 |
NON_TERMINAL_STATUSES = {
|
|
|
|
| 14 |
from app.config import settings
|
| 15 |
from app.logging_config import setup_logging
|
| 16 |
from app.middleware import RequestIDMiddleware
|
| 17 |
+
from app.routers import pipelines, pipeline_v2, ai, jobs, share, profile, sequences, uniprot, alignment, structures, pathways, domains, interactions, primers, structure_analysis, phylo, export, api_keys, cache_stats, docking, sequencing, audit, admet, md, function_predict, seq_tools
|
| 18 |
from app.services.cache import init_redis
|
| 19 |
|
| 20 |
setup_logging()
|
|
|
|
| 67 |
app.include_router(admet.router)
|
| 68 |
app.include_router(md.router)
|
| 69 |
app.include_router(function_predict.router)
|
| 70 |
+
app.include_router(seq_tools.router)
|
| 71 |
|
| 72 |
TERMINAL_STATUSES = {"complete", "failed"}
|
| 73 |
NON_TERMINAL_STATUSES = {
|
bioai-platform/backend/app/routers/seq_tools.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sequence-tool endpoints: sequence utilities, motif scanner and dot plot.
|
| 2 |
+
|
| 3 |
+
All three are pure-local computations (no external services), so errors are
|
| 4 |
+
user-input errors and map to HTTP 400.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from fastapi import APIRouter, HTTPException
|
| 13 |
+
from pydantic import BaseModel, Field
|
| 14 |
+
|
| 15 |
+
from app.tools.sequence_utilities import SequenceUtilitiesError, analyze_sequence
|
| 16 |
+
from app.tools.motif_scanner import MotifError, MOTIF_LIBRARY, scan_library, scan_pattern
|
| 17 |
+
from app.tools.dotplot import DotPlotError, compute_dotplot
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
router = APIRouter(prefix="/api/seq-tools", tags=["sequence-tools"])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# --- Sequence utilities ----------------------------------------------------
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AnalyzeRequest(BaseModel):
|
| 27 |
+
sequence: str = Field(..., min_length=1, description="Raw sequence or FASTA (DNA/RNA/protein)")
|
| 28 |
+
seq_type: str = Field("auto", description="auto|dna|rna|protein — force interpretation")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class TranslationFrames(BaseModel):
|
| 32 |
+
frames: dict[str, str]
|
| 33 |
+
best: dict[str, Any] | None = None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class RestrictionSite(BaseModel):
|
| 37 |
+
name: str
|
| 38 |
+
recognition: str
|
| 39 |
+
count: int
|
| 40 |
+
positions: list[int]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AaComposition(BaseModel):
|
| 44 |
+
aa: str
|
| 45 |
+
count: int
|
| 46 |
+
pct: float
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AnalyzeResponse(BaseModel):
|
| 50 |
+
sequence_type: str
|
| 51 |
+
detected_type: str
|
| 52 |
+
length: int
|
| 53 |
+
gc_content: float | None = None
|
| 54 |
+
molecular_weight: float | None = None
|
| 55 |
+
reverse_complement: str | None = None
|
| 56 |
+
translation: TranslationFrames | None = None
|
| 57 |
+
aa_composition: list[AaComposition] | None = None
|
| 58 |
+
restriction_sites: list[RestrictionSite] | None = None
|
| 59 |
+
issues: list[str]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@router.post("/analyze", response_model=AnalyzeResponse)
|
| 63 |
+
async def analyze_sequence_endpoint(req: AnalyzeRequest):
|
| 64 |
+
try:
|
| 65 |
+
return analyze_sequence(req.sequence, req.seq_type)
|
| 66 |
+
except SequenceUtilitiesError as e:
|
| 67 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# --- Motif scanner ---------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PatternScanRequest(BaseModel):
|
| 74 |
+
sequence: str = Field(..., min_length=1, description="Protein sequence (raw or FASTA)")
|
| 75 |
+
pattern: str = Field(..., min_length=1, description="PROSITE pattern, e.g. [ST]-x-[RK]")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class LibraryScanRequest(BaseModel):
|
| 79 |
+
sequence: str = Field(..., min_length=1, description="Protein sequence (raw or FASTA)")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class MotifMatch(BaseModel):
|
| 83 |
+
start: int
|
| 84 |
+
end: int
|
| 85 |
+
motif: str
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class PatternScanResponse(BaseModel):
|
| 89 |
+
sequence_type: str
|
| 90 |
+
pattern: str
|
| 91 |
+
regex: str
|
| 92 |
+
count: int
|
| 93 |
+
matches: list[MotifMatch]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class LibraryHit(BaseModel):
|
| 97 |
+
name: str
|
| 98 |
+
description: str
|
| 99 |
+
pattern: str
|
| 100 |
+
count: int
|
| 101 |
+
matches: list[MotifMatch]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class LibraryScanResponse(BaseModel):
|
| 105 |
+
sequence_type: str
|
| 106 |
+
length: int
|
| 107 |
+
patterns_scanned: int
|
| 108 |
+
motifs_found: int
|
| 109 |
+
hits: list[LibraryHit]
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@router.post("/motif-scan", response_model=PatternScanResponse)
|
| 113 |
+
async def scan_custom_pattern(req: PatternScanRequest):
|
| 114 |
+
try:
|
| 115 |
+
return scan_pattern(req.sequence, req.pattern)
|
| 116 |
+
except MotifError as e:
|
| 117 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@router.post("/motif-library", response_model=LibraryScanResponse)
|
| 121 |
+
async def scan_motif_library(req: LibraryScanRequest):
|
| 122 |
+
try:
|
| 123 |
+
return scan_library(req.sequence)
|
| 124 |
+
except MotifError as e:
|
| 125 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@router.get("/motif-library/patterns")
|
| 129 |
+
async def list_motif_patterns():
|
| 130 |
+
"""Return the curated motif library so the UI can offer presets."""
|
| 131 |
+
return [{"name": name, "description": entry["description"], "pattern": entry["pattern"]}
|
| 132 |
+
for name, entry in MOTIF_LIBRARY.items()]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# --- Dot plot --------------------------------------------------------------
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class DotPlotRequest(BaseModel):
|
| 139 |
+
seq_a: str = Field(..., min_length=1, description="First sequence (query, vertical axis)")
|
| 140 |
+
seq_b: str = Field(..., min_length=1, description="Second sequence (subject, horizontal axis)")
|
| 141 |
+
window: int = Field(10, ge=1, le=200, description="Comparison window length")
|
| 142 |
+
stringency: int = Field(80, ge=1, le=100, description="Percent identity required in the window")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class DotPlotResponse(BaseModel):
|
| 146 |
+
sequence_type: str
|
| 147 |
+
seq_a_length: int
|
| 148 |
+
seq_b_length: int
|
| 149 |
+
window: int
|
| 150 |
+
stringency: int
|
| 151 |
+
threshold: int
|
| 152 |
+
total_matches: int
|
| 153 |
+
dot_count: int
|
| 154 |
+
downsampled: bool
|
| 155 |
+
dots: list[list[int]]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@router.post("/dotplot", response_model=DotPlotResponse)
|
| 159 |
+
async def run_dotplot(req: DotPlotRequest):
|
| 160 |
+
try:
|
| 161 |
+
return compute_dotplot(req.seq_a, req.seq_b, window=req.window, stringency=req.stringency)
|
| 162 |
+
except DotPlotError as e:
|
| 163 |
+
raise HTTPException(status_code=400, detail=str(e))
|
bioai-platform/backend/app/tools/dotplot.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dot plot computation for sequence-vs-sequence comparison.
|
| 2 |
+
|
| 3 |
+
A dot plot marks every pair of positions ``(i, j)`` whose surrounding
|
| 4 |
+
``window`` residues are similar at or above ``stringency`` percent identity.
|
| 5 |
+
Identical sequences produce the classic diagonal; repeats and rearrangements
|
| 6 |
+
show up as off-diagonal lines.
|
| 7 |
+
|
| 8 |
+
Uses a vectorised (numpy) scan: matches are computed positionally along each
|
| 9 |
+
``(i, j)`` diagonal with sliding-window sums, so a 2000 x 2000 comparison
|
| 10 |
+
completes in well under a second. Pure local computation — no network calls.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from app.services.sequence_utils import detect_sequence_type
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DotPlotError(ValueError):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
MAX_CELLS = 4_000_000 # ~2000 x 2000
|
| 27 |
+
MAX_DOTS = 20_000
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _normalize(seq: str) -> str:
|
| 31 |
+
return "".join(ch for ch in seq.upper() if ch.isalpha())
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def compute_dotplot(
|
| 35 |
+
seq_a: str,
|
| 36 |
+
seq_b: str,
|
| 37 |
+
window: int = 10,
|
| 38 |
+
stringency: int = 80,
|
| 39 |
+
max_dots: int = MAX_DOTS,
|
| 40 |
+
) -> dict:
|
| 41 |
+
seq_a = _normalize(seq_a)
|
| 42 |
+
seq_b = _normalize(seq_b)
|
| 43 |
+
if not seq_a or not seq_b:
|
| 44 |
+
raise DotPlotError("Both sequences are required")
|
| 45 |
+
n, m = len(seq_a), len(seq_b)
|
| 46 |
+
if n * m > MAX_CELLS:
|
| 47 |
+
raise DotPlotError(
|
| 48 |
+
f"Sequences too large for a dot plot ({n} x {m} cells, max {MAX_CELLS}). "
|
| 49 |
+
"Use shorter sequences or trim the input."
|
| 50 |
+
)
|
| 51 |
+
window = max(1, min(int(window), n, m))
|
| 52 |
+
stringency = max(1, min(100, int(stringency)))
|
| 53 |
+
threshold = max(1, math.ceil(window * stringency / 100.0))
|
| 54 |
+
|
| 55 |
+
a = np.frombuffer(seq_a.encode("ascii", "ignore"), dtype=np.uint8)
|
| 56 |
+
b = np.frombuffer(seq_b.encode("ascii", "ignore"), dtype=np.uint8)
|
| 57 |
+
if a.size == 0 or b.size == 0:
|
| 58 |
+
raise DotPlotError("Both sequences are required")
|
| 59 |
+
|
| 60 |
+
if window == 1:
|
| 61 |
+
# Single-residue windows are plain character matches.
|
| 62 |
+
eq = (a[:, None] == b[None, :])
|
| 63 |
+
ys, xs = np.nonzero(eq)
|
| 64 |
+
else:
|
| 65 |
+
# Positional window matches: along each anti-diagonal j = i + d, the
|
| 66 |
+
# equality signal is 1-D, so a sliding-window sum flags the dots.
|
| 67 |
+
ys_list: list[np.ndarray] = []
|
| 68 |
+
xs_list: list[np.ndarray] = []
|
| 69 |
+
for d in range(-(n - 1), m):
|
| 70 |
+
i0 = max(0, -d)
|
| 71 |
+
j0 = max(0, d)
|
| 72 |
+
length = min(n - i0, m - j0)
|
| 73 |
+
if length < window:
|
| 74 |
+
continue
|
| 75 |
+
eq_diag = (a[i0:i0 + length] == b[j0:j0 + length]).astype(np.int16)
|
| 76 |
+
csum = np.concatenate([[0], np.cumsum(eq_diag)])
|
| 77 |
+
sums = csum[window:] - csum[:-window]
|
| 78 |
+
kk = np.nonzero(sums >= threshold)[0]
|
| 79 |
+
if kk.size:
|
| 80 |
+
ys_list.append(i0 + kk)
|
| 81 |
+
xs_list.append(j0 + kk)
|
| 82 |
+
if ys_list:
|
| 83 |
+
ys = np.concatenate(ys_list)
|
| 84 |
+
xs = np.concatenate(xs_list)
|
| 85 |
+
else:
|
| 86 |
+
ys = np.empty(0, dtype=np.int64)
|
| 87 |
+
xs = np.empty(0, dtype=np.int64)
|
| 88 |
+
|
| 89 |
+
total_matches = int(ys.size)
|
| 90 |
+
downsampled = False
|
| 91 |
+
if total_matches > max_dots:
|
| 92 |
+
step = max(1, int(math.ceil(total_matches / max_dots)))
|
| 93 |
+
ys = ys[::step]
|
| 94 |
+
xs = xs[::step]
|
| 95 |
+
downsampled = True
|
| 96 |
+
|
| 97 |
+
dots = [[int(y), int(x)] for y, x in zip(ys.tolist(), xs.tolist())]
|
| 98 |
+
return {
|
| 99 |
+
"sequence_type": detect_sequence_type(seq_a),
|
| 100 |
+
"seq_a_length": n,
|
| 101 |
+
"seq_b_length": m,
|
| 102 |
+
"window": window,
|
| 103 |
+
"stringency": stringency,
|
| 104 |
+
"threshold": threshold,
|
| 105 |
+
"total_matches": total_matches,
|
| 106 |
+
"dot_count": len(dots),
|
| 107 |
+
"downsampled": downsampled,
|
| 108 |
+
"dots": dots,
|
| 109 |
+
}
|
| 110 |
+
|
bioai-platform/backend/app/tools/motif_scanner.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local protein motif scanner.
|
| 2 |
+
|
| 3 |
+
Implements the two scanning modes a bench biologist uses to find short
|
| 4 |
+
functional motifs in a protein:
|
| 5 |
+
|
| 6 |
+
* Custom PROSITE patterns (e.g. ``[ST]-x-[RK]``, ``N-{P}-[ST]-{P}``) parsed
|
| 7 |
+
into a Python regular expression and matched against the query.
|
| 8 |
+
* A curated library of well-known eukaryotic motif patterns (glycosylation,
|
| 9 |
+
phosphorylation, myristoylation, zinc fingers, the P-loop, ...).
|
| 10 |
+
|
| 11 |
+
Pure local computation — no network calls. This is the "scan your sequence
|
| 12 |
+
for motifs" workflow that PROSITE/ScanProsite expose as a web service.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
from app.services.sequence_utils import detect_sequence_type
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class MotifError(ValueError):
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Well-known PROSITE-style patterns. Keys are display names; each entry has a
|
| 27 |
+
# human-readable description plus the PROSITE pattern string.
|
| 28 |
+
MOTIF_LIBRARY: dict[str, dict[str, str]] = {
|
| 29 |
+
"N-glycosylation site": {
|
| 30 |
+
"description": "Asn-linked glycosylation: N-{P}-[ST]-{P}",
|
| 31 |
+
"pattern": "N-{P}-[ST]-{P}",
|
| 32 |
+
},
|
| 33 |
+
"cAMP/cGMP kinase site": {
|
| 34 |
+
"description": "cAMP/cGMP-dependent protein kinase phosphorylation: [RK]-{2}-x-[ST]",
|
| 35 |
+
"pattern": "[RK]-{2}-x-[ST]",
|
| 36 |
+
},
|
| 37 |
+
"Protein kinase C site": {
|
| 38 |
+
"description": "Protein kinase C phosphorylation: [ST]-x-[RK]",
|
| 39 |
+
"pattern": "[ST]-x-[RK]",
|
| 40 |
+
},
|
| 41 |
+
"Casein kinase II site": {
|
| 42 |
+
"description": "Casein kinase II phosphorylation: [ST]-x(2)-[DE]",
|
| 43 |
+
"pattern": "[ST]-x(2)-[DE]",
|
| 44 |
+
},
|
| 45 |
+
"Tyrosine kinase site": {
|
| 46 |
+
"description": "Tyrosine kinase phosphorylation: [RK]-x(2,3)-[DE]-x(2,3)-Y",
|
| 47 |
+
"pattern": "[RK]-x(2,3)-[DE]-x(2,3)-Y",
|
| 48 |
+
},
|
| 49 |
+
"N-myristoylation site": {
|
| 50 |
+
"description": "Myristyl anchor: G-{EDRKHPFYW}-x(2)-[STAGCN]-{P}",
|
| 51 |
+
"pattern": "G-{EDRKHPFYW}-x(2)-[STAGCN]-{P}",
|
| 52 |
+
},
|
| 53 |
+
"Amidation site": {
|
| 54 |
+
"description": "C-terminal amidation signal: x-G-[RK]-x",
|
| 55 |
+
"pattern": "x-G-[RK]-x",
|
| 56 |
+
},
|
| 57 |
+
"RGD cell-attachment": {
|
| 58 |
+
"description": "Integrin-binding tripeptide: R-G-D",
|
| 59 |
+
"pattern": "R-G-D",
|
| 60 |
+
},
|
| 61 |
+
"ATP/GTP-binding P-loop": {
|
| 62 |
+
"description": "Walker A motif: [AG]-x(4)-G-K-[ST]",
|
| 63 |
+
"pattern": "[AG]-x(4)-G-K-[ST]",
|
| 64 |
+
},
|
| 65 |
+
"C2H2 zinc finger (part)": {
|
| 66 |
+
"description": "Classic zinc finger half: C-x(2,4)-C-x(3)-[LIVMFYWC]-x(8)-H-x(3,5)-H",
|
| 67 |
+
"pattern": "C-x(2,4)-C-x(3)-[LIVMFYWC]-x(8)-H-x(3,5)-H",
|
| 68 |
+
},
|
| 69 |
+
"Leucine zipper": {
|
| 70 |
+
"description": "Heptad repeat: L-x(6)-L-x(6)-L-x(6)-L",
|
| 71 |
+
"pattern": "L-x(6)-L-x(6)-L-x(6)-L",
|
| 72 |
+
},
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def prosite_to_regex(pattern: str) -> str:
|
| 77 |
+
"""Translate a PROSITE pattern string into a Python regular expression.
|
| 78 |
+
|
| 79 |
+
Supported syntax: ``-`` (separator, ignored), ``x`` (any residue),
|
| 80 |
+
``[AC]`` (one of), ``{ED}`` (none of), ``x(4)`` / ``x(2,4)``
|
| 81 |
+
(repetition), ``<`` (N-terminus) and ``>`` (C-terminus).
|
| 82 |
+
"""
|
| 83 |
+
pattern = (pattern or "").strip()
|
| 84 |
+
if not pattern:
|
| 85 |
+
raise MotifError("Pattern is empty")
|
| 86 |
+
i = 0
|
| 87 |
+
n = len(pattern)
|
| 88 |
+
out: list[str] = []
|
| 89 |
+
|
| 90 |
+
def consume_repeat() -> None:
|
| 91 |
+
nonlocal i
|
| 92 |
+
if i < n and pattern[i] == "(":
|
| 93 |
+
j = pattern.find(")", i + 1)
|
| 94 |
+
if j == -1:
|
| 95 |
+
raise MotifError(f"Unterminated repeat quantifier at position {i}")
|
| 96 |
+
quant = pattern[i + 1:j]
|
| 97 |
+
if not re.fullmatch(r"\d+(,\d+)?", quant):
|
| 98 |
+
raise MotifError(f"Invalid repeat quantifier ({quant}) at position {i}")
|
| 99 |
+
out.append("{" + quant + "}")
|
| 100 |
+
i = j + 1
|
| 101 |
+
|
| 102 |
+
while i < n:
|
| 103 |
+
c = pattern[i]
|
| 104 |
+
if c == "-":
|
| 105 |
+
i += 1
|
| 106 |
+
elif c == "<":
|
| 107 |
+
out.append("^")
|
| 108 |
+
i += 1
|
| 109 |
+
elif c == ">":
|
| 110 |
+
out.append("$")
|
| 111 |
+
i += 1
|
| 112 |
+
elif c == "[":
|
| 113 |
+
j = pattern.find("]", i + 1)
|
| 114 |
+
if j == -1:
|
| 115 |
+
raise MotifError(f"Unterminated '[' group at position {i}")
|
| 116 |
+
group = pattern[i + 1:j]
|
| 117 |
+
if not group or any(ch not in "ACDEFGHIKLMNPQRSTVWY" for ch in group):
|
| 118 |
+
raise MotifError(f"Invalid residue group [{group}] at position {i}")
|
| 119 |
+
out.append("[" + group + "]")
|
| 120 |
+
i = j + 1
|
| 121 |
+
consume_repeat()
|
| 122 |
+
elif c == "{":
|
| 123 |
+
j = pattern.find("}", i + 1)
|
| 124 |
+
if j == -1:
|
| 125 |
+
raise MotifError(f"Unterminated '{{' group at position {i}")
|
| 126 |
+
group = pattern[i + 1:j]
|
| 127 |
+
if not group or any(ch not in "ACDEFGHIKLMNPQRSTVWY" for ch in group):
|
| 128 |
+
raise MotifError(f"Invalid exclusion group {{{group}}} at position {i}")
|
| 129 |
+
out.append("[^" + group + "]")
|
| 130 |
+
i = j + 1
|
| 131 |
+
consume_repeat()
|
| 132 |
+
elif c in ("x", "X"):
|
| 133 |
+
out.append("[A-Z]")
|
| 134 |
+
i += 1
|
| 135 |
+
consume_repeat()
|
| 136 |
+
elif c in "ACDEFGHIKLMNPQRSTVWY":
|
| 137 |
+
out.append(c)
|
| 138 |
+
i += 1
|
| 139 |
+
consume_repeat()
|
| 140 |
+
else:
|
| 141 |
+
raise MotifError(f"Unsupported symbol {c!r} at position {i}")
|
| 142 |
+
return "".join(out)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _clean_protein(seq: str) -> str:
|
| 146 |
+
return "".join(ch for ch in seq.upper() if ch.isalpha())
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def scan_pattern(sequence: str, pattern: str) -> dict:
|
| 150 |
+
"""Scan a protein for a single PROSITE pattern."""
|
| 151 |
+
seq = _clean_protein(sequence)
|
| 152 |
+
if not seq:
|
| 153 |
+
raise MotifError("Sequence is empty")
|
| 154 |
+
regex_src = prosite_to_regex(pattern)
|
| 155 |
+
try:
|
| 156 |
+
regex = re.compile(regex_src)
|
| 157 |
+
except re.error as e:
|
| 158 |
+
raise MotifError(f"Pattern compiles to an invalid regular expression: {e}")
|
| 159 |
+
matches = []
|
| 160 |
+
for m in regex.finditer(seq):
|
| 161 |
+
matches.append({
|
| 162 |
+
"start": m.start() + 1,
|
| 163 |
+
"end": m.end(),
|
| 164 |
+
"motif": m.group(0),
|
| 165 |
+
})
|
| 166 |
+
return {
|
| 167 |
+
"sequence_type": detect_sequence_type(seq),
|
| 168 |
+
"pattern": pattern,
|
| 169 |
+
"regex": regex_src,
|
| 170 |
+
"count": len(matches),
|
| 171 |
+
"matches": matches,
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def scan_library(sequence: str) -> dict:
|
| 176 |
+
"""Scan a protein against the curated PROSITE library."""
|
| 177 |
+
seq = _clean_protein(sequence)
|
| 178 |
+
if not seq:
|
| 179 |
+
raise MotifError("Sequence is empty")
|
| 180 |
+
hits = []
|
| 181 |
+
for name, entry in MOTIF_LIBRARY.items():
|
| 182 |
+
try:
|
| 183 |
+
result = scan_pattern(seq, entry["pattern"])
|
| 184 |
+
except MotifError:
|
| 185 |
+
continue
|
| 186 |
+
if result["count"] > 0:
|
| 187 |
+
hits.append({
|
| 188 |
+
"name": name,
|
| 189 |
+
"description": entry["description"],
|
| 190 |
+
"pattern": entry["pattern"],
|
| 191 |
+
"count": result["count"],
|
| 192 |
+
"matches": result["matches"],
|
| 193 |
+
})
|
| 194 |
+
hits.sort(key=lambda h: (-h["count"], h["name"]))
|
| 195 |
+
return {
|
| 196 |
+
"sequence_type": detect_sequence_type(seq),
|
| 197 |
+
"length": len(seq),
|
| 198 |
+
"patterns_scanned": len(MOTIF_LIBRARY),
|
| 199 |
+
"motifs_found": len(hits),
|
| 200 |
+
"hits": hits,
|
| 201 |
+
}
|
bioai-platform/backend/app/tools/sequence_utilities.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sequence utilities toolkit.
|
| 2 |
+
|
| 3 |
+
Computes the everyday metrics a biologist needs on a single sequence:
|
| 4 |
+
|
| 5 |
+
* GC content (nucleotides)
|
| 6 |
+
* Reverse complement (nucleotides, IUPAC-aware)
|
| 7 |
+
* Molecular weight (ssDNA / ssRNA / protein average-residue)
|
| 8 |
+
* Six-frame-free translation of the forward three frames with the longest
|
| 9 |
+
open reading frame (ORF) flagged
|
| 10 |
+
* Amino-acid composition (proteins / translated CDS)
|
| 11 |
+
* Restriction-enzyme site scan against a curated set of common, unambiguous
|
| 12 |
+
(palindromic) recognition sequences
|
| 13 |
+
|
| 14 |
+
Pure local computation — no network calls. Mirrors the "Sequence Stats"
|
| 15 |
+
workflow every bench tool (ExPASy, BioPython scripts) implements.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
from Bio.SeqUtils.ProtParam import ProteinAnalysis
|
| 23 |
+
|
| 24 |
+
from app.services.sequence_utils import detect_sequence_type
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SequenceUtilitiesError(ValueError):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Standard genetic code — stop codons map to '*', ambiguous codons to 'X'.
|
| 32 |
+
_CODON_TABLE = {
|
| 33 |
+
"TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
|
| 34 |
+
"TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
|
| 35 |
+
"TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
|
| 36 |
+
"TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
|
| 37 |
+
"CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
|
| 38 |
+
"CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
|
| 39 |
+
"CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
|
| 40 |
+
"CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
|
| 41 |
+
"ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
|
| 42 |
+
"ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
|
| 43 |
+
"AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
|
| 44 |
+
"AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
|
| 45 |
+
"GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
|
| 46 |
+
"GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
|
| 47 |
+
"GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
|
| 48 |
+
"GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# Monoisotopic-ish single-strand base weights (g/mol).
|
| 52 |
+
_SSDNA_MW = {"A": 313.21, "C": 289.18, "G": 329.21, "T": 304.20}
|
| 53 |
+
_SSRNA_MW = {"A": 329.21, "C": 305.18, "G": 345.21, "U": 306.17}
|
| 54 |
+
|
| 55 |
+
# Curated common restriction enzymes — all palindromic so a forward-strand
|
| 56 |
+
# scan finds every cut site. Recognition site is given 5' -> 3'.
|
| 57 |
+
_RESTRICTION_ENZYMES = [
|
| 58 |
+
("EcoRI", "GAATTC"),
|
| 59 |
+
("BamHI", "GGATCC"),
|
| 60 |
+
("HindIII", "AAGCTT"),
|
| 61 |
+
("SalI", "GTCGAC"),
|
| 62 |
+
("XbaI", "TCTAGA"),
|
| 63 |
+
("XhoI", "CTCGAG"),
|
| 64 |
+
("NotI", "GCGGCCGC"),
|
| 65 |
+
("KpnI", "GGTACC"),
|
| 66 |
+
("SmaI", "CCCGGG"),
|
| 67 |
+
("PstI", "CTGCAG"),
|
| 68 |
+
("SacI", "GAGCTC"),
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
_RNA_TO_DNA = str.maketrans("Uu", "Tt")
|
| 72 |
+
_AA_ALPHABET = "ACDEFGHIKLMNPQRSTVWY"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _strip_fasta(seq: str) -> str:
|
| 76 |
+
"""Return just the sequence body of a raw or FASTA-formatted input."""
|
| 77 |
+
lines = (seq or "").strip().splitlines()
|
| 78 |
+
lines = [ln.strip() for ln in lines if not ln.strip().startswith(">")]
|
| 79 |
+
return "".join(lines)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def clean_sequence(seq: str, seq_type: str) -> str:
|
| 83 |
+
"""Normalize to uppercase alpha-only. For nucleotides, drop ambiguous IUPAC
|
| 84 |
+
codes so downstream math (GC%, MW) only counts real bases."""
|
| 85 |
+
body = _strip_fasta(seq)
|
| 86 |
+
letters = "".join(re.findall(r"[A-Za-z]", body)).upper()
|
| 87 |
+
if not letters:
|
| 88 |
+
raise SequenceUtilitiesError("Sequence is empty")
|
| 89 |
+
if seq_type in ("dna", "rna"):
|
| 90 |
+
allowed = set("ACGTRYSWKMBDHVN") if seq_type == "dna" else set("ACGURSYKMWBDHVN")
|
| 91 |
+
kept = "".join(c for c in letters if c in allowed)
|
| 92 |
+
if not kept:
|
| 93 |
+
raise SequenceUtilitiesError(f"Sequence contains no valid {seq_type.upper()} bases")
|
| 94 |
+
return kept.translate(_RNA_TO_DNA) if seq_type == "rna" else kept
|
| 95 |
+
valid = set("ACDEFGHIKLMNPQRSTVWY")
|
| 96 |
+
kept = "".join(c for c in letters if c in valid)
|
| 97 |
+
if not kept:
|
| 98 |
+
raise SequenceUtilitiesError("Sequence contains no valid amino acids")
|
| 99 |
+
return kept
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _translate_frame(seq: str, frame: int) -> str:
|
| 103 |
+
codons = [seq[i:i + 3] for i in range(frame, len(seq) - 2, 3)]
|
| 104 |
+
return "".join(_CODON_TABLE.get(c, "X") for c in codons)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _best_orf(seq: str, frame: int, translated: str) -> dict | None:
|
| 108 |
+
"""Longest ORF (M -> stop/end) in a translated frame, with 1-based start."""
|
| 109 |
+
best = None
|
| 110 |
+
for m in re.finditer("M[^*]*", translated):
|
| 111 |
+
length = len(m.group(0))
|
| 112 |
+
start = frame + m.start() * 3 + 1
|
| 113 |
+
if best is None or length > best["length"]:
|
| 114 |
+
best = {
|
| 115 |
+
"frame": frame + 1,
|
| 116 |
+
"protein": m.group(0),
|
| 117 |
+
"start": start,
|
| 118 |
+
"length": length,
|
| 119 |
+
"has_stop": len(translated) > m.end() and translated[m.end()] == "*",
|
| 120 |
+
"starts_with_m": True,
|
| 121 |
+
}
|
| 122 |
+
return best
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _protein_mw(seq: str) -> float:
|
| 126 |
+
try:
|
| 127 |
+
return round(ProteinAnalysis(seq).molecular_weight(), 2)
|
| 128 |
+
except Exception:
|
| 129 |
+
avg = 110.0
|
| 130 |
+
return round(sum(avg for _ in seq), 2)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _nucleotide_mw(seq: str, seq_type: str) -> float:
|
| 134 |
+
table = _SSDNA_MW if seq_type == "dna" else _SSRNA_MW
|
| 135 |
+
n = len(seq)
|
| 136 |
+
if n == 0:
|
| 137 |
+
return 0.0
|
| 138 |
+
total = sum(table.get(c, table["A"]) for c in seq)
|
| 139 |
+
return round(total - 61.96 * (n - 1) + 18.02, 2)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _aa_composition(seq: str) -> list[dict]:
|
| 143 |
+
counts: dict[str, int] = {}
|
| 144 |
+
for c in seq.upper():
|
| 145 |
+
if c in _AA_ALPHABET:
|
| 146 |
+
counts[c] = counts.get(c, 0) + 1
|
| 147 |
+
total = sum(counts.values())
|
| 148 |
+
comp = [
|
| 149 |
+
{"aa": aa, "count": count, "pct": round(count / total * 100, 1) if total else 0.0}
|
| 150 |
+
for aa, count in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
|
| 151 |
+
]
|
| 152 |
+
return comp
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _restriction_scan(seq: str) -> list[dict]:
|
| 156 |
+
sites = []
|
| 157 |
+
for name, recognition in _RESTRICTION_ENZYMES:
|
| 158 |
+
positions = [m.start() + 1 for m in re.finditer(recognition, seq)]
|
| 159 |
+
if positions:
|
| 160 |
+
sites.append({"name": name, "recognition": recognition, "count": len(positions), "positions": positions})
|
| 161 |
+
return sites
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def analyze_sequence(sequence: str, seq_type: str = "auto") -> dict:
|
| 165 |
+
"""Analyze a single sequence and return a flat report dict.
|
| 166 |
+
|
| 167 |
+
``seq_type`` may be 'auto', 'dna', 'rna' or 'protein'. Auto-detection uses
|
| 168 |
+
the shared alphabet classifier (a pure ACGTN/U string is treated as DNA).
|
| 169 |
+
"""
|
| 170 |
+
seq_type = (seq_type or "auto").lower()
|
| 171 |
+
if seq_type not in ("auto", "dna", "rna", "protein"):
|
| 172 |
+
raise SequenceUtilitiesError("seq_type must be auto, dna, rna or protein")
|
| 173 |
+
|
| 174 |
+
raw = _strip_fasta(sequence)
|
| 175 |
+
detected = detect_sequence_type(raw) if raw else "unknown"
|
| 176 |
+
effective = seq_type if seq_type != "auto" else detected
|
| 177 |
+
if effective == "unknown":
|
| 178 |
+
raise SequenceUtilitiesError(
|
| 179 |
+
"Could not detect sequence type — expected nucleotide or protein characters"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
seq = clean_sequence(raw, effective)
|
| 183 |
+
issues: list[str] = []
|
| 184 |
+
report: dict = {
|
| 185 |
+
"sequence_type": effective,
|
| 186 |
+
"detected_type": detected,
|
| 187 |
+
"length": len(seq),
|
| 188 |
+
"gc_content": None,
|
| 189 |
+
"molecular_weight": None,
|
| 190 |
+
"reverse_complement": None,
|
| 191 |
+
"translation": None,
|
| 192 |
+
"aa_composition": None,
|
| 193 |
+
"restriction_sites": None,
|
| 194 |
+
"issues": issues,
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
if effective in ("dna", "rna"):
|
| 198 |
+
report["gc_content"] = round((seq.count("G") + seq.count("C")) / len(seq) * 100.0, 1)
|
| 199 |
+
report["molecular_weight"] = _nucleotide_mw(seq, effective)
|
| 200 |
+
if effective == "dna":
|
| 201 |
+
comp = {"A": "T", "T": "A", "G": "C", "C": "G", "N": "N"}
|
| 202 |
+
else:
|
| 203 |
+
comp = {"A": "U", "U": "A", "G": "C", "C": "G", "N": "N"}
|
| 204 |
+
report["reverse_complement"] = "".join(comp.get(c, "N") for c in reversed(seq))
|
| 205 |
+
|
| 206 |
+
dna_seq = seq.translate(_RNA_TO_DNA)
|
| 207 |
+
if len(dna_seq) < 3:
|
| 208 |
+
issues.append("Sequence too short for translation (<3 nt)")
|
| 209 |
+
else:
|
| 210 |
+
frames = {}
|
| 211 |
+
best = None
|
| 212 |
+
for frame in (0, 1, 2):
|
| 213 |
+
translated = _translate_frame(dna_seq, frame)
|
| 214 |
+
frames[str(frame + 1)] = translated
|
| 215 |
+
orf = _best_orf(dna_seq, frame, translated)
|
| 216 |
+
if orf and (best is None or orf["length"] > best["length"]):
|
| 217 |
+
best = orf
|
| 218 |
+
report["translation"] = {"frames": frames, "best": best}
|
| 219 |
+
if best is None:
|
| 220 |
+
issues.append("No in-frame methionine (ATG) found — no ORF to report")
|
| 221 |
+
else:
|
| 222 |
+
report["aa_composition"] = _aa_composition(best["protein"])
|
| 223 |
+
|
| 224 |
+
if effective == "dna":
|
| 225 |
+
report["restriction_sites"] = _restriction_scan(seq)
|
| 226 |
+
else:
|
| 227 |
+
issues.append("Restriction-site scan is DNA-only")
|
| 228 |
+
else:
|
| 229 |
+
report["molecular_weight"] = _protein_mw(seq)
|
| 230 |
+
report["aa_composition"] = _aa_composition(seq)
|
| 231 |
+
if len(seq) < 2:
|
| 232 |
+
issues.append("Protein sequence very short — composition may be uninformative")
|
| 233 |
+
|
| 234 |
+
return report
|
bioai-platform/backend/tests/test_seq_tools.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sequence utilities toolkit, motif scanner and dot plot tests.
|
| 3 |
+
|
| 4 |
+
Known-answer checks against hand-verified arithmetic:
|
| 5 |
+
|
| 6 |
+
* reverse complement / GC% / MW for a short oligo
|
| 7 |
+
* translation frames and longest-ORF detection on a mini CDS
|
| 8 |
+
* restriction-site positions on a sequence containing EcoRI + BamHI sites
|
| 9 |
+
* PROSITE pattern parsing (alternation, exclusion, repeats, anchors)
|
| 10 |
+
* motif library hits on a small protein containing N-glycosylation sites
|
| 11 |
+
* dot-plot geometry (diagonal for identical sequences, off-diagonal dot for
|
| 12 |
+
a shared repeat, window/stringency behavior)
|
| 13 |
+
* router error mapping (bad pattern / too-large dot plot -> HTTP 400)
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
from fastapi import FastAPI
|
| 21 |
+
from fastapi.testclient import TestClient
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
| 24 |
+
|
| 25 |
+
from app.tools.sequence_utilities import analyze_sequence, clean_sequence
|
| 26 |
+
from app.tools.motif_scanner import prosite_to_regex, scan_library, scan_pattern
|
| 27 |
+
from app.tools.dotplot import compute_dotplot
|
| 28 |
+
|
| 29 |
+
# p53 residues 1-70 with two N-glycosylation consensus hits (N-S-T, N-C-S)
|
| 30 |
+
P53_N_TERM = (
|
| 31 |
+
"MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGPDEAPRMPEAAPPVAPAPAA"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@pytest.fixture(scope="module")
|
| 36 |
+
def seq_client():
|
| 37 |
+
app = FastAPI(title="Seq Tools Tests")
|
| 38 |
+
from app.routers import seq_tools
|
| 39 |
+
app.include_router(seq_tools.router)
|
| 40 |
+
with TestClient(app, raise_server_exceptions=False) as c:
|
| 41 |
+
yield c
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ============================================================================
|
| 45 |
+
# 1. Sequence utilities
|
| 46 |
+
# ============================================================================
|
| 47 |
+
|
| 48 |
+
class TestAnalyzeSequence:
|
| 49 |
+
def test_dna_reverse_complement_and_gc(self):
|
| 50 |
+
res = analyze_sequence("ATGCGAATTCGGATCC", seq_type="dna")
|
| 51 |
+
assert res["sequence_type"] == "dna"
|
| 52 |
+
assert res["length"] == 16
|
| 53 |
+
assert res["reverse_complement"] == "GGATCCGAATTCGCAT"
|
| 54 |
+
# G=4, C=4 in ATGCGAATTCGGATCC
|
| 55 |
+
assert res["gc_content"] == pytest.approx(8 / 16 * 100, abs=0.1)
|
| 56 |
+
|
| 57 |
+
def test_restriction_sites_ecoRI_bamHI(self):
|
| 58 |
+
res = analyze_sequence("ATGCGAATTCGGATCC", seq_type="dna")
|
| 59 |
+
names = {s["name"]: s for s in res["restriction_sites"]}
|
| 60 |
+
assert "EcoRI" in names and "BamHI" in names
|
| 61 |
+
# EcoRI site (GAATTC) starts at index 5, BamHI (GGATCC) at index 11
|
| 62 |
+
assert names["EcoRI"]["positions"] == [5]
|
| 63 |
+
assert names["BamHI"]["positions"] == [11]
|
| 64 |
+
|
| 65 |
+
def test_translation_frames_and_best_orf(self):
|
| 66 |
+
# ATG CAT TAA CGT GCA TGA -> frame 1 = "MH*RA*"; best ORF = MH (stops)
|
| 67 |
+
res = analyze_sequence("ATGCATTAACGTGCATGAA", seq_type="dna")
|
| 68 |
+
tr = res["translation"]
|
| 69 |
+
assert tr is not None
|
| 70 |
+
assert tr["frames"]["1"] == "MH*RA*"
|
| 71 |
+
assert tr["best"]["frame"] == 1
|
| 72 |
+
assert tr["best"]["protein"] == "MH"
|
| 73 |
+
assert tr["best"]["has_stop"] is True
|
| 74 |
+
|
| 75 |
+
def test_protein_mw_and_composition(self):
|
| 76 |
+
res = analyze_sequence("MEEPQSDPSVEP", seq_type="protein")
|
| 77 |
+
assert res["sequence_type"] == "protein"
|
| 78 |
+
assert res["molecular_weight"] is not None and res["molecular_weight"] > 0
|
| 79 |
+
comp = {c["aa"]: c["count"] for c in res["aa_composition"]}
|
| 80 |
+
assert comp["M"] == 1 and comp["E"] == 3 and comp["P"] == 3
|
| 81 |
+
total_pct = round(sum(c["pct"] for c in res["aa_composition"]), 1)
|
| 82 |
+
assert total_pct == pytest.approx(100.0, abs=0.1)
|
| 83 |
+
|
| 84 |
+
def test_fasta_input_handled(self):
|
| 85 |
+
res = analyze_sequence(">probe\nATGCGAATTCGGATCC\n", seq_type="dna")
|
| 86 |
+
assert res["length"] == 16
|
| 87 |
+
|
| 88 |
+
def test_auto_detects_dna(self):
|
| 89 |
+
res = analyze_sequence("ACGTACGTTGCA", seq_type="auto")
|
| 90 |
+
assert res["sequence_type"] == "dna"
|
| 91 |
+
|
| 92 |
+
def test_empty_raises(self):
|
| 93 |
+
with pytest.raises(Exception):
|
| 94 |
+
analyze_sequence(" ", seq_type="dna")
|
| 95 |
+
|
| 96 |
+
def test_clean_drops_ambiguous_for_gc(self):
|
| 97 |
+
cleaned = clean_sequence("ATGCNNNGG", "dna")
|
| 98 |
+
assert set(cleaned) <= set("ATCGN")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# ============================================================================
|
| 102 |
+
# 2. Motif scanner
|
| 103 |
+
# ============================================================================
|
| 104 |
+
|
| 105 |
+
class TestPrositeToRegex:
|
| 106 |
+
def test_literal_and_x(self):
|
| 107 |
+
assert prosite_to_regex("A-x-V") == "A[A-Z]V"
|
| 108 |
+
|
| 109 |
+
def test_alternation_and_exclusion(self):
|
| 110 |
+
assert prosite_to_regex("[ST]-x-[RK]") == "[ST][A-Z][RK]"
|
| 111 |
+
assert prosite_to_regex("N-{P}-[ST]-{P}") == "N[^P][ST][^P]"
|
| 112 |
+
|
| 113 |
+
def test_repeat_quantifiers(self):
|
| 114 |
+
assert prosite_to_regex("x(2,4)") == "[A-Z]{2,4}"
|
| 115 |
+
assert prosite_to_regex("[ST]-x(2)-[DE]") == "[ST][A-Z]{2}[DE]"
|
| 116 |
+
|
| 117 |
+
def test_anchors(self):
|
| 118 |
+
assert prosite_to_regex("<A") == "^A"
|
| 119 |
+
assert prosite_to_regex("G>") == "G$"
|
| 120 |
+
|
| 121 |
+
def test_invalid_symbol_raises(self):
|
| 122 |
+
from app.tools.motif_scanner import MotifError
|
| 123 |
+
with pytest.raises(MotifError):
|
| 124 |
+
prosite_to_regex("A-*")
|
| 125 |
+
|
| 126 |
+
def test_invalid_group_raises(self):
|
| 127 |
+
from app.tools.motif_scanner import MotifError
|
| 128 |
+
with pytest.raises(MotifError):
|
| 129 |
+
prosite_to_regex("[1]x")
|
| 130 |
+
with pytest.raises(MotifError):
|
| 131 |
+
prosite_to_regex("A-@-B")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class TestScanPattern:
|
| 135 |
+
def test_nglycosylation_finds_expected(self):
|
| 136 |
+
# N-glycosylation consensus N-{P}-[ST]-{P}: "QNSTL" -> match "NSTL"
|
| 137 |
+
res = scan_pattern("MKDYQNSTLPVARKTGH", "N-{P}-[ST]-{P}")
|
| 138 |
+
assert res["count"] >= 1
|
| 139 |
+
for m in res["matches"]:
|
| 140 |
+
assert m["end"] - m["start"] + 1 == 4
|
| 141 |
+
|
| 142 |
+
def test_overlapping_matches_reported(self):
|
| 143 |
+
res = scan_pattern("NNSTP", "N-{P}-[ST]-{P}")
|
| 144 |
+
# position 1 starts "NNST" -> one match
|
| 145 |
+
assert res["count"] == 1
|
| 146 |
+
|
| 147 |
+
def test_cleans_sequence_case(self):
|
| 148 |
+
res = scan_pattern("Mnnstlpv", "N-{P}-[ST]-{P}")
|
| 149 |
+
assert res["count"] == 1
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class TestScanLibrary:
|
| 153 |
+
def test_known_motifs_found(self):
|
| 154 |
+
# This construct has two obvious hits: N-glycosylation N-S-T and PKC [ST]-x-[RK]
|
| 155 |
+
seq = "MKDYQNSTLPVARKTGH"
|
| 156 |
+
res = scan_library(seq)
|
| 157 |
+
assert res["motifs_found"] >= 1
|
| 158 |
+
names = {h["name"] for h in res["hits"]}
|
| 159 |
+
assert "N-glycosylation site" in names
|
| 160 |
+
|
| 161 |
+
def test_library_reports_length(self):
|
| 162 |
+
res = scan_library(P53_N_TERM)
|
| 163 |
+
assert res["length"] == len(P53_N_TERM)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# ============================================================================
|
| 167 |
+
# 3. Dot plot
|
| 168 |
+
# ============================================================================
|
| 169 |
+
|
| 170 |
+
class TestDotPlot:
|
| 171 |
+
def test_identical_sequences_diagonal(self):
|
| 172 |
+
# Every window position trivially matches itself, so a self-plot lights
|
| 173 |
+
# the whole main diagonal and nothing off it.
|
| 174 |
+
res = compute_dotplot("AAAACCCCGGGGTTTT", "AAAACCCCGGGGTTTT", window=4, stringency=100)
|
| 175 |
+
assert res["dot_count"] == 16 - 4 + 1
|
| 176 |
+
for y, x in res["dots"]:
|
| 177 |
+
assert y == x
|
| 178 |
+
assert res["seq_a_length"] == 16 and res["seq_b_length"] == 16
|
| 179 |
+
|
| 180 |
+
def test_shared_repeat_off_diagonal(self):
|
| 181 |
+
a = "AAAACCCCGGGGTTTT"
|
| 182 |
+
b = "AAAAGGGGAAAACCCC"
|
| 183 |
+
res = compute_dotplot(a, b, window=4, stringency=100)
|
| 184 |
+
coords = set(map(tuple, res["dots"]))
|
| 185 |
+
# "AAAA" appears in both at position 0; "CCCC" in a at 4 and b at 12
|
| 186 |
+
assert (0, 0) in coords
|
| 187 |
+
assert (4, 12) in coords
|
| 188 |
+
|
| 189 |
+
def test_stringency_filters_weak_matches(self):
|
| 190 |
+
a = "AAAAAAAAAA"
|
| 191 |
+
b = "AAAAAAAAAG" # differs at last position
|
| 192 |
+
# window 5, stringency 100 -> only positions with 5/5 identical
|
| 193 |
+
res = compute_dotplot(a, b, window=5, stringency=100)
|
| 194 |
+
assert (0, 0) in {tuple(d) for d in res["dots"]}
|
| 195 |
+
# window 5, stringency 80 -> last position (4, 4) matches 4/5
|
| 196 |
+
res80 = compute_dotplot(a, b, window=5, stringency=80)
|
| 197 |
+
assert (4, 4) in {tuple(d) for d in res80["dots"]}
|
| 198 |
+
|
| 199 |
+
def test_window_one_is_char_match(self):
|
| 200 |
+
res = compute_dotplot("ACGT", "ACGT", window=1, stringency=100)
|
| 201 |
+
assert res["dot_count"] == 4
|
| 202 |
+
|
| 203 |
+
def test_too_large_raises(self):
|
| 204 |
+
from app.tools.dotplot import DotPlotError
|
| 205 |
+
with pytest.raises(DotPlotError):
|
| 206 |
+
compute_dotplot("A" * 5000, "A" * 5000)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ============================================================================
|
| 210 |
+
# 4. Router-level
|
| 211 |
+
# ============================================================================
|
| 212 |
+
|
| 213 |
+
class TestSeqToolsEndpoints:
|
| 214 |
+
def test_analyze_endpoint(self, seq_client):
|
| 215 |
+
resp = seq_client.post("/api/seq-tools/analyze", json={
|
| 216 |
+
"sequence": "ATGCGAATTCGGATCC", "seq_type": "dna",
|
| 217 |
+
})
|
| 218 |
+
assert resp.status_code == 200, resp.text
|
| 219 |
+
body = resp.json()
|
| 220 |
+
assert body["reverse_complement"] == "GGATCCGAATTCGCAT"
|
| 221 |
+
assert body["length"] == 16
|
| 222 |
+
|
| 223 |
+
def test_analyze_bad_type_400(self, seq_client):
|
| 224 |
+
resp = seq_client.post("/api/seq-tools/analyze", json={
|
| 225 |
+
"sequence": "ACGT", "seq_type": "bogus",
|
| 226 |
+
})
|
| 227 |
+
assert resp.status_code == 400
|
| 228 |
+
|
| 229 |
+
def test_motif_scan_endpoint(self, seq_client):
|
| 230 |
+
resp = seq_client.post("/api/seq-tools/motif-scan", json={
|
| 231 |
+
"sequence": "MNSST", "pattern": "N-{P}-[ST]-{P}",
|
| 232 |
+
})
|
| 233 |
+
assert resp.status_code == 200, resp.text
|
| 234 |
+
assert resp.json()["count"] >= 1
|
| 235 |
+
|
| 236 |
+
def test_motif_scan_bad_pattern_400(self, seq_client):
|
| 237 |
+
resp = seq_client.post("/api/seq-tools/motif-scan", json={
|
| 238 |
+
"sequence": "MNSST", "pattern": "A-*",
|
| 239 |
+
})
|
| 240 |
+
assert resp.status_code == 400
|
| 241 |
+
|
| 242 |
+
def test_motif_library_endpoint(self, seq_client):
|
| 243 |
+
resp = seq_client.post("/api/seq-tools/motif-library", json={
|
| 244 |
+
"sequence": "MKDYQNSTLPVARKTGH",
|
| 245 |
+
})
|
| 246 |
+
assert resp.status_code == 200, resp.text
|
| 247 |
+
assert resp.json()["motifs_found"] >= 1
|
| 248 |
+
|
| 249 |
+
def test_motif_patterns_list(self, seq_client):
|
| 250 |
+
resp = seq_client.get("/api/seq-tools/motif-library/patterns")
|
| 251 |
+
assert resp.status_code == 200
|
| 252 |
+
assert len(resp.json()) >= 5
|
| 253 |
+
|
| 254 |
+
def test_dotplot_endpoint(self, seq_client):
|
| 255 |
+
resp = seq_client.post("/api/seq-tools/dotplot", json={
|
| 256 |
+
"seq_a": "AAAACCCCGGGGTTTT", "seq_b": "AAAACCCCGGGGTTTT",
|
| 257 |
+
"window": 4, "stringency": 100,
|
| 258 |
+
})
|
| 259 |
+
assert resp.status_code == 200, resp.text
|
| 260 |
+
body = resp.json()
|
| 261 |
+
assert body["dot_count"] == 16 - 4 + 1
|
| 262 |
+
assert all(d[0] == d[1] for d in body["dots"])
|
| 263 |
+
|
| 264 |
+
def test_dotplot_too_large_400(self, seq_client):
|
| 265 |
+
resp = seq_client.post("/api/seq-tools/dotplot", json={
|
| 266 |
+
"seq_a": "A" * 5000, "seq_b": "A" * 5000,
|
| 267 |
+
"window": 4, "stringency": 100,
|
| 268 |
+
})
|
| 269 |
+
assert resp.status_code == 400
|
bioai-platform/frontend/src/app/(dashboard)/analyze/dotplot/page.tsx
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useMemo, useState } from 'react';
|
| 4 |
+
import { motion } from 'framer-motion';
|
| 5 |
+
import { CircleNotch as LoaderCircle } from '@phosphor-icons/react';
|
| 6 |
+
import {
|
| 7 |
+
ResponsiveContainer, ScatterChart, Scatter, XAxis, YAxis, Tooltip,
|
| 8 |
+
CartesianGrid, ReferenceLine, Brush,
|
| 9 |
+
} from 'recharts';
|
| 10 |
+
import { fadeUp } from '@/lib/animations';
|
| 11 |
+
import { runDotPlot } from '@/lib/api';
|
| 12 |
+
import { extractErrorMessage } from '@/lib/errors';
|
| 13 |
+
import { useAuditTrail } from '@/hooks/useAuditTrail';
|
| 14 |
+
import { BackButton, CriticalButton, ClaySlider, ClayToggle, FlatTextarea, PageHeader } from '@/components/ui';
|
| 15 |
+
import type { DotPlotResult } from '@/types/pipeline';
|
| 16 |
+
|
| 17 |
+
const SAMPLE_A = '>p53_human\nMEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGPDEAPRMPEAAPPVAPAPAAPTPAAPAPAPSWPLSSSVPSQKTYQGSYGFRLGFLHSGTAKSVTCTYSPALNKMFCQLAKTCPVQLWVDSTPPPGTRVRAMAIYKQSQHMTEVVRRCPHHERCSDSDGLAPPQHLIRVEGNLRVEYLDDRNTFRHSVVVPYEPPEVGSDCTTIHYNYMCNSSCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGRDRRTEEENLRKKGEPHHELPPGSTKRALPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPGGSRAHSSHLKSKKGQSTSRHKKLMFKTEGPDSD';
|
| 18 |
+
const SAMPLE_B = '>p53_mouse\nMEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWFTEDPGPDEAPRMSEAAPPAAPAPAAPTPAAPAPAPSWPLSSFVPSQKTYQGNYGFHLGFLQSGTAKSVMCTYSPPLNKLFCQLAKTCPVQLWVSATPPAGSRVRAMAIYKKSQHMTEVVRRCPHHERCSDSSDGLAPPQHLIRVEGNLRAEYLDDRNTFRHSIVVPYEPPEVGSDCTTIHYNYMCNSSCMGGMNRRPILTIITLEDSSGNLLGRDSFEVRVCACPGRDRRTEEENFKKKEPCPEPPPGSTRALGSTSTSSPTPKKKPLDGEYFTLKIRGRERFEMFRELNEALELKDAHATEEPFGGSRAHSSHLKSKKGQSTSRHKKFKKTADPSS';
|
| 19 |
+
|
| 20 |
+
function cleanLength(seq: string): number {
|
| 21 |
+
return seq.replace(/[^A-Za-z]/g, '').length;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const tooltipStyle = {
|
| 25 |
+
contentStyle: { background: '#0E1521', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 8, fontSize: 12 },
|
| 26 |
+
labelStyle: { color: '#94A3B8' },
|
| 27 |
+
itemStyle: { color: '#E2E8F0' },
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
export default function DotPlotPage() {
|
| 31 |
+
const [seqA, setSeqA] = useState('');
|
| 32 |
+
const [seqB, setSeqB] = useState('');
|
| 33 |
+
const [selfCompare, setSelfCompare] = useState(false);
|
| 34 |
+
const [window, setWindow] = useState(10);
|
| 35 |
+
const [stringency, setStringency] = useState(80);
|
| 36 |
+
const [loading, setLoading] = useState(false);
|
| 37 |
+
const [result, setResult] = useState<DotPlotResult | null>(null);
|
| 38 |
+
const [error, setError] = useState<string | null>(null);
|
| 39 |
+
const audit = useAuditTrail();
|
| 40 |
+
|
| 41 |
+
const effectiveB = selfCompare ? seqA : seqB;
|
| 42 |
+
const canRun = cleanLength(seqA) >= 1 && cleanLength(effectiveB) >= 1 && !loading;
|
| 43 |
+
|
| 44 |
+
const data = useMemo(
|
| 45 |
+
() => (result ? result.dots.map(([y, x], i) => ({ x, y, idx: i })) : []),
|
| 46 |
+
[result],
|
| 47 |
+
);
|
| 48 |
+
|
| 49 |
+
const handleRun = async () => {
|
| 50 |
+
if (!canRun) return;
|
| 51 |
+
setLoading(true);
|
| 52 |
+
setError(null);
|
| 53 |
+
setResult(null);
|
| 54 |
+
const summary = `lenA:${cleanLength(seqA)},lenB:${cleanLength(effectiveB)},w:${window},s:${stringency},self:${selfCompare}`;
|
| 55 |
+
audit.emitStarted('dot_plot', 'Dot Plot', summary);
|
| 56 |
+
try {
|
| 57 |
+
const res = await runDotPlot({
|
| 58 |
+
seq_a: seqA,
|
| 59 |
+
seq_b: effectiveB,
|
| 60 |
+
window,
|
| 61 |
+
stringency,
|
| 62 |
+
});
|
| 63 |
+
setResult(res);
|
| 64 |
+
audit.emitSuccess('dot_plot', 'Dot Plot', summary, `dots:${res.dot_count}`);
|
| 65 |
+
} catch (err: unknown) {
|
| 66 |
+
const errMsg = extractErrorMessage(err, 'Dot plot failed');
|
| 67 |
+
setError(errMsg);
|
| 68 |
+
audit.emitFailed('dot_plot', 'Dot Plot', summary, errMsg);
|
| 69 |
+
} finally {
|
| 70 |
+
setLoading(false);
|
| 71 |
+
}
|
| 72 |
+
};
|
| 73 |
+
|
| 74 |
+
const toggleSelf = (value: boolean) => {
|
| 75 |
+
setSelfCompare(value);
|
| 76 |
+
if (value) setSeqB(seqA);
|
| 77 |
+
};
|
| 78 |
+
|
| 79 |
+
return (
|
| 80 |
+
<div className="max-w-4xl">
|
| 81 |
+
<BackButton />
|
| 82 |
+
|
| 83 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
|
| 84 |
+
<PageHeader
|
| 85 |
+
title="Dot Plot"
|
| 86 |
+
subtitle="Compare two sequences visually — every dot marks a window of matching residues. Identical sequences trace the main diagonal; repeats and rearranged segments appear as off-diagonal lines."
|
| 87 |
+
/>
|
| 88 |
+
</motion.div>
|
| 89 |
+
|
| 90 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-6">
|
| 91 |
+
<div className="data-card p-5 space-y-4">
|
| 92 |
+
<div className="flex items-center justify-between gap-3 flex-wrap">
|
| 93 |
+
<h3 className="text-sm font-semibold text-text-primary">Sequence A (vertical axis)</h3>
|
| 94 |
+
<button
|
| 95 |
+
onClick={() => setSeqA(SAMPLE_A)}
|
| 96 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 97 |
+
>
|
| 98 |
+
Load p53 human
|
| 99 |
+
</button>
|
| 100 |
+
</div>
|
| 101 |
+
<FlatTextarea
|
| 102 |
+
value={seqA}
|
| 103 |
+
onChange={e => setSeqA(e.target.value)}
|
| 104 |
+
placeholder="Paste first sequence (raw or FASTA)..."
|
| 105 |
+
className="w-full h-28 text-sm"
|
| 106 |
+
/>
|
| 107 |
+
|
| 108 |
+
<div className="flex items-center gap-3 flex-wrap">
|
| 109 |
+
<h3 className="text-sm font-semibold text-text-primary">Sequence B (horizontal axis)</h3>
|
| 110 |
+
<ClayToggle
|
| 111 |
+
checked={selfCompare}
|
| 112 |
+
onChange={toggleSelf}
|
| 113 |
+
label={selfCompare ? 'Self-comparison' : 'Compare to self'}
|
| 114 |
+
/>
|
| 115 |
+
{!selfCompare && (
|
| 116 |
+
<button
|
| 117 |
+
onClick={() => setSeqB(SAMPLE_B)}
|
| 118 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 119 |
+
>
|
| 120 |
+
Load p53 mouse
|
| 121 |
+
</button>
|
| 122 |
+
)}
|
| 123 |
+
</div>
|
| 124 |
+
<FlatTextarea
|
| 125 |
+
value={effectiveB}
|
| 126 |
+
onChange={e => setSeqB(e.target.value)}
|
| 127 |
+
disabled={selfCompare}
|
| 128 |
+
placeholder="Paste second sequence (raw or FASTA)..."
|
| 129 |
+
className="w-full h-28 text-sm"
|
| 130 |
+
/>
|
| 131 |
+
</div>
|
| 132 |
+
|
| 133 |
+
<div className="glass p-4 border border-glass-border grid grid-cols-1 sm:grid-cols-2 gap-5">
|
| 134 |
+
<ClaySlider
|
| 135 |
+
label="Window size"
|
| 136 |
+
value={window}
|
| 137 |
+
min={1}
|
| 138 |
+
max={50}
|
| 139 |
+
unit="residues"
|
| 140 |
+
onChange={setWindow}
|
| 141 |
+
/>
|
| 142 |
+
<ClaySlider
|
| 143 |
+
label="Stringency"
|
| 144 |
+
value={stringency}
|
| 145 |
+
min={40}
|
| 146 |
+
max={100}
|
| 147 |
+
unit="% identity"
|
| 148 |
+
onChange={setStringency}
|
| 149 |
+
/>
|
| 150 |
+
</div>
|
| 151 |
+
|
| 152 |
+
<div className="flex justify-end">
|
| 153 |
+
<CriticalButton onClick={handleRun} disabled={!canRun}>
|
| 154 |
+
{loading ? <LoaderCircle className="w-4 h-4 animate-spin" /> : null}
|
| 155 |
+
{loading ? 'Computing...' : 'Compute dot plot'}
|
| 156 |
+
</CriticalButton>
|
| 157 |
+
</div>
|
| 158 |
+
|
| 159 |
+
{error && (
|
| 160 |
+
<div className="rounded-lg bg-error/10 border border-error/30 px-4 py-3 text-sm text-error">
|
| 161 |
+
<strong>Dot plot failed:</strong> {error}
|
| 162 |
+
</div>
|
| 163 |
+
)}
|
| 164 |
+
|
| 165 |
+
{result && !loading && (
|
| 166 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-4 mt-8">
|
| 167 |
+
<div className="data-card p-5">
|
| 168 |
+
<div className="flex items-center gap-3 mb-4 flex-wrap">
|
| 169 |
+
<h3 className="text-sm font-semibold text-text-primary">Dot plot</h3>
|
| 170 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-accent-cyan/10 border border-accent-cyan/30 text-accent-cyan font-medium">
|
| 171 |
+
{result.dot_count.toLocaleString()} dots
|
| 172 |
+
</span>
|
| 173 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-surface-1 border border-glass-border text-text-muted font-medium">
|
| 174 |
+
A: {result.seq_a_length} · B: {result.seq_b_length}
|
| 175 |
+
</span>
|
| 176 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-surface-1 border border-glass-border text-text-muted font-medium">
|
| 177 |
+
window {result.window} · {result.stringency}% (≥{result.threshold})
|
| 178 |
+
</span>
|
| 179 |
+
<div className="ml-auto flex items-center gap-2">
|
| 180 |
+
<button
|
| 181 |
+
onClick={() => setResult({ ...result })}
|
| 182 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 183 |
+
>
|
| 184 |
+
Reset zoom
|
| 185 |
+
</button>
|
| 186 |
+
</div>
|
| 187 |
+
</div>
|
| 188 |
+
|
| 189 |
+
{result.downsampled && (
|
| 190 |
+
<p className="mb-3 text-xs text-accent-amber">
|
| 191 |
+
Downsampled: {result.total_matches.toLocaleString()} raw matches, showing a uniform subset.
|
| 192 |
+
</p>
|
| 193 |
+
)}
|
| 194 |
+
|
| 195 |
+
<div className="w-full h-[520px]">
|
| 196 |
+
<ResponsiveContainer width="100%" height="100%">
|
| 197 |
+
<ScatterChart margin={{ top: 10, right: 20, bottom: 24, left: 8 }}>
|
| 198 |
+
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
|
| 199 |
+
<XAxis
|
| 200 |
+
type="number"
|
| 201 |
+
dataKey="x"
|
| 202 |
+
name="Position in B"
|
| 203 |
+
domain={[0, result.seq_b_length]}
|
| 204 |
+
tick={{ fontSize: 10, fill: '#64748B' }}
|
| 205 |
+
label={{ value: 'Sequence B position', position: 'insideBottom', offset: -12, fill: '#94A3B8', fontSize: 11 }}
|
| 206 |
+
/>
|
| 207 |
+
<YAxis
|
| 208 |
+
type="number"
|
| 209 |
+
dataKey="y"
|
| 210 |
+
name="Position in A"
|
| 211 |
+
domain={[0, result.seq_a_length]}
|
| 212 |
+
tick={{ fontSize: 10, fill: '#64748B' }}
|
| 213 |
+
label={{ value: 'Sequence A position', angle: -90, position: 'insideLeft', offset: 4, fill: '#94A3B8', fontSize: 11 }}
|
| 214 |
+
/>
|
| 215 |
+
{result.seq_a_length === result.seq_b_length && (
|
| 216 |
+
<ReferenceLine segment={[{ x: 0, y: 0 }, { x: result.seq_b_length, y: result.seq_a_length }]} stroke="rgba(168,85,247,0.5)" strokeDasharray="4 4" />
|
| 217 |
+
)}
|
| 218 |
+
<Tooltip {...tooltipStyle} />
|
| 219 |
+
<Scatter data={data} fill="#22D3EE" fillOpacity={0.55} stroke="none" shape="circle" isAnimationActive={false} />
|
| 220 |
+
<Brush dataKey="x" height={18} travellerWidth={8} stroke="#22D3EE" fill="rgba(34,211,238,0.08)" />
|
| 221 |
+
</ScatterChart>
|
| 222 |
+
</ResponsiveContainer>
|
| 223 |
+
</div>
|
| 224 |
+
</div>
|
| 225 |
+
</motion.div>
|
| 226 |
+
)}
|
| 227 |
+
</motion.div>
|
| 228 |
+
</div>
|
| 229 |
+
);
|
| 230 |
+
}
|
bioai-platform/frontend/src/app/(dashboard)/analyze/motif/page.tsx
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useEffect, useState } from 'react';
|
| 4 |
+
import { motion } from 'framer-motion';
|
| 5 |
+
import { CircleNotch as LoaderCircle } from '@phosphor-icons/react';
|
| 6 |
+
import { fadeUp } from '@/lib/animations';
|
| 7 |
+
import { fetchMotifPatterns, scanMotifLibrary, scanMotifPattern } from '@/lib/api';
|
| 8 |
+
import { extractErrorMessage } from '@/lib/errors';
|
| 9 |
+
import { useAuditTrail } from '@/hooks/useAuditTrail';
|
| 10 |
+
import { BackButton, CriticalButton, ClaySegmented, FlatTextarea, PageHeader } from '@/components/ui';
|
| 11 |
+
import { MotifTrack, MatchTable } from '@/components/motifs/MotifTrack';
|
| 12 |
+
import type { MotifLibraryPattern, MotifLibraryResult, MotifPatternScanResult } from '@/types/pipeline';
|
| 13 |
+
|
| 14 |
+
type Mode = 'library' | 'custom';
|
| 15 |
+
|
| 16 |
+
const SAMPLE = '>kinase\nMKDYQNSTLPVARKTGHMRKNGGGGGPMNSSTLDEIYGKPPASDVAVCGHWMQEVDVCVGVIGRSGYGFRLGFLHSGTAKSVTCTYSPALNKMFCQLAKTCPVQLWVDSTPPPGTRVRAMAIYKQSQHMTEVVRRCPHHERCSDSDGLAPPQHLIRVEGNLRVEYLDDRNTFRHSVVVPYEPPEVGSDCTTIHYNYMCNSSCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGRDRRTEEENLRKKGEPHHELPPGSTKRALPNNTSSSPQPKKKPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPGGSRAHSSHLKSKKGQSTSRHKKLMFKTEGPDSD';
|
| 17 |
+
|
| 18 |
+
function cleanLength(seq: string): number {
|
| 19 |
+
return seq.replace(/[^A-Za-z]/g, '').length;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
export default function MotifScannerPage() {
|
| 23 |
+
const [sequence, setSequence] = useState('');
|
| 24 |
+
const [mode, setMode] = useState<Mode>('library');
|
| 25 |
+
const [patterns, setPatterns] = useState<MotifLibraryPattern[]>([]);
|
| 26 |
+
const [customPattern, setCustomPattern] = useState('N-{P}-[ST]-{P}');
|
| 27 |
+
const [loading, setLoading] = useState(false);
|
| 28 |
+
const [result, setResult] = useState<MotifLibraryResult | null>(null);
|
| 29 |
+
const [patternResult, setPatternResult] = useState<MotifPatternScanResult | null>(null);
|
| 30 |
+
const [error, setError] = useState<string | null>(null);
|
| 31 |
+
const audit = useAuditTrail();
|
| 32 |
+
|
| 33 |
+
useEffect(() => {
|
| 34 |
+
fetchMotifPatterns().then(setPatterns).catch(() => {});
|
| 35 |
+
}, []);
|
| 36 |
+
|
| 37 |
+
const canRun = cleanLength(sequence) >= 1 && !loading;
|
| 38 |
+
|
| 39 |
+
const handleRun = async () => {
|
| 40 |
+
if (!canRun) return;
|
| 41 |
+
setLoading(true);
|
| 42 |
+
setError(null);
|
| 43 |
+
setResult(null);
|
| 44 |
+
setPatternResult(null);
|
| 45 |
+
const summary = `len:${cleanLength(sequence)},mode:${mode}`;
|
| 46 |
+
audit.emitStarted('motif_scanner', 'Motif Scanner', summary);
|
| 47 |
+
try {
|
| 48 |
+
if (mode === 'library') {
|
| 49 |
+
const res = await scanMotifLibrary(sequence);
|
| 50 |
+
setResult(res);
|
| 51 |
+
audit.emitSuccess('motif_scanner', 'Motif Scanner', summary, `motifs:${res.motifs_found}`);
|
| 52 |
+
} else {
|
| 53 |
+
const res = await scanMotifPattern({ sequence, pattern: customPattern });
|
| 54 |
+
setPatternResult(res);
|
| 55 |
+
audit.emitSuccess('motif_scanner', 'Motif Scanner', summary, `matches:${res.count}`);
|
| 56 |
+
}
|
| 57 |
+
} catch (err: unknown) {
|
| 58 |
+
const errMsg = extractErrorMessage(err, 'Motif scan failed');
|
| 59 |
+
setError(errMsg);
|
| 60 |
+
audit.emitFailed('motif_scanner', 'Motif Scanner', summary, errMsg);
|
| 61 |
+
} finally {
|
| 62 |
+
setLoading(false);
|
| 63 |
+
}
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
const seqLen = cleanLength(sequence);
|
| 67 |
+
|
| 68 |
+
return (
|
| 69 |
+
<div className="max-w-3xl">
|
| 70 |
+
<BackButton />
|
| 71 |
+
|
| 72 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
|
| 73 |
+
<PageHeader
|
| 74 |
+
title="Motif Scanner"
|
| 75 |
+
subtitle="Find short functional motifs in a protein — scan against a curated library of well-known patterns (glycosylation, phosphorylation, zinc fingers, P-loop...) or enter your own PROSITE pattern."
|
| 76 |
+
/>
|
| 77 |
+
</motion.div>
|
| 78 |
+
|
| 79 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-6">
|
| 80 |
+
<div className="data-card p-5 space-y-4">
|
| 81 |
+
<FlatTextarea
|
| 82 |
+
value={sequence}
|
| 83 |
+
onChange={e => setSequence(e.target.value)}
|
| 84 |
+
placeholder="Paste a protein sequence (raw or FASTA)..."
|
| 85 |
+
className="w-full h-36 text-sm"
|
| 86 |
+
/>
|
| 87 |
+
<div className="flex items-center justify-between gap-3 flex-wrap">
|
| 88 |
+
<ClaySegmented
|
| 89 |
+
options={[
|
| 90 |
+
{ value: 'library', label: 'Curated library' },
|
| 91 |
+
{ value: 'custom', label: 'Custom pattern' },
|
| 92 |
+
]}
|
| 93 |
+
value={mode}
|
| 94 |
+
onChange={setMode}
|
| 95 |
+
size="sm"
|
| 96 |
+
/>
|
| 97 |
+
<button
|
| 98 |
+
onClick={() => setSequence(SAMPLE)}
|
| 99 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 100 |
+
>
|
| 101 |
+
Load sample protein
|
| 102 |
+
</button>
|
| 103 |
+
</div>
|
| 104 |
+
|
| 105 |
+
{mode === 'custom' && (
|
| 106 |
+
<div>
|
| 107 |
+
<label className="block text-[10px] uppercase tracking-wider text-text-muted mb-1.5">
|
| 108 |
+
PROSITE pattern
|
| 109 |
+
</label>
|
| 110 |
+
<div className="flex items-center gap-2">
|
| 111 |
+
<input
|
| 112 |
+
value={customPattern}
|
| 113 |
+
onChange={e => setCustomPattern(e.target.value)}
|
| 114 |
+
placeholder="e.g. N-{P}-[ST]-{P}, [ST]-x-[RK], x(2,4)"
|
| 115 |
+
className="input-flat font-mono text-sm flex-1"
|
| 116 |
+
/>
|
| 117 |
+
<div className="hidden md:block max-w-56">
|
| 118 |
+
{patterns.length > 0 && (
|
| 119 |
+
<select
|
| 120 |
+
onChange={e => { if (e.target.value) setCustomPattern(e.target.value); }}
|
| 121 |
+
value=""
|
| 122 |
+
className="input-flat text-xs w-full"
|
| 123 |
+
aria-label="Choose a preset pattern"
|
| 124 |
+
>
|
| 125 |
+
<option value="">Presets…</option>
|
| 126 |
+
{patterns.map(p => (
|
| 127 |
+
<option key={p.name} value={p.pattern}>{p.name}</option>
|
| 128 |
+
))}
|
| 129 |
+
</select>
|
| 130 |
+
)}
|
| 131 |
+
</div>
|
| 132 |
+
</div>
|
| 133 |
+
<p className="mt-1.5 text-[11px] text-text-muted">
|
| 134 |
+
Syntax: <code className="font-mono text-accent-cyan">-</code> separator,{' '}
|
| 135 |
+
<code className="font-mono text-accent-cyan">x</code> any residue,{' '}
|
| 136 |
+
<code className="font-mono text-accent-cyan">[ST]</code> one of,{' '}
|
| 137 |
+
<code className="font-mono text-accent-cyan">{'{ED}'}</code> none of,{' '}
|
| 138 |
+
<code className="font-mono text-accent-cyan">x(2,4)</code> repeats,{' '}
|
| 139 |
+
<code className="font-mono text-accent-cyan"><</code>/<code className="font-mono text-accent-cyan">></code> anchors.
|
| 140 |
+
</p>
|
| 141 |
+
</div>
|
| 142 |
+
)}
|
| 143 |
+
</div>
|
| 144 |
+
|
| 145 |
+
<div className="flex justify-end">
|
| 146 |
+
<CriticalButton onClick={handleRun} disabled={!canRun}>
|
| 147 |
+
{loading ? <LoaderCircle className="w-4 h-4 animate-spin" /> : null}
|
| 148 |
+
{loading ? 'Scanning...' : mode === 'library' ? 'Scan library' : 'Scan pattern'}
|
| 149 |
+
</CriticalButton>
|
| 150 |
+
</div>
|
| 151 |
+
|
| 152 |
+
{error && (
|
| 153 |
+
<div className="rounded-lg bg-error/10 border border-error/30 px-4 py-3 text-sm text-error">
|
| 154 |
+
<strong>Scan failed:</strong> {error}
|
| 155 |
+
</div>
|
| 156 |
+
)}
|
| 157 |
+
|
| 158 |
+
{patternResult && !loading && (
|
| 159 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-4 mt-8">
|
| 160 |
+
<div className="data-card p-5">
|
| 161 |
+
<div className="flex items-center gap-3 mb-1 flex-wrap">
|
| 162 |
+
<h3 className="text-sm font-semibold text-text-primary">Pattern matches</h3>
|
| 163 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-accent-cyan/10 border border-accent-cyan/30 text-accent-cyan font-medium">
|
| 164 |
+
{patternResult.count} hits
|
| 165 |
+
</span>
|
| 166 |
+
<code className="text-xs font-mono text-text-muted ml-auto">{patternResult.pattern}</code>
|
| 167 |
+
</div>
|
| 168 |
+
<p className="text-[11px] font-mono text-text-muted mb-3">regex: {patternResult.regex}</p>
|
| 169 |
+
{patternResult.count === 0 ? (
|
| 170 |
+
<p className="text-sm text-text-muted">No matches found for this pattern.</p>
|
| 171 |
+
) : (
|
| 172 |
+
<>
|
| 173 |
+
<MotifTrack
|
| 174 |
+
length={seqLen}
|
| 175 |
+
tracks={[{ name: 'Pattern', matches: patternResult.matches }]}
|
| 176 |
+
/>
|
| 177 |
+
<div className="mt-3">
|
| 178 |
+
<MatchTable matches={patternResult.matches} />
|
| 179 |
+
</div>
|
| 180 |
+
</>
|
| 181 |
+
)}
|
| 182 |
+
</div>
|
| 183 |
+
</motion.div>
|
| 184 |
+
)}
|
| 185 |
+
|
| 186 |
+
{result && !loading && (
|
| 187 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-4 mt-8">
|
| 188 |
+
<div className="data-card p-5">
|
| 189 |
+
<div className="flex items-center gap-3 mb-1 flex-wrap">
|
| 190 |
+
<h3 className="text-sm font-semibold text-text-primary">Motif library scan</h3>
|
| 191 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-accent-purple/10 border border-accent-purple/30 text-accent-purple font-medium">
|
| 192 |
+
{result.motifs_found} motifs · {result.patterns_scanned} patterns
|
| 193 |
+
</span>
|
| 194 |
+
</div>
|
| 195 |
+
<p className="text-xs text-text-muted mb-3">
|
| 196 |
+
{result.length} residues · {result.sequence_type} sequence
|
| 197 |
+
</p>
|
| 198 |
+
|
| 199 |
+
{result.motifs_found === 0 ? (
|
| 200 |
+
<p className="text-sm text-text-muted">No known motifs found in this sequence.</p>
|
| 201 |
+
) : (
|
| 202 |
+
<div className="space-y-5">
|
| 203 |
+
<MotifTrack
|
| 204 |
+
length={result.length}
|
| 205 |
+
tracks={result.hits.map(h => ({ name: h.name, matches: h.matches }))}
|
| 206 |
+
/>
|
| 207 |
+
{result.hits.map(hit => (
|
| 208 |
+
<div key={hit.name} className="rounded-lg bg-surface-0 border border-glass-border p-4">
|
| 209 |
+
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
| 210 |
+
<h4 className="text-sm font-semibold text-accent-purple">{hit.name}</h4>
|
| 211 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-surface-1 border border-glass-border text-text-muted font-medium">
|
| 212 |
+
{hit.count}×
|
| 213 |
+
</span>
|
| 214 |
+
<code className="text-[11px] font-mono text-text-muted ml-auto">{hit.pattern}</code>
|
| 215 |
+
</div>
|
| 216 |
+
<p className="text-[11px] text-text-muted mb-2">{hit.description}</p>
|
| 217 |
+
<MatchTable matches={hit.matches} />
|
| 218 |
+
</div>
|
| 219 |
+
))}
|
| 220 |
+
</div>
|
| 221 |
+
)}
|
| 222 |
+
</div>
|
| 223 |
+
</motion.div>
|
| 224 |
+
)}
|
| 225 |
+
</motion.div>
|
| 226 |
+
</div>
|
| 227 |
+
);
|
| 228 |
+
}
|
bioai-platform/frontend/src/app/(dashboard)/analyze/page.tsx
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
'use client';
|
| 2 |
|
| 3 |
import { useRouter } from 'next/navigation';
|
| 4 |
-
import { Dna, SquaresFour as Layout, MagnifyingGlass as Search, Globe, GitBranch, Flask as Beaker, Stack as Layers, ShareNetwork as Share2, TestTube as FlaskConical, Shuffle, GitFork, Atom, Pill, Pulse as Activity, Brain, ArrowsLeftRight as ArrowSwap } from '@phosphor-icons/react';
|
| 5 |
import { motion } from 'framer-motion';
|
| 6 |
import { fadeUp, stagger, hoverGlow, press } from '@/lib/animations';
|
| 7 |
import { ReactNode } from 'react';
|
|
@@ -27,6 +27,9 @@ const groups: { title: string; items: Operation[] }[] = [
|
|
| 27 |
{ id: 'domains', name: 'Domain Analysis', description: 'Fetch domain/motif annotations from InterPro.', icon: Layers, active: true },
|
| 28 |
{ id: 'phylo', name: 'Phylogenetic Tree', description: 'Build and visualize phylogenetic trees from sequences.', icon: GitFork, active: true },
|
| 29 |
{ id: 'sequencing', name: 'Sequencing Pipeline', description: 'Raw FASTQ → QC → alignment → variant calling → report for genomic data.', icon: Dna, active: true, badge: 'New' },
|
|
|
|
|
|
|
|
|
|
| 30 |
],
|
| 31 |
},
|
| 32 |
{
|
|
|
|
| 1 |
'use client';
|
| 2 |
|
| 3 |
import { useRouter } from 'next/navigation';
|
| 4 |
+
import { Dna, SquaresFour as Layout, MagnifyingGlass as Search, Globe, GitBranch, Flask as Beaker, Stack as Layers, ShareNetwork as Share2, TestTube as FlaskConical, Shuffle, GitFork, Atom, Pill, Pulse as Activity, Brain, ArrowsLeftRight as ArrowSwap, Calculator, Target, ChartScatter } from '@phosphor-icons/react';
|
| 5 |
import { motion } from 'framer-motion';
|
| 6 |
import { fadeUp, stagger, hoverGlow, press } from '@/lib/animations';
|
| 7 |
import { ReactNode } from 'react';
|
|
|
|
| 27 |
{ id: 'domains', name: 'Domain Analysis', description: 'Fetch domain/motif annotations from InterPro.', icon: Layers, active: true },
|
| 28 |
{ id: 'phylo', name: 'Phylogenetic Tree', description: 'Build and visualize phylogenetic trees from sequences.', icon: GitFork, active: true },
|
| 29 |
{ id: 'sequencing', name: 'Sequencing Pipeline', description: 'Raw FASTQ → QC → alignment → variant calling → report for genomic data.', icon: Dna, active: true, badge: 'New' },
|
| 30 |
+
{ id: 'sequences', name: 'Sequence Utilities', description: 'GC content, reverse complement, translation, molecular weight, restriction sites.', icon: Calculator, active: true, badge: 'New' },
|
| 31 |
+
{ id: 'motif', name: 'Motif Scanner', description: 'Scan a protein against curated PROSITE patterns or a custom motif.', icon: Target, active: true, badge: 'New' },
|
| 32 |
+
{ id: 'dotplot', name: 'Dot Plot', description: 'Visual self/dot-plot comparison of two sequences with window & stringency.', icon: ChartScatter, active: true, badge: 'New' },
|
| 33 |
],
|
| 34 |
},
|
| 35 |
{
|
bioai-platform/frontend/src/app/(dashboard)/analyze/sequences/page.tsx
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useState } from 'react';
|
| 4 |
+
import { motion } from 'framer-motion';
|
| 5 |
+
import { CircleNotch as LoaderCircle } from '@phosphor-icons/react';
|
| 6 |
+
import { fadeUp } from '@/lib/animations';
|
| 7 |
+
import { analyzeSequence } from '@/lib/api';
|
| 8 |
+
import { extractErrorMessage } from '@/lib/errors';
|
| 9 |
+
import { useAuditTrail } from '@/hooks/useAuditTrail';
|
| 10 |
+
import { BackButton, CriticalButton, ClaySegmented, FlatTextarea, PageHeader } from '@/components/ui';
|
| 11 |
+
import { SequenceUtilitiesView } from '@/components/sequences/SequenceUtilitiesView';
|
| 12 |
+
import type { SequenceUtilitiesResult } from '@/types/pipeline';
|
| 13 |
+
|
| 14 |
+
type SeqType = 'auto' | 'dna' | 'rna' | 'protein';
|
| 15 |
+
|
| 16 |
+
const SAMPLE_DNA = '>probe\nAGCTAGCGGATCCGAATTCGATCGTACGATCGATCGTACGATGACGTAGCTAGCATCGATCGTAGCTAGCG';
|
| 17 |
+
const SAMPLE_PROTEIN = '>p53_1_70\nMEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGPDEAPRMPEAAPPVAPAPAA';
|
| 18 |
+
|
| 19 |
+
function cleanLength(seq: string): number {
|
| 20 |
+
return seq.replace(/[^A-Za-z]/g, '').length;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
export default function SequenceUtilitiesPage() {
|
| 24 |
+
const [sequence, setSequence] = useState('');
|
| 25 |
+
const [seqType, setSeqType] = useState<SeqType>('auto');
|
| 26 |
+
const [loading, setLoading] = useState(false);
|
| 27 |
+
const [result, setResult] = useState<SequenceUtilitiesResult | null>(null);
|
| 28 |
+
const [error, setError] = useState<string | null>(null);
|
| 29 |
+
const audit = useAuditTrail();
|
| 30 |
+
|
| 31 |
+
const canRun = cleanLength(sequence) >= 1 && !loading;
|
| 32 |
+
|
| 33 |
+
const handleRun = async () => {
|
| 34 |
+
if (!canRun) return;
|
| 35 |
+
setLoading(true);
|
| 36 |
+
setError(null);
|
| 37 |
+
setResult(null);
|
| 38 |
+
const summary = `len:${cleanLength(sequence)},type:${seqType}`;
|
| 39 |
+
audit.emitStarted('sequence_utilities', 'Sequence Utilities', summary);
|
| 40 |
+
try {
|
| 41 |
+
const res = await analyzeSequence({ sequence, seq_type: seqType });
|
| 42 |
+
setResult(res);
|
| 43 |
+
audit.emitSuccess('sequence_utilities', 'Sequence Utilities', summary, `type:${res.sequence_type},length:${res.length}`);
|
| 44 |
+
} catch (err: unknown) {
|
| 45 |
+
const errMsg = extractErrorMessage(err, 'Sequence analysis failed');
|
| 46 |
+
setError(errMsg);
|
| 47 |
+
audit.emitFailed('sequence_utilities', 'Sequence Utilities', summary, errMsg);
|
| 48 |
+
} finally {
|
| 49 |
+
setLoading(false);
|
| 50 |
+
}
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
return (
|
| 54 |
+
<div className="max-w-3xl">
|
| 55 |
+
<BackButton />
|
| 56 |
+
|
| 57 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show">
|
| 58 |
+
<PageHeader
|
| 59 |
+
title="Sequence Utilities"
|
| 60 |
+
subtitle="GC content, reverse complement, molecular weight, six-frame translation with best-ORF detection, amino-acid composition and restriction-enzyme site scanning — all computed instantly."
|
| 61 |
+
/>
|
| 62 |
+
</motion.div>
|
| 63 |
+
|
| 64 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="space-y-6">
|
| 65 |
+
<div className="data-card p-5 space-y-4">
|
| 66 |
+
<FlatTextarea
|
| 67 |
+
value={sequence}
|
| 68 |
+
onChange={e => setSequence(e.target.value)}
|
| 69 |
+
placeholder="Paste DNA, RNA or protein sequence (raw or FASTA)..."
|
| 70 |
+
className="w-full h-40 text-sm"
|
| 71 |
+
/>
|
| 72 |
+
<div className="flex items-center justify-between gap-3 flex-wrap">
|
| 73 |
+
<ClaySegmented
|
| 74 |
+
options={[
|
| 75 |
+
{ value: 'auto', label: 'Auto-detect' },
|
| 76 |
+
{ value: 'dna', label: 'DNA' },
|
| 77 |
+
{ value: 'rna', label: 'RNA' },
|
| 78 |
+
{ value: 'protein', label: 'Protein' },
|
| 79 |
+
]}
|
| 80 |
+
value={seqType}
|
| 81 |
+
onChange={setSeqType}
|
| 82 |
+
/>
|
| 83 |
+
<div className="flex gap-2">
|
| 84 |
+
<button
|
| 85 |
+
onClick={() => setSequence(SAMPLE_DNA)}
|
| 86 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 87 |
+
>
|
| 88 |
+
Load DNA sample
|
| 89 |
+
</button>
|
| 90 |
+
<button
|
| 91 |
+
onClick={() => setSequence(SAMPLE_PROTEIN)}
|
| 92 |
+
className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition"
|
| 93 |
+
>
|
| 94 |
+
Load protein sample
|
| 95 |
+
</button>
|
| 96 |
+
</div>
|
| 97 |
+
</div>
|
| 98 |
+
</div>
|
| 99 |
+
|
| 100 |
+
<div className="flex justify-end">
|
| 101 |
+
<CriticalButton onClick={handleRun} disabled={!canRun}>
|
| 102 |
+
{loading ? <LoaderCircle className="w-4 h-4 animate-spin" /> : null}
|
| 103 |
+
{loading ? 'Analyzing...' : 'Analyze sequence'}
|
| 104 |
+
</CriticalButton>
|
| 105 |
+
</div>
|
| 106 |
+
|
| 107 |
+
{error && (
|
| 108 |
+
<div className="rounded-lg bg-error/10 border border-error/30 px-4 py-3 text-sm text-error">
|
| 109 |
+
<strong>Analysis failed:</strong> {error}
|
| 110 |
+
</div>
|
| 111 |
+
)}
|
| 112 |
+
|
| 113 |
+
{result && !loading && (
|
| 114 |
+
<motion.div variants={fadeUp} initial={{ y: 24 }} animate="show" className="mt-8">
|
| 115 |
+
<SequenceUtilitiesView result={result} />
|
| 116 |
+
</motion.div>
|
| 117 |
+
)}
|
| 118 |
+
</motion.div>
|
| 119 |
+
</div>
|
| 120 |
+
);
|
| 121 |
+
}
|
bioai-platform/frontend/src/components/motifs/MotifTrack.tsx
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import type { MotifMatch } from '@/types/pipeline';
|
| 4 |
+
|
| 5 |
+
const TRACK_COLORS = ['#22D3EE', '#A855F7', '#FBBF24', '#FB923C', '#34D399', '#F87171', '#60A5FA', '#E879F9'];
|
| 6 |
+
|
| 7 |
+
export function MotifTrack({
|
| 8 |
+
length,
|
| 9 |
+
tracks,
|
| 10 |
+
}: {
|
| 11 |
+
length: number;
|
| 12 |
+
tracks: Array<{ name: string; matches: MotifMatch[] }>;
|
| 13 |
+
}) {
|
| 14 |
+
if (length === 0) return null;
|
| 15 |
+
const W = 1000;
|
| 16 |
+
const ROW_H = 18;
|
| 17 |
+
const headerH = 18;
|
| 18 |
+
|
| 19 |
+
const px = (pos: number) => (pos / length) * W;
|
| 20 |
+
|
| 21 |
+
return (
|
| 22 |
+
<div className="overflow-x-auto">
|
| 23 |
+
<svg viewBox={`0 0 ${W} ${headerH + tracks.length * ROW_H + 6}`} className="w-full min-w-[480px] h-auto" role="img" aria-label="Motif match map">
|
| 24 |
+
{/* sequence backbone */}
|
| 25 |
+
<line x1={0} y1={headerH + 8} x2={W} y2={headerH + 8} stroke="rgba(132,140,164,0.35)" strokeWidth={2} />
|
| 26 |
+
{tracks.map((track, ti) => {
|
| 27 |
+
const color = TRACK_COLORS[ti % TRACK_COLORS.length];
|
| 28 |
+
const y = headerH + ti * ROW_H;
|
| 29 |
+
return (
|
| 30 |
+
<g key={track.name}>
|
| 31 |
+
<text x={0} y={y + 6} fill="#94A3B8" fontSize={11}>
|
| 32 |
+
{track.name}
|
| 33 |
+
</text>
|
| 34 |
+
{track.matches.map((m, mi) => {
|
| 35 |
+
const x = px(m.start - 1);
|
| 36 |
+
const w = Math.max(6, px(m.end - m.start + 1) - px(m.start - 1));
|
| 37 |
+
return (
|
| 38 |
+
<g key={`${m.start}-${mi}`}>
|
| 39 |
+
<rect x={x} y={y + 10} width={w} height={6} rx={2} fill={color} opacity={0.9} />
|
| 40 |
+
<title>{`${track.name}: ${m.start}–${m.end} (${m.motif})`}</title>
|
| 41 |
+
</g>
|
| 42 |
+
);
|
| 43 |
+
})}
|
| 44 |
+
</g>
|
| 45 |
+
);
|
| 46 |
+
})}
|
| 47 |
+
{/* scale ticks every 10% */}
|
| 48 |
+
{Array.from({ length: 11 }).map((_, i) => (
|
| 49 |
+
<g key={i}>
|
| 50 |
+
<line x1={(i / 10) * W} y1={headerH + tracks.length * ROW_H} x2={(i / 10) * W} y2={headerH + tracks.length * ROW_H + 5} stroke="rgba(132,140,164,0.4)" strokeWidth={1} />
|
| 51 |
+
<text x={(i / 10) * W - 12} y={headerH + tracks.length * ROW_H + 15} fill="#64748B" fontSize={9} textAnchor="middle">
|
| 52 |
+
{Math.round((i / 10) * length)}
|
| 53 |
+
</text>
|
| 54 |
+
</g>
|
| 55 |
+
))}
|
| 56 |
+
</svg>
|
| 57 |
+
</div>
|
| 58 |
+
);
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
export function MatchTable({ matches }: { matches: MotifMatch[] }) {
|
| 62 |
+
return (
|
| 63 |
+
<div className="overflow-x-auto">
|
| 64 |
+
<table className="w-full text-xs">
|
| 65 |
+
<thead>
|
| 66 |
+
<tr className="text-left text-[10px] uppercase tracking-wider text-text-muted border-b border-glass-border">
|
| 67 |
+
<th className="py-2 pr-4">#</th>
|
| 68 |
+
<th className="py-2 pr-4">Start</th>
|
| 69 |
+
<th className="py-2 pr-4">End</th>
|
| 70 |
+
<th className="py-2">Match</th>
|
| 71 |
+
</tr>
|
| 72 |
+
</thead>
|
| 73 |
+
<tbody>
|
| 74 |
+
{matches.map((m, i) => (
|
| 75 |
+
<tr key={i} className="border-b border-glass-border/60 last:border-0">
|
| 76 |
+
<td className="py-2 pr-4 text-text-muted">{i + 1}</td>
|
| 77 |
+
<td className="py-2 pr-4 font-mono text-accent-cyan">{m.start}</td>
|
| 78 |
+
<td className="py-2 pr-4 font-mono text-accent-cyan">{m.end}</td>
|
| 79 |
+
<td className="py-2 font-mono text-text-secondary">{m.motif}</td>
|
| 80 |
+
</tr>
|
| 81 |
+
))}
|
| 82 |
+
</tbody>
|
| 83 |
+
</table>
|
| 84 |
+
</div>
|
| 85 |
+
);
|
| 86 |
+
}
|
bioai-platform/frontend/src/components/sequences/SequenceUtilitiesView.tsx
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useState } from 'react';
|
| 4 |
+
import { Copy, Check } from '@phosphor-icons/react';
|
| 5 |
+
import type { SequenceUtilitiesResult } from '@/types/pipeline';
|
| 6 |
+
|
| 7 |
+
function StatChip({ label, value, valueClass = 'text-text-primary' }: { label: string; value: string; valueClass?: string }) {
|
| 8 |
+
return (
|
| 9 |
+
<div className="flex flex-col items-center justify-center px-4 py-3 rounded-lg bg-surface-0 border border-glass-border min-w-[96px]">
|
| 10 |
+
<span className="text-[10px] uppercase tracking-wider text-text-muted">{label}</span>
|
| 11 |
+
<span className={`text-lg font-bold font-mono mt-0.5 ${valueClass}`}>{value}</span>
|
| 12 |
+
</div>
|
| 13 |
+
);
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
function CopyButton({ text }: { text: string }) {
|
| 17 |
+
const [copied, setCopied] = useState(false);
|
| 18 |
+
return (
|
| 19 |
+
<button
|
| 20 |
+
onClick={async () => {
|
| 21 |
+
await navigator.clipboard.writeText(text);
|
| 22 |
+
setCopied(true);
|
| 23 |
+
setTimeout(() => setCopied(false), 1500);
|
| 24 |
+
}}
|
| 25 |
+
className="px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-xs text-text-secondary hover:text-accent-cyan transition flex items-center gap-1.5"
|
| 26 |
+
aria-label="Copy to clipboard"
|
| 27 |
+
>
|
| 28 |
+
{copied ? <Check className="w-3.5 h-3.5 text-accent-cyan" /> : <Copy className="w-3.5 h-3.5" />}
|
| 29 |
+
{copied ? 'Copied' : 'Copy'}
|
| 30 |
+
</button>
|
| 31 |
+
);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
function CompositionBars({ comp }: { comp: NonNullable<SequenceUtilitiesResult['aa_composition']> }) {
|
| 35 |
+
const max = Math.max(...comp.map(c => c.count));
|
| 36 |
+
return (
|
| 37 |
+
<div className="space-y-1.5">
|
| 38 |
+
{comp.map(c => (
|
| 39 |
+
<div key={c.aa} className="flex items-center gap-2">
|
| 40 |
+
<span className="w-6 text-right font-mono text-[11px] text-accent-cyan">{c.aa}</span>
|
| 41 |
+
<div className="flex-1 h-2 rounded-full bg-surface-1 overflow-hidden">
|
| 42 |
+
<div
|
| 43 |
+
className="h-full rounded-full bg-gradient-to-r from-accent-cyan/40 to-accent-cyan/90"
|
| 44 |
+
style={{ width: `${Math.max(2, (c.count / max) * 100)}%` }}
|
| 45 |
+
/>
|
| 46 |
+
</div>
|
| 47 |
+
<span className="w-8 text-right text-[11px] font-mono text-text-muted">{c.count}</span>
|
| 48 |
+
<span className="w-12 text-right text-[11px] font-mono text-text-muted">{c.pct}%</span>
|
| 49 |
+
</div>
|
| 50 |
+
))}
|
| 51 |
+
</div>
|
| 52 |
+
);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
export function SequenceUtilitiesView({ result }: { result: SequenceUtilitiesResult }) {
|
| 56 |
+
const isNuc = result.sequence_type === 'dna' || result.sequence_type === 'rna';
|
| 57 |
+
const typeColor =
|
| 58 |
+
result.sequence_type === 'dna' ? 'text-accent-cyan' :
|
| 59 |
+
result.sequence_type === 'rna' ? 'text-accent-purple' :
|
| 60 |
+
result.sequence_type === 'protein' ? 'text-accent-amber' : 'text-text-muted';
|
| 61 |
+
|
| 62 |
+
return (
|
| 63 |
+
<div className="space-y-4">
|
| 64 |
+
{result.issues.length > 0 && (
|
| 65 |
+
<div className="rounded-lg bg-accent-amber/10 border border-accent-amber/30 px-4 py-3 text-xs text-accent-amber">
|
| 66 |
+
{result.issues.map((issue, i) => (
|
| 67 |
+
<p key={i}>{issue}</p>
|
| 68 |
+
))}
|
| 69 |
+
</div>
|
| 70 |
+
)}
|
| 71 |
+
|
| 72 |
+
<div className="flex flex-wrap gap-2">
|
| 73 |
+
<StatChip label="Type" value={result.sequence_type.toUpperCase()} valueClass={typeColor} />
|
| 74 |
+
<StatChip label="Length" value={String(result.length)} valueClass="text-accent-cyan" />
|
| 75 |
+
{result.gc_content !== null && (
|
| 76 |
+
<StatChip label="GC content" value={`${result.gc_content}%`} valueClass="text-accent-purple" />
|
| 77 |
+
)}
|
| 78 |
+
{result.molecular_weight !== null && (
|
| 79 |
+
<StatChip label="Mol. weight" value={`${result.molecular_weight.toLocaleString()} Da`} valueClass="text-text-primary" />
|
| 80 |
+
)}
|
| 81 |
+
</div>
|
| 82 |
+
|
| 83 |
+
{isNuc && result.reverse_complement && (
|
| 84 |
+
<div className="data-card p-5">
|
| 85 |
+
<div className="flex items-center justify-between mb-2">
|
| 86 |
+
<h3 className="text-sm font-semibold text-text-primary">Reverse complement</h3>
|
| 87 |
+
<CopyButton text={result.reverse_complement} />
|
| 88 |
+
</div>
|
| 89 |
+
<pre className="font-mono text-xs text-text-secondary bg-surface-0 rounded-xl p-3 overflow-x-auto whitespace-pre-wrap break-all max-h-40 overflow-y-auto">
|
| 90 |
+
{result.reverse_complement}
|
| 91 |
+
</pre>
|
| 92 |
+
</div>
|
| 93 |
+
)}
|
| 94 |
+
|
| 95 |
+
{result.translation && (
|
| 96 |
+
<div className="data-card p-5">
|
| 97 |
+
<h3 className="text-sm font-semibold text-text-primary mb-2">Translation (forward frames)</h3>
|
| 98 |
+
{result.translation.best && (
|
| 99 |
+
<div className="mb-3 rounded-lg bg-accent-cyan/10 border border-accent-cyan/30 px-3 py-2 text-xs text-text-secondary">
|
| 100 |
+
Best ORF — frame <strong className="text-accent-cyan">{result.translation.best.frame}</strong>, starts at residue{' '}
|
| 101 |
+
<strong className="text-accent-cyan">{result.translation.best.start}</strong>, {result.translation.best.length} aa
|
| 102 |
+
{result.translation.best.has_stop ? ' (ends at a stop codon)' : ' (runs to the sequence end)'}.
|
| 103 |
+
</div>
|
| 104 |
+
)}
|
| 105 |
+
{(() => {
|
| 106 |
+
const translation = result.translation;
|
| 107 |
+
if (!translation) return null;
|
| 108 |
+
return (
|
| 109 |
+
<div className="space-y-2">
|
| 110 |
+
{Object.entries(translation.frames).map(([frame, protein]) => (
|
| 111 |
+
<div key={frame}>
|
| 112 |
+
<div className="flex items-center justify-between mb-1">
|
| 113 |
+
<span className="text-[10px] uppercase tracking-wider text-text-muted">Frame {frame}</span>
|
| 114 |
+
{translation.best?.frame === Number(frame) && (
|
| 115 |
+
<span className="text-[10px] px-2 py-0.5 rounded-full bg-accent-cyan/10 border border-accent-cyan/30 text-accent-cyan font-medium">
|
| 116 |
+
longest ORF
|
| 117 |
+
</span>
|
| 118 |
+
)}
|
| 119 |
+
</div>
|
| 120 |
+
<pre className="font-mono text-xs text-text-secondary bg-surface-0 rounded-lg p-2.5 overflow-x-auto whitespace-pre-wrap break-all">
|
| 121 |
+
{protein || '(too short to translate)'}
|
| 122 |
+
</pre>
|
| 123 |
+
</div>
|
| 124 |
+
))}
|
| 125 |
+
</div>
|
| 126 |
+
);
|
| 127 |
+
})()}
|
| 128 |
+
</div>
|
| 129 |
+
)}
|
| 130 |
+
|
| 131 |
+
{result.aa_composition && result.aa_composition.length > 0 && (
|
| 132 |
+
<div className="data-card p-5">
|
| 133 |
+
<h3 className="text-sm font-semibold text-text-primary mb-3">
|
| 134 |
+
Amino-acid composition ({result.translation ? 'translated CDS' : 'protein'})
|
| 135 |
+
</h3>
|
| 136 |
+
<CompositionBars comp={result.aa_composition} />
|
| 137 |
+
</div>
|
| 138 |
+
)}
|
| 139 |
+
|
| 140 |
+
{result.restriction_sites && result.restriction_sites.length > 0 && (
|
| 141 |
+
<div className="data-card p-5">
|
| 142 |
+
<h3 className="text-sm font-semibold text-text-primary mb-3">
|
| 143 |
+
Restriction sites ({result.restriction_sites.length} enzymes)
|
| 144 |
+
</h3>
|
| 145 |
+
<div className="overflow-x-auto">
|
| 146 |
+
<table className="w-full text-xs">
|
| 147 |
+
<thead>
|
| 148 |
+
<tr className="text-left text-[10px] uppercase tracking-wider text-text-muted border-b border-glass-border">
|
| 149 |
+
<th className="py-2 pr-4">Enzyme</th>
|
| 150 |
+
<th className="py-2 pr-4">Site</th>
|
| 151 |
+
<th className="py-2 pr-4">Sites</th>
|
| 152 |
+
<th className="py-2">Positions (1-based)</th>
|
| 153 |
+
</tr>
|
| 154 |
+
</thead>
|
| 155 |
+
<tbody>
|
| 156 |
+
{result.restriction_sites.map(site => (
|
| 157 |
+
<tr key={site.name} className="border-b border-glass-border/60 last:border-0">
|
| 158 |
+
<td className="py-2 pr-4 font-semibold text-accent-cyan">{site.name}</td>
|
| 159 |
+
<td className="py-2 pr-4 font-mono text-text-secondary">{site.recognition}</td>
|
| 160 |
+
<td className="py-2 pr-4 font-mono text-text-secondary">{site.count}</td>
|
| 161 |
+
<td className="py-2 font-mono text-text-muted">
|
| 162 |
+
{site.positions.slice(0, 12).join(', ')}
|
| 163 |
+
{site.positions.length > 12 ? ` … +${site.positions.length - 12}` : ''}
|
| 164 |
+
</td>
|
| 165 |
+
</tr>
|
| 166 |
+
))}
|
| 167 |
+
</tbody>
|
| 168 |
+
</table>
|
| 169 |
+
</div>
|
| 170 |
+
</div>
|
| 171 |
+
)}
|
| 172 |
+
</div>
|
| 173 |
+
);
|
| 174 |
+
}
|
bioai-platform/frontend/src/lib/api.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import axios from 'axios';
|
| 2 |
-
import type { JobStatus, UniprotSummary, SequenceResult, SequenceValidation, SequenceSearchResponse, PairwiseAlignResult } from '@/types/pipeline';
|
| 3 |
import { getSupabase } from './supabase';
|
| 4 |
|
| 5 |
const api = axios.create({
|
|
@@ -304,6 +304,45 @@ export async function runPairwiseAlignment(options: PairwiseAlignOptions): Promi
|
|
| 304 |
return res.data;
|
| 305 |
}
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
export type StructureResult = {
|
| 308 |
source: string;
|
| 309 |
pdb_id?: string;
|
|
|
|
| 1 |
import axios from 'axios';
|
| 2 |
+
import type { JobStatus, UniprotSummary, SequenceResult, SequenceValidation, SequenceSearchResponse, PairwiseAlignResult, SequenceUtilitiesResult, MotifPatternScanResult, MotifLibraryResult, MotifLibraryPattern, DotPlotResult } from '@/types/pipeline';
|
| 3 |
import { getSupabase } from './supabase';
|
| 4 |
|
| 5 |
const api = axios.create({
|
|
|
|
| 304 |
return res.data;
|
| 305 |
}
|
| 306 |
|
| 307 |
+
export async function analyzeSequence(payload: {
|
| 308 |
+
sequence: string;
|
| 309 |
+
seq_type?: 'auto' | 'dna' | 'rna' | 'protein';
|
| 310 |
+
}): Promise<SequenceUtilitiesResult> {
|
| 311 |
+
const res = await api.post('/api/seq-tools/analyze', {
|
| 312 |
+
sequence: payload.sequence,
|
| 313 |
+
seq_type: payload.seq_type ?? 'auto',
|
| 314 |
+
});
|
| 315 |
+
return res.data;
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
export async function scanMotifPattern(payload: {
|
| 319 |
+
sequence: string;
|
| 320 |
+
pattern: string;
|
| 321 |
+
}): Promise<MotifPatternScanResult> {
|
| 322 |
+
const res = await api.post('/api/seq-tools/motif-scan', payload);
|
| 323 |
+
return res.data;
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
export async function scanMotifLibrary(sequence: string): Promise<MotifLibraryResult> {
|
| 327 |
+
const res = await api.post('/api/seq-tools/motif-library', { sequence });
|
| 328 |
+
return res.data;
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
export async function fetchMotifPatterns(): Promise<MotifLibraryPattern[]> {
|
| 332 |
+
const res = await api.get('/api/seq-tools/motif-library/patterns');
|
| 333 |
+
return res.data;
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
export async function runDotPlot(payload: {
|
| 337 |
+
seq_a: string;
|
| 338 |
+
seq_b: string;
|
| 339 |
+
window: number;
|
| 340 |
+
stringency: number;
|
| 341 |
+
}): Promise<DotPlotResult> {
|
| 342 |
+
const res = await api.post('/api/seq-tools/dotplot', payload);
|
| 343 |
+
return res.data;
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
export type StructureResult = {
|
| 347 |
source: string;
|
| 348 |
pdb_id?: string;
|
bioai-platform/frontend/src/types/pipeline.ts
CHANGED
|
@@ -255,3 +255,97 @@ export interface AlphaFoldResult {
|
|
| 255 |
confidence: number | null;
|
| 256 |
model_created_date: string;
|
| 257 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
confidence: number | null;
|
| 256 |
model_created_date: string;
|
| 257 |
}
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
// --- Sequence utilities toolkit -------------------------------------------
|
| 261 |
+
|
| 262 |
+
export interface SeqTranslationFrames {
|
| 263 |
+
frames: Record<string, string>;
|
| 264 |
+
best: {
|
| 265 |
+
frame: number;
|
| 266 |
+
protein: string;
|
| 267 |
+
start: number;
|
| 268 |
+
length: number;
|
| 269 |
+
has_stop: boolean;
|
| 270 |
+
starts_with_m: boolean;
|
| 271 |
+
} | null;
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
export interface SeqRestrictionSite {
|
| 275 |
+
name: string;
|
| 276 |
+
recognition: string;
|
| 277 |
+
count: number;
|
| 278 |
+
positions: number[];
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
export interface SeqAaComposition {
|
| 282 |
+
aa: string;
|
| 283 |
+
count: number;
|
| 284 |
+
pct: number;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
export interface SequenceUtilitiesResult {
|
| 288 |
+
sequence_type: 'dna' | 'rna' | 'protein' | 'unknown';
|
| 289 |
+
detected_type: string;
|
| 290 |
+
length: number;
|
| 291 |
+
gc_content: number | null;
|
| 292 |
+
molecular_weight: number | null;
|
| 293 |
+
reverse_complement: string | null;
|
| 294 |
+
translation: SeqTranslationFrames | null;
|
| 295 |
+
aa_composition: SeqAaComposition[] | null;
|
| 296 |
+
restriction_sites: SeqRestrictionSite[] | null;
|
| 297 |
+
issues: string[];
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
// --- Motif scanner --------------------------------------------------------
|
| 301 |
+
|
| 302 |
+
export interface MotifMatch {
|
| 303 |
+
start: number;
|
| 304 |
+
end: number;
|
| 305 |
+
motif: string;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
export interface MotifPatternScanResult {
|
| 309 |
+
sequence_type: string;
|
| 310 |
+
pattern: string;
|
| 311 |
+
regex: string;
|
| 312 |
+
count: number;
|
| 313 |
+
matches: MotifMatch[];
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
export interface MotifLibraryHit {
|
| 317 |
+
name: string;
|
| 318 |
+
description: string;
|
| 319 |
+
pattern: string;
|
| 320 |
+
count: number;
|
| 321 |
+
matches: MotifMatch[];
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
export interface MotifLibraryResult {
|
| 325 |
+
sequence_type: string;
|
| 326 |
+
length: number;
|
| 327 |
+
patterns_scanned: number;
|
| 328 |
+
motifs_found: number;
|
| 329 |
+
hits: MotifLibraryHit[];
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
export interface MotifLibraryPattern {
|
| 333 |
+
name: string;
|
| 334 |
+
description: string;
|
| 335 |
+
pattern: string;
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
// --- Dot plot -------------------------------------------------------------
|
| 339 |
+
|
| 340 |
+
export interface DotPlotResult {
|
| 341 |
+
sequence_type: string;
|
| 342 |
+
seq_a_length: number;
|
| 343 |
+
seq_b_length: number;
|
| 344 |
+
window: number;
|
| 345 |
+
stringency: number;
|
| 346 |
+
threshold: number;
|
| 347 |
+
total_matches: number;
|
| 348 |
+
dot_count: number;
|
| 349 |
+
downsampled: boolean;
|
| 350 |
+
dots: Array<[number, number]>;
|
| 351 |
+
}
|