File size: 10,987 Bytes
8321d59
 
 
033540e
8321d59
527a85d
c83d9b9
 
8321d59
033540e
 
 
 
 
 
 
8321d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c83d9b9
 
 
 
 
8321d59
 
 
 
527a85d
 
 
 
 
 
 
 
 
 
 
 
c83d9b9
 
 
 
 
527a85d
 
 
 
 
 
 
 
 
 
 
 
 
8321d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527a85d
033540e
 
 
 
 
 
527a85d
 
 
 
 
 
 
 
 
8321d59
 
c83d9b9
 
 
 
 
 
8321d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
'use client';

import { useMemo } from 'react';
import { DownloadSimple as Download, ChartScatter as Scatter } from '@phosphor-icons/react';
import type { PairwiseAlignResult } from '@/types/pipeline';
import { downloadText, downloadTsv } from '@/lib/export-utils';
import { computeAlignmentStats } from '@/lib/alignment-stats';
import { AlignmentStatsBar } from '@/components/alignment/AlignmentStatsBar';

const DOTPLOT_MATRICES = ['blosum62', 'blosum50', 'blosum45', 'pam30', 'pam70', 'pam250'];

function dotplotScoringFor(matrix: string): string {
  const m = matrix.toLowerCase();
  return DOTPLOT_MATRICES.includes(m) ? m : 'identity';
}

const BLOCK_SIZE = 60;

interface Column {
  q: string;
  h: string;
  qPos: number;
  hPos: number;
  match: boolean;
  gap: boolean;
}

function buildColumns(result: PairwiseAlignResult): Column[] {
  const a = result.aligned_query;
  const b = result.aligned_hit;
  const cols: Column[] = [];
  let qPos = result.query_start;
  let hPos = result.hit_start;
  for (let i = 0; i < a.length; i++) {
    const q = a[i];
    const h = b[i];
    cols.push({
      q,
      h,
      qPos,
      hPos,
      match: q !== '-' && h !== '-' && q === h,
      gap: q === '-' || h === '-',
    });
    if (q !== '-') qPos++;
    if (h !== '-') hPos++;
  }
  return cols;
}

function charClass(c: string, match: boolean): string {
  if (c === '-') return 'text-text-muted/25';
  return match ? 'text-accent-cyan' : 'text-text-primary';
}

function CoverageStrip({
  label,
  start,
  end,
  length,
}: {
  label: string;
  start: number;
  end: number;
  length: number;
}) {
  const covered = length > 0 ? ((end - start + 1) / length) * 100 : 0;
  const left = length > 0 ? ((start - 1) / length) * 100 : 0;
  return (
    <div className="flex items-center gap-2">
      <span className="w-10 shrink-0 text-[10px] uppercase tracking-wider text-text-muted">{label}</span>
      <div className="h-1.5 flex-1 rounded-full bg-surface-1 overflow-hidden relative">
        <div
          className="absolute inset-y-0 rounded-full bg-gradient-to-r from-accent-cyan/40 to-accent-cyan/80"
          style={{ left: `${left}%`, width: `${covered}%` }}
        />
      </div>
      <span className="w-8 shrink-0 text-right text-[10px] font-mono text-text-muted">{Math.round(covered)}%</span>
    </div>
  );
}

function CoverageNote({ result }: { result: PairwiseAlignResult }) {
  if (result.alignment_length === 0) {
    return (
      <p className="mt-3 text-sm text-accent-amber">
        No significant {result.mode} alignment detected — the two sequences show no local similarity.
      </p>
    );
  }
  const queryOnlyCoversPart =
    result.query_start > 1 || result.query_end < result.query_length;
  const hitOnlyCoversPart = result.hit_start > 1 || result.hit_end < result.hit_length;
  if (!queryOnlyCoversPart && !hitOnlyCoversPart) return null;
  return (
    <p className="text-xs text-text-muted">
      {queryOnlyCoversPart && (
        <>
          Alignment covers residues <strong className="text-accent-cyan">{result.query_start}–{result.query_end}</strong> of a {result.query_length}-residue query.
        </>
      )}
      {queryOnlyCoversPart && hitOnlyCoversPart && <span className="mx-1.5">·</span>}
      {hitOnlyCoversPart && (
        <>
          Residues <strong className="text-accent-cyan">{result.hit_start}–{result.hit_end}</strong> of a {result.hit_length}-residue subject.
        </>
      )}
    </p>
  );
}

