genomenet commited on
Commit
d660863
·
1 Parent(s): 84deb4c

Improve UI: custom fonts & embedding heatmap visualization

Browse files
Files changed (1) hide show
  1. app.py +137 -26
app.py CHANGED
@@ -10,12 +10,34 @@ import numpy as np
10
  import matplotlib
11
  matplotlib.use('Agg')
12
  import matplotlib.pyplot as plt
 
13
 
14
  from inference import predict_sequence, embed_sequence, WINDOW_SIZE
15
  from inference.model_loader import get_model, warmup_model, get_gpu_status
16
  from inference.tokenizer import validate_sequence, strip_fasta_header
17
  from inference.inference import detect_crispr_regions
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  # Real example sequences from training data
20
  CRISPR_EXAMPLE = """TCCCCATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTCTGTTTACTTCCCTCTATATCTTTTTTTGTTCGGTCATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAAAATCACACTCACAGCCAATACAAGCGGGGGGGGAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTTGCAGTAGGGCAGACTGGCAGTTTTCGGGTAATGATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACATTCATACGAATAATCATTTCCGAAAGACTCCTTTTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACAGGTCATGAGCATTCAAAACGTTCTCCCCGTTCAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAGCCTGGACCAAATAATGTACGAACCTCTCCATCTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACATGAATTATATAACAGGGATTAAAATTTTTCTTATTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAAATTTGAGCAAATACTAAAAAAATGAGACAAAAAGATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTCCGGCAATGAATTGATAGGACTTAAAATAATTGTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACACCAAGAAAATGAAAGAAATTTTCTTTGGAGAAACATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTGAGCCATCGACGGTCTCCGGAAGTAAAACCCCAAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACACATTCAAGTCGCTGCCTACCGTTGAAACATGGAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACCTTAATGGAAAGGCACGTAATACAAACGCGGGTAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTATCACGTTGAA"""
21
 
@@ -51,6 +73,83 @@ def create_prediction_plot(positions, probabilities, threshold=0.3):
51
  return fig
52
 
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  def predict(sequence: str, stride: int = 100, threshold: float = 0.3):
55
  """Predict CRISPR array probability for each position."""
56
  sequence = strip_fasta_header(sequence.strip())
@@ -112,43 +211,55 @@ def detect(sequence: str, threshold: float = 0.3, min_length: int = 160):
112
 
113
 
114
  def get_embedding(sequence: str, mode: str = "mean"):
115
- """Extract hidden state embedding."""
116
  sequence = strip_fasta_header(sequence.strip())
117
 
118
  is_valid, error = validate_sequence(sequence)
119
  if not is_valid:
120
- return {"error": error}, f"**Error**: {error}"
121
 
122
  result = embed_sequence(sequence, mode=mode)
123
 
124
  if mode == "trajectory":
 
 
 
 
 
125
  summary = f"""## Trajectory Embedding
126
- - **Sequence length**: {result.sequence_length:,} bp
127
- - **Windows**: {result.num_windows}
128
- - **Embedding dim**: {result.embedding_dim}
 
 
 
 
 
 
129
  """
130
- output = {
131
- "num_windows": result.num_windows,
132
- "embedding_dim": result.embedding_dim,
133
- "first_5_windows_first_10_dims": [emb[:10] for emb in result.embeddings[:5]],
134
- }
135
  else:
 
 
 
 
 
136
  summary = f"""## Embedding Extracted
137
- - **Sequence length**: {result.sequence_length:,} bp
138
- - **Method**: {result.method}
139
- - **Embedding dim**: {result.embedding_dim}
 
 
 
 
 
 
140
  """
141
- output = {
142
- "embedding_first_20_dims": result.embedding[:20],
143
- "method": result.method,
144
- "embedding_dim": result.embedding_dim,
145
- }
146
 
147
- return output, summary
148
 
149
 
150
  # Build interface
