Download modules/visualizer.py from zhq0/RNA-flow: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/zhq0/RNA-flow/resolve/main/modules/visualizer.py
- Command line
-
hf download hf://spaces/zhq0/RNA-flow/modules/visualizer.py
-
curl -L -o visualizer.py https://huggingface.co/spaces/zhq0/RNA-flow/resolve/main/modules/visualizer.py
11.5 kB
| 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 |