示例#1
0
    def FillAtom(self,mol, atom, frag, fatom_idx):
        """
        find all the atom in fragment recursively
        input:
            mol, Class OBMol
            atom, Class OBAtom
            frag, Class OBMol
            fatom_idx, Record the atom has existed
        """
        frag.AddAtom(atom)
        fatom_idx.append(atom.GetIdx())
        if atom.GetValence == 0:
            return frag
        elif self.IsNearTerminal(atom):
            for _atom in ob.OBAtomAtomIter(atom):
                index = _atom.GetIdx()
                if index in fatom_idx: continue
                frag.AddAtom(_atom)
                fatom_idx.append(index)
            return frag
        else:
            for _atom in ob.OBAtomAtomIter(atom):
                index = _atom.GetIdx()
                if index in fatom_idx: continue
                elif _atom.GetValence == 1:
                    frag.AddAtom(_atom)
                    fatom_idx.append(index)
                else:
                    self.FillAtom(mol, _atom, frag, fatom_idx)

        return
示例#2
0
def CheckBondConnectivity(poltype,mol,optmol):
    atomitermol=openbabel.OBMolAtomIter(mol)
    atomiteroptmol=openbabel.OBMolAtomIter(optmol)
    for atm in atomitermol:
       
        atmidxmol=atm.GetIdx()
        
        atmoptmol=optmol.GetAtom(atmidxmol)
        atmidxoptmol=atmoptmol.GetIdx()
        atmneighbidxlist=[]
        iteratomatommol = openbabel.OBAtomAtomIter(atm)
        for newatm in iteratomatommol:
            atmneighbidxlist.append(newatm.GetIdx())
        atmneighbidxlistoptmol=[]
        iteratomatomoptmol = openbabel.OBAtomAtomIter(atmoptmol)
        for newatm in iteratomatomoptmol:
            atmneighbidxlistoptmol.append(newatm.GetIdx())
        if set(atmneighbidxlist)!=set(atmneighbidxlistoptmol):
            if len(set(atmneighbidxlist))>len(set(atmneighbidxlistoptmol)):
                diff=set(atmneighbidxlist)-set(atmneighbidxlistoptmol)
                idxset='mol'
            else:
                diff=set(atmneighbidxlistoptmol)-set(atmneighbidxlist)
                idxset='optmol'
            RaiseConnectivityError(poltype,diff,idxset)
示例#3
0
def _is_hydrogen_bond(protein_xyz, protein, ligand_xyz, ligand, contact,
                      hbond_angle_cutoff):
    '''
  Determine if a pair of atoms (contact = tuple of protein_atom_index, ligand_atom_index)
  between protein and ligand represents a hydrogen bond. Returns a boolean result.
  '''

    protein_atom_index = contact[0]
    ligand_atom_index = contact[1]
    protein_atom = protein.GetAtom(protein_atom_index + 1)
    ligand_atom = ligand.GetAtom(ligand_atom_index + 1)
    if protein_atom.IsHbondAcceptor() and ligand_atom.IsHbondDonor():
        for atom in ob.OBAtomAtomIter(ligand_atom):
            if atom.GetAtomicNum() == 1:
                hydrogen_xyz = ligand_xyz[atom.GetIndex(), :]
                vector_i = protein_xyz[protein_atom_index, :] - hydrogen_xyz
                vector_j = ligand_xyz[ligand_atom_index, :] - hydrogen_xyz
                return _is_angle_within_cutoff(vector_i, vector_j,
                                               hbond_angle_cutoff)

    elif ligand_atom.IsHbondAcceptor() and protein_atom.IsHbondDonor():
        for atom in ob.OBAtomAtomIter(protein_atom):
            if atom.GetAtomicNum() == 1:
                hydrogen_xyz = protein_xyz[atom.GetIndex(), :]
                vector_i = protein_xyz[protein_atom_index, :] - hydrogen_xyz
                vector_j = ligand_xyz[ligand_atom_index, :] - hydrogen_xyz
                return _is_angle_within_cutoff(vector_i, vector_j,
                                               hbond_angle_cutoff)

    return False
示例#4
0
def find_path2(mol,atom0_index,atom1_index):
    """
    Find the path between 2 atoms separated by 1 atom
    """
    atom0_index = atom0_index+1
    atom1_index = atom1_index+1
    atom_iter=ob.OBAtomAtomIter(mol.GetAtom(atom0_index))
    alist=[]
    
    index=0
    for a in atom_iter:
        alist.append(a.GetIdx())
        index=index+1
    #print('The list of bound atoms is:', alist)
    index=0
    depth=0
    finished=False
    for atom_index in alist:
        path=atom_index
        atom_iter=ob.OBAtomAtomIter(mol.GetAtom(atom_index))
        for a in atom_iter:
            #print(a.GetIdx())
            if a.GetIdx() ==atom1_index:
                finished=True
                break
            
        if finished:
            break
    if not finished:
        #print('Unable to find a path between atoms',atom0_index-1,' and ',atom1_index-1,'with a depth of 2')
        return -1
    path=path-1
    return path
示例#5
0
def ProAtomTyper(a):
    idx = a.GetIdx() - 1
    res = a.GetResidue().GetName()
    atype = a.GetType()
    nidx = a.GetAtomicNum()  #Zn,Mg,Ca,Fe,Mn,K
    pmf_type = ''
    if a.IsCarbon():  #CF,CP,cF,cP,CN,CO
        num_connected_het = 0
        for an in ob.OBAtomAtomIter(a):
            antype = an.GetType()
            if not an.IsCarbon() and not an.IsHydrogen():
                num_connected_het += 1
        if not a.IsAromatic():
            if num_connected_het == 0:
                pmf_type = 'CF'
            else:
                pmf_type = 'CP'
        else:
            if num_connected_het == 0:
                pmf_type = 'AF'
            else:
                pmf_type = 'AP'
        for an in ob.OBAtomAtomIter(a):
            if IsChargedN(an):
                pmf_type = 'CN'
                break
        for an in ob.OBAtomAtomIter(a):
            if IsChargedO(an):
                pmf_type = 'CO'
                break
    elif a.IsOxygen():  #OC,OA,OD,OW
        pmf_type = 'OA'
        if a.IsHbondDonor(
        ) or a.ImplicitHydrogenCount() > 0 or NumConnectH(a) > 0:
            pmf_type = 'OD'
        if IsChargedO(a):
            pmf_type = 'OC'
        if res == 'HOH' or res == "WAT":
            pmf_type = 'OW'
    elif a.IsNitrogen():  #NC,ND,NA
        pmf_type = 'NA'
        if a.IsHbondDonor(
        ) or a.ImplicitHydrogenCount() > 0 or NumConnectH(a) > 0:
            pmf_type = 'ND'
        if IsChargedN(a):
            pmf_type = 'NC'
    elif a.IsSulfur():  #SA,SD
        pmf_type = 'SA'
        if a.IsHbondDonor(
        ) or a.ImplicitHydrogenCount() > 0 or NumConnectH(a) > 0:
            pmf_type = 'SD'
    elif a.IsHydrogen():
        pmf_type = "HH"
    elif nidx in [30, 12, 20, 26, 25, 19, 11, 27, 28, 29, 80, 38,
                  48]:  #Zn,Mg,Ca,Fe,Mg,K,Na,Co,Ni,Cu,Hg,Sr,Cd
        pmf_type = 'ME'
    return pmf_type
示例#6
0
 def ComputeBondResidual(self, db):
     for f in self.frags:
         # constructing submolecule from the fragment
         efpmol = pyEFP.EFP2mol("./"+db.dirname+"/"+f.ename+"/"+f.fname+".efp")
         # fit atoms from the core lists
         rot, COMRef, COMFit = pyEFP.SolveKabsch(efpmol, f.subMol, f.efpcore, f.molcore)
         # deleting extra atoms
         complete = 0
         while (complete == 0):
             complete = 1
             for at in openbabel.OBMolAtomIter(efpmol):
                 extra = 0
                 if at.GetIndex()+1 not in f.efptotal:
                     extra = 1
                     for at1 in openbabel.OBAtomAtomIter(at):
                         if (at1.GetIndex()+1 in f.efptotal) and (at.GetAtomicNum() == 1):
                             extra = 0
                             break
                 if (extra == 1):
                     efpmol.DeleteAtom(at)
                     complete = 0
         efpmol.AddHydrogens()
         pyEFP.ApplyKabsch(efpmol, COMFit, COMRef, rot)
         for i in xrange(len(f.links)):
             dx = efpmol.GetAtom(f.links[i][0]).x() - self.frags[f.links[i][2]].subMol.GetAtom(f.links[i][4]).x() 
             dy = efpmol.GetAtom(f.links[i][0]).y() - self.frags[f.links[i][2]].subMol.GetAtom(f.links[i][4]).y() 
             dz = efpmol.GetAtom(f.links[i][0]).z() - self.frags[f.links[i][2]].subMol.GetAtom(f.links[i][4]).z()
             f.links[i].append(np.sqrt(dx*dx + dy*dy + dz*dz))
