Exemple #1
0
 def read_chem_comp_atom_model_cartn(self, fields, field_dict, values):
     cartn_x = field_dict['_chem_comp_atom_model_cartn_x']
     cartn_y = field_dict['_chem_comp_atom_model_cartn_y']
     cartn_z = field_dict['_chem_comp_atom_model_cartn_z']
     print cartn_x, cartn_y, cartn_z
     name = field_dict.get('_chem_comp_atom_atom_id', None)
     symbol = field_dict.get('_chem_comp_atom_type_symbol', None)
     resn = field_dict.get('_chem_comp_atom.comp_id', None)
     partial_charge = field_dict.get('_chem_comp_atom_partial_charge', None)
     formal_charge = field_dict.get('chem_comp_atom_charge', None)
     str_fields = []
     if symbol != None: str_fields.append(('symbol', symbol))
     if name != None: str_fields.append(('name', name))
     if resn != None: str_fields.append(('resn', resn))
     float_fields = []
     if partial_charge != None:
         float_fields.append(('partial_charge', partial_charge))
     int_fields = []
     if formal_charge != None:
         int_fields.append(('formal_charge', formal_charge))
     for value in values:
         atom = Atom()
         atom.coord = [
             self.index_to_float(cartn_x, value),
             self.index_to_float(cartn_y, value),
             self.index_to_float(cartn_z, value)
         ]
         self.model.atom.append(atom)
         for field in str_fields:
             setattr(atom, field[0], value[field[1]])
         for field in float_fields:
             setattr(atom, field[0], self.index_to_float(field[1], value))
         for field in int_fields:
             setattr(atom, field[0], self.index_to_int(field[1], value))
Exemple #2
0
 def read_chem_comp_atom_model_cartn(self,fields,field_dict,values):
     cartn_x = field_dict['_chem_comp_atom_model_cartn_x']
     cartn_y = field_dict['_chem_comp_atom_model_cartn_y']
     cartn_z = field_dict['_chem_comp_atom_model_cartn_z']
     print cartn_x,cartn_y,cartn_z
     name = field_dict.get('_chem_comp_atom_atom_id',None)
     symbol = field_dict.get('_chem_comp_atom_type_symbol',None)
     resn = field_dict.get('_chem_comp_atom.comp_id',None)
     partial_charge = field_dict.get('_chem_comp_atom_partial_charge',None)
     formal_charge = field_dict.get('chem_comp_atom_charge',None)
     str_fields = []
     if symbol != None: str_fields.append( ('symbol',symbol) )
     if name != None: str_fields.append( ('name',name) )
     if resn != None: str_fields.append( ('resn',resn) )
     float_fields = []
     if partial_charge != None: float_fields.append( ('partial_charge',partial_charge) )
     int_fields = []
     if formal_charge != None: int_fields.append( ('formal_charge',formal_charge) ) 
     for value in values:
         atom = Atom()
         atom.coord = [
             self.index_to_float(cartn_x,value),
             self.index_to_float(cartn_y,value),
             self.index_to_float(cartn_z,value)]
         self.model.atom.append(atom)
         for field in str_fields:
             setattr(atom,field[0],value[field[1]])
         for field in float_fields:
             setattr(atom,field[0],self.index_to_float(field[1],value))
         for field in int_fields:
             setattr(atom,field[0],self.index_to_int(field[1],value))
Exemple #3
0
    def read_atom_site_fract(self, fields, field_dict, values):
        self.model.fractional = 1

        fract_x = field_dict['_atom_site_fract_x']
        fract_y = field_dict['_atom_site_fract_y']
        fract_z = field_dict['_atom_site_fract_z']
        symbol = field_dict.get('_atom_site_type_symbol', None)
        name = field_dict.get('_atom_site_label', None)
        u = field_dict.get('_atom_site_u_iso_or_equiv', None)
        str_fields = []
        if symbol != None: str_fields.append(('symbol', symbol))
        if name != None: str_fields.append(('name', name))
        float_fields = []
        if u != None: float_fields.append(('u', u))
        int_fields = []
        for value in values:
            atom = Atom()
            atom.coord = [
                self.index_to_float(fract_x, value),
                self.index_to_float(fract_y, value),
                self.index_to_float(fract_z, value)
            ]
            self.model.atom.append(atom)
            for field in str_fields:
                setattr(atom, field[0], value[field[1]])
            for field in float_fields:
                setattr(atom, field[0], self.index_to_float(field[1], value))
            for field in int_fields:
                setattr(atom, field[0], self.index_to_int(field[1], value))
Exemple #4
0
    def read_atom_site_fract(self,fields,field_dict,values):
        self.model.fractional = 1

        fract_x = field_dict['_atom_site_fract_x']
        fract_y = field_dict['_atom_site_fract_y']
        fract_z = field_dict['_atom_site_fract_z']
        symbol = field_dict.get('_atom_site_type_symbol',None)
        name = field_dict.get('_atom_site_label',None)
        u = field_dict.get('_atom_site_u_iso_or_equiv',None)                
        str_fields = []
        if symbol != None: str_fields.append( ('symbol',symbol) )
        if name != None: str_fields.append( ('name',name) )
        float_fields = []
        if u != None: float_fields.append( ('u', u))
        int_fields = []
        for value in values:
            atom = Atom()
            atom.coord = [
                self.index_to_float(fract_x,value),
                self.index_to_float(fract_y,value),
                self.index_to_float(fract_z,value)]
            self.model.atom.append(atom)
            for field in str_fields:
                setattr(atom,field[0],value[field[1]])
            for field in float_fields:
                setattr(atom,field[0],self.index_to_float(field[1],value))
            for field in int_fields:
                setattr(atom,field[0],self.index_to_int(field[1],value))
