Esempio n. 1
0
def hydrogen_bonds(traj):
  print( '.... computing hbonds (can take few minutes) ....')

  list_peptide_hbonds=[]
  hbonds = mdtraj.baker_hubbard(traj, freq =0.4)

  for hbond in hbonds:
      #if ( hbond[0] in  traj.topology.select( 'chainid  %s to %s' % (3,5) ) and   hbond[2] not in  traj.topology.select( 'chainid  %s to %s' % (3,5)) ) :
      if ( hbond[0] in  traj.topology.select( 'chainid  %s ' % (3) ) and   hbond[2] not in  traj.topology.select( 'chainid  %s' % (3)) ) :
          list_peptide_hbonds.append( hbond[[0,2]] )
          print(' hbond : %s -- %s' % (traj.topology.atom(hbond[0]), traj.topology.atom(hbond[2])))
          print( 'hbond : %s -- %s' % (hbond[0], hbond[2]))
      #elif ( hbond[0] not in  traj.topology.select( 'chainid  %s to %s' % (3,5) ) and   hbond[2]  in  traj.topology.select( 'chainid  %s to %s' % (3,5)) ) :
      elif ( hbond[0] not in  traj.topology.select( 'chainid  %s ' % (3) ) and   hbond[2]  in  traj.topology.select( 'chainid  %s ' % (3)) ) :
          list_peptide_hbonds.append( hbond[[0,2]] )
          print(' hbond : %s -- %s' % (traj.topology.atom(hbond[0]), traj.topology.atom(hbond[2])))
          print('hbond : %s -- %s' % (hbond[0], hbond[2]))
  '''
  da_distances = mdtraj.compute_distances(traj,  np.array(list_peptide_hbonds), periodic=False)

  color = cycle(['r', 'b', 'gold'])
  print(len(np.array(list_peptide_hbonds)))
  for i in  range(len(np.array(list_peptide_hbonds))):
      plt.hist(da_distances[:, i], color=next(color), label=label(hbonds[i]), alpha=0.5)
  plt.legend()
  plt.ylabel('Freq');
  plt.xlabel('Donor-acceptor distance [nm]')
  plt.savefig('hbonds.png', bbox_inches='tight')
  '''
  return np.array(list_peptide_hbonds)