示例#7
0
def mol_find_all_paths(mol, start, end, coupling_length, path=[]):
    # append atom to start
    path = path + [start]
    # check if we have reached target atom
    if start == end:
        # if we have, return succesful path
        if len(path) == 1:
            return []
        else:
            return [path]
    # define new path
    paths = []
    # loop over neighbouring atoms
    for nbr_atom in openbabel.OBAtomAtomIter(mol.atoms[start].OBAtom):
        # get ID of neighbour
        node = nbr_atom.GetId()
        # check the neighbour is not already in the path, and that the path is not over the required length
        if node not in path and len(path) <= coupling_length:
            # get new paths for the neighbour
            newpaths = mol_find_all_paths(mol, node, end, coupling_length,
                                          path)
            #for each new path, check for paths of correct length
            for newpath in newpaths:
                if len(newpath) == coupling_length + 1 and newpath != []:
                    paths.append(newpath)

    return paths
示例#8
0
def save_structfile(poltype,molstruct, structfname):
    """
    Intent: Output the data in the OBMol structure to a file (such as *.xyz)
    Input:
        molstruct: OBMol structure
        structfname: output file name
    Output:
        file is output to structfname
    Referenced By: tor_opt_sp, compute_mm_tor_energy
    Description: -
    """
    strctext = os.path.splitext(structfname)[1]
    tmpconv = openbabel.OBConversion()
    if strctext in '.xyz':
        tmpfh = open(structfname, "w")
        maxidx =  max(poltype.symmetryclass)
        iteratom = openbabel.OBMolAtomIter(molstruct)
        etab = openbabel.OBElementTable()
        tmpfh.write('%6d   %s\n' % (molstruct.NumAtoms(), molstruct.GetTitle()))
        for ia in iteratom:
            tmpfh.write( '%6d %2s %13.6f %11.6f %11.6f %5d' % (ia.GetIdx(), etab.GetSymbol(ia.GetAtomicNum()), ia.x(), ia.y(), ia.z(), poltype.prmstartidx + (maxidx - poltype.symmetryclass[ia.GetIdx() - 1])))
            iteratomatom = openbabel.OBAtomAtomIter(ia)
            neighbors = []
            for iaa in iteratomatom:
                neighbors.append(iaa.GetIdx())
            neighbors = sorted(neighbors)
            for iaa in neighbors:
                tmpfh.write('%5d' % iaa)
            tmpfh.write('\n')
    else:
        inFormat = openbabel.OBConversion.FormatFromExt(structfname)
        tmpconv.SetOutFormat(inFormat)
    return tmpconv.WriteFile(molstruct, structfname)
示例#9
0
def nbr_smarts(a1, a2=None):
    # construct smarts of each neighbor, possible excluding a2
    smarts = []  # each neighbor as array element for later sort
    for nbr in openbabel.OBAtomAtomIter(a1):
        if nbr.GetAtomicNum() == 1: continue
        #if a2 and nbr.GetIdx() == a2.GetIdx():
        # continue
        # include bond order if necessary (not single or aromatic)
        b = a1.GetBond(nbr)
        if b.IsSingle() and a1.IsAromatic():
            bnd = "-"
        elif b.IsDouble():
            bnd = "="
        elif b.IsTriple():
            bnd = "#"
        else:
            bnd = ""
        smarts.append(bnd + atom_sym(nbr, True))
    # now sort each neighbor smarts to provide unique ordering
    smarts.sort()
    slen = len(smarts)
    sma = ""
    # assemble final smarts, if there are neighbors
    if slen > 0:
        # include parens when 2 or more neighbors
        for i in range(0, slen - 1):
            sma += "(" + smarts[i] + ")"
        sma += smarts[slen - 1]
    return sma