151
- with gr.Blocks(title="CRISPR Array Detection", theme=gr.themes.Soft()) as demo:
152
  gr.Markdown("""
153
  # CRISPR Array Detection
154
 
@@ -196,9 +307,9 @@ Detect CRISPR arrays in DNA sequences using a BERT-based deep learning model (43
196
  )
197
 
198
  with gr.Tab("Embeddings"):
199
- gr.Markdown("Extract hidden state embeddings for downstream analysis (e.g., clustering, visualization).")
200
  with gr.Row():
201
- with gr.Column():
202
  embed_seq = gr.Textbox(
203
  label="DNA Sequence",
204
  placeholder="Paste DNA sequence...",
@@ -209,14 +320,14 @@ Detect CRISPR arrays in DNA sequences using a BERT-based deep learning model (43
209
  choices=["mean", "max", "trajectory"],
210
  value="mean",
211
  label="Embedding Mode",
212
- info="mean: single vector | trajectory: per-window vectors"
213
  )
214
  embed_btn = gr.Button("Extract Embedding", variant="primary")
215
- with gr.Column():
216
  embed_summary = gr.Markdown()
217
- embed_json = gr.JSON(label="Embedding (truncated)")
 
218
 
219
- embed_btn.click(get_embedding, inputs=[embed_seq, embed_mode], outputs=[embed_json, embed_summary])
220
 
221
  with gr.Tab("About"):
222
  gr.Markdown("""
 
10
  import matplotlib
11
  matplotlib.use('Agg')
12
  import matplotlib.pyplot as plt
13
+ from matplotlib.colors import TwoSlopeNorm
14
 
15
  from inference import predict_sequence, embed_sequence, WINDOW_SIZE
16
  from inference.model_loader import get_model, warmup_model, get_gpu_status
17
  from inference.tokenizer import validate_sequence, strip_fasta_header
18
  from inference.inference import detect_crispr_regions
19
 
20
+ # Custom CSS for better fonts
21
+ CUSTOM_CSS = """
22
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono&display=swap');
23
+
24
+ * {
25
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
26
+ }
27
+
28
+ code, pre, .code, textarea {
29
+ font-family: 'JetBrains Mono', 'Fira Code', monospace !important;
30
+ }
31
+
32
+ h1, h2, h3 {
33
+ font-weight: 600 !important;
34
+ }
35
+
36
+ .gradio-container {
37
+ max-width: 1200px !important;
38
+ }
39
+ """
40
+
41
  # Real example sequences from training data
42
  CRISPR_EXAMPLE = """TCCCCATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTCTGTTTACTTCCCTCTATATCTTTTTTTGTTCGGTCATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAAAATCACACTCACAGCCAATACAAGCGGGGGGGGAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTTGCAGTAGGGCAGACTGGCAGTTTTCGGGTAATGATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACATTCATACGAATAATCATTTCCGAAAGACTCCTTTTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACAGGTCATGAGCATTCAAAACGTTCTCCCCGTTCAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAGCCTGGACCAAATAATGTACGAACCTCTCCATCTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACATGAATTATATAACAGGGATTAAAATTTTTCTTATTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTAAATTTGAGCAAATACTAAAAAAATGAGACAAAAAGATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTCCGGCAATGAATTGATAGGACTTAAAATAATTGTATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACACCAAGAAAATGAAAGAAATTTTCTTTGGAGAAACATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTGAGCCATCGACGGTCTCCGGAAGTAAAACCCCAAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACACATTCAAGTCGCTGCCTACCGTTGAAACATGGAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACCTTAATGGAAAGGCACGTAATACAAACGCGGGTAAATTCGAGAGCAAGATCCACTAAAACAAGGATTGAAACTATCACGTTGAA"""
43
 
 
73
  return fig
74
 
75
 
76
+ def create_embedding_heatmap(embedding, title="Sequence Embedding", cols=30):
77
+ """Create a heatmap visualization of the embedding vector."""
78
+ embedding = np.array(embedding)
79
+ n_dims = len(embedding)
80
+
81
+ # Calculate grid dimensions
82
+ rows = int(np.ceil(n_dims / cols))
83
+
84
+ # Pad embedding to fill grid
85
+ padded_size = rows * cols
86
+ padded = np.full(padded_size, np.nan)
87
+ padded[:n_dims] = embedding
88
+
89
+ # Reshape to 2D grid
90
+ grid = padded.reshape(rows, cols)
91
+
92
+ # Create figure
93
+ fig, ax = plt.subplots(figsize=(14, max(3, rows * 0.25)))
94
+
95
+ # Use diverging colormap centered at 0
96
+ vmax = max(abs(np.nanmin(embedding)), abs(np.nanmax(embedding)))
97
+ norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax)
98
+
99
+ im = ax.imshow(grid, cmap='RdBu_r', norm=norm, aspect='auto')
100
+
101
+ # Add colorbar
102
+ cbar = plt.colorbar(im, ax=ax, shrink=0.8, pad=0.02)
103
+ cbar.set_label('Activation', fontsize=10)
104
+
105
+ # Labels
106
+ ax.set_xlabel(f'Dimension (columns of {cols})', fontsize=10)
107
+ ax.set_ylabel('Row', fontsize=10)
108
+ ax.set_title(f'{title} ({n_dims} dimensions)', fontsize=12, fontweight='bold')
109
+
110
+ # Add dimension markers
111
+ ax.set_xticks(np.arange(0, cols, 5))
112
+ ax.set_xticklabels([str(i) for i in range(0, cols, 5)], fontsize=8)
113
+ ax.set_yticks(np.arange(rows))
114
+ ax.set_yticklabels([f'{i*cols}-{min((i+1)*cols-1, n_dims-1)}' for i in range(rows)], fontsize=8)
115
+
116
+ plt.tight_layout()
117
+ return fig
118
+
119
+
120
+ def create_trajectory_heatmap(embeddings, title="Embedding Trajectory"):
121
+ """Create a heatmap showing how embeddings change across windows."""
122
+ embeddings = np.array(embeddings)
123
+ n_windows, n_dims = embeddings.shape
124
+
125
+ # Subsample dimensions if too many
126
+ if n_dims > 100:
127
+ step = n_dims // 100
128
+ embeddings = embeddings[:, ::step]
129
+ n_dims = embeddings.shape[1]
130
+ dim_label = f'Dimension (subsampled, every {step}th)'
131
+ else:
132
+ dim_label = 'Dimension'
133
+
134
+ fig, ax = plt.subplots(figsize=(14, max(4, n_windows * 0.3)))
135
+
136
+ # Use diverging colormap
137
+ vmax = max(abs(embeddings.min()), abs(embeddings.max()))
138
+ norm = TwoSlopeNorm(vmin=-vmax, vcenter=0, vmax=vmax)
139
+
140
+ im = ax.imshow(embeddings, cmap='RdBu_r', norm=norm, aspect='auto')
141
+
142
+ cbar = plt.colorbar(im, ax=ax, shrink=0.8, pad=0.02)
143
+ cbar.set_label('Activation', fontsize=10)
144
+
145
+ ax.set_xlabel(dim_label, fontsize=10)
146
+ ax.set_ylabel('Window', fontsize=10)
147
+ ax.set_title(f'{title} ({n_windows} windows)', fontsize=12, fontweight='bold')
148
+
149
+ plt.tight_layout()
150
+ return fig
151
+
152
+
153
  def predict(sequence: str, stride: int = 100, threshold: float = 0.3):
