### Load Example Molecule3D Data with Python Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt This Python code snippet shows how to retrieve and utilize example data provided by the Molecule3D component. It demonstrates fetching example URLs and payloads, which are useful for testing, demonstrations, and pre-loading structures into the Gradio interface. This functionality requires the Gradio and Gradio-molecule3d libraries. ```python from gradio_molecule3d import Molecule3D # Get example value (URL string) component = Molecule3D() example_url = component.example_value() print(example_url) # Output: "https://files.rcsb.org/view/1PGA.pdb" # For multiple file mode component_multi = Molecule3D(file_count="multiple") example_urls = component_multi.example_value() print(example_urls) # Output: ["https://files.rcsb.org/view/1PGA.pdb"] # Get example payload (FileData object) example_payload = component.example_payload() print(example_payload) # Output: FileData object pointing to 1PGA.pdb # Use in Gradio interface import gradio as gr reps = [{"model": 0, "style": "cartoon", "color": "spectrum"}] with gr.Blocks() as demo: molecule = Molecule3D( value=component.example_value(), # Pre-load example label="Example Protein", reps=reps ) demo.launch() ``` -------------------------------- ### Install gradio_molecule3d Package Source: https://github.com/farisflaifil/gradio_molecule3d_fairchem/blob/main/README.md This command installs the gradio_molecule3d package using pip. It is a prerequisite for using the custom Gradio component. ```bash pip install gradio_molecule3d ``` -------------------------------- ### Custom Configuration Options for Molecule3D Viewer (Python) Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Allows customization of the Molecule3D viewer's appearance and behavior using the 'config' parameter. This example demonstrates setting dark and light themes with different projection modes (orthographic/perspective) and fog effects. Useful for tailoring the visualization to specific needs or preferences. ```python import gradio as gr from gradio_molecule3d import Molecule3D # Dark theme configuration dark_config = { "backgroundColor": "black", "orthographic": True, # Parallel projection (no perspective) "disableFog": True # Disable depth-based fading } # Light theme configuration light_config = { "backgroundColor": "white", "orthographic": False, # Perspective projection "disableFog": False # Enable depth fading } reps = [{ "model": 0, "style": "cartoon", "color": "spectrum" }] with gr.Blocks() as demo: gr.Markdown("# Custom Viewer Configuration") with gr.Row(): dark_viewer = Molecule3D( value="https://files.rcsb.org/view/1CRN.pdb", label="Dark Theme (Orthographic)", reps=reps, config=dark_config ) light_viewer = Molecule3D( value="https://files.rcsb.org/view/1CRN.pdb", label="Light Theme (Perspective)", reps=reps, config=light_config ) demo.launch() ``` -------------------------------- ### Integrate Molecule3D with Public Databases using Python Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt This Python example illustrates how to integrate the Molecule3D component with public molecular databases like RCSB PDB, AlphaFold, and ESM Atlas. It defines a function to construct database URLs based on user input (structure ID and database choice) and displays the retrieved structure in the Gradio interface. This requires Gradio and Gradio-molecule3d libraries and relies on the availability of the specified database URLs. ```python import gradio as gr from gradio_molecule3d import Molecule3D reps = [ { "model": 0, "style": "cartoon", "color": "alphafold" } ] # Database URLs follow these patterns: database_examples = { "RCSB PDB": "https://files.rcsb.org/view/{PDB_ID}.pdb", "AlphaFold": "https://alphafold.ebi.ac.uk/files/AF-{UNIPROT_ID}-F1-model_v4.pdb", "ESM Atlas": "https://api.esmatlas.com/fetchPredictedStructure/{ESM_ID}.pdb" } def load_from_database(pdb_id, database="RCSB"): """ Load structure from specified database """ if database == "RCSB": url = f"https://files.rcsb.org/view/{pdb_id}.pdb" elif database == "AlphaFold": url = f"https://alphafold.ebi.ac.uk/files/AF-{pdb_id}-F1-model_v4.pdb" elif database == "ESM": url = f"https://api.esmatlas.com/fetchPredictedStructure/{pdb_id}.pdb" else: return None return url with gr.Blocks() as demo: gr.Markdown("# Database Retrieval") with gr.Row(): database = gr.Dropdown( choices=["RCSB", "AlphaFold", "ESM"], value="RCSB", label="Database" ) structure_id = gr.Textbox( label="Structure ID", placeholder="e.g., 1PGA or Q5VSL9" ) load_btn = gr.Button("Load Structure") molecule = Molecule3D( label="Retrieved Structure", reps=reps ) load_btn.click( load_from_database, inputs=[structure_id, database], outputs=molecule ) demo.launch() ``` -------------------------------- ### Chain-Specific Visualization with Gradio Molecule3D Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Visualizes multi-chain proteins, assigning different colors to each chain for clear differentiation. This example sets up the representation for chain-specific coloring. ```python import gradio as gr from gradio_molecule3d import Molecule3D ``` -------------------------------- ### Basic Usage of Molecule3D Component in Gradio Source: https://github.com/farisflaifil/gradio_molecule3d_fairchem/blob/main/README.md Demonstrates how to use the Molecule3D custom component within a Gradio interface. It initializes the component, defines a prediction function, and sets up a simple Gradio Blocks application to display and interact with the molecule visualization. ```python import gradio as gr from gradio_molecule3d import Molecule3D example = Molecule3D().example_value() reps = [ { "model": 0, "chain": "", "resname": "", "style": "cartoon", "color": "hydrophobicity", # "residue_range": "", "around": 0, "byres": False, # "visible": False, # "opacity": 0.5 } ] def predict(x): print("predict function", x) print(x.name) return x # def update_color(mol, color): # reps[0]['color'] = color # print(reps) # return Molecule3D(mol, reps=reps) with gr.Blocks() as demo: gr.Markdown("# Molecule3D") # color_choices = ['redCarbon', 'greenCarbon', 'orangeCarbon', 'blackCarbon', 'blueCarbon', 'grayCarbon', 'cyanCarbon'] inp = Molecule3D(label="Molecule3D", reps=reps) # cdr_color = gr.Dropdown(choices=color_choices, label="CDR color", value='redCarbon') out = Molecule3D(label="Output", reps=reps) # cdr_color.change(update_color, inputs=[inp,cdr_color], outputs=out) btn = gr.Button("Predict") gr.Markdown(""" You can configure the default rendering of the molecule by adding a list of representations
        reps =    [
        {
          "model": 0,
          "style": "cartoon",
          "color": "whiteCarbon",
          "residue_range": "",
          "around": 0,
          "opacity":1
          
        },
        {
          "model": 0,
          "chain": "A",
          "resname": "HIS",
          "style": "stick",
          "color": "red"
        }
      ]
    
