File size: 11,450 Bytes
624e906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9319b6
 
612f24a
 
 
d9319b6
 
 
 
612f24a
 
 
 
d9319b6
612f24a
 
 
 
 
 
 
624e906
612f24a
 
 
 
 
 
d9319b6
 
624e906
612f24a
624e906
612f24a
d9319b6
 
612f24a
d9319b6
 
 
 
 
 
 
612f24a
 
 
 
 
d9319b6
612f24a
d9319b6
612f24a
 
 
d9319b6
612f24a
d9319b6
 
 
 
 
 
 
 
612f24a
 
624e906
612f24a
d9319b6
 
 
612f24a
 
d9319b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612f24a
d9319b6
612f24a
d9319b6
612f24a
d9319b6
 
 
612f24a
 
d9319b6
 
 
 
 
 
 
 
612f24a
d9319b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612f24a
 
 
d9319b6
 
 
 
 
624e906
 
 
612f24a
 
 
 
 
 
 
 
 
d9319b6
612f24a
 
 
 
d9319b6
 
 
 
 
 
612f24a
 
 
d9319b6
612f24a
 
d9319b6
 
612f24a
 
 
 
 
624e906
 
 
612f24a
 
 
 
 
 
 
 
 
 
 
 
d9319b6
612f24a
d9319b6
 
612f24a
 
d9319b6
612f24a
d9319b6
 
 
 
 
 
612f24a
624e906
612f24a
 
d9319b6
 
612f24a
d9319b6
 
612f24a
624e906
612f24a
 
 
 
624e906
 
 
612f24a
d9319b6
 
 
612f24a
 
 
 
d9319b6
612f24a
 
 
 
 
 
 
 
 
 
 
d9319b6
 
 
 
 
 
 
612f24a
 
 
 
d9319b6
 
 
 
 
 
 
612f24a
 
d9319b6
 
612f24a
d9319b6
 
612f24a
 
 
 
 
 
 
 
624e906
612f24a
 
 
 
 
 
 
624e906
612f24a
 
 
d9319b6
624e906
 
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
from plotly.subplots import make_subplots
import random

