Spaces:
Runtime error
Runtime error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628"""RNA Motif Multi-Structure Comparison ToolStreamlit app for comparing multiple RNA motif structures simultaneouslyBased on working pairwise alignment code"""
import streamlit as stimport numpy as npimport pandas as pdfrom pathlib import Pathimport ioimport tempfileimport osfrom itertools import combinations
# Import our RMSD calculation functionsfrom rmsd_utils import ( parse_residue_atoms, get_backbone_sugar_and_selectbase_coords_fixed, calculate_COM, calculate_rotation_rmsd, translate_rotate_coords, get_backbone_sugar_coords_from_residue, get_base_coords_from_residue)
# Page configurationst.set_page_config( page_title="RNA Motif Multi-Structure Comparison", page_icon="π§¬", layout="wide", initial_sidebar_state="expanded")
# Custom CSSst.markdown("""<style> /* Global base font size increase */ html { font-size: 16px !important; } body { font-size: 1.05rem !important; } .main-header { font-size: 2.5rem; font-weight: bold; color: #1f77b4; margin-bottom: 1rem; } .sub-header { font-size: 1.2rem; color: #666; margin-bottom: 2rem; } .metric-box { background-color: #f0f2f6; padding: 1rem; border-radius: 0.5rem; margin: 0.5rem 0; } /* GLOBAL font size increase for main content */ .main * { font-size: 1.05rem !important; } /* Restore proper header sizes */ .main h1 { font-size: 2.5rem !important; } .main h2 { font-size: 1.75rem !important; } .main h3 { font-size: 1.5rem !important; } /* Button text should stay normal */ .main button { font-size: 1rem !important; } /* Ultra-compact sidebar - MAXIMUM density */ section[data-testid="stSidebar"] { padding-top: 0.2rem !important; } section[data-testid="stSidebar"] > div { padding-top: 0.2rem !important; } /* Zero margin on markdown */ section[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] { margin: 0rem !important; } /* Minimal subheader spacing - THE KEY FIX */ section[data-testid="stSidebar"] h1, section[data-testid="stSidebar"] h2, section[data-testid="stSidebar"] h3 { margin-top: 0.1rem !important; margin-bottom: 0.2rem !important; padding: 0rem !important; line-height: 1.2 !important; } /* Tight widget spacing */ section[data-testid="stSidebar"] .stSelectbox, section[data-testid="stSidebar"] .stNumberInput, section[data-testid="stSidebar"] .stRadio, section[data-testid="stSidebar"] .stFileUploader { margin-top: 0.1rem !important; margin-bottom: 0.2rem !important; } section[data-testid="stSidebar"] .stButton { margin: 0.2rem 0 !important; } /* Minimal element container spacing */ section[data-testid="stSidebar"] .element-container { margin: 0.1rem 0 !important; } /* Compact alert boxes */ section[data-testid="stSidebar"] .stAlert { padding: 0.3rem 0.5rem !important; margin: 0.1rem 0 !important; } /* Remove extra label spacing */ section[data-testid="stSidebar"] label { margin-bottom: 0.1rem !important; } /* Compact captions */ section[data-testid="stSidebar"] .stCaptionContainer { margin: 0.1rem 0 !important; } /* Remove hr spacing completely */ section[data-testid="stSidebar"] hr { margin: 0.2rem 0 !important; } /* Keep sidebar font size normal */ section[data-testid="stSidebar"] * { font-size: 0.875rem !important; } section[data-testid="stSidebar"] h3 { font-size: 1rem !important; }</style>""", unsafe_allow_html=True)
def save_uploaded_file(uploaded_file, directory): """Save an uploaded file to a temporary directory""" file_path = os.path.join(directory, uploaded_file.name) with open(file_path, "wb") as f: f.write(uploaded_file.getbuffer()) return file_path
def get_structure_info(pdb_path): """Get information about a structure's residues.""" residues = parse_residue_atoms(pdb_path) structure_info = [] for idx, res in enumerate(residues): structure_info.append({ 'index': idx, 'resnum': res['resnum'], 'resname': res['resname'], 'full_name': f"{idx+1}. {res['resname']} (residue #{res['resnum']})" }) return structure_info
def extract_window_coords(residues, window_indices): """Extract coordinates for a specific window of residues.""" all_coords = [] for idx in window_indices: if idx < len(residues): residue = residues[idx] backbone_coords = get_backbone_sugar_coords_from_residue(residue) all_coords.extend(backbone_coords) base_coords = get_base_coords_from_residue(residue) all_coords.extend(base_coords) return np.asarray(all_coords)
def generate_windows_from_selection(selected_indices, win_size, win_type): """Generate windows from selected indices""" if len(selected_indices) < win_size: return [] if win_type == "contiguous": windows = [] for i in range(len(selected_indices) - win_size + 1): windows.append(selected_indices[i:i + win_size]) return windows else: # non-contiguous return [list(combo) for combo in combinations(selected_indices, win_size)]
def main(): # Header st.markdown('<p class="main-header">𧬠RNA Motif Multi-Structure Comparison</p>', unsafe_allow_html=True) st.markdown('<p class="sub-header">Compare multiple RNA motifs simultaneously with window-based alignment</p>', unsafe_allow_html=True) # Sidebar st.sidebar.header("βοΈ Configuration") # Step 1: File upload st.sidebar.subheader("1οΈβ£ Upload Structures") uploaded_files = st.sidebar.file_uploader( "Upload RNA Motif PDB files", type=['pdb', 'PDB'], accept_multiple_files=True, key="structures", help="Upload all RNA motif structures to compare" ) if not uploaded_files: st.info("π Please upload RNA motif PDB files to begin analysis") with st.expander("βΉοΈ About this tool"): st.markdown(""" ### Multi-Structure RNA Motif Comparison This tool compares multiple RNA motif structures simultaneously using window-based alignment. **Workflow:** 1. Upload all PDB structures 2. Structures ranked by length (shortest first) 3. Select residues for each structure via dropdown 4. Choose reference structure (default: shortest) 5. Configure window size and type 6. Run comparison - all structures aligned to reference 7. View all structures superimposed in 3D **Features:** - Window-based comparison (contiguous or non-contiguous) - Best match selection per structure - Interactive 3D visualization with all structures - Color-coded structures - RMSD-based alignment quality """) return # Create temporary directory temp_dir = tempfile.mkdtemp() # Save uploaded files for file in uploaded_files: save_uploaded_file(file, temp_dir) # Step 2: Rank structures by length and create dropdown #st.sidebar.markdown("---") st.sidebar.subheader("2οΈβ£ Structure Selection") # Get structure sizes structure_data = [] for file in uploaded_files: file_path = os.path.join(temp_dir, file.name) residues = parse_residue_atoms(file_path) structure_data.append({ 'file': file, 'name': file.name, 'path': file_path, 'num_residues': len(residues), 'residues': residues }) # Sort by number of residues (shortest first) structure_data.sort(key=lambda x: x['num_residues']) # Display ranked structures st.markdown("---") st.subheader("π Uploaded Structures (Ranked by Length)") rank_df = pd.DataFrame([ {'Rank': i+1, 'Filename': s['name'], 'Residues': s['num_residues']} for i, s in enumerate(structure_data) ]) st.dataframe(rank_df, use_container_width=True) # Step 3: Atom selection for each structure using dropdown st.markdown("---") st.subheader("π¬ Configure Atom Selections") # Dropdown to select structure selected_structure_name = st.selectbox( "Select structure to configure (excluding two bases in 5' and 3' by default)", options=[s['name'] for s in structure_data], help="Choose a structure to configure its residue selection" ) # Initialize session state for selections if 'selections' not in st.session_state: st.session_state['selections'] = {} # Auto-initialize selections for all structures (exclude first and last residue) if 'auto_initialized' not in st.session_state: for struct in structure_data: num_res = struct['num_residues'] if num_res > 4: # Need at least 5 residues to do 2 to len-2 # Auto-select from index 1 to index len-2 (which is residue 2 to residue len-1) auto_selection = list(range(1, num_res - 1)) st.session_state['selections'][struct['name']] = auto_selection else: # For small structures, use all residues st.session_state['selections'][struct['name']] = list(range(num_res)) st.session_state['auto_initialized'] = True # Find selected structure data selected_struct = next((s for s in structure_data if s['name'] == selected_structure_name), None) if selected_struct: st.markdown(f"### {selected_struct['name']} ({selected_struct['num_residues']} residues)") # Display residue table structure_info = get_structure_info(selected_struct['path']) info_df = pd.DataFrame(structure_info)[['index', 'resnum', 'resname']] info_df.columns = ['Index (0-based)', 'Residue Number', 'Base Type'] info_df['Index (1-based)'] = info_df['Index (0-based)'] + 1 info_df = info_df[['Index (1-based)', 'Index (0-based)', 'Residue Number', 'Base Type']] with st.expander(f"π View Residue Table", expanded=False): st.dataframe(info_df, use_container_width=True, height=min(300, len(structure_info) * 35 + 38)) # Selection method selection_method = st.radio( f"Selection method for {selected_struct['name']}", ["Select by range", "Select specific residues", "Use all residues"], key=f"method_{selected_struct['name']}", index = 1, horizontal=True ) selected_indices = [] if selection_method == "Select by range": # Get current saved selection or auto-initialized values current_selection = st.session_state['selections'].get(selected_struct['name'], []) default_start = current_selection[0] + 2 if current_selection else 2 default_end = current_selection[-1] + 1 if current_selection else max(2, len(structure_info) - 2) col1, col2 = st.columns(2) with col1: start_idx = st.number_input( "Start index (1-based)", min_value=1, max_value=len(structure_info), value=default_start, key=f"start_{selected_struct['name']}" ) with col2: end_idx = st.number_input( "End index (1-based, inclusive)", min_value=1, max_value=len(structure_info), value=default_end, key=f"end_{selected_struct['name']}" ) if start_idx <= end_idx: selected_indices = list(range(start_idx - 1, end_idx)) st.success(f"β Selected residues: {[i+1 for i in selected_indices]}") else: st.error("Start index must be β€ end index") elif selection_method == "Select specific residues": # Get current selection or default current_selection = st.session_state['selections'].get(selected_struct['name'], []) default_names = [structure_info[i]['full_name'] for i in range(2, len(structure_info)-2)] if current_selection else [] selected_names = st.multiselect( "Select residues", options=[info['full_name'] for info in structure_info], default=default_names, key=f"specific_{selected_struct['name']}" ) name_to_idx = {info['full_name']: info['index'] for info in structure_info} selected_indices = [name_to_idx[name] for name in selected_names] selected_indices.sort() if selected_indices: st.success(f"β Selected {len(selected_indices)} residues: {[i+1 for i in selected_indices]}") else: # Use all residues selected_indices = list(range(len(structure_info))) st.info(f"β Using all {len(selected_indices)} residues") # Save selection button if st.button(f"πΎ Save Selection for {selected_struct['name']}", type="primary"): st.session_state['selections'][selected_struct['name']] = selected_indices st.success(f"β
Saved selection for {selected_struct['name']}") # Show current saved selections if selected_struct['name'] in st.session_state['selections']: saved_indices = st.session_state['selections'][selected_struct['name']] st.info(f"**Current saved selection:** {len(saved_indices)} residues: {[i+1 for i in saved_indices]}") # Step 4: Reference structure selection #st.sidebar.markdown("---") st.sidebar.subheader("3οΈβ£ Reference Structure") # Default: shortest structure (first in sorted list) default_ref = structure_data[0]['name'] reference_structure_name = st.sidebar.selectbox( "Select reference structure", options=[s['name'] for s in structure_data], index=0, help="All other structures will be aligned to this reference (default: shortest)" ) ref_struct = next((s for s in structure_data if s['name'] == reference_structure_name), None) if ref_struct: st.sidebar.info(f"**Reference:** {ref_struct['name']} ({ref_struct['num_residues']} residues)") # Step 5: Window configuration #st.sidebar.markdown("---") st.sidebar.subheader("4οΈβ£ Window Configuration") # Check if all structures have selections all_have_selections = all(s['name'] in st.session_state.get('selections', {}) for s in structure_data) if all_have_selections: selections = st.session_state['selections'] min_selection_size = min(len(selections[s['name']]) for s in structure_data) window_size = st.sidebar.number_input( "Window Size", min_value=2, max_value=min_selection_size, value=min(4, min_selection_size), step=1, help="Number of residues per comparison window" ) window_type = st.sidebar.radio( "Window Type", ["contiguous", "non-contiguous"], index=0, help="Contiguous: sliding windows. Non-contiguous: all combinations" ) else: st.sidebar.warning("β οΈ Configure selections for all structures first") window_size = 4 window_type = "contiguous" # Step 6: Run analysis #st.sidebar.markdown("---") st.sidebar.subheader("5οΈβ£ Run Analysis") if st.sidebar.button("π Run Multi-Structure Analysis", type="primary", disabled=not all_have_selections): if not all_have_selections: st.error("Please configure atom selections for all structures") return # Get selections selections = st.session_state['selections'] # Find reference structure ref_struct = next((s for s in structure_data if s['name'] == reference_structure_name), None) ref_indices = selections[ref_struct['name']] # Generate reference windows ref_windows = generate_windows_from_selection(ref_indices, window_size, window_type) if not ref_windows: st.error(f"Reference structure needs at least {window_size} selected residues") return # Run comparisons with st.spinner("Analyzing structures..."): results = [] # For each reference window for ref_window in ref_windows: # Extract reference coords ref_coords = extract_window_coords(ref_struct['residues'], ref_window) ref_com = calculate_COM(ref_coords) ref_sequence = ''.join([ref_struct['residues'][i]['resname'] for i in ref_window]) # Compare against all other structures for query_struct in structure_data: if query_struct['name'] == ref_struct['name']: continue # Skip self-comparison query_indices = selections[query_struct['name']] query_windows = generate_windows_from_selection(query_indices, window_size, window_type) for query_window in query_windows: # Extract query coords query_coords = extract_window_coords(query_struct['residues'], query_window) query_com = calculate_COM(query_coords) query_sequence = ''.join([query_struct['residues'][i]['resname'] for i in query_window]) # Calculate RMSD U, RMSD = calculate_rotation_rmsd(ref_coords, query_coords, ref_com, query_com) if U is None or RMSD is None: RMSD = 999.0 U = np.eye(3) results.append({ 'Reference': ref_struct['name'], 'Ref_Window': ref_window, 'Ref_Sequence': ref_sequence, 'Query': query_struct['name'], 'Query_Window': query_window, 'Query_Sequence': query_sequence, 'RMSD': RMSD, 'Rotation_Matrix': U, 'Ref_COM': ref_com, 'Query_COM': query_com, 'Ref_Path': ref_struct['path'], 'Query_Path': query_struct['path'] }) results_df = pd.DataFrame(results) st.session_state['results'] = results_df st.session_state['structure_data'] = structure_data st.session_state['reference_name'] = reference_structure_name st.success(f"β
Analysis complete! {len(results_df)} comparisons performed.") # Display results if 'results' in st.session_state: results_df = st.session_state['results'] structure_data = st.session_state['structure_data'] reference_name = st.session_state['reference_name'] st.markdown("---") st.subheader("π Results Summary") # RMSD threshold filter col1, col2 = st.columns([1, 3]) with col1: rmsd_threshold = st.slider( "RMSD Threshold (Γ
)", min_value=0.0, max_value=10.0, value=3.0, step=0.1 ) filtered_df = results_df[results_df['RMSD'] <= rmsd_threshold] with col2: st.metric("Comparisons Below Threshold", f"{len(filtered_df)} / {len(results_df)}") # Best match per structure st.markdown("### π Best Match per Structure") best_matches = results_df.loc[results_df.groupby('Query')['RMSD'].idxmin()] best_display = best_matches[['Query', 'Query_Sequence', 'RMSD']].copy() best_display['RMSD'] = best_display['RMSD'].round(3) best_display.columns = ['Structure', 'Sequence', 'RMSD (Γ
)'] st.dataframe(best_display, use_container_width=True) # Full results with st.expander("π All Comparison Results"): display_df = filtered_df[['Reference', 'Ref_Sequence', 'Query', 'Query_Sequence', 'RMSD']].copy() display_df['RMSD'] = display_df['RMSD'].round(3) display_df = display_df.sort_values('RMSD').reset_index(drop=True) st.dataframe(display_df, use_container_width=True, height=300) # Visualization st.markdown("---") st.subheader("π¬ 3D Structure Visualization") st.markdown("**Select a comparison to visualize:**") # Create dropdown options showing all comparisons viz_options = [] for idx, row in filtered_df.iterrows(): ref_res_str = ','.join([str(i+1) for i in row['Ref_Window']]) query_res_str = ','.join([str(i+1) for i in row['Query_Window']]) option_text = f"{row['Reference']}[{ref_res_str}] ({row['Ref_Sequence']}) vs {row['Query']}[{query_res_str}] ({row['Query_Sequence']}) | RMSD: {row['RMSD']:.3f} Γ
" viz_options.append((idx, option_text)) if viz_options: # Sort by RMSD (best first) viz_options.sort(key=lambda x: filtered_df.loc[x[0], 'RMSD']) selected_viz_idx = st.selectbox( "Choose comparison to visualize", options=[opt[0] for opt in viz_options], format_func=lambda idx: next(opt[1] for opt in viz_options if opt[0] == idx), help="All comparisons below RMSD threshold, sorted by RMSD" ) # Get the selected comparison selected_comparison = filtered_df.loc[selected_viz_idx] # Import visualization function from visualization_multi import create_pairwise_visualization # Create visualization for selected comparison try: viz_html = create_pairwise_visualization( ref_path=selected_comparison['Ref_Path'], query_path=selected_comparison['Query_Path'], ref_window=selected_comparison['Ref_Window'], query_window=selected_comparison['Query_Window'], rotation_matrix=selected_comparison['Rotation_Matrix'], ref_com=selected_comparison['Ref_COM'], query_com=selected_comparison['Query_COM'], rmsd=selected_comparison['RMSD'], ref_name=selected_comparison['Reference'], query_name=selected_comparison['Query'] ) st.components.v1.html(viz_html, width=1400, height=750, scrolling=False) except Exception as e: st.error(f"Error creating visualization: {str(e)}") import traceback st.code(traceback.format_exc()) else: st.warning("No comparisons below RMSD threshold to visualize")
if __name__ == "__main__": main()app.pyAdded+628