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))
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))
def MakeAtom(self, atnum): at = Atom() at.index = self.atomN self.atomN = self.atomN+1 at.symbol = CEX.CEXsmilesParser.num2sym(self,atnum) self.model.atom.append(at) return at
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))
def MakeAtom(self, atnum): at = Atom() at.index = self.atomN self.atomN = self.atomN + 1 at.symbol = CEX.CEXsmilesParser.num2sym(self, atnum) self.model.atom.append(at) return at
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))
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 = ''
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))
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))
def set_name(self,name): hidden_name = None if self.points_name != '': if self.points_name in self.cmd.get_names("all"): hidden_name = "_"+self.cgo_name self.cmd.disable(self.points_name) self.cmd.set_name(self.points_name, hidden_name) # hide self.name = name self.points_name = self.name + "_points" self.cgo_name = self.name if self.copying and hidden_name != None: self.cmd.copy(self.points_name, hidden_name, zoom=0) print("copy") else: hidden_name = "_"+self.cgo_name if hidden_name in self.cmd.get_names("all"): self.cmd.set_name(hidden_name, self.points_name) self.copying = 0 if not self.points_name in self.cmd.get_names(): model = Indexed() origin = self.cmd.get_view()[12:15] for a in pseudo_atoms: new_atom = Atom() (new_atom.symbol, new_atom.name, new_atom.resi, new_atom.resn, new_atom.coord) = a new_atom.coord[0] = new_atom.coord[0] + origin[0] new_atom.coord[1] = new_atom.coord[1] + origin[1] new_atom.coord[2] = new_atom.coord[2] + origin[2] new_atom.flags = 0x2200000 # set surface ignore flag model.atom.append(new_atom) self.cmd.load_model(model,self.points_name,zoom=0) self.cmd.set("surface_mode",0,self.points_name) # make sure no surface is shown self.coord = None self.cmd.color("green","%s`1"%self.points_name) self.cmd.color("green","%s`2"%self.points_name) self.cmd.color("red" ,"%s`3"%self.points_name) self.cmd.color("blue" ,"%s`4"%self.points_name) self.cmd.show_as("nb_spheres",self.points_name) self.auto_position(0.75,0.5) self.cmd.enable(self.points_name) self.points_enabled = 1
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}\"")
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 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)
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)
def __init__(self, object, name='MMTK_model', configuration=None, b_values=None): self.object = object self.universe = object.universe() self.name = name self.model = Indexed() self.index_map = {} self.atoms = [] chain_id_number = 0 in_chain = True for o in object.bondedUnits(): if Utility.isSequenceObject(o): groups = [(g, g.name) for g in o] if not in_chain: chain_id_number = (chain_id_number + 1) % len( self.chain_ids) in_chain = True else: groups = [(o, o.name)] in_chain = False residue_number = 1 for g, g_name in groups: for a in g.atomList(): atom = Atom() atom.symbol = a.symbol atom.name = a.name atom.resi_number = residue_number atom.chain = self.chain_ids[chain_id_number] if b_values is not None: atom.b = b_values[a] atom.resn = g_name self.model.atom.append(atom) self.index_map[a] = len(self.atoms) self.atoms.append(a) residue_number = residue_number + 1 if in_chain: chain_id_number = (chain_id_number + 1) % len(self.chain_ids) try: bonds = o.bonds except AttributeError: bonds = [] for b in bonds: bond = Bond() bond.index = [self.index_map[b.a1], self.index_map[b.a2]] self.model.bond.append(bond) self._setCoordinates(configuration)
def fromList(self, MMODList): # returns a list of indexed models mp = MAEParser(lst=MMODList) mp_rec = mp.parse() full_model = None result = [] for mp_ent in mp_rec: if mp_ent[0] == 'f_m_ct': f_m_ct = mp_ent[1] model = Indexed() if f_m_ct.has_key('s_m_title'): model.molecule.title = string.strip(f_m_ct['s_m_title']) if f_m_ct.has_key('m_atom'): m_atom = f_m_ct['m_atom'] nAtom = m_atom[0] for a in range(nAtom): model.atom.append(Atom()) self._read_m_atom(m_atom, model) if f_m_ct.has_key('m_bond'): m_bond = f_m_ct['m_bond'] self._read_m_bond(m_bond, model) full_model = model result.append(model) elif mp_ent[0] == 'p_m_ct' and full_model != None: model = copy.deepcopy(full_model) f_m_ct = mp_ent[1] if f_m_ct.has_key('s_m_title'): model.molecule.title = string.strip(f_m_ct['s_m_title']) if f_m_ct.has_key('m_atom'): m_atom = f_m_ct['m_atom'] nAtom = m_atom[0] self._read_m_atom(m_atom, model) if f_m_ct.has_key('m_bond'): m_bond = f_m_ct['m_bond'] self._read_m_bond(m_bond, model) full_model = model result.append(model) return result
def com_object(selection): states = cmd.count_states(selection) outstates = [] for i in range(states): coords = cmd.centerofmass(selection, i + 1) outstates.append(Indexed()) outstates[-1].atom.append(Atom()) outstates[-1].atom[0].name = "GA" outstates[-1].atom[0].symbol = "Ga" outstates[-1].atom[0].index = 0 outstates[-1].atom[0].resid = 0 outstates[-1].atom[0].resn = "" outstates[-1].atom[0].coord = coords # print("QL",outstates[-1].atom[0].coord) # if i>=1: # print("QL2",outstates[-2].atom[0].coord) for i in range(len(outstates)): cmd.load_model(outstates[i], "COM", 1 + i)
def __init__(self, object, name = 'MMTK_model', configuration = None, b_values = None): self.object = object self.universe = object.universe() self.name = name self.model = Indexed() self.index_map = {} self.atoms = [] chain_id_number = 0 in_chain = True for o in object.bondedUnits(): if Utility.isSequenceObject(o): groups = [(g, g.name) for g in o] if not in_chain: chain_id_number = (chain_id_number+1) % len(self.chain_ids) in_chain = True else: groups = [(o, o.name)] in_chain = False residue_number = 1 for g, g_name in groups: for a in g.atomList(): atom = Atom() atom.symbol = a.symbol atom.name = a.name atom.resi_number = residue_number atom.chain = self.chain_ids[chain_id_number] if b_values is not None: atom.b = b_values[a] atom.resn = g_name self.model.atom.append(atom) self.index_map[a] = len(self.atoms) self.atoms.append(a) residue_number = residue_number + 1 if in_chain: chain_id_number = (chain_id_number+1) % len(self.chain_ids) try: bonds = o.bonds except AttributeError: bonds = [] for b in bonds: bond = Bond() bond.index = [self.index_map[b.a1], self.index_map[b.a2]] self.model.bond.append(bond) self._setCoordinates(configuration)
def set_name(self, name): hidden_name = None if self.points_name != '': if self.points_name in self.cmd.get_names("all"): hidden_name = "_" + self.cgo_name self.cmd.disable(self.points_name) self.cmd.set_name(self.points_name, hidden_name) # hide self.name = name self.points_name = self.name + "_points" self.cgo_name = self.name if self.copying and hidden_name is not None: self.cmd.copy(self.points_name, hidden_name, zoom=0) print("copy") else: hidden_name = "_" + self.cgo_name if hidden_name in self.cmd.get_names("all"): self.cmd.set_name(hidden_name, self.points_name) self.copying = 0 if self.points_name not in self.cmd.get_names(): model = Indexed() origin = self.cmd.get_view()[12:15] for a in pseudo_atoms: new_atom = Atom() (new_atom.symbol, new_atom.name, new_atom.resi, new_atom.resn, new_atom.coord) = a new_atom.coord[0] = new_atom.coord[0] + origin[0] new_atom.coord[1] = new_atom.coord[1] + origin[1] new_atom.coord[2] = new_atom.coord[2] + origin[2] new_atom.flags = 0x2200000 # set surface ignore flag model.atom.append(new_atom) self.cmd.load_model(model, self.points_name, zoom=0) self.cmd.set("surface_mode", 0, self.points_name) # make sure no surface is shown self.coord = None self.cmd.color("green", "%s`1" % self.points_name) self.cmd.color("green", "%s`2" % self.points_name) self.cmd.color("red", "%s`3" % self.points_name) self.cmd.color("blue", "%s`4" % self.points_name) self.cmd.show_as("nb_spheres", self.points_name) self.auto_position(0.75, 0.5) self.cmd.enable(self.points_name) self.points_enabled = 1
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
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)
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
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
from pymol import cmd 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,\
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
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)
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 load_3d(filename, object=''): ''' DESCRIPTION Load a survex 3d cave survey as "molecule" http://survex.com http://trac.survex.com/browser/trunk/doc/3dformat.htm ''' from chempy import Atom, Bond, models from struct import unpack if object == '': object = os.path.splitext(os.path.basename(filename))[0] f = open(filename, 'rb') line = f.readline() # File ID if not line.startswith('Survex 3D Image File'): print(" Error: not a Survex 3D File") raise CmdException line = f.readline() # File format version assert line[0] == 'v' ff_version = int(line[1:]) line = f.readline().decode('latin1') # Survex title line = f.readline() # Timestamp class Station: def __init__(self): self.labels = [] self.adjacent = [] self.lrud = None self.flag = 0 def connect(self, other): self.adjacent.append(other) def is_surface(self): return self.flag & 0x01 def is_underground(self): return self.flag & 0x02 def is_entrance(self): return self.flag & 0x04 def is_exported(self): return self.flag & 0x08 def is_fixed(self): return self.flag & 0x10 class Survey(dict): def __init__(self): self.prev = None self.curr_label = '' self.labelmap = {} def get(self, xyz): return dict.setdefault(self, tuple(xyz), Station()) def line(self, xyz): s = self.get(xyz) self.prev.connect(s) self.prev = s def move(self, xyz): s = self.get(xyz) self.prev = s def label(self, xyz, flag=0): s = self.get(xyz) s.labels.append(self.curr_label) self.labelmap[s.labels[-1]] = s if flag > 0: s.flag = flag def lrud(self, lrud): s = self.labelmap[self.curr_label] s.lrud = lrud survey = Survey() def read_xyz(): return unpack('<iii', f.read(12)) def read_len(): len = read_byte() if len == 0xfe: len += unpack('<H', f.read(2))[0] elif len == 0xff: len += unpack('<I', f.read(4))[0] return len def read_label(): len = read_len() if len > 0: survey.curr_label += skip_bytes(len) def skip_bytes(n): return f.read(n) def read_byte(): byte = f.read(1) if len(byte) != 1: return -1 return ord(byte) while 1: byte = read_byte() if byte == -1: break if byte == 0x00: # STOP survey.curr_label = '' elif byte <= 0x0e: # TRIM # FIXME: according to doc, trim 16 bytes, but img.c does 17! (i, n) = (-17, 0) while n < byte: i -= 1 if survey.curr_label[i] == '.': n += 1 survey.curr_label = survey.curr_label[:i + 1] elif byte <= 0x0f: # MOVE xyz = read_xyz() survey.move(xyz) elif byte <= 0x1f: # TRIM survey.curr_label = survey.curr_label[:15 - byte] elif byte <= 0x20: # DATE if ff_version < 7: skip_bytes(4) else: skip_bytes(2) elif byte <= 0x21: # DATE if ff_version < 7: skip_bytes(8) else: skip_bytes(3) elif byte <= 0x22: # Error info skip_bytes(5 * 4) elif byte <= 0x23: # DATE skip_bytes(4) elif byte <= 0x24: # DATE continue elif byte <= 0x2f: # Reserved continue elif byte <= 0x31: # XSECT read_label() lrud = unpack('<hhhh', f.read(8)) survey.lrud(lrud) elif byte <= 0x33: # XSECT read_label() lrud = unpack('<iiii', f.read(16)) survey.lrud(lrud) elif byte <= 0x3f: # Reserved continue elif byte <= 0x7f: # LABEL read_label() xyz = read_xyz() survey.label(xyz, byte & 0x3f) elif byte <= 0xbf: # LINE read_label() xyz = read_xyz() survey.line(xyz) elif byte <= 0xff: # Reserved continue model = models.Indexed() for (xyz, s) in survey.items(): l0, _, l1 = s.labels[0].rpartition('.') resi, name = l1[:5], l1[5:] segi, chain, resn = l0[-8:-4], l0[-4:-3], l0[-3:] atom = Atom() atom.coord = [i / 100.0 for i in xyz] atom.segi = segi atom.chain = chain atom.resn = resn atom.name = name atom.resi = resi atom.b = atom.coord[2] atom.label = s.labels[0] if s.lrud is not None: atom.vdw = sum(s.lrud) / 400.0 model.add_atom(atom) s2i = dict((s, i) for (i, s) in enumerate(survey.values())) for (s, i) in s2i.items(): for o in s.adjacent: bnd = Bond() bnd.index = [i, s2i[o]] model.add_bond(bnd) cmd.load_model(model, object, 1) cmd.show_as('lines', object) cmd.spectrum('b', 'rainbow', object)
def load_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 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 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
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 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
[16, 21, 1], [17, 18, 1], [17, 19, 1], [17, 20, 1], ] # okay, now we'll build the object from scratch... # create a model instance 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:
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 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)
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)
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 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 get_model(proc, info,number): vmodel=Indexed() atoms=info["AtomsPerMolecule"][number] atomsread=0 ratoms=True rcoords=False rbfactors=False rss=False first=True while(True): v=proc.stdout.readline() if "Molname" in v and ratoms: ad=json.loads(v) at=Atom() at.name=ad["Name"] at.symbol=ad["Symbol"] at.chain=ad["Chain"] at.id=ad["ID"] at.resi_number=ad["MolID"] at.resn=ad["Molname"] vmodel.atom.append(at) atomsread=atomsread+1 if atomsread==atoms: ratoms=False rcoords=True atomsread=0 continue if "Coords" in v and not "Molname" in v and rcoords: coords=json.loads(v) vmodel.atom[atomsread].coord=coords["Coords"] atomsread=atomsread+1 if atomsread==atoms: rcoords=False atomsread=0 if info["Bfactors"]: rbfactors=True if info["SS"]: rss=True continue #In many cases this part will not be needed if "Bfactors" in v: bf=json.loads(v) vmodel.atom[atomsread].b=bf["Bfactors"] atomsread=atomsread+1 if atomsread==atoms: atomsread=0 rbfactors=False if info["SS"]: rss=True continue #This one should be needed only seldomly if "SS" in v: SS=json.loads(v) vmodel.atom[atomsread].ss=SS["SS"] ++atomsread if atomsread==atoms: atomsread=0 rss=False continue # print "me fui con una deuda de 500" break return vmodel
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 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))
def append_node(model, list, test = None): at = Atom() at.name = '0' at.vdw = list[3] at.coord = list[:3] model.atom.append(at)
[16,21,1], [17,18,1], [17,19,1], [17,20,1], ] # okay, now we'll build the object from scratch... # create a model instance 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: