Py3DMol

repository·master·Indexed 40 days ago

https://github.com/avirshup/py3dmol

A Python package for dependency-free molecular visualization in iPython notebooks using 3DMol.js and WebGL. It allows users to visualize and manipulate molecular objects from libraries such as MDAnalysis, MDTraj, OpenBabel, and CClib. Note: This project is no longer maintained; users are encouraged to use the Notebook Molecular Visualization Library, nbmolviz2d, or nbmolviz3d.

Tokens
2.4K
Snippets
10
Records
12
Agent score
50%

What's inside Py3DMol

  1. Overview of Py3DMol

    master
    Py3DMol is a Python package designed for dependency-free molecular visualization within iPython notebooks. It allows users to visualize and manipulate molecular objects from libraries such as MDAnalysis, MDTraj, OpenBabel, and CClib directly in a notebook environment. The package includes 3DMol.js as a backend, utilizing JavaScript and WebGL to ensure visualizations work in any modern browser without requiring additional external libraries.
  2. Install Py3DMol dependencies

    master

    Py3DMol is designed for the Jupyter Notebook platform. To use it, you must ensure that ipython[notebook] and ipywidgets are installed in your environment.

    # Ensure these dependencies are installed
    ip install ipython[notebook] ipywidgets
  3. Visualize atomic clashes with mdanalysis_3dmol

    master

    Once clashes are identified using MDAnalysis atom groups, you can visualize them in 3D using mdanalysis_3dmol. You can set a global style for the protein (e.g., 'cartoon') and then overlay specific atoms involved in a clash using a 'sphere' style with a distinct color like 'red'.

    import mdanalysis_3dmol as m3d
    
    # Initialize visualization with the MDAnalysis Universe
    viz = m3d.JS3DMol(ubiquitin)
    
    # Set the base protein style
    viz.set_style('cartoon')
    
    # Highlight the clash group (e.g., clash2) as red spheres
    viz.set_style('sphere', clash2, spec={'color': 'red'})
  4. Visualize MDAnalysis selections with MdaViz

    master

    You can use MdaViz to visualize specific atom selections from an MDAnalysis.Universe. By passing an MDAnalysis.SelectionGroup (returned by select_atoms) to the MdaViz constructor, you can isolate and style specific parts of a molecular system, such as a protein or a specific residue.

    import MDAnalysis as mda
    from py3dmol.vizinterfaces import MdaViz
    
    # Load the universe
    u = mda.Universe('topology.gro', 'trajectory.xtc')
    
    # Select a subset (e.g., protein)
    protein = u.select_atoms('protein')
    
    # Initialize visualization for the subset
    vizp = MdaViz(protein)
    vizp.set_style('stick')
  5. Initialize MdaViz with MDAnalysis objects

    master

    To visualize molecular structures or trajectories, use the m3d.MdaViz class. You can pass either an MDAnalysis.Universe object to visualize the entire system or an MDAnalysis.SelectionGroup (atoms) to visualize a specific subset of atoms.

    import mdanalysis_3dmol as m3d
    import MDAnalysis as mda
    
    # Initialize with a selection
    u = mda.Universe('topology.gro', 'trajectory.xtc')
    r = u.select_atoms('resid 1')
    rviz = m3d.MdaViz(r)
    
    # Or initialize with the full universe
    v = m3d.MdaViz(u)
  6. Detect atomic clashes using MDAnalysis and custom logic

    master

    To detect steric clashes in a molecular structure, you can use a combination of MDAnalysis for atom selection and distance calculations. A common approach involves calculating the distance between all atom pairs and comparing the sum of their Van der Waals (VdW) radii against the actual distance, adjusted by an allowance and a cutoff threshold.

    For detecting clashes, cutoff values of 0.4-1.0 Å and allowance values of 0.2-0.6 Å are generally considered reasonable.

    Note: The implementation below requires MDAnalysis and MDAnalysis.lib.distances to be available in your environment.

    import MDAnalysis as mda
    import MDAnalysis.topology.tables as tables
    import MDAnalysis.lib.distances as distances
    
    # Load structure
    structure = "1UBQ.pdb"
    ubiquitin = mda.Universe(structure)
    
    # Define a function to check for clashes
    def check_for_clashes(atoms, cutoff=0.6, allowance=0.4, vdwradii=None):
        clashes = set()
        positions = atoms.positions
        
        if not vdwradii:
            vdwradii = tables.vdwradii
    
        for a in atoms:
            if not a.type in vdwradii.keys(): 
                print(f"{a.type} has no defined vdw radius")
                return clashes
    
        # Calculate all-to-all distance matrix
        dist = distances.self_distance_array(positions)
        N = len(positions)
        
        # Generate pairs for the upper triangle
        pairs = []
        for i in range(N):
            for j in range(i + 1, N):
                pairs.append((i, j))
    
        for x, (d, (i, j)) in enumerate(zip(dist, pairs)):
            a1, a2 = atoms[i], atoms[j]
            r1, r2 = vdwradii[a1.type], vdwradii[a2.type]
            overlap = (r1 + r2) - dist[x] - allowance
            
            if overlap >= cutoff:
                clashes.add(frozenset([i+1, j+1]))
    
        return clashes
    
    # Example usage with specific residues
    gln49 = ubiquitin.select_atoms('resid 49')
    arg42 = ubiquitin.select_atoms('resid 42')
    clash_group = arg42 + gln49
    
    clashes = check_for_clashes(clash_group, cutoff=0.0, allowance=0.0)
  7. Update molecular positions in real-time

    master

    You can update the visual representation of a molecule during a trajectory loop by calling set_positions(). This method accepts MDAnalysis atom positions or a list of coordinates. To ensure the view is centered on the molecule, call center() before starting the loop.

    import time
    
    rviz.center()
    for i in xrange(100):
        u.trajectory.next()
        # Update positions from the current trajectory frame
        rviz.set_positions(r.positions)
        time.sleep(0.1)
  8. Set visual styles and atom selections

    master

    Use set_style(style, selection) to change how atoms are rendered.

    • style: A string representing the rendering mode (e.g., 'sphere', 'stick', 'cartoon').
    • selection: An optional MDAnalysis.SelectionGroup to apply the style only to specific atoms. If omitted, the style applies to the entire object.

    To clear a style from a selection, you can pass an empty list [] as the selection.

    # Set global style
    viz.set_style('stick')
    
    # Set specific style for a selection
    selection = u.select_atoms('name H*')
    viz.set_style('sphere', selection)
    
    # Clear style for a selection
    viz.set_style('sphere', [])