class RNAVisualizer:
    def __init__(self):
        self.colors = {
            'A': '#FF6B6B',  # Red
            'U': '#4ECDC4',  # Teal
            'G': '#45B7D1',  # Blue
            'C': '#96CEB4',  # Green
        }
    
    def create_interactive_structure_plot(self, sequence, structure):
        """Create an interactive RNA structure visualization with better UX"""
        try:
            fig = make_subplots(
                rows=2, cols=1,
                subplot_titles=(
                    f'Sequence Composition (Length: {len(sequence)} bases)',
                    'Secondary Structure Prediction'
                ),
                vertical_spacing=0.15,
                row_heights=[0.4, 0.6]
            )
            
            # Plot 1: Enhanced sequence composition
            base_counts = {
                'A': sequence.count('A'),
                'U': sequence.count('U'), 
                'G': sequence.count('G'),
                'C': sequence.count('C')
            }
            
            fig.add_trace(
                go.Bar(
                    x=list(base_counts.keys()),
                    y=list(base_counts.values()),
                    marker_color=[self.colors[base] for base in base_counts.keys()],
                    text=list(base_counts.values()),
                    textposition='auto',
                    hovertemplate='<b>Base: %{x}</b><br>Count: %{y}<extra></extra>',
                    name='Base Count'
                ),
                row=1, col=1
            )
            
            # Plot 2: Interactive structure visualization
            # Create base markers with hover information
            for i, (base, struct) in enumerate(zip(sequence, structure)):
                # Determine marker symbol based on structure
                marker_symbol = 'circle'
                if struct == '(':
                    marker_symbol = 'triangle-up'
                elif struct == ')':
                    marker_symbol = 'triangle-down'
                
                fig.add_trace(
                    go.Scatter(
                        x=[i], y=[0],
                        mode='markers+text',
                        marker=dict(
                            size=15,
                            color=self.colors[base],
                            symbol=marker_symbol,
                            line=dict(width=2, color='black')
                        ),
                        text=base,
                        textfont=dict(color='white', size=10, weight='bold'),
                        textposition='middle center',
                        showlegend=False,
                        hovertemplate=(
                            f'<b>Position: {i}</b><br>'
                            f'Base: {base}<br>'
                            f'Structure: {struct}<br>'
                            f'<extra></extra>'
                        ),
                        name=f'Base {i}'
                    ),
                    row=2, col=1
                )
            
            # Add structure pairing lines
            stack = []
            pairs = []
            for i, symbol in enumerate(structure):
                if symbol == '(':
                    stack.append(i)
                elif symbol == ')' and stack:
                    start = stack.pop()
                    pairs.append((start, i))
            
            for start, end in pairs:
                fig.add_trace(
                    go.Scatter(
                        x=[start, end], y=[0.2, 0.2],
                        mode='lines',
                        line=dict(color='purple', width=2),
                        showlegend=False,
                        hovertemplate=f'Base pair: {start}-{end}<extra></extra>'
                    ),
                    row=2, col=1
                )
            
            # Update layout for better interactivity
            fig.update_layout(
                height=700,
                showlegend=False,
                title_text="Interactive RNA Structure Analysis",
                hovermode='closest',
                dragmode='pan'
            )
            
            # Configure axes for better UX
            fig.update_xaxes(
                title_text="Nucleotide Bases",
                row=1, col=1,
                tickmode='linear',
                tick0=0,
                dtick=1
            )
            fig.update_yaxes(title_text="Count", row=1, col=1)
            
            fig.update_xaxes(
                title_text="Sequence Position",
                row=2, col=1,
                tickmode='linear',
                tick0=0,
                dtick=10,  # Show ticks every 10 positions
                range=[-1, len(sequence)]  # Add some padding
            )
            fig.update_yaxes(
                visible=False,
                row=2, col=1,
                range=[-0.5, 0.5]  # Better y-range for structure view
            )
            
            # Add annotations for structure symbols
            fig.add_annotation(
                x=0.02, y=0.95,
                xref="paper", yref="paper",
                text="🎯 Structure Legend:<br>▲ = Opening pair<br>▼ = Closing pair<br>● = Unpaired",
                showarrow=False,
                bgcolor="white",
                bordercolor="black",
                borderwidth=1,
                row=2, col=1
            )
            
            return fig
        except Exception as e:
            return self.create_error_plot(f"Structure visualization error: {str(e)}")

    def create_advanced_structure_plot(self, sequence, structure):
        """Alias for backward compatibility"""
        return self.create_interactive_structure_plot(sequence, structure)
    
    def create_embedding_visualization(self, embeddings, sequence):
        """Create visualization for RNA embeddings"""
        try:
            if 'error' in embeddings:
                # Create a mock embedding visualization
                embedding_size = embeddings.get('embedding_dim', 64)
                mock_embeddings = np.random.randn(embedding_size)
            else:
                embedding_data = embeddings.get('embeddings', [])
                mock_embeddings = np.array(embedding_data)
            
            # Create interactive heatmap of embedding values
            fig = go.Figure(data=go.Heatmap(
                z=[mock_embeddings],
                colorscale='Viridis',
                showscale=True,
                hoverinfo='z',
                hovertemplate=(
                    'Dimension: %{x}<br>'
                    'Value: %{z:.3f}<br>'
                    '<extra></extra>'
                )
            ))
            
            fig.update_layout(
                title="RNA Sequence Embeddings - AI Feature Space",
                xaxis_title="Embedding Dimension",
                yaxis_title="Sequence",
                height=400,
                hovermode='closest'
            )
            
            return fig
        except Exception as e:
            return self.create_error_plot(f"Embedding visualization error: {str(e)}")
    
    def create_sequence_logo(self, sequence):
        """Create a sequence logo-style visualization"""
        try:
            positions = list(range(len(sequence)))
            bases = list(sequence)
            
            fig = go.Figure()
            
            for i, base in enumerate(bases):
                fig.add_trace(
                    go.Scatter(
                        x=[i], y=[1],
                        mode='markers+text',
                        marker=dict(
                            size=25,
                            color=self.colors[base],
                            symbol='square',
                            line=dict(width=1, color='black')
                        ),
                        text=base,
                        textfont=dict(color='white', size=12, weight='bold'),
                        textposition='middle center',
                        showlegend=False,
                        hovertemplate=(
                            f'<b>Position: {i}</b><br>'
                            f'Base: {base}<br>'
                            f'<extra></extra>'
                        )
                    )
                )
            
            fig.update_layout(
                title="Sequence Logo - Positional Base Composition",
                xaxis_title="Sequence Position",
                yaxis=dict(visible=False, range=[0.8, 1.2]),
                height=300,
                hovermode='closest',
                showlegend=False
            )
            
            return fig
        except Exception as e:
            return self.create_error_plot(f"Sequence logo error: {str(e)}")
    
    def create_gc_content_plot(self, sequence):
        """Create a sliding window GC content plot"""
        try:
            window_size = min(20, len(sequence) // 10)  # Adaptive window size
            if window_size < 5:
                window_size = 5
                
            gc_content = []
            positions = []
            
            for i in range(0, len(sequence) - window_size + 1, max(1, window_size // 2)):
                window = sequence[i:i + window_size]
                gc = (window.count('G') + window.count('C')) / window_size * 100
                gc_content.append(gc)
                positions.append(i + window_size // 2)
            
            fig = go.Figure()
            
            fig.add_trace(go.Scatter(
                x=positions, y=gc_content,
                mode='lines+markers',
                name='GC Content',
                line=dict(color='#2E8B57', width=3),
                marker=dict(size=4, color='#2E8B57'),
                hovertemplate=(
                    'Position: %{x}<br>'
                    'GC Content: %{y:.1f}%<br>'
                    '<extra></extra>'
                )
            ))
            
            # Add average line
            avg_gc = (sequence.count('G') + sequence.count('C')) / len(sequence) * 100
            fig.add_hline(
                y=avg_gc, 
                line_dash="dash", 
                line_color="red",
                annotation_text=f"Average GC: {avg_gc:.1f}%",
                annotation_position="bottom right"
            )
            
            fig.update_layout(
                title="GC Content Profile Along Sequence",
                xaxis_title="Sequence Position",
                yaxis_title="GC Content (%)",
                height=400,
                hovermode='closest'
            )
            
            return fig
        except Exception as e:
            return self.create_error_plot(f"GC content plot error: {str(e)}")
    
    def create_error_plot(self, message):
        """Create a plot showing error message"""
        fig = go.Figure()
        fig.add_annotation(
            text=message,
            xref="paper", yref="paper",
            x=0.5, y=0.5,
            showarrow=False,
            font=dict(size=16, color="red")
        )
        fig.update_layout(
            xaxis=dict(visible=False),
            yaxis=dict(visible=False),
            plot_bgcolor="white",
            height=300
        )
        return fig