示例#10
0
def assign_atom_types(selection='all'):
    """
    TODO document me!

    read http://openbabel.org/dev-api/classOpenBabel_1_1OBAtom.shtml#ae09ed28481ac044dab3f31c8605b44a9
    for available functions provided by openbabel to extract atom properties. There is a GetType() function
    but I found that function very limited.
    """
    atom_types = []
    pdb_string = cmd.get_pdbstr(selection)
    mol = ob.OBMol()
    obconversion = ob.OBConversion()
    obconversion.SetInAndOutFormats('pdb', 'pdb')
    obconversion.ReadString(mol, pdb_string)
    rings = mol.GetSSSR()
    for at in ob.OBMolAtomIter(mol):
        ring_member = [ring.IsMember(at) for ring in rings]
        neighbors = [
            neighbor.GetAtomicNum() for neighbor in ob.OBAtomAtomIter(at)
        ]
        atom_types.append(
            (at.GetIndex(), at.GetAtomicNum(), at.GetHvyValence(),
             any(ring_member), at.IsAromatic(), at.MemberOfRingCount(),
             (neighbors)))
    return atom_types
示例#11
0
def AtLeastOneHeavyNeighb(poltype, atom):
    foundatleastoneheavy = False
    checkneighbs = [neighb for neighb in openbabel.OBAtomAtomIter(atom)]
    for neighb in checkneighbs:
        if neighb.GetAtomicNum() != 1:
            foundatleastoneheavy = True
    return foundatleastoneheavy
示例#12
0
文件: align.py 项目: wuyulele/Scripts
def GetNewBondVector(mol, idx, nvpf):
    atom = mol.OBMol.GetAtom(idx)
    nbrvecs = []
    newbond = np.zeros((3))
    nbrs = []
    for nbr in ob.OBAtomAtomIter(atom):
        # shouldn't really be += ...
        newbond += np.array([
            atom.GetX() - nbr.GetX(),
            atom.GetY() - nbr.GetY(),
            atom.GetZ() - nbr.GetZ()
        ])
        nbrvecs.append([
            atom.GetX() - nbr.GetX(),
            atom.GetY() - nbr.GetY(),
            atom.GetZ() - nbr.GetZ()
        ])
        nbrs.append(nbr)

    if atom.GetValence() == 2:
        ang = mol.OBMol.GetAngle(nbrs[0], atom, nbrs[1])
        #print ang
        if ang > 175.:
            newbond = cross_with_axis(atom)

    if atom.GetValence() == 3:
        imptorv = mol.OBMol.GetTorsion(nbrs[0], atom, nbrs[1], nbrs[2])
        if abs(imptorv):
            newbond = planar_cross(atom, nbrs)
            nvpf = nvpf + 1

    newbond = newbond / np.linalg.norm(newbond)
    return newbond, nvpf
示例#13
0
    def get_connectivity(self):
        '''
        Retrieve the connectivity matrix of the molecule.

        Returns:
            numpy.ndarray: (n_atoms x n_atoms) array containing the pairwise bond orders
                between atoms (0 for no bond).
        '''
        if self._connectivity is None:
            # get connectivity matrix
            connectivity = np.zeros((self.n_atoms, len(self.numbers)))
            for atom in ob.OBMolAtomIter(self.get_obmol()):
                index = atom.GetIdx() - 1
                # loop over all neighbors of atom
                for neighbor in ob.OBAtomAtomIter(atom):
                    idx = neighbor.GetIdx() - 1
                    bond_order = neighbor.GetBond(atom).GetBO()
                    #print(f'{index}-{idx}: {bond_order}')
                    # do not count bonds between two hydrogen atoms
                    if (self.numbers[index] == 1 and self.numbers[idx] == 1
                            and bond_order > 0):
                        bond_order = 0
                    connectivity[index, idx] = bond_order
            self._connectivity = connectivity
        return self._connectivity
示例#14
0
def __count_bonds(a1, a2, exclude):
    """Count number of bonds between two pharmacophore points, if the shortest
    path does not contain any other pharmacophore point.

    Args:
       a1, a2 (OBAtom): source and target atoms
       exclude (list): atoms (ids) that cannot be in the shortest path

    Returns:
       int: number of bonds in path or -1 if there is no path between a1 and a2
    """
    visited = []
    bonds_nr = -1
    queue = deque([(a1, 0)])
    while queue:
        atom, depth = queue.popleft()
        idx = atom.GetIdx()
        visited.append(idx)
        if atom == a2:
            bonds_nr = depth
            break
        else:
            for atom in ob.OBAtomAtomIter(atom):
                if atom.GetIdx() not in visited and atom.GetIdx() not in exclude:
                    queue.append((atom, depth+1))
    return bonds_nr