Esempio n. 2
0
def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError("usage:"):
        print('hh_newtorks.py -i <inputfile> -o <outputfile>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('hh_newtorks.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    # 1. Protonate molecule
    _ = protonate_mol(inputfile)
    inputfile_protonated = f"{inputfile[:-4]}-chainA_protonated.pdb"

    t = md.load(inputfile_protonated)
    hbonds = md.baker_hubbard(t, sidechain_only=True)
    graph = make_graph_hh(hbonds, t)
    comp, _ = label_components(graph)
    if comp.a.any():
        write_networks(graph, comp, inputfile_protonated, outputfile)
        postprocess_session(inputfile_protonated, outputfile)
        logger.info("Saving VMD sessions")
    else:
        logger.warning("No Hydrogen Bonds found")
Esempio n. 3
0
def test_baker_hubbard_2():
    t = md.load(get_fn('1vii_sustiva_water.pdb'))
    triplets = md.baker_hubbard(t)
    N = 1000
    rows = triplets[:, 0] * N*N + triplets[:, 1] * N + triplets[:, 2]
    # ensure that there aren't any repeat rows
    eq(len(np.unique(rows)), len(rows))
Esempio n. 4
0
def screening_Hbond(mol2_fnm='input.mol2', scan_fnm='scan.xyz'):
    traj = md.load(scan_fnm, top=mol2_fnm)
    hbonds = md.baker_hubbard(traj)
    if len(hbonds) == 0:
        return True, hbonds
    else:
        return False, hbonds
def hydrogen_bonds(traj):
  print( '.... computing hbonds (can take few minutes) ....')

  trajwtwater=traj.atom_slice(  traj.topology.select('protein'))
#  hbonds = mdtraj.baker_hubbard(traj, freq =0.4)
  hbonds = mdtraj.baker_hubbard(trajwtwater, freq =0.4)
  return hbonds
Esempio n. 6
0
def apply_h_bond_filter(smiles: str) -> Tuple[str, bool, bool]:

    try:

        molecule = smiles_to_molecule(smiles)
        molecule.generate_conformers(n_conformers=800, rms_cutoff=0.1 * unit.angstrom)

        if len(molecule.conformers) == 0:
            return smiles, False, True

        conformers = numpy.array(
            [
                conformer.value_in_unit(unit.nanometers).tolist()
                for conformer in molecule.conformers
            ]
        )

        topology = molecule.to_topology()._to_mdtraj()
        trajectory = mdtraj.Trajectory(conformers * unit.nanometers, topology)

        h_bonds = mdtraj.baker_hubbard(trajectory, freq=0.0, periodic=False)

        return smiles, len(h_bonds) == 0, False

    except:

        return smiles, False, True
Esempio n. 7
0
def test_hbond_structure(pdb_id):
    file_name = join(data_dir("structure"), pdb_id + ".mmtf")

    array = load_structure(file_name)
    # Only consider amino acids for consistency
    # with bonded hydrogen detection in MDTraj
    array = array[..., struc.filter_amino_acids(array)]
    if isinstance(array, struc.AtomArrayStack):
        # For consistency with MDTraj 'S' cannot be acceptor element
        # https://github.com/mdtraj/mdtraj/blob/master/mdtraj/geometry/hbond.py#L365
        triplets, mask = struc.hbond(array, acceptor_elements=("O", "N"))
    else:
        triplets = struc.hbond(array, acceptor_elements=("O", "N"))

    # Save to new pdb file for consistent treatment of inscode/altloc
    # im MDTraj
    temp = NamedTemporaryFile("w+", suffix=".pdb")
    save_structure(temp.name, array)

    # Compare with MDTraj
    import mdtraj
    traj = mdtraj.load(temp.name)
    temp.close()
    triplets_ref = mdtraj.baker_hubbard(traj, freq=0, periodic=False)

    # Both packages may use different order
    # -> use set for comparison
    triplets_set = set([tuple(tri) for tri in triplets])
    triplets_ref_set = set([tuple(tri) for tri in triplets_ref])
    assert triplets_set == triplets_ref_set
    def compute_hbonds(self,
                       plot=True,
                       color=itertools.cycle(["r", "b", "gold", "g"]),
                       hbonds_to_plot=[14, 15, 16, 17]):
        """

        """

        hbonds = md.baker_hubbard(self.traj, periodic=False)
        label = lambda hbond: "%s -- %s" % (self.traj.topology.atom(hbond[0]),
                                            self.traj.topology.atom(hbond[2]))
        dist = md.compute_distances(self.traj,
                                    hbonds[:, [0, 2]],
                                    periodic=False)
        for hbond in hbonds:
            print(label(hbond))
        if plot:
            for i in hbonds_to_plot:
                plt.hist(dist[:, i],
                         color=next(color),
                         label=label(hbonds[i]),
                         alpha=0.5)
            plt.legend()
            plt.ylabel("Freq", labelpad=20)
            plt.xlabel("donor-receptor distance [nm]", labelpad=20)
            plt.show()
Esempio n. 9
0
def hhbond_plot(chimera: Chimera = None, filename: str = None):
    """
    Computes a hhbond plot of a chimera object or a file. One of the two inputs
    must be provided.
    :param chimera: the chimera from where to compute the hydrogen bond plot
    :param filename: a path where to find the pdb file.
    :return: A contact map with hydrogen bond as metric
    """
    if chimera and filename:
        raise ValueError("Only a Chimera object or the path to a pdb file must be specified")
    if not chimera and not filename:
        raise ValueError("At least a Chimera object or the path to a pdb file must be specified")
    if chimera:
        filename = "/tmp/structure.pdb"
        chimera.write(filename)
    mol = md.load_pdb(filename)
    hbonds = md.baker_hubbard(mol, periodic=False)
    for hbond in hbonds:
        a = mol.topology.atom(hbond[0])
        residue1 = re.findall("\d+", str(a))[0]
        resid1 = int(residue1)
        b = mol.topology.atom(hbond[2])
        residue2 = re.findall("\d+", str(b))[0]
        resid2 = int(residue2)
        plt.plot(resid1, resid2, 'b.')
    plt.show()
Esempio n. 10
0
 def fit(self, traj_list, y=None):
     all_trajs = join(traj_list)
     indices = baker_hubbard(all_trajs,
                             freq=self.freq,
                             exclude_water=self.exclude_water,
                             periodic=self.periodic,
                             sidechain_only=self.sidechain_only)
     self.indices = indices[:, 1:]
def check_Hbond(scan_fnm, top_fnm=None):
    """
    Check if the torsion scan contains conformers with internal hydrogen bonds
    """

    traj = md.load(scan_fnm, top=top_fnm)
    hbonds = md.baker_hubbard(traj)
    if len(hbonds) == 0:
        return True
    else:
        return False
Esempio n. 12
0
def findHbonds(traj, boundIndices, results, frameIndex, resultsFrame):
    print("Computing Hydrogen Bond at Index: " + str(frameIndex))
    tic = time.clock()
    hbonds = md.baker_hubbard(traj,
                              freq=0.55,
                              exclude_water=True,
                              periodic=False)
    for hbond in hbonds:
        if (hbond[0] in boundIndices) and (hbond[2] in boundIndices):
            results[tuple(hbond)] += 1
            resultsFrame[tuple(hbond)].append(frameIndex)
    toc = time.clock()
    print("Finished computing for ", str(frameIndex), " in time: ",
          str(toc - tic))
Esempio n. 13
0
def calculate_hbond_occurences(traj):
    topology = traj.topology
    get_label = lambda hbond: '%s -- %s' % (topology.atom(hbond[0]),
                                            topology.atom(hbond[2]))
    # occurences = {get_label(i) : 0 for i in  md.baker_hubbard(traj, freq = 0, periodic=False)}
    occurences = defaultdict(int)

    for i in traj:
        for j in md.baker_hubbard(i, periodic=True):
            occurences[get_label(j)] += 1
        # yield occurences

    labels = [str(i) for i in topology.residues]
    return {
        "occurences": dict(occurences),
        "labels": labels,
        "num_frames": len(traj)
    }
Esempio n. 14
0
def hydrogenbond(pdbfile):
    """
        Calculate number of hydrogen bonds [1,2] and hydrogen bond energy [3]
        using three methods as implemented in MDtraj [4] for a single PDB file.
        [1] E. N. Baker and R. E. Hubbard, "Hydrogen bonding in globular proteins",
            Progress in Biophysics and Molecular Biology, vol. 44, no. 2, 
            pp. 97-179, 1984.
        [2] P. Wernet et al., "The Structure of the First Coordination Shell in 
            Liquid Water", Science, vol. 304, no. 5673, pp. 995-999, 2004.
        [3] W. Kabsch and C. Sander, "Dictionary of protein secondary structure: 
            Pattern recognition of hydrogen-bonded and geometrical features",
            Biopolymers, vol. 22, no. 12, pp. 2577"2637, 1983.
        [4] R. T. McGibbon et al., "MDTraj: A Modern Open Library for the 
            Analysis of Molecular Dynamics Trajectories", Biophysical Journal, 
            vol. 109, no. 8, pp. 1528-1532, 2015.
    """
    pdb = mdtraj.load(pdbfile)
    desc = dict()
    desc['HB_BH'] = float(mdtraj.baker_hubbard(pdb).shape[0])
    desc['HB_WN'] = float(mdtraj.wernet_nilsson(pdb)[0].shape[0])
    desc['HB_KS'] = float(mdtraj.kabsch_sander(pdb)[0].sum())
    return desc
Esempio n. 15
0
def get_h_bonds(pdb_dir):
    '''get bond list of H-Bonds
    '''

    bond_list = []
    atom_list = get_pdb_atom_list(pdb_dir)

    topo = mdtraj.load_pdb(pdb_dir)

    # hbon_list = [ [ donor_indice, H_indice, acceptor_indice ] ], indice = pdbindice-1
    hbon_list = mdtraj.baker_hubbard(topo,
                                     freq=0,
                                     exclude_water=False,
                                     periodic=False,
                                     sidechain_only=False)

    for hbon in hbon_list:
        H_indice = hbon[1]
        acceptor_indice = hbon[2]

        at_h = 'None'
        at_acc = 'None'

        for at_indice, at_name in atom_list:

            if H_indice == (int(at_indice) - 1):
                at_h = at_name

            if acceptor_indice == (int(at_indice) - 1):
                at_acc = at_name

        bond = at_h + '=' + at_acc

        bond_list.append(bond)

    print('Processing: ' + pdb_dir + '\tDetected H bonds: ' +
          str(len(bond_list)))

    return bond_list
Esempio n. 16
0
    def _filter_function(self, result: "_BaseResult", record: RecordBase,
                         molecule: Molecule) -> bool:

        import mdtraj

        conformers = numpy.array([
            conformer.value_in_unit(unit.nanometers).tolist()
            for conformer in molecule.conformers
        ])

        mdtraj_topology = mdtraj.Topology.from_openmm(
            molecule.to_topology().to_openmm())
        mdtraj_trajectory = mdtraj.Trajectory(conformers * unit.nanometers,
                                              mdtraj_topology)

        if self.method == "baker-hubbard":
            h_bonds = mdtraj.baker_hubbard(mdtraj_trajectory,
                                           freq=0.0,
                                           periodic=False)
        else:
            raise NotImplementedError()

        return len(h_bonds) == 0
Esempio n. 17
0
# coding: utf-8

# In[3]:

get_ipython().magic(u'matplotlib inline')
from __future__ import print_function
import numpy as np
import mdtraj as md
t = md.load_frame('.\\trajectory-1.xtc', 9999, top='.\\fs-peptide.pdb')
print(t)

# In[7]:

hbonds = md.baker_hubbard(t, periodic=False)
label = lambda hbond: '%s -- %s' % (t.topology.atom(hbond[0]),
                                    t.topology.atom(hbond[2]))
for hbond in hbonds:
    print(label(hbond))

hbond_score = len(hbonds)
print('\n\nH-Bond score:', hbond_score)
# calculate heavy atom to atom contacts
# basically a number that looks like Nij/root(ninj)

# In[8]:

da_distances = md.compute_distances(t, hbonds[:, [0, 2]], periodic=False)

# In[14]:

import itertools
Esempio n. 18
0
def Hbonds(grofile, trajfile, frame_iterator, freq=0.1):
    """
    NOTE: For atomistic simulations
    Calculates baker-hubbard hydrogen bond for frame_iterator
    Returns the hbonds distances found in frame_iterator using two criteria:
     - Average distances of hbonds cummulatively found in all the frames in frame_iterator
     - hbonds cummulatively calculated using mdtraj for a particular frequency (freq) avlue
     (See mdtraj documentation for more info)
    Hbond criteria: DHA angle > 2*np.pi/3  and H-A separation < 2.5 A
    """

    traj = mdtraj.load(trajfile, top=grofile)

    positions = traj.xyz

    hbonds_all = np.empty((0, 3))
    framewise_hbonds = []
    for f in frame_iterator:
        hbonds = mdtraj.baker_hubbard(traj[f])
        # FILTER Hbonds that are only between NH and C=O
        hbonds_ = []
        for b in hbonds:
            if traj.top.atom(b[0]).name == 'N' and traj.top.atom(
                    b[2]).name == 'O':
                hbonds_ += [b]
        hbonds = np.array(hbonds_)

        if len(hbonds) == 0:
            hbonds = hbonds.reshape((0, 3))

        framewise_hbonds += [hbonds]

        hbonds_all = np.append(hbonds_all, hbonds, axis=0).astype(int)

    hbonds_all = np.unique(hbonds_all, axis=0)

    num_hbonds_all = len(hbonds_all)

    r_DH = []
    r_DA = []
    r_AH = []
    r_DH_all = []
    r_DA_all = []
    r_AH_all = []
    theta = []
    num_hbonds = 0

    for i, f in enumerate(frame_iterator):
        Lx, Ly, Lz = traj.unitcell_lengths[f]
        hbonds = framewise_hbonds[i]
        if len(hbonds) == 0:
            continue
        num_hbonds += len(hbonds)
        posH = positions[f, hbonds[:, 1]]
        posD = utils.unwrap_points(positions[f, hbonds[:, 0]], posH, Lx, Ly,
                                   Lz)
        posA = utils.unwrap_points(positions[f, hbonds[:, 2]], posH, Lx, Ly,
                                   Lz)
        r_AH_ = np.linalg.norm(posA - posH, axis=-1)
        r_DA_ = np.linalg.norm(posD - posA, axis=-1)
        r_DH_ = np.linalg.norm(posD - posH, axis=-1)
        r_DH += list(r_DH_)
        r_AH += list(r_AH_)
        r_DA += list(r_DA_)

        posH = positions[f, hbonds_all[:, 1]]
        posD = utils.unwrap_points(positions[f, hbonds_all[:, 0]], posH, Lx,
                                   Ly, Lz)
        posA = utils.unwrap_points(positions[f, hbonds_all[:, 2]], posH, Lx,
                                   Ly, Lz)
        r_AH_all_ = np.linalg.norm(posA - posH, axis=-1)
        r_DA_all_ = np.linalg.norm(posD - posA, axis=-1)
        r_DH_all_ = np.linalg.norm(posD - posH, axis=-1)
        r_DH_all += list(r_DH_all_)
        r_AH_all += list(r_AH_all_)
        r_DA_all += list(r_DA_all_)

        v1 = posA - posH
        v2 = posD - posH
        theta_ = [
            abs(quaternion.angle_v1tov2(v1[i], v2[i]))
            for i in range(v1.shape[0])
        ]
        theta += [theta_]

    num_hbonds_perframe = num_hbonds / len(frame_iterator)

    return (np.mean(r_DH), np.std(r_DH), np.mean(r_AH), np.std(r_AH),
            np.mean(r_DA), np.std(r_DA),
            num_hbonds_perframe, np.mean(r_DH_all), np.std(r_DH_all),
            np.mean(r_AH_all), np.std(r_AH_all), np.mean(r_DA_all),
            np.std(r_DA_all), num_hbonds_all)
Esempio n. 19
0
"""
Chord Diagram
=============
"""
from msmbuilder.example_datasets import FsPeptide

import numpy as np
import mdtraj as md

import msmexplorer as msme
from msmexplorer.utils import make_colormap

# # Load Fs Peptide Data
trajs = FsPeptide().get().trajectories

# Compute Hydrogen Bonding Residue Pairs
baker_hubbard = md.baker_hubbard(trajs[0])
top = trajs[0].topology
pairs = [(top.atom(di).residue.index, top.atom(ai).residue.index)
         for di, _, ai in baker_hubbard]

# Create Hydrogen Bonding Network
hbonds = np.zeros((top.n_residues, top.n_residues))
hbonds[list(zip(*pairs))] = 1.

# Make a Colormap
cmap = make_colormap(['rawdenim', 'lightgray', 'pomegranate'])

# Plot Chord Diagram
msme.plot_chord(hbonds, cmap=cmap)
Esempio n. 20
0
def do_hbonds(trajectory,
              topology=None,
              verbose=True,
              distance_cutoff=0.35,
              angle_cutoff=120,
              start_time=-np.inf,
              end_time=np.inf,
              skip=1,
              chunk_size=100,
              periodic=True,
              exclude_waters=False,
              sidechain_only=False,
              dt=None):
    if chunk_size % skip:
        raise ValueError(
            'do_hbonds: chunk_size must be an integer multiple of step')
    if topology is None:
        base, _ = os.path.splitext(trajectory)
        topology = base + '.pdb'
    hbonds = []
    for i, trj in enumerate(
            md.iterload(trajectory, top=topology, chunk=chunk_size)):
        if dt:
            first_time = i * len(trj) * dt
            last_time = ((i + 1) * len(trj) - 1) * dt
            if first_time >= end_time or last_time <= start_time:
                continue
            _time = np.linspace(first_time, last_time + dt, len(trj) + 1)
            indices = np.argwhere((_time >= start_time) & (_time <= end_time))

        else:
            if trj.time[0] >= end_time or trj.time[-1] <= start_time:
                continue
            indices = np.argwhere((trj.time >= start_time)
                                  & (trj.time <= end_time))

        keep = list(range(0, chunk_size, skip))
        ok_indices = [index[0] for index in indices if index in keep]
        skip_range = range(min(ok_indices), max(ok_indices) + skip, skip)
        trj_ok = trj[skip_range]

        for j in range(len(trj_ok)):

            frame = trj_ok[j]
            time = frame.time[0]
            if dt:
                time = j * dt + i * len(trj) * dt
            if verbose:
                print(f'HBONDS - Processing time: {time}', end='\r')
            the_hbonds = md.baker_hubbard(frame,
                                          periodic=periodic,
                                          distance_cutoff=distance_cutoff,
                                          angle_cutoff=angle_cutoff,
                                          exclude_water=exclude_waters,
                                          sidechain_only=sidechain_only,
                                          freq=0)
            hbonds.append((time, the_hbonds))
    if verbose:
        print()
        print('Done.')
    return hbonds
Esempio n. 21
0
def test_baker_hubbard_1():
    # no hydrogens in this file -> no hydrogen bonds
    t = md.load(get_fn('1bpi.pdb'))
    eq(np.zeros((0, 3), dtype=int), md.baker_hubbard(t))
Esempio n. 22
0
def draw_snapshot(grofile, trajfile, topfile, itpfiles, molnames, 
    molattributes=[], hbondattributes=[], slice_slab=[],
    draw_box=False, frame=-1, filename='snapshot.png', preview=True,
    view=[['axono']], primitive='cylinder', lights=''):
    """
    For gromacs atomistic simulations.

    Draw snapshots with hbonds shown
    
    molattributes = [ [particle_id_start, particle_id_end, hexcolor, radius, outline_width], [particle_id_start, particle_id_end, hexcolor, radius, outline_width],... ]
    particle ids not covered in the colors list are not draw
    
    hbondattributes = [hexcolor, radius, outline_width]

    slice_slab = ['eig',i,j, thickness (nm)] | []
    from center cut the slice along vi and slicing in vj direction using thickness

    preview: fresnel preview or pathtrace
    view: ['axono','name']  axonometric view
          ['axis', i, j, name] - looking from axis i, axis j points upwards
          ['eig', i,j, name] - looking from vi to system center, vj is upward direction
    vi -> {0,1,2} are gyration vectors ids, 0 and 2 correspond to largest and smallest eigenvale
          [] - diagonal - axonometric view
          snapshots are saved for each view in the list
          name is the optional name appended before filename for each view snapshot

    primitive: sphere | cylinder

    lights: fresnel lights - lightbox, cloudy, rembrandt
    Notes: no water drawn | only backbone atoms are drawn
    """

    #-------------------------------------- default parameters ---------------------------------
    
    # radius_dir = dict(H=0, C=0.15, N=0.12, S=0.15, O=0.15) # for sphere primitive
    # radius_cylinder = 0.03
    # outline_width_cylinder = 0.00
    # outline_width_sphere = 0.01
    # radius_cylinder_hbond = 0.015
    # outline_width_cylinder_hbonds = 0.005

    radius = 0.1
    outline_width = 0.01
    
    # color_C16  = to_rgb('#0D2D6C') #542e71
    # color_12C  = to_rgb('#0D2D6C')
    # color_pep = to_rgb('#00FF00')
    # color_pep2 = to_rgb('#00FF00')
    # color_BMP  = to_rgb('#e41a1c')

    #------------------------------------ Read system attributes -----------------------------

    traj = mdtraj.load(trajfile, top=grofile)
    
    Lx, Ly, Lz = traj.unitcell_lengths[frame]

    
    atoms = np.array([r for r in traj.top.atoms])

    num_atomss  = []
    nmols       = []
    positionss  = []
    atomss = []
    start = 0
    for i,molname in enumerate(molnames):
        num_atomss  += [utils.get_num_atoms_fromGRO(itpfiles[i].replace('.itp','')+'.gro')]
        nmols       += [utils.get_num_molecules_fromtop(topfile, molname)]
        positionss  += [ traj.xyz[frame,start:start+num_atomss[i]*nmols[i]] ]
        atomss += [ atoms[start:start+num_atomss[i]*nmols[i]] ]
        start += num_atomss[i]*nmols[i]
    

    # c: green, blue, red
    c = [to_rgb('#00FF00'), to_rgb('#2978b5'), to_rgb('#fb3640')]
    # if molattributes == []:
    #     for i,molname in enumerate(molnames):
    #         molattributes += [ [ [0,num_atomss[i]*nmols[i], c[i], radius, outline_width] ] ]
    if molattributes != []:
        for i,molattribute in enumerate(molattributes):
            for j,m in enumerate(molattribute):
                molattributes[i][j][2] = to_rgb(m[2])

    
    # Read bonds per molecule type
    bondss = get_bonds_fromtopfile(topfile, molnames)
    backbone_bondss = []
    alkyl_bondss = []
    bb_and_alkyl_bondss = []
    start = 0
    for i,molname in enumerate(molnames):
        # Collect backbone bonds i.e., only between C,N,CA (not C16) 
        bonds_=[]
        for b in bondss[i]:
            resname0 = atomss[i][b[0]].residue.name
            resname1 = atomss[i][b[1]].residue.name
            atomname0 = atomss[i][b[0]].name
            atomname1 = atomss[i][b[1]].name
            if resname0 in ['C16','12C', 'HOH'] or resname1 in ['C16','12C', 'HOH']:
                continue
            if atomname0 in ['C','N','CA'] and atomname1 in ['C','N','CA']:
                bonds_ += [ [b[0], b[1]] ]
        backbone_bondss += [np.array(bonds_)]
        
        # Collect alkyl bonds i.e., bonds between C-C
        bonds_=[]
        for b in bondss[i]:
            resname0 = atomss[i][b[0]].residue.name
            resname1 = atomss[i][b[1]].residue.name
            atomname0 = atomss[i][b[0]].name
            atomname1 = atomss[i][b[1]].name
            if resname0 in ['C16','12C'] and resname1 in ['C16','12C']:
                if atomname0[0] == 'C' and atomname1[0] == 'C':
                    bonds_ += [ [b[0], b[1]] ]
        alkyl_bondss += [np.array(bonds_)]

        # collect both backbone and alkyl bonds that can be draw
        bb_and_alkyl_bondss += [ np.append(backbone_bondss[i], alkyl_bondss[i], axis=0) ]


    # Backbone positions
    backbone_positionss=[]
    for i,bb in enumerate(backbone_bondss):
        backbone_positions = np.empty((0,3))
        for j in range(nmols[i]):
            args = np.sort(list(set((bb + j * num_atomss[i]).reshape(-1))))
            backbone_positions = np.append(backbone_positions, positionss[i][args], axis=0)
    backbone_positionss += [backbone_positions]



    #------------------------------------  gyration eigenvectors ------------------------
    
    points = np.empty((0,3))
    for p in backbone_positionss:
        points = np.append(points, p, axis=0)
    
    center = np.mean(points, axis=0)

    # Calculate gyration eigenvectors using only backbone atoms
            
    # Gij = 1/N SUM_n:1_N [ rn_i * rn_j ]
    points -= center
    G = np.zeros((3,3))
    for i,j in itertools.product(range(3),range(3)):
        G[i,j] = np.mean(points[:,i]*points[:,j])
    

    w,v = scipy.linalg.eig(G)

    args = np.argsort(w)[::-1]

    eigvec = v[:,args]


    #------------------------------------  slice or not ------------------------

    if slice_slab != []:
        if slice_slab[0]=='eig':
            
            vi = eigvec[:,slice_slab[1]]
            vj = eigvec[:,slice_slab[2]]
            thickness = slice_slab[3]
            
            slice_filtrs = [] 
            for pos in positionss:
                t = (pos-center).dot(vj.reshape(-1,1)).reshape(-1)
                slice_filtrs += [ (t <= thickness/2) * (t >= -thickness/2) ]

            

    #------------------------------------ draw fresnel scene --------------------------------------------------

    
    # Start scene    
    scene = fresnel.Scene()

    # Primitive
    if primitive == 'cylinder':    
        
        for k,molattribute in enumerate(molattributes):
            
            for id1, id2, color_, radius, outline_width in molattribute:
                
                filtr = (bb_and_alkyl_bondss[k][:,0]>=id1) * \
                        (bb_and_alkyl_bondss[k][:,0]<=id2) * \
                        (bb_and_alkyl_bondss[k][:,1]>=id1) * \
                        (bb_and_alkyl_bondss[k][:,1]<=id2)

                bb_ = bb_and_alkyl_bondss[k][filtr]
                bb = []
                for m in range(nmols[k]):
                    bb += list( bb_ + m * num_atomss[k] )
                bb = np.array(bb).astype(int)

                if slice_slab != []:
                    filtr = slice_filtrs[k][bb[:,0]] * \
                             slice_filtrs[k][bb[:,1]]
                    bb = bb[filtr] 

                points1 = positionss[k][bb[:,0]]
                points2 = utils.unwrap_points(positionss[k][bb[:,1]], points1, Lx, Ly, Lz)
                
                geometry                  = fresnel.geometry.Cylinder(scene, N = len(points1))
                geometry.radius[:]        = radius
                geometry.outline_width    = outline_width
                geometry.points[:]        = list(zip(points1, points2))
                geometry.color[:]         = color_
                geometry.material         = fresnel.material.Material(
                                            roughness=0.5, 
                                            primitive_color_mix=1)

    elif primitive == 'sphere':    

        for k,molattribute in enumerate(molattributes):
            
            for id1, id2, color_, radius, outline_width in molattribute:
                
                args_ = np.array(list(set(bb_and_alkyl_bondss[k].reshape(-1))))
                args_ = args_[(args_>=id1) * (args_<=id2)]
                args = []
                for m in range(nmols[k]):
                     args += list( args_ + m * num_atomss[k] )

                if slice_slab != []:
                    filtr = slice_filtrs[k][args] * \
                             slice_filtrs[k][args]
                    args = args[filtr]

                points = positionss[k][args]
                
                geometry                  = fresnel.geometry.Sphere(scene, N = len(points))
                geometry.radius[:]        = radius
                geometry.outline_width    = outline_width
                geometry.position[:]      = points
                geometry.color[:]         = color_
                geometry.material         = fresnel.material.Material(
                                            roughness=0.5, 
                                            primitive_color_mix=1)


    # Hbonds
    if hbondattributes != []:
        color_, radius, outline_width = hbondattributes
        color_ = to_rgb(color_)

        hbonds = mdtraj.baker_hubbard(traj[frame])
        hbonds_=[]
        for b in hbonds:
            if traj.top.atom(b[0]).name == 'N' and traj.top.atom(b[2]).name == 'O':
                hbonds_ += [b]
        hbonds = np.array(hbonds_)
        
        if slice_slab != []:
            slice_filtr = np.empty(0, dtype=bool)
            for f in slice_filtrs:
                slice_filtr = np.append(slice_filtr, f)
            filtr = slice_filtr[hbonds[:,0]] * \
                     slice_filtr[hbonds[:,1]]
            hbonds = hbonds[filtr] 

        pos = np.empty((0,3))
        for p in positionss:
            pos = np.append(pos,p,axis=0)
        posH = pos[hbonds[:,1]]
        posA = utils.unwrap_points(pos[hbonds[:,2]], posH, Lx, Ly, Lz)

        points1 = posH
        points2 = posA
        
        geometry                  = fresnel.geometry.Cylinder(scene, N = len(points1))
        geometry.radius[:]        = radius
        geometry.outline_width    = outline_width
        geometry.points[:]        = list(zip(points1, points2))
        geometry.color[:]         = color_
        geometry.material         = fresnel.material.Material(
                                    roughness=0.5, 
                                    primitive_color_mix=1)



    # Lights
    if lights == 'lightbox':
        scene.lights = fresnel.light.lightbox()
    elif lights == 'cloudy':
        scene.lights = fresnel.light.cloudy()
    elif lights == 'rembrandt':
        scene.lights = fresnel.light.rembrandt()


    # Camera    
    for view_ in view:
        if view_[0] == 'eig':
            try:
                vname = view_[3]
            except:
                vname = ''
            
            vi = eigvec[:,view_[1]]
            vj = eigvec[:,view_[2]]
            
            scene.camera = fresnel.camera.Orthographic.fit(scene)
            scene.camera.position = 5 * vi + center
            scene.camera.look_at = center
            scene.camera.up = vj

        elif view_[0] == 'axono': # use axonometric view
            try:
                vname = view_[1]
            except:
                vname = ''

            scene.camera = fresnel.camera.Orthographic.fit(scene)
            scene.camera.position = center + [4, 4, 5]
            scene.camera.look_at = center    

        if preview:
            out = fresnel.preview(scene, w=800, h=800)
        else:
            out = fresnel.pathtrace(scene, w=800, h=800, samples=16, light_samples=32)
        
        PIL.Image.fromarray(out[:], mode='RGBA').save(vname+filename)
Esempio n. 23
0
t = md.load('traj.nc', top=topology)
t = t.image_molecules(
    anchor_molecules=solute_ref.topology.find_molecules()[0:1], inplace=True)
print('finish imaging molecules')
equi = 300  # the structure seems stable after this frame
length = len(t)
print(f'length of the simulation: {length}.')

# hard code the residue indices of CDK6 and CRBN (1-based)
CDK6 = list(range(1, 294))
CRBN = list(range(541, 922))
key_inter = dict()
lig_inter = dict()

for i in tqdm(range(length)):
    hbonds = md.baker_hubbard(t[i])
    label = lambda hbond: '%s -- %s' % (t.topology.atom(hbond[0]),
                                        t.topology.atom(hbond[2]))
    for hbond in hbonds:
        if (str(t.topology.atom(hbond[0]))[4] == '-'
                and int(str(t.topology.atom(hbond[0]))[3]) in CDK6) or (
                    str(t.topology.atom(hbond[0]))[5] == '-'
                    and int(str(t.topology.atom(hbond[0]))[3:5]) in CDK6) or (
                        str(t.topology.atom(hbond[0]))[6] == '-'
                        and int(str(t.topology.atom(hbond[0]))[3:6])
                        in CDK6):  # 1-digit CDK6 or 2-digit or 3-digit
            if len(str(t.topology.atom(hbond[2]))) > 6:
                if str(t.topology.atom(hbond[2]))[6] == '-' and int(
                        str(t.topology.atom(hbond[2]))
                    [3:6]) in CRBN:  # CRBN can only be 3-digit
                    if label(hbond) not in key_inter.keys():
Esempio n. 24
0
def test_baker_hubbard_3(get_fn):
    #different distance cutoffs->different hydrogen bonds found
    t = md.load(get_fn('2waters_baker_hubbard.pdb'))
    eq(np.zeros((0,3), dtype=int), md.baker_hubbard(t, exclude_water=False, distance_cutoff = 0.18))
    eq(np.zeros((0,3), dtype=int), md.baker_hubbard(t, exclude_water=False, angle_cutoff=180))
    eq(np.array([[0, 1, 3]]), md.baker_hubbard(t, exclude_water=False))
Esempio n. 25
0
def plot_hbonds(args):
    residue_pairs = set()
    for r1 in args.residue_group_1:
        for r2 in args.residue_group_2:
            residue_pairs.add(tuple(sorted((r1, r2))))

    print residue_pairs

    print "Reading frames"
    traj = md.load(args.input_traj,
                   top=args.pdb_file)

    print "Computing hbonds"
    n_windows = int(np.ceil(traj.n_frames / float(args.window_size)))
    hbond_freq = dict()
    for pair in residue_pairs:
        hbond_freq[pair] = np.zeros(n_windows)

    all_residues = set()
    for r1, r2 in residue_pairs:
        all_residues.add(r1)
        all_residues.add(r2)
    
    selection = " or ".join(["(resid %s)" % r for r in all_residues])
    print selection
    selected_atom_indices = traj.topology.select(selection)
    traj = traj.atom_slice(selected_atom_indices)

    print traj.n_atoms, traj.n_residues
    
    for i in xrange(traj.n_frames):
        hbonds = md.baker_hubbard(traj[i],
                                  periodic=False)

        if i % 1000 == 0:
            print "Frame", (i+1)

        seen_pairs = set()
        for donor_idx, hydrogen_idx, acceptor_idx in hbonds:
            res1 = traj.topology.atom(donor_idx).residue.index
            res2 = traj.topology.atom(acceptor_idx).residue.index
            key = tuple(sorted((res1, res2)))
            if key in residue_pairs and key not in seen_pairs:
                window_idx = i / args.window_size
                hbond_freq[key][window_idx] += 1.0
                seen_pairs.add(key)

    for pair, freq in hbond_freq.iteritems():
        freq /= float(args.window_size)
    
    print "plotting"
    if args.plot_type == "timeseries":
        time = np.arange(1, n_windows + 1) * traj.timestep * args.window_size / 10.
        for i, ((r1, r2), freq) in enumerate(hbond_freq.iteritems()):
            label = "%s -- %s" % (r1 + 1, r2 + 1)
            plt.plot(time, freq, label=label)
            plt.xlabel('Time (ns)', fontsize=16)
            plt.ylabel('H-bond Frequency', fontsize=16)
            plt.ylim([-0.01, 1.01])
    elif args.plot_type == "distribution":
        for i, ((r1, r2), freq) in enumerate(hbond_freq.iteritems()):
            label = "%s -- %s" % (r1 + 1, r2 + 1)
            sns.distplot(freq, kde=False, label=label)
            plt.ylabel('Counts', fontsize=16)
            plt.xlabel('H-bond Frequency', fontsize=16)
    plt.legend()
    plt.savefig(args.figure_fl,
                DPI=300)
Esempio n. 26
0
import mdtraj as md
import mdtraj.testing

# Load up some example data. This is a little 20 frame PDB, straight
# from the RCSB
path = mdtraj.testing.get_fn('2EQQ.pdb')
t = md.load(path)
print t

# :func:`md.baker_hubbard` idenfies hydrogen bonds baced on cutoffs
# for the Donor-H...Acceptor distance and angle. The criterion employed
# is :math:`\theta > 120` and :math:`r_\text{H...Acceptor} < 2.5 A` in
# at least 10% of the trajectory. The return value is a list of the 
# indices of the atoms (donor, h, acceptor) that satisfy this criteria.

hbonds = md.baker_hubbard(t)
label = lambda hbond : '%s -- %s' % (t.topology.atom(hbond[0]), t.topology.atom(hbond[2]))
for hbond in hbonds:
    print label(hbond)

# Let's compute the actual distances between the donors and acceptors

da_distances = md.compute_distances(t, hbonds[:, [0,2]], periodic=False)

# Plot a histogram for a few of them

import matplotlib.pyplot as pp
pp.figure();
color = itertools.cycle(['r', 'b', 'gold'])
for i in [2, 3, 4]:
    pp.hist(da_distances[:, i], color=next(color), label=label(hbonds[i]), alpha=0.5)
Esempio n. 27
0
def Hbond_autocorrelation(grofile,
                          trajfile,
                          frame_iterator,
                          window_duration,
                          frame_interval,
                          filename=None):
    """
    NOTE: For atomistic simulations
    Autocorrelation is calculated as
    auto(t) = < kij(t0) * k(t0+t) / <kij(t0)^2> >
    kij: binary variable defining H-bond presence between i, j atoms
    auto is averaged over all the hbonds and multiple time windows
    
    frame_iterator: traj frames to use for calculating auto
    window_duration: max time up till which auto is calculated
    frame_interval: number of frames between start of consecutive time windows

    autos are calculated after every frame_interval and then averaged
    """

    traj = mdtraj.load(trajfile, top=grofile)

    positions = traj.xyz

    framewise_hbonds = []
    all_hbonds = np.empty((0, 3))
    k = {}  # key is (D,H,A)
    for n, f in enumerate(frame_iterator):
        Lx, Ly, Lz = traj.unitcell_lengths[f]
        hbonds = mdtraj.baker_hubbard(traj[f])
        framewise_hbonds += [hbonds]

        all_hbonds = np.append(all_hbonds, hbonds, axis=0)

    all_hbonds = np.unique(all_hbonds, axis=0)

    hbond_id_dict = {}
    for i, hbond in enumerate(all_hbonds):
        hbond_id_dict[tuple(hbond)] = i

    # k is the array that stores hbond presence
    k = np.zeros((len(all_hbonds), len(frame_iterator)))
    for f, hbonds in enumerate(framewise_hbonds):
        for hbond in hbonds:
            k[hbond_id_dict[tuple(hbond)], f] = 1

    # So <kij(t0)^2> = 1 because kij(t0) is 1 for all hbonds in that frame
    # Caluclate average < kij(t0) * k(t0+t) >
    # auto = np.empty((0,window_duration)) # collect auto for each window
    # for i,_ in enumerate(frame_iterator[::frame_interval]):
    #     hbonds0 = framewise_hbonds[i]
    #     args = [hbond_id_dict[tuple(hbond)] for hbond in hbonds0]
    #     if len(frame_iterator[i:])>=window_duration:
    #         auto_ = k[args,i:i+1]*k[args,i:i+window_duration]
    #         auto = np.append(auto, auto_, axis=0)
    # auto = np.mean(auto, axis=0)

    auto = [1]
    args = []
    for i in range(1, len(frame_iterator)):
        hbonds0 = framewise_hbonds[i]
        args += [[hbond_id_dict[tuple(hbond)] for hbond in hbonds0]]
    args = np.array(args)

    auto = [1]
    for i in range(1, len(frame_iterator)):
        auto_ = []
        for j in range(len(frame_iterator) - i):
            auto_ += [np.mean(k[args[j], j] * k[args[j], j + i])]
        auto += [np.mean(auto_)]
    auto = np.array(auto)

    if type(filename) != type(None):
        fig = plt.figure(figsize=(4 / 1.2, 3 / 1.2))
        plt.plot(range(len(auto)), auto, marker='o')
        plt.title('H-bond Autocorrelation')
        plt.xlabel('Frame Number')
        plt.ylabel('Autocorrelation')
        plt.subplots_adjust(bottom=0.14, left=0.15)
        plt.savefig(filename, dpi=400)

    return auto
Esempio n. 28
0
def Hbond_orientation(grofile, trajfile, frame_iterator, eig_index):
    """
    NOTE: For atomistic simulations
    Calculates baker-hubbard hydrogen bond for frame_iterator
    
    Calculates the fluctuation of the direction O-H bond as 
    theta is angle between the OH orientation and it's average.

    Calculates Hbond orientation wrt to its molecule and wrt to the fiber axis
    eig_index: {0,1,2} 0: largest eigenvalue 2: lowest eigenvalue 
    eigenvectors are ussed for calculating the fiber axis 
    and are calculated using the peptide backbone.

    spatial_fluctuation 

    Hbond criteria: DHA angle > 2*np.pi/3  and H-A separation < 2.5 A
    """

    traj = mdtraj.load(trajfile, top=grofile)

    positions = traj.xyz

    # all hbonds that ever occured in the traj
    hbonds_all = np.empty((0, 3))
    framewise_hbonds = []
    for f in frame_iterator:
        hbonds = mdtraj.baker_hubbard(traj[f])
        # FILTER Hbonds that are only between NH and C=O
        hbonds_ = []
        for b in hbonds:
            if traj.top.atom(b[0]).name == 'N' and traj.top.atom(
                    b[2]).name == 'O':
                hbonds_ += [b]
        hbonds = np.array(hbonds_)
        framewise_hbonds += [hbonds]
        hbonds_all = np.append(hbonds_all, hbonds, axis=0).astype(int)
    hbonds_all = np.unique(hbonds_all, axis=0)

    rOH = []
    for i, f in enumerate(frame_iterator):
        Lx, Ly, Lz = traj.unitcell_lengths[f]

        posH = positions[f, hbonds_all[:, 1]]
        posA = utils.unwrap_points(positions[f, hbonds_all[:, 2]], posH, Lx,
                                   Ly, Lz)

        rOH += [posH - posA]

    rOH = np.array(rOH)

    #------------------------------------ Gyration eigenvectors ------------------------

    points = np.empty((0, 3))
    for p in backbone_positionss:
        points = np.append(points, p, axis=0)

    center = np.mean(points, axis=0)

    # Calculate gyration eigenvectors using only backbone atoms

    # Gij = 1/N SUM_n:1_N [ rn_i * rn_j ]
    points -= center
    G = np.zeros((3, 3))
    for i, j in itertools.product(range(3), range(3)):
        G[i, j] = np.mean(points[:, i] * points[:, j])

    w, v = scipy.linalg.eig(G)

    args = np.argsort(w)[::-1]

    eigvec = v[:, args]

    #------------------------------------ Calculate ------------------------

    # Calculate spatial fluctuation, averaged over all frames
    fluc_spatial = []
    rOH_mean = np.mean(rOH, axis=1)
    for i in range(rOH.shape[0]):
        thetas = [
            quaternion.angle_v1tov2(rOH_, rOH_mean[i]) for rOH_ in rOH[i]
        ]

        fluc_spatial += [np.sqrt(np.mean(np.array(thetas)**2))]

    fluc_spatial = np.mean(fluc_spatial)

    # Calculate temporal fluctuation, averaged over all hbonds
    fluc_temporal = []
    rOH_mean = np.mean(rOH, axis=0)
    for i in range(rOH.shape[1]):
        thetas = [
            quaternion.angle_v1tov2(rOH_, rOH_mean[i]) for rOH_ in rOH[:, i]
        ]

        fluc_temporal += [np.sqrt(np.mean(np.array(thetas)**2))]

    fluc_temporal = np.mean(fluc_temporal)

    return fluc_spatial, fluc_temporal
Esempio n. 29
0
def draw_Hbonds(grofile, trajfile, topfile, itpfiles, 
    molnames, draw_box, frame, filename='snapshot_hbonds.png', preview=True):
    """
    For atomistic simulations.

    Draw snapshots with hbonds along the three gyration eigenvectors
    
    """
    
    #---------------------------------------- Parameters ---------------------------------
    
    radius_dir = dict(H=0, C=0.15, N=0.12, S=0.15, O=0.15)
    radius_cylinder = 0.03
    outline_width = 0.0001

    color_C16  = to_rgb('#0D2D6C')
    color_12C  = to_rgb('#0D2D6C')
    color_pep =  to_rgb('#00FF00')
    color_pep2 = to_rgb('#00FF00')
    color_BMP  = to_rgb('#e41a1c')


    #--------------------------------------------------------------------------------------
    # Calculate bonds and colors

    traj = mdtraj.load(trajfile, top=grofile)

    num_atomss  = []
    nmols       = []
    positions   = []
    start = 0
    for i,molname in enumerate(molnames):
        num_atomss  += [utils.get_num_atoms_fromGRO(itpfiles[i].replace('.itp','')+'.gro')]
        nmols       += [utils.get_num_molecules_fromtop(topfile, molname)]
        positions   += list(traj.xyz[frame,start:start+num_atomss[i]*nmols[i]])
        start += num_atomss[i]*nmols[i]
    positions = np.array(positions)

    N = len(positions)

    Lx, Ly, Lz = traj.unitcell_lengths[frame]

    residues = np.array([r for r in traj.top.residues])[:N]
    atoms = np.array([a for a in traj.top.atoms])[:N]

    # Collect backbone bonds i.e., only between C,N,CA (not C16) 
    bonds=[] 
    for b in traj.top.bonds:
        if b[0].residue.name in ['C16','12C', 'HOH'] or b[1].residue.name in ['C16','12C', 'HOH']:
            continue
        if b[0].name in ['C','N','CA'] and b[1].name in ['C','N','CA']:
            bonds += [ [b[0].index, b[1].index] ]
    bonds = np.array(bonds)

    radius = []
    for atom in atoms:
        radius += [ radius_dir[atom.name[0]] ]

    # Hbonds
    hbonds = mdtraj.baker_hubbard(traj[frame])
    hbonds_=[]
    for b in hbonds:
        if traj.top.atom(b[0]).name == 'N' and traj.top.atom(b[2]).name == 'O':
            hbonds_ += [b]
    hbonds = np.array(hbonds_)
    posH = positions[hbonds[:,1]]
    posA = utils.unwrap_points(positions[hbonds[:,2]], posH, Lx, Ly, Lz)

    # Define custom colors
    colors = np.zeros((N,3))
    colors[0:num_atomss[0]*nmols[0]] = color_pep
    # colors[num_atomss[0]*nmols[0]:num_atomss[0]*nmols[0]+num_atomss[1]*nmols[1]] = color_pep2
    # c_=[]
    # for i in range(nmols[1]):
    #     c_+=[color_BMP]*128+[color_pep2]*(num_atomss[1]-128)
    # colors[num_atomss[0]*nmols[0]:] = c_
    for i,atom in enumerate(atoms):
        if atom.residue.name == 'C16':
            colors[i] = color_C16
        elif atom.residue.name == '12C':
            colors[i] = color_12C
    colors = np.array(colors)
    # alpha = 0.2
    # colors = np.append(colors, [[alpha]]*len(colors), axis=1)
    positions_backbone = positions[ np.sort(list(set(bonds.reshape(-1)))) ]
    center = np.mean(positions_backbone, axis=0)

    #--------------------------------------------------------------------------------------
    # Calculate gyration eigenvectors

    # Gij = 1/N SUM_n:1_N [ rn_i * rn_j ]
    points = positions_backbone - np.mean(positions_backbone, axis=0)
    G = np.zeros((3,3))
    for i,j in itertools.product(range(3),range(3)):
        G[i,j] = np.sum(points[:,i]*points[:,j])
    G /= len(positions_backbone)

    w,v = scipy.linalg.eig(G)

    args = np.argsort(w)

    v1 = v[:,args[2]]
    v2 = v[:,args[1]]
    v3 = v[:,args[0]]

    
    #--------------------------------------------------------------------------------------
    # Draw fresnel scene

    # Sphere
    # scene = fresnel.Scene()
    # geometry = fresnel.geometry.Sphere(scene, N=len(positions), radius=np.array(radius),  outline_width = 0.01)
    # geometry.position[:] = positions
    # geometry.color[:] = colors #fresnel.color.linear(colors)

    for i,vi,vj in [['v3',v3,v1]]:
        # Cylinder
        scene = fresnel.Scene()
        # scene.background_color = [1, 1, 1]
        # scene.background_alpha = 1
        
        geometry = fresnel.geometry.Cylinder(scene, N=len(bonds), radius=radius_cylinder, outline_width=outline_width)
        geometry.points[:] = list(zip(positions[bonds[:,0]], positions[bonds[:,1]]))
        geometry.color[:] = list(zip(colors[bonds[:,0]], colors[bonds[:,1]]))
        geometry.material = fresnel.material.Material(
            # color=fresnel.color.linear([0.1, 0.1, 0.6]),
            roughness=0.5, 
            primitive_color_mix=1,
            # specular=0,
            spec_trans=1
            )
        

        # hbonds
        geometry = fresnel.geometry.Cylinder(scene, N=len(hbonds), radius=0.015, outline_width=0.005)
        geometry.points[:] = list(zip(posH, posA))
        geometry.color[:] = to_rgb('#325288')
        geometry.material = fresnel.material.Material(
            # color=fresnel.color.linear([0.1, 0.1, 0.6]),
            roughness=0.5, 
            primitive_color_mix=1,
            # specular=1,
            # spec_trans=1
            )


        scene.lights = fresnel.light.lightbox()

        scene.camera = fresnel.camera.Orthographic.fit(scene)

        scene.camera.position = 5 * vi + center
        scene.camera.look_at = center
        scene.camera.up = vj

        # scene.lights = fresnel.light.lightbox()
        if preview:
            out = fresnel.preview(scene)
        else:
            out = fresnel.pathtrace(scene, w=800, h=800)
            # out = fresnel.pathtrace(scene, w=800, h=800, samples=16, light_samples=32)
        
        PIL.Image.fromarray(out[:], mode='RGBA').save(i+filename)
Esempio n. 30
0
def create_json(self,isGPCR,trj_file,top_file,resi_to_group,resi_to_name,newpath,stride):
    out_file  = re.search("(\w*)(\.\w*)$" , newpath).group()
    self.stdout.write(self.style.NOTICE("Reading MD trajectory..."))
    num_frames=get_num_frames(trj_file,stride)
    it=md.iterload(filename=trj_file,chunk=(50/stride), top=top_file , stride=stride)
    f=0
    
    self.stdout.write(self.style.NOTICE("Analyzing Hbond network. It may take a while..."))
    hbond_frames = defaultdict(set)
    for t in it:
        for fnum,frame in enumerate(t[:]):
            hbonds = md.baker_hubbard(frame, periodic=True)
            for hbond in hbonds:
                resi_1 = t.topology.atom(hbond[0]).residue
                resi_2 = t.topology.atom(hbond[2]).residue
                if ((resi_1 != resi_2) and (resi_1.is_protein) and (resi_2.is_protein)):
                    if (resi_1.index < resi_2.index):
                        key = ((str(resi_1.resSeq),str(resi_1.chain.index)),(str(resi_2.resSeq),str(resi_2.chain.index)))
                    else:
                        key = ((str(resi_2.resSeq),str(resi_2.chain.index)),(str(resi_1.resSeq),str(resi_1.chain.index)))
                    hbond_frames[key].add(f)
            f+=1
        self.stdout.write(self.style.NOTICE("%d%% completed"%((f/num_frames)*100)))
    
    self.stdout.write(self.style.NOTICE("Writing hbonds to %s .."%out_file))
    #Collect entries for edges and trees (grouping of nodes)
    edge_entries = []
    tree_paths   = set()
    for resi1,resi2 in hbond_frames:
        if not resi1 in resi_to_name: continue
        if not resi2 in resi_to_name: continue
        resn1 = resi_to_name[resi1] if resi1 in resi_to_name else resi1[0]
        resn2 = resi_to_name[resi2] if resi2 in resi_to_name else resi2[0]
        if resn1=="None" or resn2=="None": continue

        framelist = sorted(list(hbond_frames[(resi1,resi2)]))
        helixinfo=get_cont_type(self,trj_file,resn1,resn2)
        if (helixinfo):
            edge_entries.append("    {\"name1\":\"%s\", \"name2\":\"%s\", \"frames\":%s, \"helixpos\":%s}"%(resn1,resn2,str(framelist),helixinfo))
        else:
            edge_entries.append("    {\"name1\":\"%s\", \"name2\":\"%s\", \"frames\":%s}"%(resn1,resn2,str(framelist)))

        tree_paths.add(resi_to_group[resi1]+"."+resn1)
        tree_paths.add(resi_to_group[resi2]+"."+resn2)


    #Collect entries for tracks (coloring of nodes)
    track_entries = []
    #helix_colors = ["#1500D6","#003D97","#00E600","#00E600","#FEE200","#FF9000","#FF3B00","#FF0000"]
    #helix_colors = ["#78C5D5","#459BA8","#79C268","#C5D747","#F5D63D","#F18C32","#E868A1","#BF63A6"]
    helix_colors = {1:"#78C5D5",12:"#5FB0BF",2:"#459BA8",23:"#5FAF88",3:"#79C268",34:"#9FCD58",4:"#C5D747",45:"#DDD742",5:"#F5D63D",56:"#F3B138",6:"#F18C32",67:"#ED7A6A",7:"#E868A1",78:"#D466A4",8:"#BF63A6"}
    if isGPCR:
        for tp in tree_paths:
            try:
                #res_name = tp[tp.rfind("x")+1:]
                res_name = tp.split(".",1)[1]
                res_helix = int(tp[tp.rfind(".")+1:tp.find("x")])
                track_entries.append("      { \"name\": \"%s\", \"color\": \"%s\" }"%(res_name,helix_colors[res_helix]))
            except ValueError: pass
            except IndexError: pass
            except KeyError: pass


        #Write everything
        with open(newpath,"w") as of:
            of.write("{\n")
            of.write("  \"edges\": [\n")
            of.write(",\n".join(edge_entries))
            of.write("\n")
            of.write("  ],\n")
            of.write("  \"nodes\": [\n")
            of.write(",\n".join(track_entries))
            of.write("\n")
            of.write("  ]\n")      
            of.write("}\n")      
          
    else:
        for tp in tree_paths:
            try:
                #res_name = tp[tp.rfind("x")+1:]
                res_name = tp[tp.rfind(".")+1:]
                res_helix = int(tp[tp.rfind(".")+1:tp.find("x")])
                track_entries.append("      { \"nodeName\": \"%s\", \"color\": \"%s\", \"size\":\"1.0\" }"%(res_name,helix_colors[res_helix]))
            except ValueError: pass
            except IndexError: pass
            except KeyError: pass


        #Write everything
        with open(newpath,"w") as of:
            of.write("{\n")
            of.write("  \"edges\": [\n")
            of.write(",\n".join(edge_entries))
            of.write("\n")
            of.write("  ],\n")
            of.write("  \"trees\": [\n")
            of.write("    {\n")
            of.write("      \"treeLabel\":\"Helices\",\n")
            of.write("      \"treePaths\": [\n")
            of.write(",\n".join(["        \""+tp+"\"" for tp in tree_paths]))
            of.write("\n")
            of.write("      ]\n")
            of.write("    }\n")
            of.write("  ],\n")
            of.write("  \"tracks\": [\n")
            of.write("    {\n")
            of.write("    \"trackLabel\": \"Helices\",\n")
            of.write("    \"trackProperties\": [\n")
            of.write(",\n".join(track_entries))
            of.write("\n")
            of.write("    ]}\n")
            of.write("  ],\n")
            of.write("  \"defaults\":{\"edgeColor\":\"rgba(50,50,50,100)\", \"edgeWidth\":2 }\n")
            of.write("}\n")
Esempio n. 31
0
        formatter_class=argparse.RawDescriptionHelpFormatter)

    #parser.add_argument('-', "--", help="", default="")

    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="be verbose")
    parser.add_argument("file", help="", default="", nargs='+')
    return parser


if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()

    if list != type(args.file):
        args.file = [args.file]

    for f in args.file:
        import mdtraj as md
        print(f, '---------------------')
        t = md.load(f)
        print(md.kabsch_sander(t))
        hb = md.wernet_nilsson(t)
        print(hb)
        print(len(hb[0]))
        hb = md.baker_hubbard(t)
        print(hb)
        print(len(hb))