def read_chem_comp_bond_atom_ids(self, fields, field_dict, values): try: label_1 = field_dict['_chem_comp_bond_atom_id_1'] label_2 = field_dict['_chem_comp_bond_atom_id_2'] except KeyError: return False order_table = {'sing': 1, 'doub': 2, 'trip': 3, 'delo': 4} # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom, 'name'): name_dict[atom.name] = cnt cnt = cnt + 1 order = field_dict.get('_chem_comp_bond_value_order', None) for value in values: try: index = [ name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)] ] except KeyError: print(" CIF _chem_comp_bond_atom_id, invalid keys:", value) continue bond = Bond() bond.index = index if order is not None: order_string = self.index_to_str(order, value).lower() bond.order = order_table.get(order_string[0:4], 1) else: bond.order = 1 self.model.bond.append(bond) # don't do distance-based bonding self.model.connect_mode = 1 return True
def read_chem_comp_bond_atom_ids(self,fields,field_dict,values): try: label_1 = field_dict['_chem_comp_bond_atom_id_1'] label_2 = field_dict['_chem_comp_bond_atom_id_2'] except KeyError: return False order_table = { 'sing' : 1, 'doub' : 2, 'trip' :3, 'delo': 4 } # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom,'name'): name_dict[atom.name] = cnt cnt = cnt + 1 order = field_dict.get('_chem_comp_bond_value_order',None) for value in values: try: index = [name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)]] except KeyError: print " CIF _chem_comp_bond_atom_id, invalid keys:", value continue bond = Bond() bond.index = index if order != None: order_string = self.index_to_str(order,value).lower() bond.order = order_table.get(order_string[0:4],1) else: bond.order = 1 self.model.bond.append(bond) # don't do distance-based bonding self.model.connect_mode = 1 return True
def cap(object): from pymol import cmd model = cmd.get_model(object) # guarantee identical ordering cmd.delete(object) cmd.load_model(model,object) n_list = cmd.identify("(n;n &!(n;c a;2.0))") c_list = cmd.identify("(n;c &!(n;n a;2.0))") print n_list print c_list for a in n_list: newat = copy.deepcopy(model.atom[a]) newat.coord = [ newat.coord[0] + random.random(), newat.coord[1] + random.random(), newat.coord[2] + random.random(), ] newat.symbol = 'H' newat.name = 'HN' newat.numeric_type = 43 bond = Bond() bond.order = 1 bond.stereo = 0 bond.index = [ a, model.nAtom ] print "adding",newat.name,bond.index model.add_atom(newat) model.add_bond(bond) for a in c_list: newat = copy.deepcopy(model.atom[a]) newat.coord = [ newat.coord[0] + random.random(), newat.coord[1] + random.random(), newat.coord[2] + random.random(), ] newat.symbol = 'H' newat.name = 'HC' newat.numeric_type = 41 bond = Bond() bond.order = 1 bond.stereo = 0 bond.index = [ a, model.nAtom ] print "adding",newat.name,bond.index model.add_atom(newat) model.add_bond(bond) # reload cmd.delete(object) cmd.load_model(model,object) cmd.sort(object)
def bondseeker(model, nbr, excludeH=True, ceil=BONDNOHMAX): pairs = [] for i, at in enumerate(model.atom): if at.symbol == "H" and excludeH: continue if at.symbol != "H" and not excludeH: continue lst = nbr.get_neighbors(at.coord) for b in lst: at2 = model.atom[b] if at2.symbol == 'H': #we can always exclude these, since we don't expect to find H-H bonds. If you want to add H2 molecules, you are not in luck, I guess continue if excludeH and [ b, i ] in pairs: #we can save some comparisons because if we are not excluding H, we are sure that at is an H, and at2 isn't, so the pair [at2,at1] can never be added. continue dst = chempy.cpv.distance(at.coord, at2.coord) if dst > ceil: if not (at.symbol == "S" and at2.symbol == "S" and dst < SSBONDMAX): #allow for SS bonds. continue pairs.append([i, b]) bnd = Bond() bnd.index = [i, b] bnd.order = 1 #yeah, not going to do the proper bond order. model.bond.append(bnd)
def read_chem_comp_bond_atom_ids(self,fields,field_dict,values): order_table = { 'sing' : 1, 'doub' : 2, 'trip' :3, 'delo': 4 } # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom,'name'): name_dict[atom.name] = cnt cnt = cnt + 1 label_1 = field_dict['_chem_comp_bond_atom_id_1'] label_2 = field_dict['_chem_comp_bond_atom_id_2'] order = field_dict.get('_chem_comp_bond_value_order',None) for value in values: bond = Bond() bond.index = [ name_dict[self.index_to_str(label_1,value)], name_dict[self.index_to_str(label_2,value)]] if order != None: order_string = string.lower(self.index_to_str(order,value)) bond.order = order_table.get(order_string[0:4],1) else: bond.order = 1 self.model.bond.append(bond)
def read_chem_comp_bond_atom_ids(self, fields, field_dict, values): order_table = {'sing': 1, 'doub': 2, 'trip': 3, 'delo': 4} # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom, 'name'): name_dict[atom.name] = cnt cnt = cnt + 1 label_1 = field_dict['_chem_comp_bond_atom_id_1'] label_2 = field_dict['_chem_comp_bond_atom_id_2'] order = field_dict.get('_chem_comp_bond_value_order', None) for value in values: bond = Bond() bond.index = [ name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)] ] if order != None: order_string = string.lower(self.index_to_str(order, value)) bond.order = order_table.get(order_string[0:4], 1) else: bond.order = 1 self.model.bond.append(bond)
def read_geom_bond_atom_site_labels(self,fields,field_dict,values): # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom,'name'): name_dict[atom.name] = cnt cnt = cnt + 1 label_1 = field_dict['_geom_bond_atom_site_label_1'] label_2 = field_dict['_geom_bond_atom_site_label_2'] for value in values: bond = Bond() bond.index = [ name_dict[self.index_to_str(label_1,value)], name_dict[self.index_to_str(label_2,value)]] bond.order = 1 self.model.bond.append(bond)
def read_geom_bond_atom_site_labels(self, fields, field_dict, values): # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom, 'name'): name_dict[atom.name] = cnt cnt = cnt + 1 label_1 = field_dict['_geom_bond_atom_site_label_1'] label_2 = field_dict['_geom_bond_atom_site_label_2'] for value in values: bond = Bond() bond.index = [ name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)] ] bond.order = 1 self.model.bond.append(bond)
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')
def add_bonds(model, topology=None, forcefield=None): if not isinstance(model, chempy.models.Indexed): raise ValueError('model is not an "Indexed" model object') nAtom = model.nAtom if nAtom: tmpl = topology.normal ffld = forcefield.normal res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] resn = base.resn if resn not in tmpl: raise RuntimeError("unknown residue type '" + resn + "'") else: # reassign atom names and build dictionary dict = {} aliases = tmpl[resn]['aliases'] for b in range(a[0], a[1]): at = model.atom[b] if at.name in aliases: at.name = aliases[at.name] dict[at.name] = b if forcefield: k = (resn, at.name) if k in ffld: at.text_type = ffld[k]['type'] at.partial_charge = ffld[k]['charge'] else: raise RuntimeError("no parameters for '" + str(k) + "'") # now add bonds for atoms which are present bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and b[1] in dict: bnd = Bond() bnd.index = [dict[b[0]], dict[b[1]]] bnd.order = bonds[b]['order'] mbond.append(bnd)
def read_geom_bond_atom_site_labels(self, fields, field_dict, values): try: label_1 = field_dict.get('_geom_bond_atom_site_id_1', None) if label_1 is not None: label_2 = field_dict['_geom_bond_atom_site_id_2'] else: label_1 = field_dict['_geom_bond_atom_site_label_1'] label_2 = field_dict['_geom_bond_atom_site_label_2'] except KeyError: return False symm_1 = field_dict.get('_geom_bond_site_symmetry_1', -1) symm_2 = field_dict.get('_geom_bond_site_symmetry_2', -1) # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom, 'name'): name_dict[atom.name] = cnt cnt = cnt + 1 for value in values: if self.index_to_str(symm_1, value) != self.index_to_str( symm_2, value): # don't bond to symmetry mates continue try: index = [ name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)] ] except KeyError: print(" CIF _geom_bond_atom_site_label, invalid keys:", value) continue bond = Bond() bond.index = index bond.order = 1 self.model.bond.append(bond) return True
def add_bonds(model, topology = None, forcefield = None ): if str(model.__class__) != 'chempy.models.Indexed': raise ValueError('model is not an "Indexed" model object') nAtom = model.nAtom if nAtom: tmpl = topology.normal ffld = forcefield.normal res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] resn = base.resn if not tmpl.has_key(resn): raise RuntimeError("unknown residue type '"+resn+"'") else: # reassign atom names and build dictionary dict = {} aliases = tmpl[resn]['aliases'] for b in range(a[0],a[1]): at = model.atom[b] if aliases.has_key(at.name): at.name = aliases[at.name] dict[at.name] = b if forcefield: k = (resn,at.name) if ffld.has_key(k): at.text_type = ffld[k]['type'] at.partial_charge = ffld[k]['charge'] else: raise RuntimeError("no parameters for '"+str(k)+"'") # now add bonds for atoms which are present bonds = tmpl[resn]['bonds'] mbond = model.bond for b in bonds.keys(): if dict.has_key(b[0]) and dict.has_key(b[1]): bnd = Bond() bnd.index = [ dict[b[0]], dict[b[1]] ] bnd.order = bonds[b]['order'] mbond.append(bnd)
def _read_m_bond(self,m_bond,model): bd_ent = m_bond[1] bd_dat = m_bond[2] nBond = m_bond[0] if len(bd_dat[0]): # not empty right? if 'i_m_from' in bd_ent and \ 'i_m_to' in bd_ent and \ 'i_m_order' in bd_ent: a1 = bd_dat[bd_ent['i_m_from']] a2 = bd_dat[bd_ent['i_m_to']] a3 = bd_dat[bd_ent['i_m_order']] for b in range(nBond): bd1 = a1[b] - 1 bd2 = a2[b] - 1 bd3 = a3[b] if bd1<bd2: bnd = Bond() bnd.index = [ bd1,bd2 ] bnd.order = bd3 model.bond.append(bnd)
def read_geom_bond_atom_site_labels(self,fields,field_dict,values): try: label_1 = field_dict.get('_geom_bond_atom_site_id_1', None) if label_1 is not None: label_2 = field_dict['_geom_bond_atom_site_id_2'] else: label_1 = field_dict['_geom_bond_atom_site_label_1'] label_2 = field_dict['_geom_bond_atom_site_label_2'] except KeyError: return False symm_1 = field_dict.get('_geom_bond_site_symmetry_1', -1) symm_2 = field_dict.get('_geom_bond_site_symmetry_2', -1) # create index of atom name cnt = 0 name_dict = {} for atom in self.model.atom: if hasattr(atom,'name'): name_dict[atom.name] = cnt cnt = cnt + 1 for value in values: if self.index_to_str(symm_1, value) != self.index_to_str(symm_2, value): # don't bond to symmetry mates continue try: index = [name_dict[self.index_to_str(label_1, value)], name_dict[self.index_to_str(label_2, value)]] except KeyError: print " CIF _geom_bond_atom_site_label, invalid keys:", value continue bond = Bond() bond.index = index bond.order = 1 self.model.bond.append(bond) return True
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())
def add_hydrogens(model, forcefield=protein_amber, skip_sort=None): # assumes no bonds between non-hetatms if feedback['actions']: print(" " + str(__name__) + ": adding hydrogens...") if not isinstance(model, chempy.models.Connected): raise ValueError('model is not a "Connected" model object') if model.nAtom: if not model.index: model.update_index() res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] if not base.hetatm: resn = base.resn # find out if this is n or c terminal residue names = [] for b in range(a[0], a[1]): names.append(model.atom[b].name) tmpl = protein_residues.normal if forcefield: ffld = forcefield.normal for b in N_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.n_terminal if forcefield: ffld = forcefield.n_terminal break for b in C_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.c_terminal if forcefield: ffld = forcefield.c_terminal break if resn not in tmpl: raise RuntimeError("unknown residue type '" + resn + "'") else: # build dictionary dict = {} for b in range(a[0], a[1]): at = model.atom[b] dict[at.name] = b # find missing bonds with hydrogens bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and (b[1] not in dict): at = model.atom[dict[b[0]]] if at.symbol != 'H': name = b[1] symbol = tmpl[resn]['atoms'][name][ 'symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn, newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k][ 'charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [idx1, idx2] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if (b[0] not in dict) and b[1] in dict: at = model.atom[dict[b[1]]] if at.symbol != 'H': name = b[0] symbol = tmpl[resn]['atoms'][name][ 'symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn, newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k][ 'charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [idx1, idx2] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if not skip_sort: model.sort()
def add_bonds(model, forcefield=protein_amber, histidine='HIE'): ''' add_bonds(model, forcefield = protein_amber, histidine = 'HIE' ) (1) fixes aliases, assigns types, makes HIS into HIE,HID, or HIP and changes cystine to CYX (2) adds bonds between existing atoms ''' if feedback['actions']: print(" " + str(__name__) + ": assigning types and bonds...") if not isinstance(model, chempy.models.Indexed): raise ValueError('model is not an "Indexed" model object') if model.nAtom: crd = model.get_coord_list() nbr = Neighbor(crd, MAX_BOND_LEN) res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] if not base.hetatm: resn = base.resn if resn == 'HIS': for c in range(a[0], a[1]): # this residue model.atom[c].resn = histidine resn = histidine if resn == 'N-M': # N-methyl from Insight II, for c in range(a[0], a[1]): # this residue model.atom[c].resn = 'NME' resn = 'NME' # find out if this is n or c terminal residue names = [] for b in range(a[0], a[1]): names.append(model.atom[b].name) tmpl = protein_residues.normal if forcefield: ffld = forcefield.normal for b in N_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.n_terminal if forcefield: ffld = forcefield.n_terminal break for b in C_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.c_terminal if forcefield: ffld = forcefield.c_terminal break if resn not in tmpl: raise RuntimeError("unknown residue type '" + resn + "'") else: # reassign atom names and build dictionary dict = {} aliases = tmpl[resn]['aliases'] for b in range(a[0], a[1]): at = model.atom[b] if at.name in aliases: at.name = aliases[at.name] dict[at.name] = b if forcefield: k = (resn, at.name) if k in ffld: at.text_type = ffld[k]['type'] at.partial_charge = ffld[k]['charge'] else: raise RuntimeError("no parameters for '" + str(k) + "'") # now add bonds for atoms which are present bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and b[1] in dict: bnd = Bond() bnd.index = [dict[b[0]], dict[b[1]]] bnd.order = bonds[b]['order'] mbond.append(bnd) if 'N' in dict: # connect residues N-C based on distance cur_n = dict['N'] at = model.atom[cur_n] lst = nbr.get_neighbors(at.coord) for b in lst: at2 = model.atom[b] if at2.name == 'C': if not at2.in_same_residue(at): dst = distance(at.coord, at2.coord) if dst <= PEPT_CUTOFF: bnd = Bond() bnd.index = [cur_n, b] bnd.order = 1 mbond.append(bnd) break if 'SG' in dict: # cysteine cur = dict['SG'] at = model.atom[cur] lst = nbr.get_neighbors(at.coord) for b in lst: if b > cur: # only do this once (only when b>cur - i.e. this is 1st CYS) at2 = model.atom[b] if at2.name == 'SG': if not at2.in_same_residue(at): dst = distance(at.coord, at2.coord) if dst <= MAX_BOND_LEN: bnd = Bond() bnd.index = [cur, b] bnd.order = 1 mbond.append(bnd) if forcefield: for c in range( a[0], a[1] ): # this residue atx = model.atom[c] atx.resn = 'CYX' resn = atx.resn k = ('CYX', atx.name) if k in ffld: atx.text_type = ffld[ k]['type'] atx.partial_charge = ffld[ k]['charge'] else: raise RuntimeError( "no parameters for '" + str(k) + "'") for d in res_list: if (b >= d[0]) and ( b < d[1] ): # find other residue for c in range( d[0], d[1]): atx = model.atom[ c] atx.resn = 'CYX' # since b>cur, assume assignment later on break
def add_bonds(model, forcefield = protein_amber, histidine = 'HIE' ): ''' add_bonds(model, forcefield = protein_amber, histidine = 'HIE' ) (1) fixes aliases, assigns types, makes HIS into HIE,HID, or HIP and changes cystine to CYX (2) adds bonds between existing atoms ''' if feedback['actions']: print(" "+str(__name__)+": assigning types and bonds...") if not isinstance(model, chempy.models.Indexed): raise ValueError('model is not an "Indexed" model object') if model.nAtom: crd = model.get_coord_list() nbr = Neighbor(crd,MAX_BOND_LEN) res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] if not base.hetatm: resn = base.resn if resn == 'HIS': for c in range(a[0],a[1]): # this residue model.atom[c].resn = histidine resn = histidine if resn == 'N-M': # N-methyl from Insight II, for c in range(a[0],a[1]): # this residue model.atom[c].resn = 'NME' resn = 'NME' # find out if this is n or c terminal residue names = [] for b in range(a[0],a[1]): names.append(model.atom[b].name) tmpl = protein_residues.normal if forcefield: ffld = forcefield.normal for b in N_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.n_terminal if forcefield: ffld = forcefield.n_terminal break for b in C_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.c_terminal if forcefield: ffld = forcefield.c_terminal break if resn not in tmpl: raise RuntimeError("unknown residue type '"+resn+"'") else: # reassign atom names and build dictionary dict = {} aliases = tmpl[resn]['aliases'] for b in range(a[0],a[1]): at = model.atom[b] if at.name in aliases: at.name = aliases[at.name] dict[at.name] = b if forcefield: k = (resn,at.name) if k in ffld: at.text_type = ffld[k]['type'] at.partial_charge = ffld[k]['charge'] else: raise RuntimeError("no parameters for '"+str(k)+"'") # now add bonds for atoms which are present bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and b[1] in dict: bnd = Bond() bnd.index = [ dict[b[0]], dict[b[1]] ] bnd.order = bonds[b]['order'] mbond.append(bnd) if 'N' in dict: # connect residues N-C based on distance cur_n = dict['N'] at = model.atom[cur_n] lst = nbr.get_neighbors(at.coord) for b in lst: at2 = model.atom[b] if at2.name=='C': if not at2.in_same_residue(at): dst = distance(at.coord,at2.coord) if dst<=PEPT_CUTOFF: bnd=Bond() bnd.index = [cur_n,b] bnd.order = 1 mbond.append(bnd) break if 'SG' in dict: # cysteine cur = dict['SG'] at = model.atom[cur] lst = nbr.get_neighbors(at.coord) for b in lst: if b>cur: # only do this once (only when b>cur - i.e. this is 1st CYS) at2 = model.atom[b] if at2.name=='SG': if not at2.in_same_residue(at): dst = distance(at.coord,at2.coord) if dst<=MAX_BOND_LEN: bnd=Bond() bnd.index = [cur,b] bnd.order = 1 mbond.append(bnd) if forcefield: for c in range(a[0],a[1]): # this residue atx = model.atom[c] atx.resn = 'CYX' resn = atx.resn k = ('CYX',atx.name) if k in ffld: atx.text_type = ffld[k]['type'] atx.partial_charge = ffld[k]['charge'] else: raise RuntimeError("no parameters for '"+str(k)+"'") for d in res_list: if (b>=d[0]) and (b<d[1]): # find other residue for c in range(d[0],d[1]): atx = model.atom[c] atx.resn = 'CYX' # since b>cur, assume assignment later on break
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
def MakeBond(self, at1, at2, bo): bnd = Bond() bnd.index = [at1.index, at2.index] bnd.order = bo self.model.bond.append(bnd)
def add_hydrogens(model, topology=None, forcefield=None): if not isinstance(model, chempy.models.Connected): raise ValueError('model is not a "Connected" model object') nAtom = model.nAtom if nAtom: if not model.index: model.update_index() ffld = forcefield.normal tmpl = topology.normal res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] resn = base.resn if resn not in tmpl: raise RuntimeError("unknown residue type '" + resn + "'") else: # build dictionary dict = {} for b in range(a[0], a[1]): at = model.atom[b] dict[at.name] = b # find missing bonds with hydrogens bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and (b[1] not in dict): at = model.atom[dict[b[0]]] if at.symbol != 'H': name = b[1] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn, newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [idx1, idx2] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if (b[0] not in dict) and b[1] in dict: at = model.atom[dict[b[1]]] if at.symbol != 'H': name = b[0] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn, newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [idx1, idx2] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd)
for a in atoms: new_atom = Atom() new_atom.symbol = a[0] # elemental symbol new_atom.name = a[1] # atom name new_atom.resi = a[2] # residue identifier new_atom.resn = a[3] # residue name model.atom.append(new_atom) # (note that there are a bunch of other fields we're not using -- and none are required) # add coordinates onto the atoms for a in model.atom: # now assign coordinates a.coord = coords.pop(0) # now specify the bonds for a in bonds: new_bond = Bond() new_bond.index = [a[0],a[1]] # atom indices (zero-based) new_bond.order = a[2] # bond order model.bond.append(new_bond) # finally, load the model into PyMOL cmd.load_model(model,"example")
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
def add_hydrogens(model,forcefield=protein_amber,skip_sort=None): # assumes no bonds between non-hetatms if feedback['actions']: print(" "+str(__name__)+": adding hydrogens...") if not isinstance(model, chempy.models.Connected): raise ValueError('model is not a "Connected" model object') if model.nAtom: if not model.index: model.update_index() res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] if not base.hetatm: resn = base.resn # find out if this is n or c terminal residue names = [] for b in range(a[0],a[1]): names.append(model.atom[b].name) tmpl = protein_residues.normal if forcefield: ffld = forcefield.normal for b in N_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.n_terminal if forcefield: ffld = forcefield.n_terminal break for b in C_TERMINAL_ATOMS: if b in names: tmpl = protein_residues.c_terminal if forcefield: ffld = forcefield.c_terminal break if resn not in tmpl: raise RuntimeError("unknown residue type '"+resn+"'") else: # build dictionary dict = {} for b in range(a[0],a[1]): at = model.atom[b] dict[at.name] = b # find missing bonds with hydrogens bonds = tmpl[resn]['bonds'] mbond = model.bond for b in list(bonds.keys()): if b[0] in dict and (b[1] not in dict): at = model.atom[dict[b[0]]] if at.symbol != 'H': name = b[1] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn,newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [ idx1, idx2 ] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if (b[0] not in dict) and b[1] in dict: at = model.atom[dict[b[1]]] if at.symbol != 'H': name = b[0] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn,newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [ idx1, idx2 ] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if not skip_sort: model.sort()
def MakeBond(self,at1, at2, bo): bnd = Bond() bnd.index = [ at1.index, at2.index ] bnd.order = bo self.model.bond.append(bnd)
def add_bond(i1, i2, order, offset=0): bond = Bond() bond.order = order bond.index = [i1 + offset, i2 + offset] model.add_bond(bond)
def add_hydrogens(model,topology=None,forcefield=None): if str(model.__class__) != 'chempy.models.Connected': raise ValueError('model is not a "Connected" model object') nAtom = model.nAtom if nAtom: if not model.index: model.update_index() ffld = forcefield.normal tmpl = topology.normal res_list = model.get_residues() if len(res_list): for a in res_list: base = model.atom[a[0]] resn = base.resn if not tmpl.has_key(resn): raise RuntimeError("unknown residue type '"+resn+"'") else: # build dictionary dict = {} for b in range(a[0],a[1]): at = model.atom[b] dict[at.name] = b # find missing bonds with hydrogens bonds = tmpl[resn]['bonds'] mbond = model.bond for b in bonds.keys(): if dict.has_key(b[0]) and (not dict.has_key(b[1])): at = model.atom[dict[b[0]]] if at.symbol != 'H': name = b[1] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn,newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [ idx1, idx2 ] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd) if (not dict.has_key(b[0])) and dict.has_key(b[1]): at = model.atom[dict[b[1]]] if at.symbol != 'H': name = b[0] symbol = tmpl[resn]['atoms'][name]['symbol'] if symbol == 'H': newat = at.new_in_residue() newat.name = name newat.symbol = symbol k = (resn,newat.name) newat.text_type = ffld[k]['type'] newat.partial_charge = ffld[k]['charge'] idx1 = model.index[id(at)] idx2 = model.add_atom(newat) bnd = Bond() bnd.index = [ idx1, idx2 ] bnd.order = bonds[b]['order'] mbond[idx1].append(bnd) mbond[idx2].append(bnd)
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 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())
model = Indexed() # append the atoms onto it for a in atoms: new_atom = Atom() new_atom.symbol = a[0] # elemental symbol new_atom.name = a[1] # atom name new_atom.resi = a[2] # residue identifier new_atom.resn = a[3] # residue name model.atom.append(new_atom) # (note that there are a bunch of other fields we're not using -- and none are required) # add coordinates onto the atoms for a in model.atom: # now assign coordinates a.coord = coords.pop(0) # now specify the bonds for a in bonds: new_bond = Bond() new_bond.index = [a[0], a[1]] # atom indices (zero-based) new_bond.order = a[2] # bond order model.bond.append(new_bond) # finally, load the model into PyMOL cmd.load_model(model, "example")
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
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))