示例#15
0
def separateFragments(pymol, dist=3.0):
    mol = pymol.OBMol
    nAtom = len(pymol.atoms)
    unvisited = set(range(1, nAtom + 1))
    q = deque([1])
    fragments = [set()]
    while q or unvisited:
        if q:
            curr = q.popleft()
            unvisited.remove(curr)
            fragments[-1].add(curr)
        else:
            curr = unvisited.pop()
            fragments.append({curr})
        atom = mol.GetAtom(curr)
        for nbr in ob.OBAtomAtomIter(atom):
            nbrNum = nbr.GetIdx()
            if nbrNum in unvisited:
                q.append(nbrNum)
    coords = []
    for atom in pymol:
        coords.append(list(atom.coords))
    nFragments = len(fragments)
    delta = -(nFragments - 1) * dist / 2.0
    for fragment in fragments:
        for atomIdx in fragment:
            x, y, z = coords[atomIdx - 1]
            coords[atomIdx - 1] = [x + delta, y + delta, z + delta]
        delta += dist
    coords = [item for sublist in coords for item in sublist]
    c_coords = ob.double_array(coords)
    mol.SetCoordinates(c_coords)
示例#16
0
def gen_pocket_graph(pocket):
    """
    generate molecular graph 
    """
    edge_l = []
    idx_map = [-1] * (len(pocket.atoms) + 1)
    idx_new = 0
    for atom in pocket:
        edges = []
        a1_sym = atom.atomicnum
        a1 = atom.idx
        if a1_sym == 1:
            continue
        idx_map[a1] = idx_new
        idx_new += 1
        for natom in openbabel.OBAtomAtomIter(atom.OBAtom):
            if natom.GetAtomicNum() == 1:
                continue
            a2 = natom.GetIdx()
            bond = openbabel.OBAtom.GetBond(natom, atom.OBAtom)
            bond_t = bond.GetBondOrder()
            edges.append((a1, a2, bond_t))
        edge_l += edges
    edge_l_new = []
    for a1, a2, t in edge_l:
        a1_, a2_ = idx_map[a1], idx_map[a2]
        assert ((a1_ != -1) & (a2_ != -1))
        edge_l_new.append((a1_, a2_, t))
    return edge_l_new
示例#17
0
    def ret_partition(self,cutBonds=[]):
        """
        Return a partition according to different non-bonded molecules.
        cutBonds is a list of tuples for bonds to cut. The order does not matter
        e.g. cutBonds=[(3,4),(7,8)]
        """
        at_lists = []
        chk_list = []
        remaining_atoms = [self.mol.NumAtoms()-i for i in xrange(self.mol.NumAtoms())]

        while(len(remaining_atoms)>0): # do the loop as long as there are still atoms which are not in at_lists
            if len(chk_list) > 0:
                curr_at = chk_list.pop()
            else:
                #print 'new at_list'
                at_lists.append([])
                curr_at = remaining_atoms.pop()
                at_lists[-1].append(curr_at)
            #print 'curr_at:',curr_at

            atom = self.mol.GetAtom(curr_at)
            for bonded in openbabel.OBAtomAtomIter(atom):
                bind = bonded.GetIdx()
                if bind in remaining_atoms:
                    if  (curr_at,bind) in cutBonds or (bind,curr_at) in cutBonds:
                        print 'cutting bond %i-%i'%(curr_at,bind)
                    else:
                        del remaining_atoms[remaining_atoms.index(bind)]
                        chk_list.append(bind)
                        at_lists[-1].append(bind)
                        #print bind



        return at_lists
示例#18
0
def connect_two_binders(binder1, binder1_smiles, binder2, binder2_smiles,
                        linker, linker_smiles1, linker_smiles2):
    b1 = get_binder_atom(binder1, binder1_smiles).GetIdx()
    b2 = get_binder_atom(binder2, binder2_smiles).GetIdx()
    linker_atom1, linker_atom2 = get_linker_atoms(linker, linker_smiles1,
                                                  linker_smiles2)
    l1 = linker_atom1.GetIdx()
    l2 = linker_atom2.GetIdx()

    linked = openbabel.OBMol()
    linked += binder1
    linked += linker
    linked += binder2

    idx_b1 = b1
    idx_l1 = binder1.NumAtoms() + l1
    idx_l2 = binder1.NumAtoms() + l2
    idx_b2 = binder1.NumAtoms() + linker.NumAtoms() + b2

    bond_order = 1
    linked.AddBond(idx_b1, idx_l1, bond_order)
    linked.AddBond(idx_b2, idx_l2, bond_order)

    foo = []
    for index in idx_b1, idx_l1, idx_l2, idx_b2:
        atom = linked.GetAtom(index)
        for child in openbabel.OBAtomAtomIter(atom):
            if child.IsHydrogen():
                j = child
        foo.append(j)
    for killme in foo:
        linked.DeleteAtom(killme)

    return linked
