Ejemplo n.º 1
0
 def read_chem_comp_bond_atom_ids(self, fields, field_dict, values):
     try:
         label_1 = field_dict['_chem_comp_bond_atom_id_1']
         label_2 = field_dict['_chem_comp_bond_atom_id_2']
     except KeyError:
         return False
     order_table = {'sing': 1, 'doub': 2, 'trip': 3, 'delo': 4}
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom, 'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     order = field_dict.get('_chem_comp_bond_value_order', None)
     for value in values:
         try:
             index = [
                 name_dict[self.index_to_str(label_1, value)],
                 name_dict[self.index_to_str(label_2, value)]
             ]
         except KeyError:
             print(" CIF _chem_comp_bond_atom_id, invalid keys:", value)
             continue
         bond = Bond()
         bond.index = index
         if order is not None:
             order_string = self.index_to_str(order, value).lower()
             bond.order = order_table.get(order_string[0:4], 1)
         else:
             bond.order = 1
         self.model.bond.append(bond)
     # don't do distance-based bonding
     self.model.connect_mode = 1
     return True
Ejemplo n.º 2
0
Archivo: cif.py Proyecto: evonove/pymol
 def read_chem_comp_bond_atom_ids(self,fields,field_dict,values):
     try:
         label_1 = field_dict['_chem_comp_bond_atom_id_1']
         label_2 = field_dict['_chem_comp_bond_atom_id_2']
     except KeyError:
         return False
     order_table = { 'sing' : 1, 'doub' : 2, 'trip' :3, 'delo': 4 }
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom,'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     order = field_dict.get('_chem_comp_bond_value_order',None)
     for value in values:
         try:
             index = [name_dict[self.index_to_str(label_1, value)],
                      name_dict[self.index_to_str(label_2, value)]]
         except KeyError:
             print " CIF _chem_comp_bond_atom_id, invalid keys:", value
             continue
         bond = Bond()
         bond.index = index
         if order != None:
             order_string = self.index_to_str(order,value).lower()
             bond.order = order_table.get(order_string[0:4],1)
         else:
             bond.order = 1
         self.model.bond.append(bond)
     # don't do distance-based bonding
     self.model.connect_mode = 1
     return True
Ejemplo n.º 3
0
 def parse_bond_block(self,count,spec,data,full):
     handler = {
         'i_m_from' : lambda x,a:a.index.__setitem__(0,int(x)-1),
         'i_m_to' : lambda x,a:a.index.__setitem__(1,int(x)-1),
         'i_m_order' : lambda x,a:setattr(a,'order',int(x)),
         'i_m_from_rep': handler_i_m_from_rep,
         'i_m_to_rep': handler_i_m_to_rep,
         'b_m_thin_bond': lambda x,a: int(x) and setattr(a,'stick_radius', 0.08),
         }
     fn_list = [ lambda x,a:setattr(a,'id',int(x)) ]
     for code in spec:
         fn_list.append(handler.get(code, dummy_handler))
     if full != None:
         count = len(data)/len(fn_list)
         bond_list = deepcopy(full)
     else:
         bond_list = []
     data.reverse()
     try:
         for a in range(count):
             if full == None:
                 bd = Bond()
                 bd.index = [0,0]
                 bond_list.append(bd)
             else:
                 bd = bond_list[int(data[-1])-1] # trusting index
             for fn in fn_list:
                 fn(data.pop(), bd)
     except IndexError:
         pass
     return bond_list
Ejemplo n.º 4
0
def bondseeker(model, nbr, excludeH=True, ceil=BONDNOHMAX):
    pairs = []
    for i, at in enumerate(model.atom):
        if at.symbol == "H" and excludeH:
            continue
        if at.symbol != "H" and not excludeH:
            continue
        lst = nbr.get_neighbors(at.coord)
        for b in lst:
            at2 = model.atom[b]
            if at2.symbol == 'H':  #we can always exclude these, since we don't expect to find H-H bonds. If you want to add H2 molecules, you are not in luck, I guess
                continue
            if excludeH and [
                    b, i
            ] in pairs:  #we can save some comparisons because if we are not excluding H, we are sure that at is an H, and at2 isn't, so the pair [at2,at1] can never be added.
                continue
            dst = chempy.cpv.distance(at.coord, at2.coord)
            if dst > ceil:
                if not (at.symbol == "S" and at2.symbol == "S"
                        and dst < SSBONDMAX):  #allow for SS bonds.
                    continue
            pairs.append([i, b])
            bnd = Bond()
            bnd.index = [i, b]
            bnd.order = 1  #yeah, not going to do the proper bond order.
            model.bond.append(bnd)
Ejemplo n.º 5
0
Archivo: cif.py Proyecto: evonove/pymol
    def read_struct_conn_(self, loop):
        try:
            type_id   = loop.get_col_idx('_struct_conn.conn_type_id')

            asym_id_1 = loop.get_col_idx('_struct_conn.ptnr1_auth_asym_id',
                                         '_struct_conn.ptnr1_label_asym_id')
            comp_id_1 = loop.get_col_idx('_struct_conn.ptnr1_auth_comp_id',
                                         '_struct_conn.ptnr1_label_comp_id')
            seq_id_1  = loop.get_col_idx('_struct_conn.ptnr1_auth_seq_id',
                                         '_struct_conn.ptnr1_label_seq_id')
            atom_id_1 = loop.get_col_idx('_struct_conn.ptnr1_label_atom_id')

            asym_id_2 = loop.get_col_idx('_struct_conn.ptnr2_auth_asym_id',
                                         '_struct_conn.ptnr2_label_asym_id')
            comp_id_2 = loop.get_col_idx('_struct_conn.ptnr2_auth_comp_id',
                                         '_struct_conn.ptnr2_label_comp_id')
            seq_id_2  = loop.get_col_idx('_struct_conn.ptnr2_auth_seq_id',
                                         '_struct_conn.ptnr2_label_seq_id')
            atom_id_2 = loop.get_col_idx('_struct_conn.ptnr2_label_atom_id')
        except KeyError:
            return False

        alt_id_1   = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr1_label_alt_id')
        ins_code_1 = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr1_pdb_ins_code')
        symm_1     = loop.get_col_idx_opt('_struct_conn.ptnr1_symmetry')
        alt_id_2   = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr2_label_alt_id')
        ins_code_2 = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr2_pdb_ins_code')
        symm_2     = loop.get_col_idx_opt('_struct_conn.ptnr2_symmetry')

        idxs_1 = [asym_id_1, comp_id_1, seq_id_1, ins_code_1, atom_id_1, alt_id_1]
        idxs_2 = [asym_id_2, comp_id_2, seq_id_2, ins_code_2, atom_id_2, alt_id_2]

        # atoms indexed by atomic identifiers
        atom_dict = dict(((a.chain, a.resn, a.resi,
            getattr(a, 'ins_code', ''), a.name, a.alt), i)
            for (i, a) in enumerate(self.model.atom))

        for row in loop.rows:
            if self.index_to_str(type_id, row).lower() != 'covale':
                # ignore non-covalent bonds (metalc, hydrog)
                continue
            if self.index_to_str(symm_1, row) != self.index_to_str(symm_2, row):
                # don't bond to symmetry mates
                continue
            key_1 = tuple(self.index_to_str(i, row) for i in idxs_1)
            key_2 = tuple(self.index_to_str(i, row) for i in idxs_2)
            try:
                index = [atom_dict[key_1], atom_dict[key_2]]
            except KeyError:
                print " CIF _struct_conn, invalid keys:", row
                continue
            bond = Bond()
            bond.index = index
            self.model.bond.append(bond)
        return True
Ejemplo n.º 6
0
def load_rigimol_inp(filename, oname, _self=cmd):
    '''
DESCRIPTION

    Load the structures from a RigiMOL "inp" file.
    '''
    import shlex
    from chempy import Atom, Bond, models

    parsestate = ''
    model = None
    state = 0

    for line in open(filename):
        lex = shlex.shlex(line, posix=True)
        lex.whitespace_split = True
        lex.quotes = '"'
        a = list(lex)

        if not a:
            continue

        if a[0] == '+':
            if a[1] == 'NAME':
                assert a[2:] == [
                    'RESI', 'RESN', 'CHAIN', 'SEGI', 'X', 'Y', 'Z', 'B'
                ]
                parsestate = 'ATOMS'
                model = models.Indexed()
            elif a[1] == 'FROM':
                assert a[2:] == ['TO']
                parsestate = 'BONDS'
            else:
                parsestate = ''
        elif a[0] == '|':
            if parsestate == 'ATOMS':
                atom = Atom()
                atom.coord = [float(x) for x in a[6:9]]
                atom.name = a[1]
                atom.resi = a[2]
                atom.resn = a[3]
                atom.chain = a[4]
                atom.segi = a[5]
                atom.b = a[9]
                atom.symbol = ''
                model.add_atom(atom)
            elif parsestate == 'BONDS':
                bnd = Bond()
                bnd.index = [int(a[1]), int(a[2])]
                model.add_bond(bnd)
        elif a[0] == 'end':
            if parsestate in ('ATOMS', 'BONDS'):
                state += 1
                _self.load_model(model, oname, state=state)
            parsestate = ''
Ejemplo n.º 7
0
def cap(object):
    from pymol import cmd
    
    model = cmd.get_model(object)
    # guarantee identical ordering
    cmd.delete(object)
    cmd.load_model(model,object)
    n_list = cmd.identify("(n;n &!(n;c a;2.0))")
    c_list = cmd.identify("(n;c &!(n;n a;2.0))")
    print n_list
    print c_list
    for a in n_list:
        newat = copy.deepcopy(model.atom[a])
        newat.coord = [
            newat.coord[0] + random.random(),
            newat.coord[1] + random.random(),
            newat.coord[2] + random.random(),
            ]
        newat.symbol = 'H'
        newat.name = 'HN'
        newat.numeric_type = 43
        bond = Bond()
        bond.order = 1
        bond.stereo = 0
        bond.index = [ a, model.nAtom ]
        print "adding",newat.name,bond.index
        model.add_atom(newat)
        model.add_bond(bond)
    for a in c_list:
        newat = copy.deepcopy(model.atom[a])
        newat.coord = [
            newat.coord[0] + random.random(),
            newat.coord[1] + random.random(),
            newat.coord[2] + random.random(),
            ]
        newat.symbol = 'H'
        newat.name = 'HC'
        newat.numeric_type = 41
        bond = Bond()
        bond.order = 1
        bond.stereo = 0
        bond.index = [ a, model.nAtom ]
        print "adding",newat.name,bond.index
        model.add_atom(newat)
        model.add_bond(bond)
    # reload
    cmd.delete(object)
    cmd.load_model(model,object)
    cmd.sort(object)
Ejemplo n.º 8
0
 def __init__(self,
              object,
              name='MMTK_model',
              configuration=None,
              b_values=None):
     self.object = object
     self.universe = object.universe()
     self.name = name
     self.model = Indexed()
     self.index_map = {}
     self.atoms = []
     chain_id_number = 0
     in_chain = True
     for o in object.bondedUnits():
         if Utility.isSequenceObject(o):
             groups = [(g, g.name) for g in o]
             if not in_chain:
                 chain_id_number = (chain_id_number + 1) % len(
                     self.chain_ids)
             in_chain = True
         else:
             groups = [(o, o.name)]
             in_chain = False
         residue_number = 1
         for g, g_name in groups:
             for a in g.atomList():
                 atom = Atom()
                 atom.symbol = a.symbol
                 atom.name = a.name
                 atom.resi_number = residue_number
                 atom.chain = self.chain_ids[chain_id_number]
                 if b_values is not None:
                     atom.b = b_values[a]
                 atom.resn = g_name
                 self.model.atom.append(atom)
                 self.index_map[a] = len(self.atoms)
                 self.atoms.append(a)
             residue_number = residue_number + 1
         if in_chain:
             chain_id_number = (chain_id_number + 1) % len(self.chain_ids)
         try:
             bonds = o.bonds
         except AttributeError:
             bonds = []
         for b in bonds:
             bond = Bond()
             bond.index = [self.index_map[b.a1], self.index_map[b.a2]]
             self.model.bond.append(bond)
     self._setCoordinates(configuration)
Ejemplo n.º 9
0
 def read_geom_bond_atom_site_labels(self,fields,field_dict,values):
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom,'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     label_1 = field_dict['_geom_bond_atom_site_label_1']
     label_2 = field_dict['_geom_bond_atom_site_label_2']
     for value in values:
         bond = Bond()
         bond.index = [
             name_dict[self.index_to_str(label_1,value)],
             name_dict[self.index_to_str(label_2,value)]]
         bond.order = 1
         self.model.bond.append(bond)
Ejemplo n.º 10
0
 def __init__(self, object, name = 'MMTK_model', configuration = None,
              b_values = None):
     self.object = object
     self.universe = object.universe()
     self.name = name
     self.model = Indexed()
     self.index_map = {}
     self.atoms = []
     chain_id_number = 0
     in_chain = True
     for o in object.bondedUnits():
         if Utility.isSequenceObject(o):
             groups = [(g, g.name) for g in o]
             if not in_chain:
                 chain_id_number = (chain_id_number+1) % len(self.chain_ids)
             in_chain = True
         else:
             groups = [(o, o.name)]
             in_chain = False
         residue_number = 1
         for g, g_name in groups:
             for a in g.atomList():
                 atom = Atom()
                 atom.symbol = a.symbol
                 atom.name = a.name
                 atom.resi_number = residue_number
                 atom.chain = self.chain_ids[chain_id_number]
                 if b_values is not None:
                     atom.b = b_values[a]
                 atom.resn = g_name
                 self.model.atom.append(atom)
                 self.index_map[a] = len(self.atoms)
                 self.atoms.append(a)
             residue_number = residue_number + 1
         if in_chain:
             chain_id_number = (chain_id_number+1) % len(self.chain_ids)
         try:
             bonds = o.bonds
         except AttributeError:
             bonds = []
         for b in bonds:
             bond = Bond()
             bond.index = [self.index_map[b.a1], self.index_map[b.a2]]
             self.model.bond.append(bond)
     self._setCoordinates(configuration)
Ejemplo n.º 11
0
 def read_geom_bond_atom_site_labels(self, fields, field_dict, values):
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom, 'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     label_1 = field_dict['_geom_bond_atom_site_label_1']
     label_2 = field_dict['_geom_bond_atom_site_label_2']
     for value in values:
         bond = Bond()
         bond.index = [
             name_dict[self.index_to_str(label_1, value)],
             name_dict[self.index_to_str(label_2, value)]
         ]
         bond.order = 1
         self.model.bond.append(bond)
Ejemplo n.º 12
0
    def make_channel(model, i, name=None):

        for a in range(len(model.atom) - 1):
            bd = Bond()
            bd.index = [a, a + 1]
            model.bond.append(bd)

        if name is None:
            name = "Tunnel" + str(i)

        cmd.load_model(model, name, state=1)
        cmd.set("sphere_mode", "0", name)
        cmd.set("sphere_color", "red", name)

        cmd.show("spheres", name)
        cmd.group("Tunnels", name)

        return Indexed()
Ejemplo n.º 13
0
    def test(self):
        from chempy import Atom, Bond, models

        m = models.Indexed()

        for i in range(2):
            a = Atom()
            a.coord = [float(i), 0., 0.]
            m.add_atom(a)

        b = Bond()
        b.index = [0, 1]
        b.order = 0
        m.add_bond(b)

        cmd.load_model(m, 'foo')

        cmd.set('valence')
        cmd.show('sticks')
Ejemplo n.º 14
0
    def fromList(self, molList):

        model = Indexed()

        # read header information
        nAtom = int(molList[0][0:3])

        # read atoms and bonds
        id_dict = {}
        irec = 1
        cnt = 0
        for a in range(nAtom):
            at = Atom()
            at.index = cnt
            id_dict[string.strip(molList[irec][3:8])] = at.index
            at.coord = [
                float(molList[irec][8:20]),
                float(molList[irec][20:32]),
                float(molList[irec][32:44])
            ]
            at.symbol = string.strip(molList[irec][0:3])
            at.numeric_type = int(molList[irec][44:49])
            lst = string.split(string.strip(molList[irec][49:]))
            at.bonds = lst
            irec = irec + 1
            cnt = cnt + 1
            model.atom.append(at)

        # interpret bonds
        cnt = 0
        for a in model.atom:
            lst = a.bonds
            del a.bonds
            for b in lst:
                if a.index < id_dict[b]:
                    bnd = Bond()
                    bnd.index = [a.index, id_dict[b]]
                    model.bond.append(bnd)

        # obtain formal charges from M  CHG record
        return model
Ejemplo n.º 15
0
def add_bonds(model, topology=None, forcefield=None):
    if not isinstance(model, chempy.models.Indexed):
        raise ValueError('model is not an "Indexed" model object')
    nAtom = model.nAtom
    if nAtom:
        tmpl = topology.normal
        ffld = forcefield.normal
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                resn = base.resn
                if resn not in tmpl:
                    raise RuntimeError("unknown residue type '" + resn + "'")
                else:
                    # reassign atom names and build dictionary
                    dict = {}
                    aliases = tmpl[resn]['aliases']
                    for b in range(a[0], a[1]):
                        at = model.atom[b]
                        if at.name in aliases:
                            at.name = aliases[at.name]
                        dict[at.name] = b
                        if forcefield:
                            k = (resn, at.name)
                            if k in ffld:
                                at.text_type = ffld[k]['type']
                                at.partial_charge = ffld[k]['charge']
                            else:
                                raise RuntimeError("no parameters for '" +
                                                   str(k) + "'")
                    # now add bonds for atoms which are present
                    bonds = tmpl[resn]['bonds']
                    mbond = model.bond
                    for b in list(bonds.keys()):
                        if b[0] in dict and b[1] in dict:
                            bnd = Bond()
                            bnd.index = [dict[b[0]], dict[b[1]]]
                            bnd.order = bonds[b]['order']
                            mbond.append(bnd)
Ejemplo n.º 16
0
    def read_geom_bond_atom_site_labels(self, fields, field_dict, values):
        try:
            label_1 = field_dict.get('_geom_bond_atom_site_id_1', None)
            if label_1 is not None:
                label_2 = field_dict['_geom_bond_atom_site_id_2']
            else:
                label_1 = field_dict['_geom_bond_atom_site_label_1']
                label_2 = field_dict['_geom_bond_atom_site_label_2']
        except KeyError:
            return False

        symm_1 = field_dict.get('_geom_bond_site_symmetry_1', -1)
        symm_2 = field_dict.get('_geom_bond_site_symmetry_2', -1)

        # create index of atom name
        cnt = 0
        name_dict = {}
        for atom in self.model.atom:
            if hasattr(atom, 'name'):
                name_dict[atom.name] = cnt
            cnt = cnt + 1
        for value in values:
            if self.index_to_str(symm_1, value) != self.index_to_str(
                    symm_2, value):
                # don't bond to symmetry mates
                continue
            try:
                index = [
                    name_dict[self.index_to_str(label_1, value)],
                    name_dict[self.index_to_str(label_2, value)]
                ]
            except KeyError:
                print(" CIF _geom_bond_atom_site_label, invalid keys:", value)
                continue
            bond = Bond()
            bond.index = index
            bond.order = 1
            self.model.bond.append(bond)
        return True
Ejemplo n.º 17
0
def add_bonds(model, topology = None, forcefield = None ):
    if str(model.__class__) != 'chempy.models.Indexed':
        raise ValueError('model is not an "Indexed" model object')
    nAtom = model.nAtom
    if nAtom:
        tmpl = topology.normal
        ffld = forcefield.normal
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                resn = base.resn
                if not tmpl.has_key(resn):
                    raise RuntimeError("unknown residue type '"+resn+"'")
                else:
                    # reassign atom names and build dictionary
                    dict = {}
                    aliases = tmpl[resn]['aliases']
                    for b in range(a[0],a[1]):
                        at = model.atom[b]
                        if aliases.has_key(at.name):
                            at.name = aliases[at.name]
                        dict[at.name] = b
                        if forcefield:
                            k = (resn,at.name)
                            if ffld.has_key(k):
                                at.text_type = ffld[k]['type']
                                at.partial_charge = ffld[k]['charge']
                            else:
                                raise RuntimeError("no parameters for '"+str(k)+"'")
                    # now add bonds for atoms which are present
                    bonds = tmpl[resn]['bonds']
                    mbond = model.bond
                    for b in bonds.keys():
                        if dict.has_key(b[0]) and dict.has_key(b[1]):
                            bnd = Bond()
                            bnd.index = [ dict[b[0]], dict[b[1]] ]
                            bnd.order = bonds[b]['order']
                            mbond.append(bnd)
Ejemplo n.º 18
0
Archivo: cc1.py Proyecto: Almad/pymol
    def fromList(self,molList):

        model = Indexed()

        # read header information
        nAtom = int(molList[0][0:3])

        # read atoms and bonds
        id_dict = {}
        irec = 1
        cnt = 0
        for a in range(nAtom):
            at = Atom()
            at.index = cnt
            id_dict[string.strip(molList[irec][3:8])] = at.index
            at.coord = [float(molList[irec][8:20]), 
                float(molList[irec][20:32]),float(molList[irec][32:44])]
            at.symbol = string.strip(molList[irec][0:3])
            at.numeric_type = int(molList[irec][44:49])
            lst = string.split(string.strip(molList[irec][49:]))
            at.bonds = lst
            irec = irec + 1
            cnt = cnt + 1
            model.atom.append(at)
            
        # interpret bonds
        cnt = 0
        for a in model.atom:
            lst = a.bonds
            del a.bonds
            for b in lst:
                if a.index<id_dict[b]:
                    bnd = Bond()
                    bnd.index = [ a.index,id_dict[b]]
                    model.bond.append(bnd)

        # obtain formal charges from M  CHG record
        return model
Ejemplo n.º 19
0
    def _read_m_bond(self,m_bond,model):
        bd_ent = m_bond[1]
        bd_dat = m_bond[2]
        
        nBond = m_bond[0]      

        if len(bd_dat[0]): # not empty right?
            if 'i_m_from' in bd_ent and \
                'i_m_to' in bd_ent and \
                'i_m_order' in bd_ent:
                a1 = bd_dat[bd_ent['i_m_from']]
                a2 = bd_dat[bd_ent['i_m_to']]
                a3 = bd_dat[bd_ent['i_m_order']]
                for b in range(nBond):
                    bd1 = a1[b] - 1
                    bd2 = a2[b] - 1
                    bd3 = a3[b]

                    if bd1<bd2:
                        bnd = Bond()
                        bnd.index = [ bd1,bd2 ]
                        bnd.order = bd3
                        model.bond.append(bnd)
Ejemplo n.º 20
0
 def read_chem_comp_bond_atom_ids(self,fields,field_dict,values):
     order_table = { 'sing' : 1, 'doub' : 2, 'trip' :3, 'delo': 4 }
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom,'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     label_1 = field_dict['_chem_comp_bond_atom_id_1']
     label_2 = field_dict['_chem_comp_bond_atom_id_2']
     order = field_dict.get('_chem_comp_bond_value_order',None)
     for value in values:
         bond = Bond()
         bond.index = [
             name_dict[self.index_to_str(label_1,value)],
             name_dict[self.index_to_str(label_2,value)]]
         if order != None:
             order_string = string.lower(self.index_to_str(order,value))
             bond.order = order_table.get(order_string[0:4],1)
         else:
             bond.order = 1
         self.model.bond.append(bond)
Ejemplo n.º 21
0
 def read_chem_comp_bond_atom_ids(self, fields, field_dict, values):
     order_table = {'sing': 1, 'doub': 2, 'trip': 3, 'delo': 4}
     # create index of atom name
     cnt = 0
     name_dict = {}
     for atom in self.model.atom:
         if hasattr(atom, 'name'):
             name_dict[atom.name] = cnt
         cnt = cnt + 1
     label_1 = field_dict['_chem_comp_bond_atom_id_1']
     label_2 = field_dict['_chem_comp_bond_atom_id_2']
     order = field_dict.get('_chem_comp_bond_value_order', None)
     for value in values:
         bond = Bond()
         bond.index = [
             name_dict[self.index_to_str(label_1, value)],
             name_dict[self.index_to_str(label_2, value)]
         ]
         if order != None:
             order_string = string.lower(self.index_to_str(order, value))
             bond.order = order_table.get(order_string[0:4], 1)
         else:
             bond.order = 1
         self.model.bond.append(bond)
Ejemplo n.º 22
0
Archivo: cif.py Proyecto: evonove/pymol
    def read_geom_bond_atom_site_labels(self,fields,field_dict,values):
        try:
            label_1 = field_dict.get('_geom_bond_atom_site_id_1', None)
            if label_1 is not None:
                label_2 = field_dict['_geom_bond_atom_site_id_2']
            else:
                label_1 = field_dict['_geom_bond_atom_site_label_1']
                label_2 = field_dict['_geom_bond_atom_site_label_2']
        except KeyError:
            return False

        symm_1 = field_dict.get('_geom_bond_site_symmetry_1', -1)
        symm_2 = field_dict.get('_geom_bond_site_symmetry_2', -1)

        # create index of atom name
        cnt = 0
        name_dict = {}
        for atom in self.model.atom:
            if hasattr(atom,'name'):
                name_dict[atom.name] = cnt
            cnt = cnt + 1
        for value in values:
            if self.index_to_str(symm_1, value) != self.index_to_str(symm_2, value):
                # don't bond to symmetry mates
                continue
            try:
                index = [name_dict[self.index_to_str(label_1, value)],
                         name_dict[self.index_to_str(label_2, value)]]
            except KeyError:
                print " CIF _geom_bond_atom_site_label, invalid keys:", value
                continue
            bond = Bond()
            bond.index = index
            bond.order = 1
            self.model.bond.append(bond)
        return True
Ejemplo n.º 23
0
def gen_model(mol):
    from chempy import models
    from chempy import Atom
    from chempy import Bond
    # print('generating model')
    model = models.Indexed()
    i = 1
    for at in mol['atoms']:
        atom = Atom()
        atom.name = at['name']
        atom.resi = at['residue']
        atom.resi_number = int(at['residue'])
        atom.segi = at['segment']
        atom.symbol = at['element']
        atom.coord = [float(at["x"]), float(at["y"]), float(at["z"])]
        model.add_atom(atom)
        # model.update_index()

    # model.update_index()
    for b in mol['bonds']:
        bond = Bond()
        bond.index = [int(b['atom1']) - 1, int(b['atom2']) - 1]
        model.add_bond(bond)
    return model