function AlignmentBlocks({ result }: { result: PairwiseAlignResult }) {
  const cols = useMemo(() => buildColumns(result), [result]);
  const blocks = useMemo(() => {
    const out: Column[][] = [];
    for (let i = 0; i < cols.length; i += BLOCK_SIZE) out.push(cols.slice(i, i + BLOCK_SIZE));
    return out;
  }, [cols]);

  if (cols.length === 0) return null;

  return (
    <div className="rounded-xl bg-surface-0 border border-glass-border overflow-x-auto">
      <div className="min-w-max font-mono text-[13px] leading-[1.55] p-4 space-y-3">
        {blocks.map((block, bi) => (
          <div key={bi} className="space-y-0.5">
            <div className="flex">
              <span className="w-14 shrink-0 pr-3 text-right text-[10px] text-text-muted/70 pt-[3px]">
                Q{block[0].qPos}
              </span>
              <span className="whitespace-pre">
                {block.map((c, i) => (
                  <span key={i} className={charClass(c.q, c.match)}>{c.q}</span>
                ))}
              </span>
            </div>
            <div className="flex">
              <span className="w-14 shrink-0 pr-3" />
              <span className="whitespace-pre">
                {block.map((c, i) => (
                  <span key={i} className={c.match ? 'text-accent-cyan/50' : 'text-text-muted/10'}>
                    {c.match ? '|' : ' '}
                  </span>
                ))}
              </span>
            </div>
            <div className="flex">
              <span className="w-14 shrink-0 pr-3 text-right text-[10px] text-text-muted/70 pt-[3px]">
                S{block[0].hPos}
              </span>
              <span className="whitespace-pre">
                {block.map((c, i) => (
                  <span key={i} className={charClass(c.h, c.match)}>{c.h}</span>
                ))}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Legend() {
  return (
    <div className="flex items-center gap-4 text-[10px] text-text-muted flex-wrap">
      <span className="flex items-center gap-1.5">
        <span className="w-2 h-2 rounded-[2px] bg-accent-cyan" /> Match
      </span>
      <span className="flex items-center gap-1.5">
        <span className="w-2 h-2 rounded-[2px] bg-text-primary" /> Mismatch
      </span>
      <span className="flex items-center gap-1.5">
        <span className="w-2 h-2 rounded-[2px] bg-text-muted/25" /> Gap
      </span>
      <span className="flex items-center gap-1.5">
        <span className="font-mono text-accent-cyan/50">|</span> Identical position
      </span>
    </div>
  );
}

export function PairwiseResultDisplay({
  result,
  queryLabel = 'Query',
  subjectLabel = 'Subject',
}: {
  result: PairwiseAlignResult;
  queryLabel?: string;
  subjectLabel?: string;
}) {
  const stats = useMemo(
    () => computeAlignmentStats([result.aligned_query, result.aligned_hit]),
    [result],
  );

  if (result.alignment_length === 0) {
    return <CoverageNote result={result} />;
  }

  const exportFasta = () => {
    const fasta = `>${queryLabel}\n${result.aligned_query.replace(/-/g, '')}\n>${subjectLabel}\n${result.aligned_hit.replace(/-/g, '')}`;
    downloadText(fasta, `${result.mode}_alignment.fasta`);
  };

  const exportTsv = () => {
    downloadTsv(
      ['Field', 'Value'],
      [
        ['Mode', result.mode],
        ['Matrix', result.matrix],
        ['Score', String(result.score)],
        ['Matched', String(stats.matched)],
        ['Mismatched', String(stats.mismatched)],
        ['Gapped columns', String(stats.gapped)],
        ['Gap characters', String(result.gaps_total)],
        ['Alignment length', String(stats.length)],
        ['Identity (%)', String(result.pct_identity)],
        ['Identical residues', String(result.identity)],
        ['Query start', String(result.query_start)],
        ['Query end', String(result.query_end)],
        ['Query length', String(result.query_length)],
        ['Subject start', String(result.hit_start)],
        ['Subject end', String(result.hit_end)],
        ['Subject length', String(result.hit_length)],
      ],
      `${result.mode}_alignment_stats.tsv`,
    );
  };

  return (
    <div>
      <div className="flex items-center gap-x-4 gap-y-1 text-xs text-text-muted mb-3 flex-wrap">
        <span>
          Score: <strong className="text-text-primary">{result.score}</strong>
        </span>
        <span>
          Identity: <strong className="text-accent-cyan">{result.pct_identity}%</strong> ({result.identity}/{result.alignment_length})
        </span>
        <span>
          Matrix: <strong className="text-text-primary">{result.matrix.toUpperCase()}</strong>
        </span>
        <span>
          Mode: <strong className="text-text-primary capitalize">{result.mode} {result.mode === 'global' ? 'Needleman-Wunsch' : 'Smith-Waterman'}</strong>
        </span>
        <span className="ml-auto flex items-center gap-2">
          <a
            href={`/analyze/dotplot?seq_a=${encodeURIComponent(result.aligned_query.replace(/-/g, ''))}&seq_b=${encodeURIComponent(result.aligned_hit.replace(/-/g, ''))}&scoring=${dotplotScoringFor(result.matrix)}`}
            className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition-colors flex items-center gap-1.5"
          >
            <Scatter className="w-3.5 h-3.5" /> Dot plot
          </a>
          <button onClick={exportFasta}
            className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition-colors flex items-center gap-1.5">
            <Download className="w-3.5 h-3.5" /> FASTA
          </button>
          <button onClick={exportTsv}
            className="text-xs px-2.5 py-1 rounded bg-surface-1 border border-glass-border text-text-secondary hover:text-accent-cyan transition-colors flex items-center gap-1.5">
            <Download className="w-3.5 h-3.5" /> TSV
          </button>
        </span>
      </div>

      <AlignmentStatsBar
        stats={stats}
        gapDetail={`${result.gaps_total} gap chars`}
        className="mb-3"
      />

      <div className="mb-3 space-y-1.5">
        <CoverageStrip label="Query" start={result.query_start} end={result.query_end} length={result.query_length} />
        <CoverageStrip label="Subject" start={result.hit_start} end={result.hit_end} length={result.hit_length} />
      </div>

      <div className="rounded-xl border border-glass-border overflow-hidden">
        <div className="flex items-center justify-between px-4 py-2 border-b border-glass-border bg-surface-1/80 backdrop-blur text-[10px] font-mono text-text-muted">
          <span>{queryLabel}</span>
          <span className="hidden sm:inline">{result.query_start}–{result.query_end} · {result.query_length} aa</span>
        </div>
        <AlignmentBlocks result={result} />
        <div className="flex items-center justify-between px-4 py-2 border-t border-glass-border bg-surface-1/80 backdrop-blur text-[10px] font-mono text-text-muted">
          <span>{subjectLabel}</span>
          <span className="hidden sm:inline">{result.hit_start}–{result.hit_end} · {result.hit_length} aa</span>
        </div>
      </div>

      <div className="mt-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <Legend />
        <CoverageNote result={result} />
      </div>
    </div>
  );
}