Exemple #5
0
def load_hypothesis_xvol(filename, name=''):
    '''
    Load excluded volumes from a hypothesis.xvol file.
    '''
    from epymol import m2io
    from chempy import Atom, models

    if not name:
        name = _name_from_filename(filename, '.xvol')

    reader = m2io.M2IOReader(filename)

    try:
        table = reader.find_block('f_m_table').m_row
        col_radius = table.keys.index('r_m_phase_radius')
        cols_xyz = [
            table.keys.index(n)
            for n in ['r_m_phase_x', 'r_m_phase_y', 'r_m_phase_z']
        ]
    except (AttributeError, IndexError):
        print(' Error: could not find table')
        return

    model = models.Indexed()

    for row in table:
        atom = Atom()
        atom.coord = [row[i] for i in cols_xyz]
        atom.vdw = row[col_radius]
        atom.trgb = 0x00FFFF00
        atom.visible = 0x2  # spheres
        model.add_atom(atom)

    pymol.cmd.load_model(model, name)
Exemple #6
0
def create_spheres(name, spheres, links, frame):

	cmd.delete(name)
	model = Indexed()
	for i in (range(len(spheres) / 4)):
		ai = i * 4
		r = spheres[ai + 3]
		cluster = int(name[7:10])
		if r <> 0.5:
			a=Atom()
			a.name = "X" + str(i)
			a.resi = str(cluster)
			a.vdw = spheres[ai + 3]
			a.coord = [spheres[ai], spheres[ai + 1], spheres[ai + 2]]
			model.atom.append(a)

	for i in (range(len(links) / 2)):
		li = i * 2
		a1 = links[li]
		a2 = links[li + 1]
		create_bond(model, a1, a2)

	cmd.load_model(model, name,frame)
	cmd.hide("lines", name)
	cmd.show("spheres", name)
Exemple #7
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 = ''
Exemple #8
0
    def read_atom_site_cartn(self, fields, field_dict, values):
        cartn_x = field_dict['_atom_site_cartn_x']
        cartn_y = field_dict['_atom_site_cartn_y']
        cartn_z = field_dict['_atom_site_cartn_z']
        group_pdb = field_dict.get('_atom_site_group_pdb', None)
        symbol = field_dict.get('_atom_site_type_symbol', None)
        name = field_dict.get('_atom_site_label_atom_id', None)
        resn = field_dict.get('_atom_site_label_comp_id', None)
        resi = field_dict.get('_atom_site_label_seq_id', None)
        chain = field_dict.get('_atom_site_label_asym_id', None)
        ins_code = field_dict.get('_atom_site_pdbx_pdb_ins_code', None)
        # use auth fields preferentially, if provided
        auth_resn = field_dict.get('_atom_site_auth_comp_id', None)
        auth_resi = field_dict.get('_atom_site_auth_seq_id', None)
        auth_name = field_dict.get('_atom_site_auth_atom_id', None)
        auth_chain = field_dict.get('_atom_site_auth_asym_id', None)
        if auth_resn != None: resn = auth_resn
        if auth_resi != None: resi = auth_resi
        if auth_name != None: name = auth_name
        if auth_chain != None: chain = auth_chain
        b = field_dict.get('_atom_site_b_iso_or_equiv', None)
        q = field_dict.get('_atom_site_occupancy', None)
        ID = field_dict.get('_atom_site_id', None)
        str_fields = []
        if symbol != None: str_fields.append(('symbol', symbol))
        if name != None: str_fields.append(('name', name))
        if resn != None: str_fields.append(('resn', resn))
        if resi != None: str_fields.append(('resi', resi))
        if chain != None: str_fields.append(('chain', chain))
        if ins_code != None: str_fields.append(('ins_code', ins_code))
        float_fields = []
        if q != None: float_fields.append(('q', q))
        if b != None: float_fields.append(('b', b))
        int_fields = []
        if ID != None: int_fields.append(('id', ID))

        for value in values:
            atom = Atom()
            atom.coord = [
                self.index_to_float(cartn_x, value),
                self.index_to_float(cartn_y, value),
                self.index_to_float(cartn_z, value)
            ]
            self.model.atom.append(atom)
            if group_pdb != None:
                if value[group_pdb] == 'ATOM':
                    atom.hetatm = 0
                else:
                    atom.hetatm = 1
            for field in str_fields:
                setattr(atom, field[0], value[field[1]])
            for field in float_fields:
                setattr(atom, field[0], self.index_to_float(field[1], value))
            for field in int_fields:
                setattr(atom, field[0], self.index_to_int(field[1], value))
Exemple #9
0
    def read_atom_site_cartn(self,fields,field_dict,values):
        cartn_x = field_dict['_atom_site_cartn_x']
        cartn_y = field_dict['_atom_site_cartn_y']
        cartn_z = field_dict['_atom_site_cartn_z']
        group_pdb = field_dict.get('_atom_site_group_pdb',None)
        symbol = field_dict.get('_atom_site_type_symbol',None)
        name = field_dict.get('_atom_site_label_atom_id',None)
        resn = field_dict.get('_atom_site_label_comp_id',None)
        resi = field_dict.get('_atom_site_label_seq_id',None)
        chain = field_dict.get('_atom_site_label_asym_id',None)
        ins_code = field_dict.get('_atom_site_pdbx_pdb_ins_code',None)
        # use auth fields preferentially, if provided
        auth_resn = field_dict.get('_atom_site_auth_comp_id',None)
        auth_resi = field_dict.get('_atom_site_auth_seq_id',None)
        auth_name = field_dict.get('_atom_site_auth_atom_id',None)
        auth_chain = field_dict.get('_atom_site_auth_asym_id',None)        
        if auth_resn != None: resn = auth_resn
        if auth_resi != None: resi = auth_resi
        if auth_name != None: name = auth_name
        if auth_chain != None: chain = auth_chain
        b = field_dict.get('_atom_site_b_iso_or_equiv',None)        
        q = field_dict.get('_atom_site_occupancy',None)
        ID = field_dict.get('_atom_site_id',None)
        str_fields = []
        if symbol != None: str_fields.append( ('symbol',symbol) )
        if name != None: str_fields.append( ('name',name) )
        if resn != None: str_fields.append( ('resn',resn) )
        if resi != None: str_fields.append( ('resi',resi) )
        if chain != None: str_fields.append( ('chain',chain) )        
        if ins_code != None: str_fields.append( ('ins_code',ins_code) )
        float_fields = []
        if q != None: float_fields.append( ('q',q) )
        if b != None: float_fields.append( ('b',b) )
        int_fields = []
        if ID != None: int_fields.append( ('id',ID) )                                

        for value in values:
            atom = Atom()
            atom.coord = [
                self.index_to_float(cartn_x,value),
                self.index_to_float(cartn_y,value),
                self.index_to_float(cartn_z,value)]
            self.model.atom.append(atom)
            if group_pdb != None:
                if value[group_pdb] == 'ATOM':
                    atom.hetatm = 0
                else:
                    atom.hetatm = 1
            for field in str_fields:
                setattr(atom,field[0],value[field[1]])
            for field in float_fields:
                setattr(atom,field[0],self.index_to_float(field[1],value))
            for field in int_fields:
                setattr(atom,field[0],self.index_to_int(field[1],value))
