Merab099/3D_Structures
0
1import streamlit as st2from rdkit import Chem3from rdkit.Chem import AllChem4from rdkit.Chem.rdForceFieldHelpers import MMFFOptimizeMolecule5import py3Dmol6import io7 8# --- Helper Functions ---9 10@st.cache_data11def generate_3d_mol(smiles):12 """13 Generates a 3D conformation of a molecule from a SMILES string14 using RDKit and returns its SDF string representation.15 """16 try:17 # Convert SMILES to RDKit molecule object18 mol = Chem.MolFromSmiles(smiles)19 if mol is None:20 return None, "Invalid SMILES string. Please check your input."21 22 # Add explicit hydrogens, crucial for proper 3D geometry23 mol = Chem.AddHs(mol)24 25 # Generate initial 3D coordinates using the ETKDGv2 algorithm26 # This is a good general-purpose conformer generator.27 AllChem.EmbedMolecule(mol, AllChem.ETKDGv2())28 29 # Optimize the geometry using the MMFF94 force field30 # This helps in obtaining a more stable and chemically reasonable conformation.31 MMFFOptimizeMolecule(mol)32 33 # Convert the RDKit molecule to an SDF (Structure-Data File) block string.34 # SDF is a common format for storing molecular structures and properties.35 sdf_string = Chem.MolToMolBlock(mol)36 return sdf_string, None37 except Exception as e:38 # Catch any errors during 3D generation and return an error message39 return None, f"Error generating 3D structure: {e}"40 41# --- Streamlit Application Layout ---42 43def main():44 """45 Main function to define the Streamlit application interface.46 """47 st.set_page_config(layout="centered", page_title="3D Molecule Viewer")48 49 st.title("🧪 3D Molecule Structure Viewer")50 st.markdown(51 """52 Enter a SMILES string (Simplified Molecular Input Line Entry System)53 to visualize its 3D molecular structure interactively.54 """55 )56 57 # Input field for SMILES string with a default example (Ethanol)58 smiles_input = st.text_input("SMILES String:", "CCO", help="e.g., CCO for Ethanol, CC(=O)Oc1ccccc1C(=O)O for Aspirin")59 60 # Button to trigger 3D structure generation61 if st.button("Generate 3D Structure"):62 if smiles_input:63 # Call the cached function to generate the 3D molecule data64 sdf_data, error = generate_3d_mol(smiles_input)65 66 if sdf_data:67 st.subheader(f"3D Structure for: `{smiles_input}`")68 69 # Create a py3Dmol viewer instance70 # Set width and height for the viewer71 view = py3Dmol.view(width=800, height=600)72 73 # Add the molecule model to the viewer using the SDF data74 view.addModel(sdf_data, 'sdf')75 76 # Apply a style to the molecule: 'stick' for bonds, 'sphere' for atoms77 view.setStyle({'stick': {}, 'sphere': {'radius': 0.3}})78 79 # Zoom to fit the molecule within the viewer80 view.zoomTo()81 82 # Optional: Make the molecule spin for better visualization83 view.spin(True)84 85 # Embed the py3Dmol viewer into the Streamlit app using st.components.v1.html86 # scrolling=False prevents scrollbars within the viewer itself87 st.components.v1.html(view.to_html(), width=800, height=600, scrolling=False)88 else:89 # Display any error messages from the 3D generation process90 st.error(error)91 else:92 st.warning("Please enter a SMILES string to generate a 3D structure.")93 94 st.markdown("---")95 st.markdown("### How it works:")96 st.markdown(97 """98 This application uses:99 - **Streamlit** for the interactive web interface.100 - **RDKit** (a cheminformatics library) to convert SMILES strings into 3D molecular coordinates and optimize their geometry.101 - **py3Dmol** to render and display the interactive 3D molecular structures in your browser.102 """103 )104 st.markdown("Built with ❤️ for chemistry enthusiasts.")105 106if __name__ == "__main__":107 main()