示例#19
0
def get_pairs(mol):
    infty = -1

    distPairs = []
    # run BFS exploration for each atom to find the distance to others
    for atom in mol.atoms:
        q = Queue()

        vis = [False] * len(mol.atoms)
        dist = [infty] * len(mol.atoms)

        vis[atom.idx - 1] = True
        dist[atom.idx - 1] = 0
        q.put(atom)

        while not q.empty():
            k = q.get()
            # mark children as visited and queue them
            children = [
                pybel.Atom(x) for x in openbabel.OBAtomAtomIter(k.OBAtom)
            ]
            for child in children:
                if not vis[child.idx - 1]:
                    vis[child.idx - 1] = True
                    dist[child.idx - 1] = dist[k.idx - 1] + 1
                    q.put(child)

        for i in range(len(mol.atoms)):
            if (dist[i] == 3):
                pair1 = "%d %d" % (atom.idx, i + 1)
                pair2 = "%d %d" % (i + 1, atom.idx)
                if (pair1 not in distPairs) and (pair2 not in distPairs):
                    distPairs.append(pair1)

    return distPairs
示例#20
0
 def FitCoords(self, db):
     Fitmol = openbabel.OBMol()
     for f in self.frags:
         # constructing submolecule from the fragment
         efpmol = pyEFP.EFP2mol("./"+db.dirname+"/"+f.ename+"/"+f.fname+".efp")
         # fit atoms from the core lists
         sys.stdout.flush()
         rot, COMRef, COMFit = pyEFP.SolveKabsch(efpmol, f.subMol, f.efpcore, f.molcore)
         f.rotat = [rot, COMRef, COMFit]
         # deleting extra atoms
         complete = 0
         while (complete == 0):
             complete = 1
             for at in openbabel.OBMolAtomIter(efpmol):
                 extra = 0
                 if at.GetIndex()+1 not in f.efpcore:
                     extra = 1
                     for at1 in openbabel.OBAtomAtomIter(at):
                         if (at1.GetIndex()+1 in f.efpcore) and (at.GetAtomicNum() == 1):
                             extra = 0
                             break
                 if (extra == 1):
                     efpmol.DeleteAtom(at)
                     complete = 0
         pyEFP.ApplyKabsch(efpmol, COMFit, COMRef, rot)
         Fitmol += efpmol
     return Fitmol
示例#21
0
def gen_canonicallabels(poltype,mol):
    poltype.symmetryclass = [ 0 ] * mol.NumAtoms()
    """
    Intent: Find the symmetry class that each atom belongs to
    Input: 
        mol: OBMol object 
    Output: 
        The global variable 'symmetryclass' is altered
    Referenced By: main
    Description:
    1. An empty bit vector is created, 'frag_atoms'
    2. OBMol.FindLargestFragment is called to fill in the 'frag_atoms' bit vector (the
    vector is filled with a 1 or 0 depending on whether the atom is part of the largest
    fragment or not)
    3. 'CalculateSymmetry' method is called to find initial symmetry classes
    4. Terminal atoms of the same element are collapsed to one symmetry class
    5. Possibly renumber the symmetry classes
    """
    # Returns symmetry classes for each atom ID
    frag_atoms = openbabel.OBBitVec()
    symmclasslist = []
    mol.FindLargestFragment(frag_atoms)
    CalculateSymmetry(poltype,mol, frag_atoms, symmclasslist)
    for ii in range(len(poltype.symmetryclass)):
        poltype.symmetryclass[ii] = symmclasslist[ii][1]

    # Collapse terminal atoms of same element to one type
    for a in openbabel.OBMolAtomIter(mol):
        for b in openbabel.OBAtomAtomIter(a):
            if b.GetValence() == 1:
                for c in openbabel.OBAtomAtomIter(a):
                    if ((b is not c) and
                        (c.GetValence() == 1) and
                        (b.GetAtomicNum() == c.GetAtomicNum()) and
                        (poltype.symmetryclass[b.GetIdx()-1] !=
                            poltype.symmetryclass[c.GetIdx()-1])):
                        poltype.symmetryclass[c.GetIdx()-1] = \
                            poltype.symmetryclass[b.GetIdx()-1]

    # Renumber symmetry classes
    allcls=list(set(poltype.symmetryclass))
    allcls.sort()
    for ii in range(len(poltype.symmetryclass)):
        poltype.symmetryclass[ii] = allcls.index(poltype.symmetryclass[ii]) + 1