Exemple #10
0
def load_crd(filename, object=''):
    """
        Load a fDynamo coordinates file (.crd)

        Parameters
        ----------
        filename : str
            file path
        object : str, optional
            name of the object (def: filename prefix)
    """

    if not object:
        object = "".join(os.path.basename(filename).rpartition('.')[:-2])

    # read file as list of strings
    with open(filename, "rt") as f:
        crd_file = f.readlines()
        # remove comment lines, trailing comments and space split
        crd_file = [
            line.split("!")[0].split() for line in crd_file
            if line.strip() and not line.startswith("!")
        ]

    # reversed dictionary of atomic numbers to elements
    atomic_number_inv = {n: elem for elem, n in atomic_number.items()}

    # create new model and append crd's atoms
    model = Indexed()
    a = Atom()
    a.hetatm = False
    for line in crd_file:
        if line[0].lower() == "subsystem":
            a.segi = str(line[2])
        elif line[0].lower() == "residue":
            a.resi_number = int(line[1])
            a.resn = str(line[2])
        elif len(line) != 6:
            continue
        else:
            a.name = str(line[1])
            a.symbol = atomic_number_inv[int(line[2])]
            a.coord = (float(line[3]), float(line[4]), float(line[5]))
            model.add_atom(deepcopy(a))
    model.update_index()
    cmd.load_model(model, object)
    cmd.rebond(object)
    cmd.dss(object)

    print(f" pyDYNAMON: \"{filename}\" loaded as \"{object}\"")
Exemple #11
0
    def load_xvol(oname):
        lines = get_blob('s_phasehypo_ExcludedVolumes').splitlines()
        if len(lines) < 2:
            return

        model = models.Indexed()

        for line in lines[1:]:
            row = [float(c) for c in line.split()]
            atom = Atom()
            atom.coord = row[:3]
            atom.vdw = row[3]
            atom.trgb = 0x0033E5F2
            atom.visible = 0x2  # spheres
            model.add_atom(atom)

        pymol.cmd.load_model(model, oname, zoom=zoom)
Exemple #12
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')
Exemple #13
0
    def fromList(self,list):   # currently no handling of conect records

        model = Indexed()

# read atoms
        cnt = 0
        at = None
        for rec in list:
            if (rec[0:4]=='ATOM') or (rec[0:6]=='HETATM'):
                at = Atom()
                if rec[0]=='A': at.hetatm=0  # default is 1
                at.index = cnt
                at.name = string.strip(rec[12:16])
                at.alt = string.strip(rec[16:17])
                at.resn = string.strip(rec[17:20])
                at.chain = string.strip(rec[21:22])
                at.resi = string.strip(rec[22:27]) # note: insertion is part of resi
                at.resi_number = int(rec[22:26])
                at.coord = [float(rec[30:38]),
                                float(rec[38:46]),
                                float(rec[46:54])]
                try:
                    at.q = float(rec[54:60])
                except ValueError:
                    at.q = 1.0
                try:
                    at.b = float(rec[60:66])
                except ValueError:
                    at.b = 0.0
                at.segi = string.strip(rec[72:76])
                at.symbol = string.strip(rec[76:78])
                if not len(at.symbol):
                    at.symbol = at.name[0:1]
                    if at.symbol in '012345678':
                        at.symbol = at.name[1:2]
                cnt = cnt + 1
                model.add_atom(at)
            elif (rec[0:3]=='TER'):
                if at:
                    at.ter=1
        return(model)
Exemple #14
0
    def fromList(self,list):   # currently no handling of conect records 

        model = Indexed()
        
# read atoms
        cnt = 0
        at = None
        for rec in list:
            if (rec[0:4]=='ATOM') or (rec[0:6]=='HETATM'):
                at = Atom()
                if rec[0]=='A': at.hetatm=0  # default is 1
                at.index = cnt
                at.name = string.strip(rec[12:16])
                at.alt = string.strip(rec[16:17])
                at.resn = string.strip(rec[17:20])
                at.chain = string.strip(rec[21:22])
                at.resi = string.strip(rec[22:27]) # note: insertion is part of resi
                at.resi_number = int(rec[22:26])
                at.coord = [float(rec[30:38]), 
                                float(rec[38:46]),
                                float(rec[46:54])]
                try:
                    at.q = float(rec[54:60])
                except ValueError:
                    at.q = 1.0
                try:               
                    at.b = float(rec[60:66])
                except ValueError:
                    at.b = 0.0
                at.segi = string.strip(rec[72:76])
                at.symbol = string.strip(rec[76:78])
                if not len(at.symbol):
                    at.symbol = at.name[0:1]
                    if at.symbol in '012345678':
                        at.symbol = at.name[1:2]
                cnt = cnt + 1
                model.add_atom(at)
            elif (rec[0:3]=='TER'):
                if at:
                    at.ter=1
        return(model)