Ejemplo n.º 24
0
    def read_struct_conn_(self, loop):
        try:
            type_id = loop.get_col_idx('_struct_conn.conn_type_id')

            asym_id_1 = loop.get_col_idx('_struct_conn.ptnr1_auth_asym_id',
                                         '_struct_conn.ptnr1_label_asym_id')
            comp_id_1 = loop.get_col_idx('_struct_conn.ptnr1_auth_comp_id',
                                         '_struct_conn.ptnr1_label_comp_id')
            seq_id_1 = loop.get_col_idx('_struct_conn.ptnr1_auth_seq_id',
                                        '_struct_conn.ptnr1_label_seq_id')
            atom_id_1 = loop.get_col_idx('_struct_conn.ptnr1_label_atom_id')

            asym_id_2 = loop.get_col_idx('_struct_conn.ptnr2_auth_asym_id',
                                         '_struct_conn.ptnr2_label_asym_id')
            comp_id_2 = loop.get_col_idx('_struct_conn.ptnr2_auth_comp_id',
                                         '_struct_conn.ptnr2_label_comp_id')
            seq_id_2 = loop.get_col_idx('_struct_conn.ptnr2_auth_seq_id',
                                        '_struct_conn.ptnr2_label_seq_id')
            atom_id_2 = loop.get_col_idx('_struct_conn.ptnr2_label_atom_id')
        except KeyError:
            return False

        alt_id_1 = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr1_label_alt_id')
        ins_code_1 = loop.get_col_idx_opt(
            '_struct_conn.pdbx_ptnr1_pdb_ins_code')
        symm_1 = loop.get_col_idx_opt('_struct_conn.ptnr1_symmetry')
        alt_id_2 = loop.get_col_idx_opt('_struct_conn.pdbx_ptnr2_label_alt_id')
        ins_code_2 = loop.get_col_idx_opt(
            '_struct_conn.pdbx_ptnr2_pdb_ins_code')
        symm_2 = loop.get_col_idx_opt('_struct_conn.ptnr2_symmetry')

        idxs_1 = [
            asym_id_1, comp_id_1, seq_id_1, ins_code_1, atom_id_1, alt_id_1
        ]
        idxs_2 = [
            asym_id_2, comp_id_2, seq_id_2, ins_code_2, atom_id_2, alt_id_2
        ]

        # atoms indexed by atomic identifiers
        atom_dict = dict(((a.chain, a.resn, a.resi, getattr(a, 'ins_code', ''),
                           a.name, a.alt), i)
                         for (i, a) in enumerate(self.model.atom))

        for row in loop.rows:
            if self.index_to_str(type_id, row).lower() != 'covale':
                # ignore non-covalent bonds (metalc, hydrog)
                continue
            if self.index_to_str(symm_1, row) != self.index_to_str(
                    symm_2, row):
                # don't bond to symmetry mates
                continue
            key_1 = tuple(self.index_to_str(i, row) for i in idxs_1)
            key_2 = tuple(self.index_to_str(i, row) for i in idxs_2)
            try:
                index = [atom_dict[key_1], atom_dict[key_2]]
            except KeyError:
                print(" CIF _struct_conn, invalid keys:", row)
                continue
            bond = Bond()
            bond.index = index
            self.model.bond.append(bond)
        return True
Ejemplo n.º 25
0
model = Indexed()

# append the atoms onto it

for a in atoms:
    new_atom = Atom()
    new_atom.symbol = a[0]  # elemental symbol
    new_atom.name = a[1]  # atom name
    new_atom.resi = a[2]  # residue identifier
    new_atom.resn = a[3]  # residue name
    model.atom.append(new_atom)
# (note that there are a bunch of other fields we're not using -- and none are required)

# add coordinates onto the atoms

for a in model.atom:  # now assign coordinates
    a.coord = coords.pop(0)

# now specify the bonds

for a in bonds:
    new_bond = Bond()
    new_bond.index = [a[0], a[1]]  # atom indices (zero-based)
    new_bond.order = a[2]  # bond order
    model.bond.append(new_bond)

# finally, load the model into PyMOL

cmd.load_model(model, "example")
Ejemplo n.º 26
0
def read_moestr(contents,
                object,
                state=0,
                finish=1,
                discrete=1,
                quiet=1,
                zoom=-1,
                _self=cmd):
    moestr = contents
    name = object

    import sys
    if sys.version_info[0] > 2 and isinstance(moestr, bytes):
        moestr = moestr.decode()

    cmd = _self
    mr = MOEReader()
    mr.appendFromStr(moestr)
    split_chains = cmd.get_setting_int("moe_separate_chains")
    cmd.group(name)
    if hasattr(mr, 'system'):
        have_valences = 0
        chain_count = 0
        cmd.set_color("_aseg0", [1.0, 1.0, 1.0])
        aseg_color = cmd.get_color_index("_aseg0")
        aseg_flag = 0
        aseg_rep = {}
        model = Indexed()
        molecule = mr.system['molecule']
        if 'atoms' in molecule:
            n_atom = molecule['atoms']
            model.atom = [Atom() for x in range(n_atom)]
        residues = {}
        chains = {}
        for columns, data in molecule['attr']:
            for row in data:
                cur_atom = None
                for key, value in zip(columns, row):
                    key = key[0]
                    if key == 'ID':
                        ID = value
                    else:
                        aProp = _atom_prop_map.get(key, None)
                        if aProp != None:
                            setattr(model.atom[ID - 1], aProp, value)
                        else:
                            xyz = _atom_coord_map.get(key, None)
                            if xyz != None:
                                coord = list(model.atom[ID - 1].coord)
                                coord[xyz] = value
                                model.atom[ID - 1].coord = coord
                            elif key in _atom_vis_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'visible'):
                                    visible = atom.visible
                                else:
                                    visible = _default_visible
                                if key == 'aBondLook':
                                    if value == 'cylinder':
                                        atom.visible = 0x00000001 | visible
                                    elif value == 'line':
                                        atom.visible = 0x00000080 | visible
                                    elif value == 'none':
                                        atom.visible = -129 & Visible  # 0xFFFFFF7F
                                elif key == 'aNucleusLook':
                                    if value == 'sphere':
                                        atom.visible = 0x00000002 | visible
                                    elif value == 'small-sphere':  # need to set sphere_scale=0.2 for these atoms
                                        atom.visible = 0x00000002 | visible
                                        atom.sphere_scale = 0.2
                                    elif value == 'point':  # nonbonded
                                        atom.visible = 0x00000800 | visible
                                    elif value == 'none':
                                        atom.visible = -2067 & visible  # 0xFFFFF7ED
                                elif key == 'aHidden':
                                    atom.visible = 0
                                    atom.hidden = 1
                                if hasattr(
                                        atom, 'hidden'
                                ):  # be sure that hidden atoms aren't shown
                                    atom.visible = 0
                            elif key in _atom_color_map:
                                if key == 'aRGB':
                                    model.atom[ID - 1].trgb = value
                                elif key == 'aColorBy':
                                    model.atom[ID - 1].aColorBy = value
                            elif key in _atom_label_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'label_dict'):
                                    atom.label_dict[key] = None
                                else:
                                    atom.label_dict = {key: None}
                            elif key in _residue_prop_map:
                                resi_dict = residues.get(ID, {})
                                resi_dict[key] = value
                                residues[ID] = resi_dict
                            elif key in _chain_prop_map:
                                chain_dict = chains.get(ID, {})
                                if ID not in chains:
                                    chain_count = chain_count + 1
                                    chain_dict['count'] = chain_count
                                chain_dict[key] = value
                                chains[ID] = chain_dict
        chn_keys = list(chains.keys())
        chn_keys.sort()
        res_keys = list(residues.keys())
        res_keys.sort()
        # map chain properties onto residues
        chn_resi = 0
        ch_colors = copy.deepcopy(_ch_colors)
        unique_chain_names = {}
        for chn_idx in chn_keys:
            chain_dict = chains[chn_idx]
            cName = make_valid_name(chain_dict.get('cName', ''))
            segi = cName[0:4]
            chain = cName[-1:]
            if not len(cName):
                if 'count' in chain_dict:
                    cName = "chain_" + str(chain_dict['count'])
                else:
                    cName = str(chn_idx)
            if cName not in unique_chain_names:
                unique_chain_names[cName] = cName
            else:
                cnt = 2
                while (cName + "_" + str(cnt)) in unique_chain_names:
                    cnt = cnt + 1
                newCName = cName + "_" + str(cnt)
                unique_chain_names[newCName] = cName
                cName = newCName
            chain_dict['chain_color'] = ch_colors[0]
            ch_colors = ch_colors[1:] + [ch_colors[0]]
            cResCount = chain_dict.get('cResidueCount', 0)
            for res_idx in range(chn_resi, chn_resi + cResCount):
                resi_dict = residues[res_keys[res_idx]]
                resi_dict['chain'] = chain
                resi_dict['segi'] = segi
                resi_dict['cName'] = cName
                resi_dict['chain_dict'] = chain_dict
            chn_resi = chn_resi + cResCount
        # map residue properties onto atoms
        res_atom = 0
        for res_idx in res_keys:
            resi_dict = residues[res_idx]
            rRibbonMode = resi_dict.get('rRibbonMode', 'none')
            rAtomCount = resi_dict['rAtomCount']
            rType = resi_dict.get('rType', '')
            if rAtomCount > 0:
                for at_idx in range(res_atom, res_atom + rAtomCount):
                    atom = model.atom[at_idx]
                    setattr(
                        atom, 'resi',
                        string.strip(
                            str(resi_dict.get('rUID', '')) +
                            resi_dict.get('rINS', '')))
                    setattr(atom, 'resn', resi_dict.get('rName', ''))
                    setattr(atom, 'chain', resi_dict.get('chain', ''))
                    setattr(atom, 'segi', resi_dict.get('segi', ''))
                    setattr(atom, 'custom', resi_dict.get('cName', ''))
                    # add labels
                    if hasattr(atom, 'label_dict'):
                        label = ''
                        label_dict = atom.label_dict
                        if 'aLabelElement' in label_dict:
                            label = atom.symbol
                        if 'aLabelRes' in label_dict:
                            if len(label):
                                label = label + ","
                            label = label + atom.resn + "_" + atom.resi
                        if 'aLabelName' in label_dict:
                            if len(label):
                                label = label + "."
                            label = label + atom.name
                        atom.label = label
                    if rType not in ['none', 'heme']:
                        atom.hetatm = 0  # all normal atoms
                    else:
                        atom.flags = 0x02000000  # hetatom or ligand -- ignore when surfacing

                    if rRibbonMode != 'none':
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible

                        rRibbonColorBy = resi_dict['rRibbonColorBy']
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if rRibbonColorBy in ['rgb', 'r:rgb'
                                                  ]:  # handled automatically
                                pass
                            elif rRibbonColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                rRibbonColorBy = cColorBy
                                repeat = 1

                        rRibbon_color = 0
                        rRibbon_trgb = 0xFFFFFF  # default -- white

                        # now color ribbon
                        if rRibbonColorBy == 'r:rgb':
                            rRibbon_trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'rgb':
                            rRibbon_trgb = resi_dict.get(
                                'rRibbonRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            rRibbon_trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'r:aseg':
                            rRibbon_trgb = None
                            rRibbon_color = aseg_color
                            aseg_flag = 1
                        elif rRibbonColorBy == 'tempfactor':
                            pass  # TO DO
                        elif rRibbonColorBy == 'c:number':  # per chain colors
                            rRibbon_trgb = chain_dict['chain_color']
                        if rRibbonMode in ['line', 'trace']:
                            atom.visible = 0x00000040 | visible  # PyMOL ribbon
                            if rRibbon_trgb != None:
                                atom.ribbon_trgb = rRibbon_trgb
                            else:
                                atom.ribbon_color = rRibbon_color
                            aseg_rep['ribbon'] = 1
                        else:
                            atom.visible = 0x00000020 | visible  # PyMOL cartoon
                            if rRibbon_trgb != None:
                                atom.cartoon_trgb = rRibbon_trgb
                            else:
                                atom.cartoon_color = rRibbon_color
                            aseg_rep['cartoon'] = 1

                    if hasattr(atom, 'label'):
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible
                        atom.visible = 0x00000028 | visible  # labels
                    if not hasattr(atom, 'aColorBy'):
                        atom.aColorBy = 'element'
                    if hasattr(atom, 'aColorBy'):
                        aColorBy = atom.aColorBy
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if aColorBy == 'ribbon':
                                aColorBy = resi_dict.get('rRibbonColorBy')
                                if aColorBy == 'rgb':
                                    aColorBy = 'rib:rgb'
                                else:
                                    repeat = 1
                                # TO DO still need to handle "cartoon_color", "ribbon_color"
                            elif aColorBy == 'element':
                                if hasattr(atom, 'trgb'):
                                    del atom.trgb
                            elif aColorBy in ['rgb', 'a:rgb'
                                              ]:  # handled automatically
                                pass
                            elif aColorBy == 'residue':
                                rColorBy = resi_dict.get('rColorBy')
                                if rColorBy == 'rgb':
                                    rColorBy = 'r:rgb'
                                aColorBy = rColorBy
                                repeat = 1
                            elif aColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                aColorBy = cColorBy
                                repeat = 1

                        # now color atom...
                        if aColorBy == 'r:rgb':
                            atom.trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif aColorBy == 'rib:rgb':
                            atom.trgb = resi_dict.get('rRibbonRGB', 0xFFFFFF)
                        elif aColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            atom.trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif aColorBy == 'r:aseg':
                            pass  # TO DO
                        elif aColorBy == 'tempfactor':
                            pass  # TO DO
                        elif aColorBy == 'c:number':  # per chain colors
                            atom.trgb = chain_dict['chain_color']

                res_atom = res_atom + rAtomCount
        bond_list = molecule.get('bond', [])
        for bond in bond_list:
            new_bond = Bond()
            new_bond.index = [bond[0] - 1, bond[1] - 1]
            if len(bond) > 2:
                new_bond.order = bond[2]
                if bond[2] == 2:  # work around .MOE bug with triple bonds
                    if model.atom[new_bond.index[0]].hybridization == 'sp':
                        if model.atom[new_bond.index[1]].hybridization == 'sp':
                            new_bond.order = 3
                have_valences = 1
            model.bond.append(new_bond)
        if 'ViewOrientationY' in mr.system:
            vy = mr.system['ViewOrientationY']
            vz = mr.system['ViewOrientationZ']
            pos = mr.system['ViewLookAt']
            scale = mr.system['ViewScale']
            vx = cpv.cross_product(vy, vz)
            m = [cpv.normalize(vx), cpv.normalize(vy), cpv.normalize(vz)]
            m = cpv.transpose(m)
            asp_rat = 0.8  # MOE default (versus 0.75 for PyMOL)
            cmd.set("field_of_view", 25.0)
            fov = float(cmd.get("field_of_view"))
            window_height = scale * asp_rat
            dist = (0.5 * window_height) / math.atan(3.1415 *
                                                     (0.5 * fov) / 180.0)
            new_view = tuple(m[0] + m[1] + m[2] + [0.0, 0.0, -dist] + pos +
                             [dist * 0.5, dist * 1.5, 0.0])
            cmd.set_view(new_view)
            zoom = 0
        cmd.set("auto_color", 0)
        cmd.set_color("carbon", [0.5, 0.5, 0.5])  # default MOE grey

        obj_name = name + ".system"
        if split_chains < 0:  # by default, don't split chains if over 50 objects would be created
            if len(unique_chain_names) > 50:
                split_chains = 0
        if not split_chains:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=quiet,
                           zoom=zoom)
            obj_name_list = [obj_name]
        else:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=1,
                           zoom=zoom)
            obj_name_list = []
            system_name = obj_name
            for chain in unique_chain_names.keys():
                obj_name = name + "." + chain
                obj_name_list.append(obj_name)
                cmd.select("_moe_ext_tmp",
                           "custom %s" % chain,
                           domain=system_name)
                cmd.extract(obj_name, "_moe_ext_tmp", quiet=quiet, zoom=0)
                # cmd.extract(obj_name,system_name+" and text_type %s"%chain,quiet=quiet)
                cmd.delete("_moe_ext_tmp")
            if not cmd.count_atoms(system_name):
                cmd.delete(system_name)
            else:
                obj_name_list.append(system_name)
            cmd.order(name + ".*", sort=1)
        for obj_name in obj_name_list:
            cmd.set("stick_radius", 0.1, obj_name)
            cmd.set("line_width", 2.0, obj_name)
            cmd.set("label_color", "white", obj_name)
            cmd.set("nonbonded_size", 0.05,
                    obj_name)  # temporary workaround...
            if have_valences:  # if this MOE file has valences, then show em!
                cmd.set("valence", 1, obj_name)
                cmd.set("stick_valence_scale", 1.25, obj_name)
            if aseg_flag:
                cmd.dss(obj_name)
                if 'cartoon' in aseg_rep:
                    cmd.set("cartoon_color", "red",
                            obj_name + " and cartoon_color _aseg0 and ss h")
                    cmd.set("cartoon_color", "yellow",
                            obj_name + " and cartoon_color _aseg0 and ss s")
                    cmd.set(
                        "cartoon_color", "cyan",
                        obj_name + " and cartoon_color _aseg0 and not ss h+s")
                if 'ribbon' in aseg_rep:
                    cmd.set("ribbon_color", "red",
                            obj_name + " and ribbon_color _aseg0 and ss h"
                            )  # need selection op ribbon_color
                    cmd.set("ribbon_color", "yellow",
                            obj_name + " and ribbon_color _aseg0 and ss s")
                    cmd.set(
                        "ribbon_color", "cyan",
                        obj_name + " and ribbon_color _aseg0 and not ss h+s")
        if 'ViewZFront' in mr.system:
            moe_front = mr.system['ViewZFront']
            moe_width = mr.system['ViewZWidth']
            extent = cmd.get_extent(
                name)  # will this work with groups? TO DO: check!
            dx = (extent[0][0] - extent[1][0])
            dy = (extent[0][1] - extent[1][1])
            dz = (extent[0][2] - extent[1][2])
            half_width = 0.5 * math.sqrt(dx * dx + dy * dy + dz * dz)
            cmd.clip("atoms", 0.0, name)
            cur_view = cmd.get_view()
            center = (cur_view[-3] +
                      cur_view[-2]) * 0.5  # center of clipping slab
            front = center - half_width
            back = center + half_width
            width = half_width * 2
            new_view = tuple(
                list(cur_view[0:15]) + [
                    front + width * moe_front, front + width *
                    (moe_front + moe_width), 0.0
                ])
            cmd.set_view(new_view)
        if 'graphics' in mr.system:
            cgo_cnt = 1
            lab_cnt = 1
            unique_cgo_names = {}
            for graphics in mr.system['graphics']:
                cgo = []
                for gvertex in graphics.get('gvertex', []):
                    vrt = gvertex[0]
                    seg_list = gvertex[1]['seg']
                    idx = gvertex[1]['idx']
                    len_idx = len(idx)
                    if not cmd.is_list(seg_list):
                        seg_list = [seg_list] * (len_idx / seg_list)
                    last_seg = None
                    ix_start = 0
                    for seg in seg_list:
                        if seg != last_seg:
                            if last_seg != None:
                                cgo.append(END)
                            if seg == 3:
                                cgo.extend([BEGIN, TRIANGLES])
                            elif seg == 2:
                                cgo.extend([BEGIN, LINES])
                            elif seg == 1:
                                cgo.extend([BEGIN, POINTS])
                        ix_stop = seg + ix_start
                        if seg == 3:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 2:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 1:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        ix_start = ix_stop
                        last_seg = seg
                    if last_seg != None:
                        cgo.append(END)
                for gtext in graphics.get('gtext', []):
                    lab_name = name + ".label_%02d" % lab_cnt
                    exists = 0
                    for entry in gtext:
                        exists = 1
                        cmd.pseudoatom(lab_name,
                                       pos=[
                                           float(entry[1]),
                                           float(entry[2]),
                                           float(entry[3])
                                       ],
                                       color="0x%06x" % entry[0],
                                       label=entry[4])
                    if exists:
                        cmd.set('label_color', -1, lab_name)
                        lab_cnt = lab_cnt + 1
                    # TO DO -- via CGO's?

                if len(cgo):
                    cgo_name = name + "." + make_valid_name(
                        graphics.get('GTitle', 'graphics'))
                    if cgo_name not in unique_cgo_names:
                        unique_cgo_names[cgo_name] = cgo_name
                    else:
                        cnt = 2
                        while cgo_name + "_" + str(cnt) in unique_cgo_names:
                            cnt = cnt + 1
                        new_name = cgo_name + "_" + str(cnt)
                        unique_cgo_names[new_name] = new_name
                        cgo_name = new_name
                    cmd.load_cgo(cgo,
                                 cgo_name,
                                 state=state,
                                 quiet=quiet,
                                 zoom=0)
                    cgo_cnt = cgo_cnt + 1
                    cmd.set("two_sided_lighting", 1)  # global setting...
                    cmd.set("cgo_line_width", 2, cgo_name)
                    if 'GTransparency' in graphics:
                        g_trans = graphics['GTransparency']
                        if len(g_trans) >= 2:
                            if g_trans[0] != 0:
                                cmd.set('cgo_transparency',
                                        '%1.6f' % (g_trans[0] / 255.0),
                                        cgo_name)
                                cmd.set('transparency_global_sort')
        if 'meter' in mr.system:
            meter_name = name + ".meter"
            exists = 0
            for meter_block in mr.system['meter']:
                if meter_block[0][0:2] == ['type', 'atoms']:
                    for meter in meter_block[1]:
                        (type, atoms) = meter[0:2]
                        arg = tuple([meter_name] + list(
                            map(lambda x, o=name: o + " and id " + str(x - 1),
                                atoms)))
                        getattr(cmd, type)(*arg)
                        exists = 1
            if exists:
                cmd.color("green", meter_name)