154
  """Predict CRISPR array probability for each position."""
155
  sequence = strip_fasta_header(sequence.strip())
 
211
 
212
 
213
  def get_embedding(sequence: str, mode: str = "mean"):
214
+ """Extract hidden state embedding and visualize as heatmap."""
215
  sequence = strip_fasta_header(sequence.strip())
216
 
217
  is_valid, error = validate_sequence(sequence)
218
  if not is_valid:
219
+ return None, f"**Error**: {error}"
220
 
221
  result = embed_sequence(sequence, mode=mode)
222
 
223
  if mode == "trajectory":
224
+ # Create trajectory heatmap (windows x dimensions)
225
+ fig = create_trajectory_heatmap(
226
+ result.embeddings,
227
+ title="Embedding Trajectory Across Sequence"
228
+ )
229
  summary = f"""## Trajectory Embedding
230
+
231
+ | Property | Value |
232
+ |----------|-------|
233
+ | Sequence length | {result.sequence_length:,} bp |
234
+ | Windows | {result.num_windows} |
235
+ | Embedding dim | {result.embedding_dim} |
236
+
237
+ Each row shows the embedding for one sliding window position.
238
+ Blue = negative activation, Red = positive activation.
239
  """
 
 
 
 
 
240
  else:
241
+ # Create single embedding heatmap
242
+ fig = create_embedding_heatmap(
243
+ result.embedding,
244
+ title=f"Sequence Embedding ({result.method})"
245
+ )
246
  summary = f"""## Embedding Extracted
247
+
248
+ | Property | Value |
249
+ |----------|-------|
250
+ | Sequence length | {result.sequence_length:,} bp |
251
+ | Pooling method | {result.method} |
252
+ | Embedding dim | {result.embedding_dim} |
253
+
254
+ Each cell represents one dimension of the {result.embedding_dim}-dimensional embedding.
255
+ Blue = negative activation, Red = positive activation.
256
  """
 
 
 
 
 
257
 
258
+ return fig, summary
259
 
260
 
261
  # Build interface
262
+ with gr.Blocks(title="CRISPR Array Detection", theme=gr.themes.Soft(), css=CUSTOM_CSS) as demo:
263
  gr.Markdown("""
264
  # CRISPR Array Detection
265
 
 
307
  )
308
 
309
  with gr.Tab("Embeddings"):
310
+ gr.Markdown("Extract hidden state embeddings and visualize as heatmaps. Useful for clustering, dimensionality reduction, or comparing sequences.")
311
  with gr.Row():
312
+ with gr.Column(scale=1):
313
  embed_seq = gr.Textbox(
314
  label="DNA Sequence",
315
  placeholder="Paste DNA sequence...",
 
320
  choices=["mean", "max", "trajectory"],
321
  value="mean",
322
  label="Embedding Mode",
323
+ info="mean/max: single pooled vector | trajectory: per-window vectors"
324
  )
325
  embed_btn = gr.Button("Extract Embedding", variant="primary")
 
326
  embed_summary = gr.Markdown()
327
+ with gr.Column(scale=2):
328
+ embed_plot = gr.Plot(label="Embedding Heatmap")
329
 
330
+ embed_btn.click(get_embedding, inputs=[embed_seq, embed_mode], outputs=[embed_plot, embed_summary])
331
 
332
  with gr.Tab("About"):
333
  gr.Markdown("""