Exemple #15
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
Exemple #16
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
Exemple #17
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
Exemple #18
0
def load_pdbml(filename, object='', discrete=0, multiplex=1, zoom=-1,
        quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a PDBML formatted structure file
    '''
    from chempy import Atom, models
    from collections import defaultdict

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

    try:
        root = etree.fromstring(_self.file_read(filename))
        PDBxNS = root.tag.rstrip('datablock')
        atom_site_list = root.findall('.'
                '/' + PDBxNS + 'atom_siteCategory'
                '/' + PDBxNS + 'atom_site')
    except etree.XMLSyntaxError:
        raise CmdException("File doesn't look like XML")
    except etree.XPathEvalError:
        raise CmdException("XML file doesn't look like a PDBML file")

    if not atom_site_list:
        raise CmdException("no PDBx:atom_site nodes found in XML file")

    # state -> model dictionary
    model_dict = defaultdict(models.Indexed)

    # atoms
    for atom_site in atom_site_list:
        atom = Atom()
        atom.coord = [None, None, None]

        model_num = 1

        for child in atom_site:
            tag = child.tag

            if tag == PDBxNS + 'Cartn_x':
                atom.coord[0] = float(child.text)
            elif tag == PDBxNS + 'Cartn_y':
                atom.coord[1] = float(child.text)
            elif tag == PDBxNS + 'Cartn_z':
                atom.coord[2] = float(child.text)
            elif tag == PDBxNS + 'B_iso_or_equiv':
                atom.b = float(child.text)
            elif tag == PDBxNS + 'auth_asym_id':
                atom.chain = child.text or ''
            elif tag == PDBxNS + 'auth_atom_id':
                atom.name = child.text or ''
            elif tag == PDBxNS + 'auth_comp_id':
                atom.resn = child.text or ''
            elif tag == PDBxNS + 'auth_seq_id':
                atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_alt_id':
                atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_asym_id':
                atom.segi = child.text or ''
            elif tag == PDBxNS + 'label_atom_id':
                if not atom.name:
                    atom.name = child.text or ''
            elif tag == PDBxNS + 'label_comp_id':
                if not atom.resn:
                    atom.resn = child.text or ''
            elif tag == PDBxNS + 'label_seq_id':
                if not atom.resi:
                    atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_entity_id':
                atom.custom = child.text or ''
            elif tag == PDBxNS + 'occupancy':
                atom.q = float(child.text)
            elif tag == PDBxNS + 'pdbx_PDB_model_num':
                model_num = int(child.text)
            elif tag == PDBxNS + 'type_symbol':
                atom.symbol = child.text or ''
            elif tag == PDBxNS + 'group_PDB':
                atom.hetatm = (child.text == 'HETATM')

        if None not in atom.coord:
            model_dict[model_num].add_atom(atom)

    # symmetry and cell
    try:
        node = root.findall('.'
                '/' + PDBxNS + 'cellCategory'
                '/' + PDBxNS + 'cell')[0]
        cell = [
            float(node.findall('./' + PDBxNS + a)[0].text)
            for a in [
                'length_a', 'length_b', 'length_c', 'angle_alpha',
                'angle_beta', 'angle_gamma'
            ]
        ]

        spacegroup = root.findall('.'
                '/' + PDBxNS + 'symmetryCategory'
                '/' + PDBxNS + 'symmetry'
                '/' + PDBxNS + 'space_group_name_H-M')[0].text
    except IndexError:
        cell = None
        spacegroup = ''

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

    # only multiplex if more than one model/state
    multiplex = multiplex and len(model_dict) > 1

    # load models as objects or states
    for model_num in sorted(model_dict):
        if model_num < 1:
            print(" Error: model_num < 1 not supported")
            continue

        model = model_dict[model_num]
        model.connect_mode = 3

        if cell:
            model.cell = cell
            model.spacegroup = spacegroup

        if multiplex:
            oname = '%s_%04d' % (object, model_num)
            model_num = 1
        else:
            oname = object

        _self.load_model(model, oname,
                state=model_num, zoom=zoom, discrete=discrete)
def _to_chempy(data, use_auth=True):
    '''
    Construct a "chempy" model (molecule) from decoded MMTF data.
    '''
    from itertools import islice
    from chempy import models, Atom, Bond

    def add_bond(i1, i2, order, offset=0):
        bond = Bond()
        bond.order = order
        bond.index = [i1 + offset, i2 + offset]
        model.add_bond(bond)

    coord_iter = data.get_table_iter([
        'xCoordList',
        'yCoordList',
        'zCoordList',
    ])

    atom_iter = data.get_table_iter([
        'bFactorList',
        'occupancyList',
        'altLocList',
        'atomIdList',
    ], [0.0, 1.0, '', -1])

    group_iter = data.get_table_iter([
        'groupTypeList',
        'sequenceIndexList',
        'groupIdList',
        'insCodeList',
        'secStructList',
    ])

    chain_list_iter = enumerate(
        data.get_table_iter([
            'chainIdList',
            'chainNameList',
            'groupsPerChain',
        ]))

    groupList = data.get('groupList')

    symmetry = (
        data.get('unitCell', None),
        as_str(data.get('spaceGroup', '')),
    )

    model_output = []

    for n_chains in data.get_iter('chainsPerModel'):
        model = models.Indexed()
        model_output.append(model)

        if symmetry[0] is not None:
            model.cell, model.spacegroup = symmetry

        for (chain_idx, (segi, chain,
                         n_groups)) in islice(chain_list_iter, n_chains):
            for (groupType, label_seq_id, auth_seq_id, ins_code, ss_info) in \
                    islice(group_iter, n_groups):

                group = groupList[groupType]
                resn = as_str(group[b'groupName'])

                group_bond_iter = izip(
                    group[b'bondAtomList'][0::2],
                    group[b'bondAtomList'][1::2],
                    group[b'bondOrderList'],
                )

                offset = len(model.atom)
                for (i1, i2, order) in group_bond_iter:
                    add_bond(i1, i2, order, offset)

                group_atom_iter = izip(
                    group[b'atomNameList'],
                    group[b'elementList'],
                    group[b'formalChargeList'],
                )

                for (name, elem, formal_charge) in group_atom_iter:
                    atom = Atom()

                    (atom.b, atom.q, atom.alt, atom.id) = next(atom_iter)

                    atom.coord = next(coord_iter)
                    atom.symbol = as_str(elem)
                    atom.name = as_str(name)
                    atom.resn = resn
                    atom.hetatm = label_seq_id == -1
                    atom.formal_charge = formal_charge
                    atom.segi = segi
                    atom.chain = chain
                    atom.ss = ss_map.get(ss_info, '')

                    if use_auth or label_seq_id is None:
                        atom.resi = auth_seq_id
                        atom.ins_code = ins_code or ''
                    else:
                        atom.resi = label_seq_id + 1

                    model.add_atom(atom)

    model_atom_max = 0
    model_atom_min = 0
    model_iter = iter(model_output)
    bondAtomList_iter = data.get_iter('bondAtomList')

    for order in data.get_iter('bondOrderList'):
        i1 = next(bondAtomList_iter)
        i2 = next(bondAtomList_iter)
        if i1 >= model_atom_max or i2 >= model_atom_max:
            model = next(model_iter)
            model_atom_min = model_atom_max
            model_atom_max += len(model.atom)
        add_bond(i1, i2, order, -model_atom_min)

    return model_output
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)
Exemple #21
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())
Exemple #22
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
Exemple #23
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)
from chempy.models import Indexed
from chempy import Atom,Bond
import math


# create a model instance

model = Indexed()

# append the atoms onto it 

for x in range(-63,63,1):
   for y in range(-63,63,1):
      new_atom = Atom()
      new_atom.symbol = 'O'
      new_atom.coord = [ x*2, y*2, 30 * math.cos(math.sqrt(x*x+y*y)/60.0) ]
      model.atom.append(new_atom)


cmd.load_model(model,"membrane")
cmd.hide("everything","membrane")
cmd.show("spheres","membrane")
cmd.color("lightblue","membrane")

cmd.set_view( (\
     0.736728907,   -0.144400939,    0.660589039,\
     0.675238073,    0.208899528,   -0.707400322,\
    -0.035847016,    0.967217624,    0.251406968,\
     0.000008686,    0.000009686, -332.961212158,\
    -2.366872311,   -1.122793436,   23.127344131,\
    11.627288818,  654.294433594,    0.000000000 ))
Exemple #25
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)
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 parse_atom_block(self,count,spec,data,full):
        handler = {
            'i_m_mmod_type' : lambda c,x,a:setattr(a,'numeric_type',int(x)),
            'r_m_x_coord' : lambda c,x,a:a.coord.__setitem__(0,float(x)),
            'r_m_y_coord' : lambda c,x,a:a.coord.__setitem__(1,float(x)),
            'r_m_z_coord' : lambda c,x,a:a.coord.__setitem__(2,float(x)),
            'i_m_residue_number' : lambda c,x,a:setattr(a,'resi',x),
            's_m_insertion_code' : lambda c,x,a:setattr(a,'ins_code',x),
#            's_m_mmod_res' : lambda c,x,a:setattr(a,'mmod_res',x),
            's_m_chain_name' : lambda c,x,a:setattr(a,'chain',x),
            'i_m_color' : lambda c,x,a:setattr(a,'trgb',_color_dict.get(int(x), 0xffffff)),
            'r_m_charge1' : lambda c,x,a:setattr(a,'partial_charge',float(x)),
#            'r_m_charge2' : lambda c,x,a:setattr(a,'',x),
            's_m_pdb_residue_name' : lambda c,x,a:setattr(a,'resn',x),
            's_m_pdb_atom_name' : handler_atom_name,
#            's_m_grow_name' : lambda c,x,a:setattr(a,'',x),
            'i_m_atomic_number' : lambda c,x,a:setattr(a,'symbol',_p2sym.get(int(x),'X')),
            'i_m_formal_charge' : lambda c,x,a:setattr(a,'formal_charge',int(x)),
            's_m_atom_name' : handler_atom_name,
            'i_m_secondary_structure' : lambda c,x,a:setattr(a,'ss',_ss2ss.get(int(x),'L')),
            's_m_label_format' : lambda c,x,a:setattr(a,'label_format',x),
            'i_m_label_color' : hanlder_i_m_label_color,
            's_m_label_user_text' : lambda c,x,a:setattr(a,'label_user_text',x),
            'i_m_ribbon_style' : handler_i_m_ribbon_style,
            'i_m_representation' : handler_i_m_representation,
            'i_m_ribbon_color' : hanlder_i_m_ribbon_color,
            'i_m_visibility' : lambda c,x,a:setattr(a,'visibility',int(x)),
            'r_m_pdb_tfactor' : lambda c,x,a:setattr(a,'b',float(x)),
#            'i_m_pdb_convert_problem' : lambda c,x,a:setattr(a,'',x),
            }
        if not self.mimic:
            handler['i_m_label_color']=lambda c,x,a:None
            handler['i_m_ribbon_color']=lambda c,x,a:None
            
        fn_list = [ ['id', lambda c,x,a:setattr(a,'id',int(x)) ] ]

        for code in spec:
            fn = handler.get(code)
            if fn is None:
                if self.load_all_atom_properties or code in self.load_atom_properties:
                    fn = default_atom_handler
                else:
                    fn = dummy_handler
            fn_list.append([ code, fn ])
            
        data.reverse()
        if full != None:
            count = len(data)/len(fn_list)
            atom_list = deepcopy(full)
        else:
            atom_list = []
        for a in range(count):
            if full == None:
                at = Atom()
                at.coord = [0.0,0.0,0.0]
                at.visible = REP_NONBONDED
                at.hetatm = 0
                atom_list.append(at)
            else:
                at = atom_list[int(data[-1])-1] # trusting index
            if 'i_m_representation' in spec: # representation information provided
                at.visible = 0

            for code, fn in fn_list: 
                fn(code, data.pop(), at)

            if hasattr(at,'label_format'):
                if at.label_format != "%OF":
                    get = {
                        "%UT": at.label_user_text,
                        "%RT": at.resn,
                        "%RN": at.resi,
                        "%CH": at.chain,
                        "%EL": at.symbol,
                        "%NU": str(at.id),
                        "%FC": "%+d" % at.formal_charge if at.formal_charge else "",
                    }.get
                    label = _label_fmt_re.sub(lambda m: get(m.group(), ''), at.label_format)
                    if len(label.replace(" ","")):
                        at.visible |= REP_LABELS
                        at.label = label
                    elif hasattr(at,'label_trgb'):
                        del at.label_trgb
                del at.label_format
                
        for atom in atom_list:
            if hasattr(atom,'ins_code'):
                atom.resi=atom.resi+atom.ins_code
                del atom.ins_code
                
        return atom_list
Exemple #28
0
    def read_atom_site_cartn(self,fields,field_dict,values):
        try:
            cartn_x = field_dict['_atom_site_cartn_x']
            cartn_y = field_dict['_atom_site_cartn_y']
            cartn_z = field_dict['_atom_site_cartn_z']
        except KeyError as e:
            return False
        group_pdb = field_dict.get('_atom_site_group_pdb',None)
        symbol = field_dict.get('_atom_site_type_symbol',None)
        name = field_dict.get('_atom_site_label_atom_id',None)
        resn = field_dict.get('_atom_site_label_comp_id',None)
        resi = field_dict.get('_atom_site_label_seq_id',None)
        chain = field_dict.get('_atom_site_label_asym_id',None)
        ins_code = field_dict.get('_atom_site_pdbx_pdb_ins_code',None)
        alt = field_dict.get('_atom_site_label_alt_id', None)
        model_num = field_dict.get('_atom_site_pdbx_pdb_model_num', None)
        # use auth fields preferentially, if provided
        auth_resn = field_dict.get('_atom_site_auth_comp_id',None)
        auth_resi = field_dict.get('_atom_site_auth_seq_id',None)
        auth_name = field_dict.get('_atom_site_auth_atom_id',None)
        auth_chain = field_dict.get('_atom_site_auth_asym_id',None)        
        if auth_resn != None: resn = auth_resn
        if auth_resi != None: resi = auth_resi
        if auth_name != None: name = auth_name
        if auth_chain != None: chain = auth_chain
        b = field_dict.get('_atom_site_b_iso_or_equiv',None)        
        q = field_dict.get('_atom_site_occupancy',None)
        ID = field_dict.get('_atom_site_id',None)
        str_fields = []
        if symbol != None: str_fields.append( ('symbol',symbol) )
        if name != None: str_fields.append( ('name',name) )
        if resn != None: str_fields.append( ('resn',resn) )
        if resi != None: str_fields.append( ('resi',resi) )
        if chain != None:
            str_fields.append( ('chain',chain) )
            if ASYM_ID_AS_SEGI:
                str_fields.append( ('segi',chain) )
        if alt != None: str_fields.append( ('alt',alt) )
        if ins_code != None: str_fields.append( ('ins_code',ins_code) )
        float_fields = []
        if q != None: float_fields.append( ('q',q) )
        if b != None: float_fields.append( ('b',b) )
        int_fields = []
        if ID != None: int_fields.append( ('id',ID) )                                

        first_model_num = self.index_to_int(model_num, values[0])

        for value in values:
            coord = [
                self.index_to_float(cartn_x,value),
                self.index_to_float(cartn_y,value),
                self.index_to_float(cartn_z,value)]

            if model_num is not None:
                v = self.index_to_int(model_num, value)
                if v != first_model_num:
                    self.extra_coords.extend(coord)
                    continue

            atom = Atom()
            atom.coord = coord
            self.model.atom.append(atom)
            if group_pdb != None:
                if value[group_pdb] == 'ATOM':
                    atom.hetatm = 0
                else:
                    atom.hetatm = 1
            for field in str_fields:
                setattr(atom,field[0],self.index_to_str(field[1],value))
            for field in float_fields:
                setattr(atom,field[0],self.index_to_float(field[1],value))
            for field in int_fields:
                setattr(atom,field[0],self.index_to_int(field[1],value))
        return True
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))
Exemple #30
0
 def append_node(model, list, test = None):
     at = Atom()
     at.name = '0'
     at.vdw = list[3]
     at.coord = list[:3]
     model.atom.append(at)
Exemple #31
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)
Exemple #32
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())
Exemple #33
0
def load_pdbml(filename, object='', discrete=0, multiplex=1, zoom=-1,
        quiet=1, _self=cmd):
    '''
DESCRIPTION

    Load a PDBML formatted structure file
    '''
    from chempy import Atom, models
    from collections import defaultdict

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

    try:
        root = etree.fromstring(_self.file_read(filename))
        PDBxNS = root.tag.rstrip('datablock')
        atom_site_list = root.findall('.'
                '/' + PDBxNS + 'atom_siteCategory'
                '/' + PDBxNS + 'atom_site')
    except etree.XMLSyntaxError:
        raise CmdException("File doesn't look like XML")
    except etree.XPathEvalError:
        raise CmdException("XML file doesn't look like a PDBML file")

    if not atom_site_list:
        raise CmdException("no PDBx:atom_site nodes found in XML file")

    # state -> model dictionary
    model_dict = defaultdict(models.Indexed)

    # atoms
    for atom_site in atom_site_list:
        atom = Atom()
        atom.coord = [None, None, None]

        model_num = 1

        for child in atom_site:
            tag = child.tag

            if tag == PDBxNS + 'Cartn_x':
                atom.coord[0] = float(child.text)
            elif tag == PDBxNS + 'Cartn_y':
                atom.coord[1] = float(child.text)
            elif tag == PDBxNS + 'Cartn_z':
                atom.coord[2] = float(child.text)
            elif tag == PDBxNS + 'B_iso_or_equiv':
                atom.b = float(child.text)
            elif tag == PDBxNS + 'auth_asym_id':
                atom.chain = child.text or ''
            elif tag == PDBxNS + 'auth_atom_id':
                atom.name = child.text or ''
            elif tag == PDBxNS + 'auth_comp_id':
                atom.resn = child.text or ''
            elif tag == PDBxNS + 'auth_seq_id':
                atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_alt_id':
                atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_asym_id':
                atom.segi = child.text or ''
            elif tag == PDBxNS + 'label_atom_id':
                if not atom.name:
                    atom.name = child.text or ''
            elif tag == PDBxNS + 'label_comp_id':
                if not atom.resn:
                    atom.resn = child.text or ''
            elif tag == PDBxNS + 'label_seq_id':
                if not atom.resi:
                    atom.resi = child.text or ''
            elif tag == PDBxNS + 'label_entity_id':
                atom.custom = child.text or ''
            elif tag == PDBxNS + 'occupancy':
                atom.q = float(child.text)
            elif tag == PDBxNS + 'pdbx_PDB_model_num':
                model_num = int(child.text)
            elif tag == PDBxNS + 'type_symbol':
                atom.symbol = child.text or ''
            elif tag == PDBxNS + 'group_PDB':
                atom.hetatm = (child.text == 'HETATM')

        if None not in atom.coord:
            model_dict[model_num].add_atom(atom)

    # symmetry and cell
    try:
        node = root.findall('.'
                '/' + PDBxNS + 'cellCategory'
                '/' + PDBxNS + 'cell')[0]
        cell = [
            float(node.findall('./' + PDBxNS + a)[0].text)
            for a in [
                'length_a', 'length_b', 'length_c', 'angle_alpha',
                'angle_beta', 'angle_gamma'
            ]
        ]

        spacegroup = root.findall('.'
                '/' + PDBxNS + 'symmetryCategory'
                '/' + PDBxNS + 'symmetry'
                '/' + PDBxNS + 'space_group_name_H-M')[0].text
    except IndexError:
        cell = None
        spacegroup = ''

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

    # only multiplex if more than one model/state
    multiplex = multiplex and len(model_dict) > 1

    # load models as objects or states
    for model_num in sorted(model_dict):
        if model_num < 1:
            print(" Error: model_num < 1 not supported")
            continue

        model = model_dict[model_num]
        model.connect_mode = 3

        if cell:
            model.cell = cell
            model.spacegroup = spacegroup

        if multiplex:
            oname = '%s_%04d' % (object, model_num)
            model_num = 1
        else:
            oname = object

        _self.load_model(model, oname,
                state=model_num, zoom=zoom, discrete=discrete)
Exemple #34
0
    def read_atom_site_cartn(self, fields, field_dict, values):
        try:
            cartn_x = field_dict['_atom_site_cartn_x']
            cartn_y = field_dict['_atom_site_cartn_y']
            cartn_z = field_dict['_atom_site_cartn_z']
        except KeyError as e:
            return False
        group_pdb = field_dict.get('_atom_site_group_pdb', None)
        symbol = field_dict.get('_atom_site_type_symbol', None)
        name = field_dict.get('_atom_site_label_atom_id', None)
        resn = field_dict.get('_atom_site_label_comp_id', None)
        resi = field_dict.get('_atom_site_label_seq_id', None)
        chain = field_dict.get('_atom_site_label_asym_id', None)
        ins_code = field_dict.get('_atom_site_pdbx_pdb_ins_code', None)
        alt = field_dict.get('_atom_site_label_alt_id', None)
        model_num = field_dict.get('_atom_site_pdbx_pdb_model_num', None)
        # use auth fields preferentially, if provided
        auth_resn = field_dict.get('_atom_site_auth_comp_id', None)
        auth_resi = field_dict.get('_atom_site_auth_seq_id', None)
        auth_name = field_dict.get('_atom_site_auth_atom_id', None)
        auth_chain = field_dict.get('_atom_site_auth_asym_id', None)
        if auth_resn is not None: resn = auth_resn
        if auth_resi is not None: resi = auth_resi
        if auth_name is not None: name = auth_name
        if auth_chain is not None: chain = auth_chain
        b = field_dict.get('_atom_site_b_iso_or_equiv', None)
        q = field_dict.get('_atom_site_occupancy', None)
        ID = field_dict.get('_atom_site_id', None)
        str_fields = []
        if symbol is not None: str_fields.append(('symbol', symbol))
        if name is not None: str_fields.append(('name', name))
        if resn is not None: str_fields.append(('resn', resn))
        if resi is not None: str_fields.append(('resi', resi))
        if chain is not None:
            str_fields.append(('chain', chain))
            if ASYM_ID_AS_SEGI:
                str_fields.append(('segi', chain))
        if alt is not None: str_fields.append(('alt', alt))
        if ins_code is not None: str_fields.append(('ins_code', ins_code))
        float_fields = []
        if q is not None: float_fields.append(('q', q))
        if b is not None: float_fields.append(('b', b))
        int_fields = []
        if ID is not None: int_fields.append(('id', ID))

        first_model_num = self.index_to_int(model_num, values[0])

        for value in values:
            coord = [
                self.index_to_float(cartn_x, value),
                self.index_to_float(cartn_y, value),
                self.index_to_float(cartn_z, value)
            ]

            if model_num is not None:
                v = self.index_to_int(model_num, value)
                if v != first_model_num:
                    self.extra_coords.extend(coord)
                    continue

            atom = Atom()
            atom.coord = coord
            self.model.atom.append(atom)
            if group_pdb is not None:
                if value[group_pdb] == 'ATOM':
                    atom.hetatm = 0
                else:
                    atom.hetatm = 1
            for field in str_fields:
                setattr(atom, field[0], self.index_to_str(field[1], value))
            for field in float_fields:
                setattr(atom, field[0], self.index_to_float(field[1], value))
            for field in int_fields:
                setattr(atom, field[0], self.index_to_int(field[1], value))
        return True
Exemple #35
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
Exemple #36
0
def sidechaincenters(object='scc', selection='all', method='bahar1996', name='PS1'):
    '''
DESCRIPTION

    Creates an object with sidechain representing pseudoatoms for each residue
    in selection.

    Two methods are available:
    (1) Sidechain interaction centers as defined by Bahar and Jernigan 1996
        http://www.ncbi.nlm.nih.gov/pubmed/9080182
    (2) Sidechain centroids, the pseudoatom is the centroid of all atoms except
        hydrogens and backbone atoms (N, C and O).

NOTE

    With method "bahar1996", if a residue has all relevant sidechain center
    atoms missing (for example a MET without SD), it will be missing in the
    created pseudoatom object.

    With method "centroid", if you want to exclude C-alpha atoms from
    sidechains, modify the selection like in this example:

    sidechaincenters newobject, all and (not name CA or resn GLY), method=2

USAGE

    sidechaincenters object [, selection [, method ]]

ARGUMENTS

    object = string: name of object to create

    selection = string: atoms to consider {default: (all)}

    method = string: bahar1996 or centroid {default: bahar1996}

    name = string: atom name of pseudoatoms {default: PS1}

SEE ALSO

    pseudoatom
    '''
    from chempy import Atom, cpv, models

    atmap = dict()
    if method in ['bahar1996', '1', 1]:
        modelAll = cmd.get_model('(%s) and resn %s' % (selection, '+'.join(sidechaincenteratoms)))
        for at in modelAll.atom:
            if at.name in sidechaincenteratoms[at.resn]:
                atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    elif method in ['centroid', '2', 2]:
        modelAll = cmd.get_model('(%s) and polymer and not (hydro or name C+N+O)' % selection)
        for at in modelAll.atom:
            atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    else:
        print('Error: unknown method:', method)
        raise CmdException

    model = models.Indexed()
    for centeratoms in atmap.values():
        center = cpv.get_null()
        for at in centeratoms:
            center = cpv.add(center, at.coord)
        center = cpv.scale(center, 1./len(centeratoms))
        atom = Atom()
        atom.coord = center
        atom.index = model.nAtom + 1
        atom.name = name
        for key in ['resn','chain','resi','resi_number','hetatm','ss','segi']:
            atom.__dict__[key] = at.__dict__[key]
        model.add_atom(atom)
    model.update_index()
    if object in cmd.get_object_list():
        cmd.delete(object)
    cmd.load_model(model, object)
    return model
Exemple #37
0
def sidechaincenters(object='scc', selection='all', method='bahar1996', name='PS1', *, _self=cmd):
    '''
DESCRIPTION

    Creates an object with sidechain representing pseudoatoms for each residue
    in selection.

    Two methods are available:
    (1) Sidechain interaction centers as defined by Bahar and Jernigan 1996
        http://www.ncbi.nlm.nih.gov/pubmed/9080182
    (2) Sidechain centroids, the pseudoatom is the centroid of all atoms except
        hydrogens and backbone atoms (N, C and O).

NOTE

    With method "bahar1996", if a residue has all relevant sidechain center
    atoms missing (for example a MET without SD), it will be missing in the
    created pseudoatom object.

    With method "centroid", if you want to exclude C-alpha atoms from
    sidechains, modify the selection like in this example:

    sidechaincenters newobject, all and (not name CA or resn GLY), method=2

USAGE

    sidechaincenters object [, selection [, method ]]

ARGUMENTS

    object = string: name of object to create

    selection = string: atoms to consider {default: (all)}

    method = string: bahar1996 or centroid {default: bahar1996}

    name = string: atom name of pseudoatoms {default: PS1}

SEE ALSO

    pseudoatom
    '''
    from chempy import Atom, cpv, models

    atmap = dict()
    if method in ['bahar1996', '1', 1]:
        modelAll = _self.get_model('(%s) and resn %s' % (selection, '+'.join(sidechaincenteratoms)))
        for at in modelAll.atom:
            if at.name in sidechaincenteratoms[at.resn]:
                atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    elif method in ['centroid', '2', 2]:
        modelAll = _self.get_model('(%s) and polymer and not (hydro or name C+N+O)' % selection)
        for at in modelAll.atom:
            atmap.setdefault((at.segi, at.chain, at.resn, at.resi), []).append(at)
    else:
        raise CmdException('unknown method: {}'.format(method))

    model = models.Indexed()
    for centeratoms in atmap.values():
        center = cpv.get_null()
        for at in centeratoms:
            center = cpv.add(center, at.coord)
        center = cpv.scale(center, 1./len(centeratoms))
        atom = Atom()
        atom.coord = center
        atom.index = model.nAtom + 1
        atom.name = name
        for key in [
                'segi',
                'chain',
                'resi_number',
                'resi',
                'resn',
                'hetatm',
                'ss',
                'b',
        ]:
            setattr(atom, key, getattr(at, key))
        model.add_atom(atom)
    model.update_index()
    if object in _self.get_object_list():
        _self.delete(object)
    _self.load_model(model, object)
    return model
Exemple #38
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