示例#22
0
 def get_bonds(self, mol, atom_id):
     #for a given atom in a molecule finds the bonds
     natoms=mol.NumAtoms()
     bonds=[]
     obatom = mol.GetAtom(atom_id+1)
     id1 = obatom.GetIndex()
     for n_atom in openbabel.OBAtomAtomIter(obatom):
         id2 = n_atom.GetIndex()
         bonds.append((id1, id2))
     return bonds
示例#23
0
    def get_all_torsions(self):
        """
        enumerate Torsions in a molecule
        """

        m = self.m
        #m.DeleteHydrogens()

        torsionSmarts = '[!$(*#*)&!D1]~[!$(*#*)&!D1]'
        q = pb.Smarts(torsionSmarts)
        iok = q.obsmarts.Match(m)

        torsions = {}
        tts = []
        for match in q.obsmarts.GetMapList():
            ia2, ia3 = match
            a2, a3 = m.GetAtom(ia2), m.GetAtom(ia3)
            hyb2, hyb3 = a2.GetHyb(), a3.GetHyb()

            if (hyb2 not in [2, 3]) or (hyb3 not in [2, 3]):
                # no formal torsion here !
                continue

            for a1 in ob.OBAtomAtomIter(a2):
                ia1 = a1.GetIdx()
                if ia1 == ia3:
                    continue

                for a4 in ob.OBAtomAtomIter(a3):
                    ia4 = a4.GetIdx()
                    if ia4 in [ia2, ia1
                               ]:  # when ia4 == ia1, it means 3-membered ring
                        continue
                    else:
                        torsion_1 = (ia1, ia2, ia3, ia4)
                        torsion_2 = (ia4, ia3, ia2, ia1)
                        if torsion_1 not in tts:
                            torsions[torsion_1] = m.GetTorsion(
                                ia1, ia2, ia3, ia4)
                            tts.append(torsion_1)
                            tts.append(torsion_2)
        return torsions
示例#24
0
def apply_cistrans(mol, bond_id, refs):
    import openbabel as ob
    bond = mol.GetBond(bond_id)
    if not refs: return
    if bond.GetBO() != 2:
        print('Non-double bond has cistrans stereo')
        return
    neighbors1 = [n.GetId() for n in ob.OBAtomAtomIter(bond.GetBeginAtom())]
    neighbors2 = [n.GetId() for n in ob.OBAtomAtomIter(bond.GetEndAtom())]
    
    #print(f'applying cistrans {refs} to bond {bond_id}, neighbors: {neighbors1} {neighbors2}')
    IMPLICIT_REF = 4294967294
    ct_stereo = ob.OBCisTransStereo(mol)
    config = ct_stereo.GetConfig()
    config.begin = bond.GetBeginAtom().GetId()
    config.end = bond.GetEndAtom().GetId()
    config.refs = [(r if r is not None else IMPLICIT_REF) for r in refs]
    config.specified = True
    ct_stereo.SetConfig(config)
    mol.CloneData(ct_stereo)
示例#25
0
文件: protein.py 项目: bwbai/bpforms
    def is_terminus(self, atom_n, atom_c):
        """ Determine if a pair of atoms are N- and C-termini

        Args:
            atom_n (:obj:`openbabel.OBAtom`): potential N-terminus
            atom_c (:obj:`openbabel.OBAtom`): potential C-terminus

        Returns:
            :obj:`bool`: :obj:`True`, if the atoms are N- and C-termini
        """
        atom_n_neighbors = set((atom.GetIdx(), atom.GetAtomicNum())
                               for atom in openbabel.OBAtomAtomIter(atom_n))
        atom_c_neighbors = set((atom.GetIdx(), atom.GetAtomicNum())
                               for atom in openbabel.OBAtomAtomIter(atom_c))
        connecting_atoms = atom_n_neighbors.intersection(atom_c_neighbors)

        for idx, atomic_num in connecting_atoms:
            if atomic_num == 6:
                return True

        return False