#            print mr.system['meter']
    elif hasattr(mr, 'feature'):
        model = Indexed()
        cols = mr.feature[0]
        rows = mr.feature[1]
        col = {}
        cnt = 0
        for a in cols:
            col[a] = cnt
            cnt = cnt + 1
        for row in rows:
            atom = Atom()
            atom.coord = [row[col['x']], row[col['y']], row[col['z']]]
            atom.vdw = row[col['r']]
            atom.custom = row[col['expr']]
            model.atom.append(atom)
        obj_name = name + ".feature"
        cmd.load_model(model,
                       obj_name,
                       state=state,
                       finish=finish,
                       discrete=discrete,
                       quiet=quiet,
                       zoom=zoom)
        rank = 1
        for row in rows:
            cmd.color("0x%06x" % row[col['color']],
                      obj_name + " & id %d" % (rank - 1))
            rank = rank + 1
        cmd.show("mesh", obj_name)
        cmd.set("min_mesh_spacing", 0.55, obj_name)
        cmd.label(obj_name, "' '+custom")
        cmd.set("label_color", "yellow", obj_name)
    else:
        print(dir(mr))
Ejemplo n.º 27
0
def load_cml(filename, object='', discrete=0, multiplex=1, zoom=-1,
        quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a CML formatted structure file
    '''
    from chempy import Atom, Bond, models

    multiplex, discrete = int(multiplex), int(discrete)

    try:
        root = etree.fromstring(_self.file_read(filename))
    except etree.XMLSyntaxError:
        raise CmdException("File doesn't look like XML")

    if root.tag != 'cml':
        raise CmdException('not a CML file')

    molecule_list = root.findall('./molecule')

    if len(molecule_list) < 2:
        multiplex = 0
    elif not multiplex:
        discrete = 1

    for model_num, molecule_node in enumerate(molecule_list, 1):
        model = models.Indexed()

        atom_idx = {}

        for atom_node in molecule_node.findall('./atomArray/atom'):
            atom = Atom()
            atom.name = atom_node.get('id', '')

            if 'x3' in atom_node.attrib:
                atom.coord = [float(atom_node.get(a))
                        for a in ['x3', 'y3', 'z3']]
            elif 'x2' in atom_node.attrib:
                atom.coord = [float(atom_node.get(a))
                        for a in ['x2', 'y2']] + [0.0]
            else:
                print(' Warning: no coordinates for atom', atom.name)
                continue

            atom.symbol = atom_node.get('elementType', '')
            atom.formal_charge = int(atom_node.get('formalCharge', 0))
            atom_idx[atom.name] = len(model.atom)
            model.add_atom(atom)

        for bond_node in molecule_node.findall('./bondArray/bond'):
            refs = bond_node.get('atomsRefs2', '').split()
            if len(refs) == 2:
                bnd = Bond()
                bnd.index = [int(atom_idx[ref]) for ref in refs]
                bnd.order = int(bond_node.get('order', 1))
                model.add_bond(bnd)

        # object name
        if not object:
            object = os.path.basename(filename).split('.', 1)[0]

        # load models as objects or states
        if multiplex:
            oname = molecule_node.get('id') or _self.get_unused_name('unnamed')
            model_num = 1
        else:
            oname = object

        _self.load_model(model, oname,
                state=model_num, zoom=zoom, discrete=discrete)
Ejemplo n.º 28
0
 def MakeBond(self, at1, at2, bo):
     bnd = Bond()
     bnd.index = [at1.index, at2.index]
     bnd.order = bo
     self.model.bond.append(bnd)
Ejemplo n.º 29
0
    def fromList(self, MMODList):

        model = Connected()

        # get header information
        nAtom = int(MMODList[0][1:6])
        model.molecule.title = string.strip(MMODList[0][8:])
        irec = 1

        # loop through atoms
        cnt = 0
        for a in range(nAtom):
            model.bond.append([])

        for a in range(nAtom):
            at = Atom()
            at.numeric_type = int(MMODList[irec][1:4])

            # extract connectivity information
            tokens = string.splitfields(MMODList[irec][5:52])
            at.neighbor = []
            at.bondorder = []

            for i in range(6):
                if tokens[2 * i] != "0":
                    a2 = int(tokens[2 * i]) - 1
                    if (a2 > cnt):
                        b = Bond()
                        b.index = [cnt, a2]
                        b.order = int(tokens[2 * i + 1])
                        model.bond[b.index[0]].append(
                            b)  # note two refs to same object
                        model.bond[b.index[1]].append(
                            b)  # note two refs to same object
                else:
                    break

# extract other information
            at.coord = [
                float(MMODList[irec][53:64]),
                float(MMODList[irec][65:76]),
                float(MMODList[irec][77:88])
            ]
            at.resi = string.strip(MMODList[irec][89:94])
            at.resi_number = int(at.resi)
            resn_code = string.strip(MMODList[irec][94:95])
            if len(resn_code): at.resn_code = resn_code
            color_code = string.strip(MMODList[irec][96:100])
            if color_code != '':
                at.color_code = int(color_code)
            else:
                at.color_code = 0
            chain = string.strip(MMODList[irec][95:96])
            if len(chain): at.chain = chain
            at.partial_charge = float(MMODList[irec][100:109])
            at.resn = MMODList[irec][119:123]
            name = string.strip(MMODList[irec][124:128])
            if len(name): at.name = name
            model.atom.append(at)
            irec = irec + 1
            cnt = cnt + 1

# fill in remaining datatypes
        cnt = 1
        for a in model.atom:
            a.text_type = MMOD_atom_data[a.numeric_type][0]
            a.symbol = MMOD_atom_data[a.numeric_type][1]
            a.formal_charge = MMOD_atom_data[a.numeric_type][4]
            cnt = cnt + 1

        return (model.convert_to_indexed())
Ejemplo n.º 30
0
def create_bond(model, a1, a2): # one-based atom serial numbers
	b = Bond()
	b.index = [a1 - 1, a2 - 1] # zero-based indices!
	model.bond.append(b)
Ejemplo n.º 31
0
for a in atoms:
   new_atom = Atom()
   new_atom.symbol = a[0]     # elemental symbol
   new_atom.name = a[1]       # atom name
   new_atom.resi = a[2]       # residue identifier
   new_atom.resn = a[3]       # residue name
   model.atom.append(new_atom)
# (note that there are a bunch of other fields we're not using -- and none are required)

# add coordinates onto the atoms

for a in model.atom: # now assign coordinates
   a.coord = coords.pop(0)

# now specify the bonds

for a in bonds:
   new_bond = Bond()
   new_bond.index = [a[0],a[1]]  # atom indices (zero-based)
   new_bond.order = a[2]         # bond order
   model.bond.append(new_bond)

# finally, load the model into PyMOL

cmd.load_model(model,"example")


   


Ejemplo n.º 32
0
def convert_to_chempy_model(atom_array):
    """
    Convert an :class:`AtomArray` into a :class:`chempy.models.Indexed`
    object.

    Returns
    -------
    chempy_model : Indexed
        The converted structure.
    """
    model = IndexedModel()

    annot_cat = atom_array.get_annotation_categories()

    for i in range(atom_array.array_length()):
        atom = Atom()

        atom.segi = atom_array.chain_id[i]
        atom.chain = atom_array.chain_id[i]

        atom.resi_number = atom_array.res_id[i]

        atom.ins_code = atom_array.ins_code[i]

        res_name = atom_array.res_name[i]
        atom.resn = res_name
        if len(res_name) == 1:
            atom.resn_code = res_name
        else:
            try:
                atom.resn_code = ProteinSequence.convert_letter_3to1(res_name)
            except KeyError:
                atom.resn_code = "X"

        atom.hetatm = 1 if atom_array.hetero[i] else 0

        atom.name = atom_array.atom_name[i]

        atom.symbol = atom_array.element[i]

        if "b_factor" in annot_cat:
            atom.b = atom_array.b_factor[i]

        if "occupancy" in annot_cat:
            atom.q = atom_array.occupancy[i]

        if "charge" in annot_cat:
            atom.formal_charge = atom_array.charge[i]

        atom.coord = tuple(atom_array.coord[..., i, :])

        atom.index = i + 1

        model.add_atom(atom)

    if atom_array.bonds is not None:
        for i, j, bond_type in atom_array.bonds.as_array():
            bond = Bond()
            bond.order = BOND_ORDER[bond_type]
            bond.index = [i, j]
            model.add_bond(bond)
    else:
        warnings.warn(
            "The given atom array (stack) has no associated bond information")

    return model
Ejemplo n.º 33
0
Archivo: mol.py Proyecto: Almad/pymol
    def fromList(self,molList):

        model = Indexed()

        # read header information
        model.molecule.title = string.strip(molList[0])
        model.molecule.dim_code = string.strip(molList[1][20:22])
        model.molecule.comments = string.strip(molList[2])
        try:
            model.molecule.chiral = int(molList[3][12:15])
        except:
            model.molecule.chiral = 0
        nAtom = int(molList[3][0:3])
        nBond = int(molList[3][3:6])

        # read atoms
        nameDict = {}
        irec = 4
        cnt = 0
        for a in range(nAtom):
            at = Atom()
            at.index = cnt
            at.coord = [float(molList[irec][0:10]), 
                float(molList[irec][10:20]),float(molList[irec][20:30])]
            at.symbol = string.strip(molList[irec][31:33])
            try:
                at.stereo = int(molList[irec][39:42])
            except:
                at.stereo = 0
            chg=int(molList[irec][36:39])
            if chg>0: chg=4-chg
            at.formal_charge = chg
            model.atom.append(at)
            irec = irec + 1
            cnt = cnt + 1

            # read bonds
        for a in range(nBond):
            bnd = Bond()
            bnd.index = [ int(molList[irec][0:3])-1,int(molList[irec][3:6])-1 ]
            bnd.order = int(molList[irec][6:9])
            try:
                bnd.stereo = int(molList[irec][9:12])
            except:
                bnd.stereo = 0
            model.bond.append(bnd)
            irec = irec+1

            # obtain formal charges from M  CHG record
        while molList[irec][0:6]!='M  END':
            if molList[irec][0:6]=='M  CHG':
                cl = string.split(string.strip(molList[irec][6:]))
                cll = int(cl[0])*2
                a=1
                while a<=cll:
                    model.atom[int(cl[a])-1].formal_charge=int(cl[a+1])
                    a=a+2
            irec =irec+1
            if irec >= len(molList): break

        return model
Ejemplo n.º 34
0
def add_bonds(model, forcefield=protein_amber, histidine='HIE'):
    '''
add_bonds(model, forcefield = protein_amber, histidine = 'HIE' )

(1) fixes aliases, assigns types, makes HIS into HIE,HID, or HIP
     and changes cystine to CYX
(2) adds bonds between existing atoms
    '''
    if feedback['actions']:
        print(" " + str(__name__) + ": assigning types and bonds...")
    if not isinstance(model, chempy.models.Indexed):
        raise ValueError('model is not an "Indexed" model object')
    if model.nAtom:
        crd = model.get_coord_list()
        nbr = Neighbor(crd, MAX_BOND_LEN)
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                if not base.hetatm:
                    resn = base.resn
                    if resn == 'HIS':
                        for c in range(a[0], a[1]):  # this residue
                            model.atom[c].resn = histidine
                        resn = histidine
                    if resn == 'N-M':  # N-methyl from Insight II,
                        for c in range(a[0], a[1]):  # this residue
                            model.atom[c].resn = 'NME'
                        resn = 'NME'
                    # find out if this is n or c terminal residue
                    names = []
                    for b in range(a[0], a[1]):
                        names.append(model.atom[b].name)
                    tmpl = protein_residues.normal
                    if forcefield:
                        ffld = forcefield.normal
                    for b in N_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.n_terminal
                            if forcefield:
                                ffld = forcefield.n_terminal
                            break
                    for b in C_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.c_terminal
                            if forcefield:
                                ffld = forcefield.c_terminal
                            break
                    if resn not in tmpl:
                        raise RuntimeError("unknown residue type '" + resn +
                                           "'")
                    else:
                        # reassign atom names and build dictionary
                        dict = {}
                        aliases = tmpl[resn]['aliases']
                        for b in range(a[0], a[1]):
                            at = model.atom[b]
                            if at.name in aliases:
                                at.name = aliases[at.name]
                            dict[at.name] = b
                            if forcefield:
                                k = (resn, at.name)
                                if k in ffld:
                                    at.text_type = ffld[k]['type']
                                    at.partial_charge = ffld[k]['charge']
                                else:
                                    raise RuntimeError("no parameters for '" +
                                                       str(k) + "'")
                        # now add bonds for atoms which are present
                        bonds = tmpl[resn]['bonds']
                        mbond = model.bond
                        for b in list(bonds.keys()):
                            if b[0] in dict and b[1] in dict:
                                bnd = Bond()
                                bnd.index = [dict[b[0]], dict[b[1]]]
                                bnd.order = bonds[b]['order']
                                mbond.append(bnd)
                        if 'N' in dict:  # connect residues N-C based on distance
                            cur_n = dict['N']
                            at = model.atom[cur_n]
                            lst = nbr.get_neighbors(at.coord)
                            for b in lst:
                                at2 = model.atom[b]
                                if at2.name == 'C':
                                    if not at2.in_same_residue(at):
                                        dst = distance(at.coord, at2.coord)
                                        if dst <= PEPT_CUTOFF:
                                            bnd = Bond()
                                            bnd.index = [cur_n, b]
                                            bnd.order = 1
                                            mbond.append(bnd)
                                            break
                        if 'SG' in dict:  # cysteine
                            cur = dict['SG']
                            at = model.atom[cur]
                            lst = nbr.get_neighbors(at.coord)
                            for b in lst:
                                if b > cur:  # only do this once (only when b>cur - i.e. this is 1st CYS)
                                    at2 = model.atom[b]
                                    if at2.name == 'SG':
                                        if not at2.in_same_residue(at):
                                            dst = distance(at.coord, at2.coord)
                                            if dst <= MAX_BOND_LEN:
                                                bnd = Bond()
                                                bnd.index = [cur, b]
                                                bnd.order = 1
                                                mbond.append(bnd)
                                                if forcefield:
                                                    for c in range(
                                                            a[0], a[1]
                                                    ):  # this residue
                                                        atx = model.atom[c]
                                                        atx.resn = 'CYX'
                                                        resn = atx.resn
                                                        k = ('CYX', atx.name)
                                                        if k in ffld:
                                                            atx.text_type = ffld[
                                                                k]['type']
                                                            atx.partial_charge = ffld[
                                                                k]['charge']
                                                        else:
                                                            raise RuntimeError(
                                                                "no parameters for '"
                                                                + str(k) + "'")
                                                    for d in res_list:
                                                        if (b >= d[0]) and (
                                                                b < d[1]
                                                        ):  # find other residue
                                                            for c in range(
                                                                    d[0],
                                                                    d[1]):
                                                                atx = model.atom[
                                                                    c]
                                                                atx.resn = 'CYX'
                                                                # since b>cur, assume assignment later on
                                                break
Ejemplo n.º 35
0
def add_hydrogens(model, forcefield=protein_amber, skip_sort=None):
    # assumes no bonds between non-hetatms
    if feedback['actions']:
        print(" " + str(__name__) + ": adding hydrogens...")
    if not isinstance(model, chempy.models.Connected):
        raise ValueError('model is not a "Connected" model object')
    if model.nAtom:
        if not model.index:
            model.update_index()
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                if not base.hetatm:
                    resn = base.resn
                    # find out if this is n or c terminal residue
                    names = []
                    for b in range(a[0], a[1]):
                        names.append(model.atom[b].name)
                    tmpl = protein_residues.normal
                    if forcefield:
                        ffld = forcefield.normal
                    for b in N_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.n_terminal
                            if forcefield:
                                ffld = forcefield.n_terminal
                            break
                    for b in C_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.c_terminal
                            if forcefield:
                                ffld = forcefield.c_terminal
                            break
                    if resn not in tmpl:
                        raise RuntimeError("unknown residue type '" + resn +
                                           "'")
                    else:
                        # build dictionary
                        dict = {}
                        for b in range(a[0], a[1]):
                            at = model.atom[b]
                            dict[at.name] = b
                        # find missing bonds with hydrogens
                        bonds = tmpl[resn]['bonds']
                        mbond = model.bond
                        for b in list(bonds.keys()):
                            if b[0] in dict and (b[1] not in dict):
                                at = model.atom[dict[b[0]]]
                                if at.symbol != 'H':
                                    name = b[1]
                                    symbol = tmpl[resn]['atoms'][name][
                                        'symbol']
                                    if symbol == 'H':
                                        newat = at.new_in_residue()
                                        newat.name = name
                                        newat.symbol = symbol
                                        k = (resn, newat.name)
                                        newat.text_type = ffld[k]['type']
                                        newat.partial_charge = ffld[k][
                                            'charge']
                                        idx1 = model.index[id(at)]
                                        idx2 = model.add_atom(newat)
                                        bnd = Bond()
                                        bnd.index = [idx1, idx2]
                                        bnd.order = bonds[b]['order']
                                        mbond[idx1].append(bnd)
                                        mbond[idx2].append(bnd)
                            if (b[0] not in dict) and b[1] in dict:
                                at = model.atom[dict[b[1]]]
                                if at.symbol != 'H':
                                    name = b[0]
                                    symbol = tmpl[resn]['atoms'][name][
                                        'symbol']
                                    if symbol == 'H':
                                        newat = at.new_in_residue()
                                        newat.name = name
                                        newat.symbol = symbol
                                        k = (resn, newat.name)
                                        newat.text_type = ffld[k]['type']
                                        newat.partial_charge = ffld[k][
                                            'charge']
                                        idx1 = model.index[id(at)]
                                        idx2 = model.add_atom(newat)
                                        bnd = Bond()
                                        bnd.index = [idx1, idx2]
                                        bnd.order = bonds[b]['order']
                                        mbond[idx1].append(bnd)
                                        mbond[idx2].append(bnd)
        if not skip_sort:
            model.sort()
Ejemplo n.º 36
0
def add_hydrogens(model,topology=None,forcefield=None):  
    if str(model.__class__) != 'chempy.models.Connected':
        raise ValueError('model is not a "Connected" model object')
    nAtom = model.nAtom
    if nAtom:
        if not model.index:
            model.update_index()
        ffld = forcefield.normal
        tmpl = topology.normal
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                resn = base.resn
                if not tmpl.has_key(resn):
                    raise RuntimeError("unknown residue type '"+resn+"'")
                else:
                    # build dictionary
                    dict = {}
                    for b in range(a[0],a[1]):
                        at = model.atom[b]
                        dict[at.name] = b
                    # find missing bonds with hydrogens
                    bonds = tmpl[resn]['bonds']
                    mbond = model.bond
                    for b in bonds.keys():
                        if dict.has_key(b[0]) and (not dict.has_key(b[1])):
                            at = model.atom[dict[b[0]]]
                            if at.symbol != 'H':
                                name = b[1]
                                symbol = tmpl[resn]['atoms'][name]['symbol']
                                if symbol == 'H':
                                    newat = at.new_in_residue()
                                    newat.name = name
                                    newat.symbol = symbol
                                    k = (resn,newat.name)
                                    newat.text_type = ffld[k]['type']
                                    newat.partial_charge = ffld[k]['charge']
                                    idx1 = model.index[id(at)]
                                    idx2 = model.add_atom(newat)
                                    bnd = Bond()
                                    bnd.index = [ idx1, idx2 ]
                                    bnd.order = bonds[b]['order']
                                    mbond[idx1].append(bnd)
                                    mbond[idx2].append(bnd)
                        if (not dict.has_key(b[0])) and dict.has_key(b[1]):
                            at = model.atom[dict[b[1]]]
                            if at.symbol != 'H':
                                name = b[0]
                                symbol = tmpl[resn]['atoms'][name]['symbol']
                                if symbol == 'H':
                                    newat = at.new_in_residue()
                                    newat.name = name
                                    newat.symbol = symbol
                                    k = (resn,newat.name)
                                    newat.text_type = ffld[k]['type']
                                    newat.partial_charge = ffld[k]['charge']
                                    idx1 = model.index[id(at)]
                                    idx2 = model.add_atom(newat)
                                    bnd = Bond()
                                    bnd.index = [ idx1, idx2 ]
                                    bnd.order = bonds[b]['order']
                                    mbond[idx1].append(bnd)
                                    mbond[idx2].append(bnd)
Ejemplo n.º 37
0
Archivo: m4x.py Proyecto: Almad/pymol
 def MakeBond(self,at1, at2, bo):
     bnd = Bond()
     bnd.index = [ at1.index, at2.index ]
     bnd.order = bo
     self.model.bond.append(bnd)
Ejemplo n.º 38
0
def load_3d(filename, object=''):
    '''
DESCRIPTION

    Load a survex 3d cave survey as "molecule"

    http://survex.com
    http://trac.survex.com/browser/trunk/doc/3dformat.htm
    '''
    from chempy import Atom, Bond, models
    from struct import unpack

    if object == '':
        object = os.path.splitext(os.path.basename(filename))[0]

    f = open(filename, 'rb')

    line = f.readline() # File ID
    if not line.startswith('Survex 3D Image File'):
        print " Error: not a Survex 3D File"
        raise CmdException

    line = f.readline() # File format version
    assert line[0] == 'v'
    ff_version = int(line[1:])

    line = unicode(f.readline(), 'latin1') # Survex title
    line = f.readline() # Timestamp

    class Station:
        def __init__(self):
            self.labels = []
            self.adjacent = []
            self.lrud = None
            self.flag = 0
        def connect(self, other):
            self.adjacent.append(other)
        def is_surface(self):
            return self.flag & 0x01
        def is_underground(self):
            return self.flag & 0x02
        def is_entrance(self):
            return self.flag & 0x04
        def is_exported(self):
            return self.flag & 0x08
        def is_fixed(self):
            return self.flag & 0x10

    class Survey(dict):
        def __init__(self):
            self.prev = None
            self.curr_label = ''
            self.labelmap = {}
        def get(self, xyz):
            return dict.setdefault(self, tuple(xyz), Station())
        def line(self, xyz):
            s = self.get(xyz)
            self.prev.connect(s)
            self.prev = s
        def move(self, xyz):
            s = self.get(xyz)
            self.prev = s
        def label(self, xyz, flag=0):
            s = self.get(xyz)
            s.labels.append(self.curr_label)
            self.labelmap[s.labels[-1]] = s
            if flag > 0:
                s.flag = flag
        def lrud(self, lrud):
            s = self.labelmap[self.curr_label]
            s.lrud = lrud

    survey = Survey()

    def read_xyz():
        return unpack('<iii', f.read(12))

    def read_len():
        len = read_byte()
        if len == 0xfe:
            len += unpack('<H', f.read(2))[0]
        elif len == 0xff:
            len += unpack('<I', f.read(4))[0]
        return len

    def read_label():
        len = read_len()
        if len > 0:
            survey.curr_label += skip_bytes(len)

    def skip_bytes(n):
        return f.read(n)

    def read_byte():
        byte = f.read(1)
        if len(byte) != 1:
            return -1
        return ord(byte)

    while 1:
        byte = read_byte()
        if byte == -1:
            break
        
        if byte == 0x00:
            # STOP
            survey.curr_label = ''
        elif byte <= 0x0e:
            # TRIM
            # FIXME: according to doc, trim 16 bytes, but img.c does 17!
            (i,n) = (-17,0)
            while n < byte:
                i -= 1
                if survey.curr_label[i] == '.': n += 1
            survey.curr_label = survey.curr_label[:i + 1]
        elif byte <= 0x0f:
            # MOVE
            xyz = read_xyz()
            survey.move(xyz)
        elif byte <= 0x1f:
            # TRIM
            survey.curr_label = survey.curr_label[:15 - byte]
        elif byte <= 0x20:
            # DATE
            if ff_version < 7:
                skip_bytes(4)
            else:
                skip_bytes(2)
        elif byte <= 0x21:
            # DATE
            if ff_version < 7:
                skip_bytes(8)
            else:
                skip_bytes(3)
        elif byte <= 0x22:
            # Error info
            skip_bytes(5 * 4)
        elif byte <= 0x23:
            # DATE
            skip_bytes(4)
        elif byte <= 0x24:
            # DATE
            continue
        elif byte <= 0x2f:
            # Reserved
            continue
        elif byte <= 0x31:
            # XSECT
            read_label()
            lrud = unpack('<hhhh', f.read(8))
            survey.lrud(lrud)
        elif byte <= 0x33:
            # XSECT
            read_label()
            lrud = unpack('<iiii', f.read(16))
            survey.lrud(lrud)
        elif byte <= 0x3f:
            # Reserved
            continue
        elif byte <= 0x7f:
            # LABEL
            read_label()
            xyz = read_xyz()
            survey.label(xyz, byte & 0x3f)
        elif byte <= 0xbf:
            # LINE
            read_label()
            xyz = read_xyz()
            survey.line(xyz)
        elif byte <= 0xff:
            # Reserved
            continue

    model = models.Indexed()
    for (xyz,s) in survey.iteritems():
        l0, _, l1 = s.labels[0].rpartition('.')
        resi, name = l1[:5], l1[5:]
        segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:]
        atom = Atom()
        atom.coord = [i/100.0 for i in xyz]
        atom.segi = segi
        atom.chain = chain
        atom.resn = resn
        atom.name = name
        atom.resi = resi
        atom.b = atom.coord[2]
        atom.label = s.labels[0]
        if s.lrud is not None:
            atom.vdw = sum(s.lrud)/400.0
        model.add_atom(atom)

    s2i = dict((s,i) for (i,s) in enumerate(survey.itervalues()))
    for (s,i) in s2i.iteritems():
        for o in s.adjacent:
            bnd = Bond()
            bnd.index = [i, s2i[o]]
            model.add_bond(bnd)

    cmd.load_model(model, object, 1)
    cmd.show_as('lines', object)
    cmd.spectrum('b', 'rainbow', object)
Ejemplo n.º 39
0
def delaunay(selection='enabled', name=None, cutoff=10.0, as_cgo=0,
        qdelaunay_exe='qdelaunay', state=-1, quiet=1):
    '''
DESCRIPTION

    Full-atom Delaunay Tessalator

    Creates either a molecular object with delaunay edges as bonds, or a CGO
    object with edge colors according to edge length.

USAGE

    delaunay [ selection [, name [, cutoff=10.0 [, as_cgo=0 ]]]]

SEE ALSO

    PyDeT plugin: http://pymolwiki.org/index.php/PyDet
    '''
    from chempy import cpv, Bond
    if name is None:
        name = cmd.get_unused_name('delaunay')
    cutoff = float(cutoff)
    as_cgo = int(as_cgo)
    state, quiet = int(state), int(quiet)
    if state < 1:
        state = cmd.get_state()
    model = cmd.get_model(selection, state)
    regions_iter = qdelaunay((a.coord for a in model.atom), 3, len(model.atom),
            qdelaunay_exe=qdelaunay_exe)
    edges = set(tuple(sorted([region[i-1], region[i]]))
            for region in regions_iter for i in range(len(region)))

    edgelist=[]
    r = []

    minco = 9999
    maxco = 0

    for edge in edges:
        ii, jj = edge
        a = model.atom[ii]
        b = model.atom[jj]
        co = cpv.distance(a.coord, b.coord)
        if cutoff > 0.0 and co > cutoff:
            continue
        if as_cgo:
            minco=min(co,minco)
            maxco=max(co,maxco)
            edgelist.append(a.coord + b.coord + [co])
        else:
            bnd = Bond()
            bnd.index = [ii, jj]
            model.add_bond(bnd)
        r.append((a,b,co))

    if not as_cgo:
        cmd.load_model(model, name, 1)
        return r

    from pymol.cgo import CYLINDER

    difco = maxco-minco
    obj = []
    mm = lambda x: max(min(x, 1.0), 0.0)
    for e in edgelist:
        co = ((e[6]-minco)/difco)**(0.75)
        color = [mm(1-2*co), mm(1-abs(2*co-1)), mm(2*co-1)]
        obj.extend([CYLINDER] + e[0:6] + [0.05] + color + color)

    cmd.load_cgo(obj, name)
    return r
Ejemplo n.º 40
0
def add_hydrogens(model,forcefield=protein_amber,skip_sort=None):
    # assumes no bonds between non-hetatms
    if feedback['actions']:
        print(" "+str(__name__)+": adding hydrogens...")
    if not isinstance(model, chempy.models.Connected):
        raise ValueError('model is not a "Connected" model object')
    if model.nAtom:
        if not model.index:
            model.update_index()
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                if not base.hetatm:
                    resn = base.resn
                    # find out if this is n or c terminal residue
                    names = []
                    for b in range(a[0],a[1]):
                        names.append(model.atom[b].name)
                    tmpl = protein_residues.normal
                    if forcefield:
                        ffld = forcefield.normal
                    for b in N_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.n_terminal
                            if forcefield:
                                ffld = forcefield.n_terminal
                            break
                    for b in C_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.c_terminal
                            if forcefield:
                                ffld = forcefield.c_terminal
                            break
                    if resn not in tmpl:
                        raise RuntimeError("unknown residue type '"+resn+"'")
                    else:
                        # build dictionary
                        dict = {}
                        for b in range(a[0],a[1]):
                            at = model.atom[b]
                            dict[at.name] = b
                        # find missing bonds with hydrogens
                        bonds = tmpl[resn]['bonds']
                        mbond = model.bond
                        for b in list(bonds.keys()):
                            if b[0] in dict and (b[1] not in dict):
                                at = model.atom[dict[b[0]]]
                                if at.symbol != 'H':
                                    name = b[1]
                                    symbol = tmpl[resn]['atoms'][name]['symbol']
                                    if symbol == 'H':
                                        newat = at.new_in_residue()
                                        newat.name = name
                                        newat.symbol = symbol
                                        k = (resn,newat.name)
                                        newat.text_type = ffld[k]['type']
                                        newat.partial_charge = ffld[k]['charge']
                                        idx1 = model.index[id(at)]
                                        idx2 = model.add_atom(newat)
                                        bnd = Bond()
                                        bnd.index = [ idx1, idx2 ]
                                        bnd.order = bonds[b]['order']
                                        mbond[idx1].append(bnd)
                                        mbond[idx2].append(bnd)
                            if (b[0] not in dict) and b[1] in dict:
                                at = model.atom[dict[b[1]]]
                                if at.symbol != 'H':
                                    name = b[0]
                                    symbol = tmpl[resn]['atoms'][name]['symbol']
                                    if symbol == 'H':
                                        newat = at.new_in_residue()
                                        newat.name = name
                                        newat.symbol = symbol
                                        k = (resn,newat.name)
                                        newat.text_type = ffld[k]['type']
                                        newat.partial_charge = ffld[k]['charge']
                                        idx1 = model.index[id(at)]
                                        idx2 = model.add_atom(newat)
                                        bnd = Bond()
                                        bnd.index = [ idx1, idx2 ]
                                        bnd.order = bonds[b]['order']
                                        mbond[idx1].append(bnd)
                                        mbond[idx2].append(bnd)
        if not skip_sort:
            model.sort()
Ejemplo n.º 41
0
def add_hydrogens(model, topology=None, forcefield=None):
    if not isinstance(model, chempy.models.Connected):
        raise ValueError('model is not a "Connected" model object')
    nAtom = model.nAtom
    if nAtom:
        if not model.index:
            model.update_index()
        ffld = forcefield.normal
        tmpl = topology.normal
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                resn = base.resn
                if resn not in tmpl:
                    raise RuntimeError("unknown residue type '" + resn + "'")
                else:
                    # build dictionary
                    dict = {}
                    for b in range(a[0], a[1]):
                        at = model.atom[b]
                        dict[at.name] = b
                    # find missing bonds with hydrogens
                    bonds = tmpl[resn]['bonds']
                    mbond = model.bond
                    for b in list(bonds.keys()):
                        if b[0] in dict and (b[1] not in dict):
                            at = model.atom[dict[b[0]]]
                            if at.symbol != 'H':
                                name = b[1]
                                symbol = tmpl[resn]['atoms'][name]['symbol']
                                if symbol == 'H':
                                    newat = at.new_in_residue()
                                    newat.name = name
                                    newat.symbol = symbol
                                    k = (resn, newat.name)
                                    newat.text_type = ffld[k]['type']
                                    newat.partial_charge = ffld[k]['charge']
                                    idx1 = model.index[id(at)]
                                    idx2 = model.add_atom(newat)
                                    bnd = Bond()
                                    bnd.index = [idx1, idx2]
                                    bnd.order = bonds[b]['order']
                                    mbond[idx1].append(bnd)
                                    mbond[idx2].append(bnd)
                        if (b[0] not in dict) and b[1] in dict:
                            at = model.atom[dict[b[1]]]
                            if at.symbol != 'H':
                                name = b[0]
                                symbol = tmpl[resn]['atoms'][name]['symbol']
                                if symbol == 'H':
                                    newat = at.new_in_residue()
                                    newat.name = name
                                    newat.symbol = symbol
                                    k = (resn, newat.name)
                                    newat.text_type = ffld[k]['type']
                                    newat.partial_charge = ffld[k]['charge']
                                    idx1 = model.index[id(at)]
                                    idx2 = model.add_atom(newat)
                                    bnd = Bond()
                                    bnd.index = [idx1, idx2]
                                    bnd.order = bonds[b]['order']
                                    mbond[idx1].append(bnd)
                                    mbond[idx2].append(bnd)
Ejemplo n.º 42
0
    def fromList(self,MMODList):

        model = Connected()
        
# get header information
        nAtom = int(MMODList[0][1:6])
        model.molecule.title = string.strip(MMODList[0][8:])
        irec = 1

# loop through atoms
        cnt = 0
        for a in range(nAtom):
            model.bond.append([])
            
        for a in range(nAtom):
            at = Atom()
            at.numeric_type = int(MMODList[irec][1:4])

# extract connectivity information
            tokens = string.splitfields(MMODList[irec][5:52])
            at.neighbor = []
            at.bondorder = []

            for i in range(6):
                if tokens[2*i] != "0":
                    a2 = int(tokens[2*i])-1
                    if (a2>cnt):
                        b = Bond()
                        b.index = [cnt,a2]
                        b.order = int(tokens[2*i+1])
                        model.bond[b.index[0]].append(b) # note two refs to same object
                        model.bond[b.index[1]].append(b) # note two refs to same object 
                else:
                    break
            
# extract other information
            at.coord = [float(MMODList[irec][53:64]), 
                float(MMODList[irec][65:76]), float(MMODList[irec][77:88])]
            at.resi = string.strip(MMODList[irec][89:94])
            at.resi_number = int(at.resi)
            resn_code = string.strip(MMODList[irec][94:95])
            if len(resn_code): at.resn_code = resn_code
            color_code = string.strip(MMODList[irec][96:100])
            if color_code!='':
                at.color_code = int(color_code)
            else:
                at.color_code = 0
            chain = string.strip(MMODList[irec][95:96])
            if len(chain): at.chain = chain
            at.partial_charge = float(MMODList[irec][100:109])
            at.resn = MMODList[irec][119:123]
            name = string.strip(MMODList[irec][124:128])
            if len(name): at.name = name
            model.atom.append(at)
            irec = irec + 1
            cnt = cnt + 1
            
# fill in remaining datatypes
        cnt = 1
        for a in model.atom:
            a.text_type = MMOD_atom_data[a.numeric_type][0]
            a.symbol = MMOD_atom_data[a.numeric_type][1]
            a.formal_charge = MMOD_atom_data[a.numeric_type][4]
            cnt = cnt + 1
            
        return(model.convert_to_indexed())
Ejemplo n.º 43
0
def load_3d(filename, object=''):
    '''
DESCRIPTION

    Load a survex 3d cave survey as "molecule"

    http://survex.com
    http://trac.survex.com/browser/trunk/doc/3dformat.htm
    '''
    from chempy import Atom, Bond, models
    from struct import unpack

    if object == '':
        object = os.path.splitext(os.path.basename(filename))[0]

    f = open(filename, 'rb')

    line = f.readline()  # File ID
    if not line.startswith('Survex 3D Image File'):
        print(" Error: not a Survex 3D File")
        raise CmdException

    line = f.readline()  # File format version
    assert line[0] == 'v'
    ff_version = int(line[1:])

    line = f.readline().decode('latin1')  # Survex title
    line = f.readline()  # Timestamp

    class Station:
        def __init__(self):
            self.labels = []
            self.adjacent = []
            self.lrud = None
            self.flag = 0

        def connect(self, other):
            self.adjacent.append(other)

        def is_surface(self):
            return self.flag & 0x01

        def is_underground(self):
            return self.flag & 0x02

        def is_entrance(self):
            return self.flag & 0x04

        def is_exported(self):
            return self.flag & 0x08

        def is_fixed(self):
            return self.flag & 0x10

    class Survey(dict):
        def __init__(self):
            self.prev = None
            self.curr_label = ''
            self.labelmap = {}

        def get(self, xyz):
            return dict.setdefault(self, tuple(xyz), Station())

        def line(self, xyz):
            s = self.get(xyz)
            self.prev.connect(s)
            self.prev = s

        def move(self, xyz):
            s = self.get(xyz)
            self.prev = s

        def label(self, xyz, flag=0):
            s = self.get(xyz)
            s.labels.append(self.curr_label)
            self.labelmap[s.labels[-1]] = s
            if flag > 0:
                s.flag = flag

        def lrud(self, lrud):
            s = self.labelmap[self.curr_label]
            s.lrud = lrud

    survey = Survey()

    def read_xyz():
        return unpack('<iii', f.read(12))

    def read_len():
        len = read_byte()
        if len == 0xfe:
            len += unpack('<H', f.read(2))[0]
        elif len == 0xff:
            len += unpack('<I', f.read(4))[0]
        return len

    def read_label():
        len = read_len()
        if len > 0:
            survey.curr_label += skip_bytes(len)

    def skip_bytes(n):
        return f.read(n)

    def read_byte():
        byte = f.read(1)
        if len(byte) != 1:
            return -1
        return ord(byte)

    while 1:
        byte = read_byte()
        if byte == -1:
            break

        if byte == 0x00:
            # STOP
            survey.curr_label = ''
        elif byte <= 0x0e:
            # TRIM
            # FIXME: according to doc, trim 16 bytes, but img.c does 17!
            (i, n) = (-17, 0)
            while n < byte:
                i -= 1
                if survey.curr_label[i] == '.': n += 1
            survey.curr_label = survey.curr_label[:i + 1]
        elif byte <= 0x0f:
            # MOVE
            xyz = read_xyz()
            survey.move(xyz)
        elif byte <= 0x1f:
            # TRIM
            survey.curr_label = survey.curr_label[:15 - byte]
        elif byte <= 0x20:
            # DATE
            if ff_version < 7:
                skip_bytes(4)
            else:
                skip_bytes(2)
        elif byte <= 0x21:
            # DATE
            if ff_version < 7:
                skip_bytes(8)
            else:
                skip_bytes(3)
        elif byte <= 0x22:
            # Error info
            skip_bytes(5 * 4)
        elif byte <= 0x23:
            # DATE
            skip_bytes(4)
        elif byte <= 0x24:
            # DATE
            continue
        elif byte <= 0x2f:
            # Reserved
            continue
        elif byte <= 0x31:
            # XSECT
            read_label()
            lrud = unpack('<hhhh', f.read(8))
            survey.lrud(lrud)
        elif byte <= 0x33:
            # XSECT
            read_label()
            lrud = unpack('<iiii', f.read(16))
            survey.lrud(lrud)
        elif byte <= 0x3f:
            # Reserved
            continue
        elif byte <= 0x7f:
            # LABEL
            read_label()
            xyz = read_xyz()
            survey.label(xyz, byte & 0x3f)
        elif byte <= 0xbf:
            # LINE
            read_label()
            xyz = read_xyz()
            survey.line(xyz)
        elif byte <= 0xff:
            # Reserved
            continue

    model = models.Indexed()
    for (xyz, s) in survey.items():
        l0, _, l1 = s.labels[0].rpartition('.')
        resi, name = l1[:5], l1[5:]
        segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:]
        atom = Atom()
        atom.coord = [i / 100.0 for i in xyz]
        atom.segi = segi
        atom.chain = chain
        atom.resn = resn
        atom.name = name
        atom.resi = resi
        atom.b = atom.coord[2]
        atom.label = s.labels[0]
        if s.lrud is not None:
            atom.vdw = sum(s.lrud) / 400.0
        model.add_atom(atom)

    s2i = dict((s, i) for (i, s) in enumerate(survey.values()))
    for (s, i) in s2i.items():
        for o in s.adjacent:
            bnd = Bond()
            bnd.index = [i, s2i[o]]
            model.add_bond(bnd)

    cmd.load_model(model, object, 1)
    cmd.show_as('lines', object)
    cmd.spectrum('b', 'rainbow', object)
def load_3d(filename, object=''):
	'''
DESCRIPTION

    Load a survex 3d cave survey as "molecule"

    http://survex.com
	'''
	from chempy import Atom, Bond, models

	if object == '':
		import os
		object = os.path.splitext(os.path.basename(filename))[0]

	f = open(filename, 'rb')

	line = f.readline() # File ID
	if not line.startswith('Survex 3D Image File'):
		print " Error: not a Survex 3D File"
		raise CmdException

	line = f.readline() # File format version
	assert line[0] == 'v'
	ff_version = int(line[1:])

	line = unicode(f.readline(), 'latin1') # Survex title
	line = f.readline() # Timestamp

	class Station(tuple):
		def __new__(cls, xyz):
			return tuple.__new__(cls, xyz)
		def __init__(self, xyz):
			self.labels = []
			self.adjacent = []
		def connect(self, other):
			self.adjacent.append(other)

	class Survey(dict):
		def __init__(self):
			self.prev = None
			self.curr_label = ''
		def get(self, xyz):
			s = Station(xyz)
			return dict.setdefault(self, s, s)
		def line(self, xyz):
			s = self.get(xyz)
			self.prev.connect(s)
			self.prev = s
		def move(self, xyz):
			s = self.get(xyz)
			self.prev = s
		def label(self, xyz):
			s = survey.get(xyz)
			s.labels.append(self.curr_label)
		def __repr__(self):
			return 'Survey(' + repr(self.keys())[1:-1] + ')'

	survey = Survey()

	def read_xyz():
		x = read_int(4, 1)
		y = read_int(4, 1)
		z = read_int(4, 1)
		return [ x, y, z ]

	def read_int(len, sign):
		int = 0
		for i in range(len):
			int |= read_byte() << (8 * i)
		if sign and (int >> (8 * len - 1)):
			int -= (1 << 8 * len)
		return int

	def read_len():
		len = read_byte()
		if len == 0xfe:
			len += read_int(2, 0)
		elif len == 0xff:
			len = read_int(4, 0)
		return len

	def read_label():
		len = read_len()
		if len > 0:
			survey.curr_label += skip_bytes(len)

	def skip_bytes(n):
		return f.read(n)

	def read_byte():
		byte = f.read(1)
		if len(byte) != 1:
			return -1
		return ord(byte)

	while 1:
		byte = read_byte()
		if byte == -1:
			break
		
		if byte == 0x00:
			# STOP
			survey.curr_label = ''
		elif byte <= 0x0e:
			# TRIM
			(i,n) = (-16,0)
			while n < byte:
				i -= 1
				if survey.curr_label[i] == '.': n += 1
			survey.curr_label = survey.curr_label[:i + 1]
		elif byte <= 0x0f:
			# MOVE
			xyz = read_xyz()
			survey.move(xyz)
		elif byte <= 0x1f:
			# TRIM
			survey.curr_label = survey.curr_label[:15 - byte]
		elif byte <= 0x20:
			# DATE
			if ff_version < 7:
				skip_bytes(4)
			else:
				skip_bytes(2)
		elif byte <= 0x21:
			# DATE
			if ff_version < 7:
				skip_bytes(8)
			else:
				skip_bytes(3)
		elif byte <= 0x22:
			# Error info
			skip_bytes(5 * 4)
		elif byte <= 0x23:
			# DATE
			skip_bytes(4)
		elif byte <= 0x24:
			# DATE
			continue
		elif byte <= 0x2f:
			# Reserved
			continue
		elif byte <= 0x31:
			# XSECT
			read_label()
			skip_bytes(4 * 2)
		elif byte <= 0x33:
			# XSECT
			read_label()
			skip_bytes(4 * 4)
		elif byte <= 0x3f:
			# Reserved
			continue
		elif byte <= 0x7f:
			# LABEL
			read_label()
			xyz = read_xyz()
			survey.label(xyz)
		elif byte <= 0xbf:
			# LINE
			read_label()
			xyz = read_xyz()
			survey.line(xyz)
		elif byte <= 0xff:
			# Reserved
			continue

	model = models.Indexed()
	for s in survey:
		l0, _, l1 = s.labels[0].rpartition('.')
		resi, name = l1[:5], l1[5:]
#		segi, chain, resn = l0[:4],l0[-4:-3], l0[-3:]
		segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:]
		atom = Atom()
		atom.coord = [i/100.0 for i in s]
		atom.segi = segi
		atom.chain = chain
		atom.resn = resn
		atom.name = name
		atom.resi = resi
		atom.b = atom.coord[2]
		model.add_atom(atom)

	s2i = dict((s,i) for (i,s) in enumerate(survey))
	for s in survey:
		for o in s.adjacent:
			bnd = Bond()
			bnd.index = [s2i[s], s2i[o]]
			model.add_bond(bnd)

	cmd.load_model(model, object, 1)
	cmd.show_as('lines', object)
	cmd.spectrum('b', 'rainbow', object)
Ejemplo n.º 45
0
def load_cml(filename, object='', discrete=0, multiplex=1, zoom=-1,
        quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a CML formatted structure file
    '''
    from chempy import Atom, Bond, models

    multiplex, discrete = int(multiplex), int(discrete)

    try:
        root = etree.fromstring(_self.file_read(filename))
    except etree.XMLSyntaxError:
        raise CmdException("File doesn't look like XML")

    if root.tag != 'cml':
        raise CmdException('not a CML file')

    molecule_list = root.findall('./molecule')

    if len(molecule_list) < 2:
        multiplex = 0
    elif not multiplex:
        discrete = 1

    for model_num, molecule_node in enumerate(molecule_list, 1):
        model = models.Indexed()

        atom_idx = {}

        for atom_node in molecule_node.findall('./atomArray/atom'):
            atom = Atom()
            atom.name = atom_node.get('id', '')

            if 'x3' in atom_node.attrib:
                atom.coord = [float(atom_node.get(a))
                        for a in ['x3', 'y3', 'z3']]
            elif 'x2' in atom_node.attrib:
                atom.coord = [float(atom_node.get(a))
                        for a in ['x2', 'y2']] + [0.0]
            else:
                print(' Warning: no coordinates for atom', atom.name)
                continue

            atom.symbol = atom_node.get('elementType', '')
            atom.formal_charge = int(atom_node.get('formalCharge', 0))
            atom_idx[atom.name] = len(model.atom)
            model.add_atom(atom)

        for bond_node in molecule_node.findall('./bondArray/bond'):
            refs = bond_node.get('atomsRefs2', '').split()
            if len(refs) == 2:
                bnd = Bond()
                bnd.index = [int(atom_idx[ref]) for ref in refs]
                bnd.order = int(bond_node.get('order', 1))
                model.add_bond(bnd)

        # object name
        if not object:
            object = os.path.basename(filename).split('.', 1)[0]

        # load models as objects or states
        if multiplex:
            oname = molecule_node.get('id') or _self.get_unused_name('unnamed')
            model_num = 1
        else:
            oname = object

        _self.load_model(model, oname,
                state=model_num, zoom=zoom, discrete=discrete)
Ejemplo n.º 46
0
def add_bonds(model, forcefield = protein_amber, histidine = 'HIE' ):
    '''
add_bonds(model, forcefield = protein_amber, histidine = 'HIE' )

(1) fixes aliases, assigns types, makes HIS into HIE,HID, or HIP
     and changes cystine to CYX
(2) adds bonds between existing atoms
    '''
    if feedback['actions']:
        print(" "+str(__name__)+": assigning types and bonds...")
    if not isinstance(model, chempy.models.Indexed):
        raise ValueError('model is not an "Indexed" model object')
    if model.nAtom:
        crd = model.get_coord_list()
        nbr = Neighbor(crd,MAX_BOND_LEN)
        res_list = model.get_residues()
        if len(res_list):
            for a in res_list:
                base = model.atom[a[0]]
                if not base.hetatm:
                    resn = base.resn
                    if resn == 'HIS':
                        for c in range(a[0],a[1]): # this residue
                            model.atom[c].resn = histidine
                        resn = histidine
                    if resn == 'N-M': # N-methyl from Insight II, 
                        for c in range(a[0],a[1]): # this residue
                            model.atom[c].resn = 'NME'
                        resn = 'NME'
                    # find out if this is n or c terminal residue
                    names = []
                    for b in range(a[0],a[1]):
                        names.append(model.atom[b].name)
                    tmpl = protein_residues.normal
                    if forcefield:
                        ffld = forcefield.normal
                    for b in N_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.n_terminal
                            if forcefield:
                                ffld = forcefield.n_terminal
                            break
                    for b in C_TERMINAL_ATOMS:
                        if b in names:
                            tmpl = protein_residues.c_terminal
                            if forcefield:
                                ffld = forcefield.c_terminal
                            break
                    if resn not in tmpl:
                        raise RuntimeError("unknown residue type '"+resn+"'")
                    else:
                        # reassign atom names and build dictionary
                        dict = {}
                        aliases = tmpl[resn]['aliases']
                        for b in range(a[0],a[1]):
                            at = model.atom[b]
                            if at.name in aliases:
                                at.name = aliases[at.name]
                            dict[at.name] = b
                            if forcefield:
                                k = (resn,at.name)
                                if k in ffld:
                                    at.text_type = ffld[k]['type']
                                    at.partial_charge = ffld[k]['charge']
                                else:
                                    raise RuntimeError("no parameters for '"+str(k)+"'")
                        # now add bonds for atoms which are present
                        bonds = tmpl[resn]['bonds']
                        mbond = model.bond
                        for b in list(bonds.keys()):
                            if b[0] in dict and b[1] in dict:
                                bnd = Bond()
                                bnd.index = [ dict[b[0]], dict[b[1]] ]
                                bnd.order = bonds[b]['order']
                                mbond.append(bnd)
                        if 'N' in dict:  # connect residues N-C based on distance
                            cur_n = dict['N']
                            at = model.atom[cur_n]
                            lst = nbr.get_neighbors(at.coord)
                            for b in lst:
                                at2 = model.atom[b]
                                if at2.name=='C':
                                    if not at2.in_same_residue(at):
                                        dst = distance(at.coord,at2.coord)
                                        if dst<=PEPT_CUTOFF:
                                            bnd=Bond()
                                            bnd.index = [cur_n,b]
                                            bnd.order = 1
                                            mbond.append(bnd)
                                            break
                        if 'SG' in dict: # cysteine
                            cur = dict['SG']
                            at = model.atom[cur]
                            lst = nbr.get_neighbors(at.coord)
                            for b in lst:
                                if b>cur: # only do this once (only when b>cur - i.e. this is 1st CYS)
                                    at2 = model.atom[b]
                                    if at2.name=='SG':
                                        if not at2.in_same_residue(at):
                                            dst = distance(at.coord,at2.coord)
                                            if dst<=MAX_BOND_LEN:
                                                bnd=Bond()
                                                bnd.index = [cur,b]
                                                bnd.order = 1
                                                mbond.append(bnd)
                                                if forcefield:
                                                    for c in range(a[0],a[1]): # this residue
                                                        atx = model.atom[c]
                                                        atx.resn = 'CYX'
                                                        resn = atx.resn
                                                        k = ('CYX',atx.name)
                                                        if k in ffld:
                                                            atx.text_type = ffld[k]['type']
                                                            atx.partial_charge = ffld[k]['charge']
                                                        else:
                                                            raise RuntimeError("no parameters for '"+str(k)+"'")
                                                    for d in res_list: 
                                                        if (b>=d[0]) and (b<d[1]): # find other residue
                                                            for c in range(d[0],d[1]):
                                                                atx = model.atom[c]
                                                                atx.resn = 'CYX'
                                                                # since b>cur, assume assignment later on
                                                break
Ejemplo n.º 47
0
    def fromList(self, molList):

        model = Indexed()

        # read header information
        model.molecule.title = string.strip(molList[0])
        model.molecule.dim_code = string.strip(molList[1][20:22])
        model.molecule.comments = string.strip(molList[2])
        try:
            model.molecule.chiral = int(molList[3][12:15])
        except:
            model.molecule.chiral = 0
        nAtom = int(molList[3][0:3])
        nBond = int(molList[3][3:6])

        # read atoms
        nameDict = {}
        irec = 4
        cnt = 0
        for a in range(nAtom):
            at = Atom()
            at.index = cnt
            at.coord = [
                float(molList[irec][0:10]),
                float(molList[irec][10:20]),
                float(molList[irec][20:30])
            ]
            at.symbol = string.strip(molList[irec][31:33])
            try:
                at.stereo = int(molList[irec][39:42])
            except:
                at.stereo = 0
            chg = int(molList[irec][36:39])
            if chg > 0: chg = 4 - chg
            at.formal_charge = chg
            model.atom.append(at)
            irec = irec + 1
            cnt = cnt + 1

            # read bonds
        for a in range(nBond):
            bnd = Bond()
            bnd.index = [
                int(molList[irec][0:3]) - 1,
                int(molList[irec][3:6]) - 1
            ]
            bnd.order = int(molList[irec][6:9])
            try:
                bnd.stereo = int(molList[irec][9:12])
            except:
                bnd.stereo = 0
            model.bond.append(bnd)
            irec = irec + 1

            # obtain formal charges from M  CHG record
        while molList[irec][0:6] != 'M  END':
            if molList[irec][0:6] == 'M  CHG':
                cl = string.split(string.strip(molList[irec][6:]))
                cll = int(cl[0]) * 2
                a = 1
                while a <= cll:
                    model.atom[int(cl[a]) - 1].formal_charge = int(cl[a + 1])
                    a = a + 2
            irec = irec + 1
            if irec >= len(molList): break

        return model
Ejemplo n.º 48
0
def delaunay(selection='enabled',
             name=None,
             cutoff=10.0,
             as_cgo=0,
             qdelaunay_exe='qdelaunay',
             state=-1,
             quiet=1,
             *,
             _self=cmd):
    '''
DESCRIPTION

    Full-atom Delaunay Tessalator

    Creates either a molecular object with delaunay edges as bonds, or a CGO
    object with edge colors according to edge length.

USAGE

    delaunay [ selection [, name [, cutoff=10.0 [, as_cgo=0 ]]]]

SEE ALSO

    PyDeT plugin: http://pymolwiki.org/index.php/PyDet
    '''
    from chempy import cpv, Bond
    if name is None:
        name = _self.get_unused_name('delaunay')
    cutoff = float(cutoff)
    as_cgo = int(as_cgo)
    state, quiet = int(state), int(quiet)
    if state < 1:
        state = _self.get_state()
    model = _self.get_model(selection, state)
    regions_iter = qdelaunay((a.coord for a in model.atom),
                             3,
                             len(model.atom),
                             qdelaunay_exe=qdelaunay_exe)
    edges = set(
        tuple(sorted([region[i - 1], region[i]])) for region in regions_iter
        for i in range(len(region)))

    edgelist = []
    r = []

    minco = 9999
    maxco = 0

    for edge in edges:
        ii, jj = edge
        a = model.atom[ii]
        b = model.atom[jj]
        co = cpv.distance(a.coord, b.coord)
        if cutoff > 0.0 and co > cutoff:
            continue
        if as_cgo:
            minco = min(co, minco)
            maxco = max(co, maxco)
            edgelist.append(a.coord + b.coord + [co])
        else:
            bnd = Bond()
            bnd.index = [ii, jj]
            model.add_bond(bnd)
        r.append((a, b, co))

    if not as_cgo:
        _self.load_model(model, name, 1)
        return r

    from pymol.cgo import CYLINDER

    difco = maxco - minco
    obj = []
    mm = lambda x: max(min(x, 1.0), 0.0)
    for e in edgelist:
        co = ((e[6] - minco) / difco)**(0.75)
        color = [mm(1 - 2 * co), mm(1 - abs(2 * co - 1)), mm(2 * co - 1)]
        obj.extend([CYLINDER] + e[0:6] + [0.05] + color + color)

    _self.load_cgo(obj, name)
    return r