""" ") btn.click(predict, inputs=inp, outputs=out) if __name__ == "__main__": demo.launch() ``` -------------------------------- ### Initialize Basic Molecule3D Component Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Initializes a Molecule3D component with default settings for displaying a molecular structure using a cartoon representation. This component is built on Gradio and utilizes 3Dmol.js for rendering. It accepts single files and can be configured for interactivity and background properties. ```python import gradio as gr from gradio_molecule3d import Molecule3D # Create a basic component with default representation reps = [ { "model": 0, "chain": "", "resname": "", "style": "cartoon", "color": "whiteCarbon", "opacity": 1.0 } ] with gr.Blocks() as demo: gr.Markdown("# Molecular Structure Viewer") molecule_viewer = Molecule3D( label="Protein Structure", reps=reps, config={ "backgroundColor": "white", "orthographic": False, "disableFog": False }, file_count="single", interactive=True ) demo.launch() # Expected output: Web interface with interactive 3D viewer # Users can upload PDB, SDF, MOL2, CIF, XYZ, or trajectory files ``` -------------------------------- ### Active Site and Ligand Highlighting with Gradio Molecule3D Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Highlights active sites and nearby residues by focusing visualization on specific regions. Ligands (e.g., HEM) are shown in red sticks, and residues within 5 Angstroms are shown in green sticks. ```python import gradio as gr from gradio_molecule3d import Molecule3D # Representation focusing on active site active_site_reps = [ { "model": 0, "style": "cartoon", "color": "grayCarbon", "opacity": 0.3 # Dim background }, { "model": 0, "resname": "HEM", # Heme ligand "style": "stick", "color": "redCarbon" }, { "model": 0, "resname": "HEM", "around": 5, # Show residues within 5 Angstroms "byres": True, # Include entire residues "style": "stick", "color": "greenCarbon" } ] def analyze_binding_site(protein_file): """ Highlight active site and nearby residues """ return protein_file with gr.Blocks() as demo: gr.Markdown("# Active Site Analysis") gr.Markdown(""" Visualization scheme: - Gray transparent cartoon: Overall structure - Red sticks: Ligand (HEM) - Green sticks: Residues within 5Å of ligand """) inp = Molecule3D(label="Protein Complex", reps=active_site_reps) out = Molecule3D(label="Analyzed Complex", reps=active_site_reps) btn = gr.Button("Analyze Binding Site") btn.click(analyze_binding_site, inputs=inp, outputs=out) demo.launch() ``` -------------------------------- ### Multiple File Upload and Comparison in Molecule3D (Python) Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Enables users to upload and compare multiple molecular structures simultaneously. The component supports various file types and automatically converts them to PDB format for visualization. Useful for comparing different states or variants of molecules. ```python import gradio as gr from gradio_molecule3d import Molecule3D reps = [{ "model": 0, "style": "cartoon", "color": "spectrum" }] def compare_structures(files): """ Process multiple uploaded structures Returns list of file paths for visualization """ if files is None: return None print(f"Processing {len(files)} structures") return files with gr.Blocks() as demo: gr.Markdown("# Structure Comparison") # Allow multiple file uploads inp = Molecule3D( label="Upload Structures", reps=reps, file_count="multiple", # Enable multiple file upload file_types=[“.pdb”, “.cif”, “.sdf”, “.xyz”] ) out = Molecule3D( label="Processed Structures", reps=reps, file_count="multiple" ) btn = gr.Button("Compare") btn.click(compare_structures, inputs=inp, outputs=out) demo.launch() ``` -------------------------------- ### Convert Molecular Files to PDB using ASE Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Provides a utility function `convert_file_to_pdb` that leverages the Atomic Simulation Environment (ASE) library to convert various molecular file formats (like SDF, MOL2, XYZ) into the PDB format. This is crucial for ensuring compatibility with web-based 3D visualization libraries like 3Dmol.js used in the gradio_molecule3d component. ```python from pathlib import Path from gradio_molecule3d.molecule3d import convert_file_to_pdb import tempfile ``` -------------------------------- ### Python Type Definitions for gradio_molecule3d_fairchem Parameters Source: https://github.com/farisflaifil/gradio_molecule3d_fairchem/blob/main/README.md Defines the expected Python types for various initialization parameters of the gradio_molecule3d_fairchem component. This includes types for the initial value, replication data, configuration settings, confidence labels, file handling options, and component appearance. ```python str | list[str] | Callable | None Any | None Literal["single", "multiple", "directory"] list[str] | None Literal["filepath", "binary"] bool | None int | None ``` -------------------------------- ### Handle Molecule3D Events with Python Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt This snippet demonstrates how to attach event listeners to the Molecule3D component in Gradio for upload, change, clear, and select events. It utilizes Python and the Gradio library to update a status textbox based on user interactions with the molecule viewer. No external dependencies beyond Gradio and Gradio-molecule3d are required. ```python import gradio as gr from gradio_molecule3d import Molecule3D reps = [ { "model": 0, "style": "cartoon", "color": "whiteCarbon" } ] def on_upload(file): """Called when file is uploaded""" print(f"File uploaded: {file.name if file else 'None'}") return file def on_change(file): """Called when value changes""" print(f"Value changed: {file.name if file else 'None'}") return f"Loaded: {file.name if file else 'None'}" def on_clear(): """Called when clear button clicked""" print("Viewer cleared") return "Structure cleared" def on_select(evt: gr.SelectData): """Called when file is selected""" print(f"Selected: {evt.value}") return f"Selected: {evt.value}" with gr.Blocks() as demo: gr.Markdown("# Event Handling Demo") molecule = Molecule3D( label="Molecule Viewer", reps=reps, interactive=True ) status = gr.Textbox(label="Status", interactive=False) # Attach event listeners molecule.upload(on_upload, inputs=molecule, outputs=molecule) molecule.change(on_change, inputs=molecule, outputs=status) molecule.clear(on_clear, outputs=status) molecule.select(on_select, outputs=status) demo.launch() ``` -------------------------------- ### Load Molecule Structures from URLs Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Loads molecular structures directly from URLs, such as those from RCSB PDB or AlphaFold, into the Molecule3D component. This allows for immediate display of publicly available structures. The component supports different representation styles and confidence-based coloring for AlphaFold models. ```python import gradio as gr from gradio_molecule3d import Molecule3D reps = [ { "model": 0, "style": "cartoon", "color": "spectrum" } ] with gr.Blocks() as demo: gr.Markdown("# Load from Database") # Load from RCSB PDB molecule = Molecule3D( value="https://files.rcsb.org/view/1PGA.pdb", label="Protein from RCSB", reps=reps ) # Alternative: AlphaFold structure alphafold_structure = Molecule3D( value="https://alphafold.ebi.ac.uk/files/AF-Q5VSL9-F1-model_v4.pdb", label="AlphaFold Prediction", reps=[{ "model": 0, "style": "cartoon", "color": "alphafold" # Confidence-based coloring }], confidenceLabel="pLDDT" ) demo.launch() # Expected output: Pre-loaded 3D structures displayed immediately # AlphaFold structure colored by confidence score (blue=high, red=low) ``` -------------------------------- ### Gradio Molecule Component User Function Signature Source: https://github.com/farisflaifil/gradio_molecule3d_fairchem/blob/main/README.md This Python function demonstrates the expected input and return types when the Gradio molecule component is used as both an input and an output. It handles various data types including bytes, strings, and lists of these types. ```python def predict( value: bytes | str | list[bytes] | list[str] | None ) -> str | list[str] | None: return value ``` -------------------------------- ### Implement Multi-Layer Molecule Representations Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Demonstrates how to create complex 3D molecular visualizations by stacking multiple representation layers on a single molecule. This allows for highlighting specific residues, chains, or regions with different styles (cartoon, stick, sphere) and colors. It's integrated within a Gradio app where user input is processed and displayed. ```python import gradio as gr from gradio_molecule3d import Molecule3D # Multiple representations for detailed visualization multi_reps = [ { "model": 0, "style": "cartoon", "color": "grayCarbon", "opacity": 0.7 }, { "model": 0, "chain": "A", "resname": "HIS", # Show only histidine residues "style": "stick", "color": "redCarbon" }, { "model": 0, "chain": "A", "resname": "CYS", # Show only cysteine residues "style": "sphere", "color": "orangeCarbon" }, { "model": 0, "residue_range": "100-150", # Highlight specific region "style": "cartoon", "color": "blueCarbon", "opacity": 1.0 } ] def predict(x): # Pass through the input structure return x with gr.Blocks() as demo: gr.Markdown("# Multi-Layer Visualization") inp = Molecule3D(label="Input Structure", reps=multi_reps) out = Molecule3D(label="Output Structure", reps=multi_reps) btn = gr.Button("Process") btn.click(predict, inputs=inp, outputs=out) demo.launch() # Expected output: 3D structure with overlaid representations # - Transparent gray cartoon for overall structure # - Red sticks for histidine residues # - Orange spheres for cysteine residues # - Blue highlighted region from residues 100-150 ``` -------------------------------- ### Multi-chain Representation in Molecule3D (Python) Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Displays a protein complex with each chain colored differently using the 'reps' parameter. Useful for visualizing quaternary structure and protein-protein interfaces. ```python import gradio as gr from gradio_molecule3d import Molecule3D chain_reps = [ { "model": 0, "chain": "A", "style": "cartoon", "color": "blueCarbon" }, { "model": 0, "chain": "B", "style": "cartoon", "color": "redCarbon" }, { "model": 0, "chain": "C", "style": "cartoon", "color": "greenCarbon" }, { "model": 0, "chain": "D", "style": "cartoon", "color": "orangeCarbon" } ] with gr.Blocks() as demo: gr.Markdown("# Multi-Chain Complex") gr.Markdown(""" Each protein chain colored differently: - Chain A: Blue - Chain B: Red - Chain C: Green - Chain D: Orange """) complex_viewer = Molecule3D( value="https://files.rcsb.org/view/1A3N.pdb", # Multi-chain example label="Protein Complex", reps=chain_reps ) demo.launch() ``` -------------------------------- ### AlphaFold Confidence Coloring with Gradio Molecule3D Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Displays AlphaFold predictions with coloring based on confidence scores (pLDDT). Higher confidence regions are shown in blue, while lower confidence regions are orange. The pLDDT scores are stored in the PDB b-factor column. ```python import gradio as gr from gradio_molecule3d import Molecule3D # AlphaFold representation with confidence coloring alphafold_reps = [ { "model": 0, "style": "cartoon", "color": "alphafold" # Colors by b-factor (pLDDT score) } ] def predict_structure(sequence_or_file): """ Display AlphaFold prediction with confidence coloring pLDDT scores stored in PDB b-factor column: - Blue (>90): Very high confidence - Cyan (70-90): High confidence - Yellow (50-70): Low confidence - Orange (<50): Very low confidence """ return sequence_or_file with gr.Blocks() as demo: gr.Markdown("# AlphaFold Structure Viewer") gr.Markdown(""" Color scheme based on pLDDT confidence scores: - **Blue**: Very high (>90) - **Cyan**: High (70-90) - **Yellow**: Low (50-70) - **Orange**: Very low (<50) """) inp = Molecule3D( label="Predicted Structure", reps=alphafold_reps, confidenceLabel="pLDDT" # Label for tooltip display ) out = Molecule3D( label="Analyzed Structure", reps=alphafold_reps, confidenceLabel="pLDDT" ) btn = gr.Button("Analyze") btn.click(predict_structure, inputs=inp, outputs=out) demo.launch() ``` -------------------------------- ### Hydrophobicity Coloring with Gradio Molecule3D Source: https://context7.com/farisflaifil/gradio_molecule3d_fairchem/llms.txt Colors protein structures based on amino acid hydrophobicity, which is useful for analyzing membrane proteins. Hydrophobic residues appear white/gray, and hydrophilic residues appear purple/magenta. ```python import gradio as gr from gradio_molecule3d import Molecule3D # Hydrophobicity representation hydro_reps = [ { "model": 0, "style": "cartoon", "color": "hydrophobicity" }, { "model": 0, "style": "surface", "color": "hydrophobicity", "opacity": 0.5 } ] with gr.Blocks() as demo: gr.Markdown("# Hydrophobicity Analysis") gr.Markdown(""" Hydrophobic residues shown in white/gray Hydrophilic residues shown in purple/magenta Useful for identifying membrane-spanning regions """) membrane_protein = Molecule3D( value="https://files.rcsb.org/view/1BL8.pdb", # Example membrane protein label="Membrane Protein", reps=hydro_reps, config={ "backgroundColor": "black", "orthographic": False } ) demo.launch() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.