示例#26
0
def find_path3(mol,atom0_index,atom1_index):
   atom0_index = atom0_index+1
   atom1_index = atom1_index+1
   atom_iter=ob.OBAtomAtomIter(mol.GetAtom(atom0_index))
   alist=[]
    
   path=[0 ,0]
   index=0
   for a in atom_iter:
       alist.append(a.GetIdx())
   #print('The list of atoms bound to[',atom0_index,']is:', alist)
   index=0
   depth=0
   finished=False
   for atom_index in alist:
       path[0]=atom_index
       atom_iter=ob.OBAtomAtomIter(mol.GetAtom(atom_index))
       alist2=[]
       for a in atom_iter:
           alist2.append(a.GetIdx())
       #print('The atoms connected to atom',path[0],'are:', alist2)    
       for atom_index2 in alist2:
           path[1]=atom_index2
           atom_iter2=ob.OBAtomAtomIter(mol.GetAtom(atom_index2))
           #print('The atoms connected to',path[1],'are:')
           for a2 in atom_iter2:
               #print(a2.GetIdx())
               if a2.GetIdx() ==atom1_index:
                   finished=True
                   break
           if finished: 
               break
       if finished:
           break
   if not finished:
       print('Unable to find a path between atoms',atom0_index-1,' and ',atom1_index-1,'with a depth of 3')
       return [-1,-1]
   path[0]=path[0]-1
   path[1]=path[1]-1
   return path
示例#27
0
 def get_bonds2(self, mol, atom_id):
     #for a given atom in a molecule find the bonds
     natoms=mol.NumAtoms()
     bonds=[]
     obatom = mol.GetAtom(atom_id)
     id1 = obatom.GetIndex()
     t1 = obatom.GetType()
     for n_atom in openbabel.OBAtomAtomIter(obatom):
         id2 = n_atom.GetIndex()
         t2=n_atom.GetType()
         bond = obatom.GetBond(n_atom)
         bonds.append((id1+1, id2+1))
     return bonds
示例#28
0
文件: align.py 项目: wuyulele/Scripts
def planar_cross(atom, nbrs):
    xs = []
    for nbr in ob.OBAtomAtomIter(atom):
        xs.append([
            -atom.GetX() + nbr.GetX(), -atom.GetY() + nbr.GetY(),
            -atom.GetZ() + nbr.GetZ()
        ])

    xs[0] = xs[0] / np.linalg.norm(xs[0])
    xs[1] = xs[1] / np.linalg.norm(xs[1])

    v1 = np.cross(xs[0], xs[1])
    return v1
示例#29
0
def find_tor_restraint_idx(poltype,mol,b1,b2):
    """
    Intent: Find the atoms 1 and 4 about which torsion angles are restrained
    Given b1, b2, finds the torsion: t1 b1 b2 t4
    Input:
        mol: OBMol object
        b1: first atom of the rotatable bond (t2 in the torsion)
        b2: second atom of the rotatable bond (t3 in the torsion)
    Output:
        t1: atom 1 in the torsion
        t4: atom 4 in the torsion
    Referenced By: get_torlist
    Description:
    1. Find the heaviest (heaviest meaning of highest sym class) 
       atom bound to atom b1 (that is not b2)
    2. Find the heaviest atom bound to atom b2 (that is not b1)
    3. These two atoms are returned as atoms 1 and 4 for the torsion
    """
    b1idx = b1.GetIdx()
    b2idx = b2.GetIdx()
    iteratomatom = openbabel.OBAtomAtomIter(b1)
    b1nbridx = list(map(lambda x: x.GetIdx(), iteratomatom))
    del b1nbridx[b1nbridx.index(b2idx)]    # Remove b2 from list
    assert(b1nbridx is not [])
    maxb1class = max(b1nbridx,key=lambda x: symm.get_symm_class(poltype,x))

    iteratomatom = openbabel.OBAtomAtomIter(b2)
    b2nbridx = list(map(lambda x: x.GetIdx(), iteratomatom))
    del b2nbridx[b2nbridx.index(b1idx)]    # Remove b1 from list
    assert(b2nbridx is not [])
    maxb2class = max(b2nbridx, key= lambda x:symm.get_symm_class(poltype,x))


    t1 = mol.GetAtom(maxb1class)
    t4 = mol.GetAtom(maxb2class)


    return t1,t4
def mol_read_conn(mol):
    """
    Get connectivity of molecule
    """
    atoms = len(mol.atoms)
    conn_mat = np.zeros((atoms, atoms), dtype=int)
    for a1 in range(atoms):
        for nbr_atom in openbabel.OBAtomAtomIter(mol.atoms[a1].OBAtom):
            a2 = nbr_atom.GetId()
            bond = mol.atoms[a1].OBAtom.GetBond(nbr_atom)
            conn_mat[a1][a2] = 1
            conn_mat[a2][a1] = 1

    return conn_mat