def parse_XML_channel(file_path, name, mole_object): xml = parse(file_path) pool = ['Tunnel', 'Pore', 'Path'] for element in pool: i = 1 for tunnel in xml.getElementsByTagName(element): if mole_object.plugin_type == "PyMOL": model = Indexed() individual_model = None else: model = Molecule() individual_model = model.newResidue( "Tunnel_" + str(i), " ", 1, " ") for node in tunnel.getElementsByTagName('Node'): nodes = [ float(node.getAttribute('X')), float(node.getAttribute('Y')), float(node.getAttribute('Z')), float(node.getAttribute('Radius')) ] plugin.append_node(model, nodes, individual_model) model = plugin.make_channel(model, i) i += 1 if mole_object.plugin_type == "PyMOL": plugin.center()
def fill_box(area,water=None,box=18.774349): if not water: test_path = path + "water.pdb" if os.path.exists(test_path): water= io.pdb.fromFile(test_path) water= hetatm.generate(water,forcefield=water_amber, topology=water_residues) if not water: raise RunError('Need water structure file.') solv_box = Indexed() half = box/2 x = area[0][0] c = 0 while x<area[1][0]: y = area[0][1] while y<area[1][1]: z = area[0][2] while z<area[1][2]: tmp = copy.deepcopy(water) lr = '' for a in tmp.atom: if a.resi!=lr: c = c + 1 lr = a.resi a.resi = str(c) b = a.coord b[0] = b[0] + x + half b[1] = b[1] + y + half b[2] = b[2] + z + half print " "+__name__+": filling box at %8.3f %8.3f %8.3f\n" % (x,y,z) solv_box.merge(tmp) z = z + box y = y + box x = x + box return solv_box
def __init__(self, cif_list): cif_list.reverse() self.list = cif_list data_line = self.list.pop() self.loops = [] self.key_value = {} self.data_name = string.strip(data_line[5:]) self.next_line() self.parse_normal() print ' CIF: For data block "%s"...' % self.data_name print " CIF: Read %d key/value pair(s)." % len(self.key_value) print " CIF: Read %d table(s)." % len(self.loops) self.convert_dot_to_underscore() self.create_field_dicts() # now build the molecule record self.model = Indexed() # by default, indicate that we want PyMOL to automatically # detect bonds based on coordinates self.model.connect_mode = 3 self.read_symmetry() self.read_atom_site() self.read_chem_comp_atom() self.read_geom_bond() self.read_chem_comp_bond()
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 parse_ct_block(self,spec,data): handler = { 's_m_title' : lambda code,x,a:setattr(a,'title',x.strip()), 'chempy_atoms' : lambda code,x,a:setattr(a,'atom',x), 'chempy_bonds' : lambda code,x,a:setattr(a,'bond',x), 's_m_entry_name' : lambda code,x,a:setattr(a,'name',x.strip()), 's_ffio_ct_type' : lambda code,x,a:setattr(a,'ct_type',x), } fn_list = [ ] load_properties_list = self.load_properties.split() load_all_properties = self.load_properties == '*' for code in spec: fn = handler.get(code) if fn is None: if load_all_properties or code in load_properties_list: fn = set_molecule_property else: fn = dummy_handler fn_list.append([ code, fn ]) bond_list = [] data.reverse() mdl = Indexed() for code, fn in fn_list: fn(code, data.pop(), mdl) return mdl
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 convert_to_indexed(self): model = Indexed() model.molecule = copy.deepcopy(self.molecule) for c in xrange(self.nAtom): at = chempy.Atom() txta = self.txta[c] for attrib in ('name', 'symbol', 'resn', 'resn_code', 'resi', 'alt', 'chain', 'segi', 'text_type'): ll = as_[attrib] setattr(at, attrib, string.strip(string.join(txta[ll[0]:ll[1]], ''))) inta = self.inta[c] for attrib in ('resi_number', 'hetatm', 'formal_charge', 'flags', 'color_code', 'stereo', 'numeric_type'): setattr(at, attrib, inta[ai[attrib]]) flta = self.flta[c] for attrib in ('b', 'q', 'partial_charge'): setattr(at, attrib, flta[af[attrib]]) crda = self.crda[c] at.coord = [crda[0], crda[1], crda[2]] # probably need to add some checking here to eliminate values # which come back as defaults model.atom.append(at) for c in xrange(self.nBond): bnd = chempy.Bond() bnda = self.bnda[c] bnd.index = [bnda[bi_index0], bnda[bi_index1]] bnd.order = bnda[bi_order] bnd.stereo = bnda[bi_stereo] model.bond.append(bnd) return model
def convert_to_indexed(self): model = Indexed() model.molecule = copy.deepcopy(self.molecule) for c in xrange(self.nAtom): at = chempy.Atom() txta = self.txta[c] for attrib in ( 'name', 'symbol', 'resn', 'resn_code', 'resi', 'alt', 'chain', 'segi', 'text_type' ): ll = as_[attrib] setattr(at,attrib,string.strip(string.join(txta[ll[0]:ll[1]],''))) inta = self.inta[c] for attrib in ( 'resi_number', 'hetatm', 'formal_charge','flags', 'color_code', 'stereo', 'numeric_type' ): setattr(at,attrib,inta[ai[attrib]]) flta = self.flta[c] for attrib in ( 'b', 'q', 'partial_charge' ) : setattr(at,attrib,flta[af[attrib]]) crda = self.crda[c] at.coord = [crda[0],crda[1],crda[2]] # probably need to add some checking here to eliminate values # which come back as defaults model.atom.append(at) for c in xrange(self.nBond): bnd = chempy.Bond() bnda = self.bnda[c] bnd.index = [bnda[bi_index0],bnda[bi_index1]] bnd.order = bnda[bi_order] bnd.stereo = bnda[bi_stereo] model.bond.append(bnd) return model
def fill_box(area, water=None, box=18.774349): if not water: test_path = path + "water.pdb" if os.path.exists(test_path): water = io.pdb.fromFile(test_path) water = hetatm.generate(water, forcefield=water_amber, topology=water_residues) if not water: raise RunError('Need water structure file.') solv_box = Indexed() half = box / 2 x = area[0][0] c = 0 while x < area[1][0]: y = area[0][1] while y < area[1][1]: z = area[0][2] while z < area[1][2]: tmp = copy.deepcopy(water) lr = '' for a in tmp.atom: if a.resi != lr: c = c + 1 lr = a.resi a.resi = str(c) b = a.coord b[0] = b[0] + x + half b[1] = b[1] + y + half b[2] = b[2] + z + half print(" " + __name__ + ": filling box at %8.3f %8.3f %8.3f\n" % (x, y, z)) solv_box.merge(tmp) z = z + box y = y + box x = x + box return solv_box
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, 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 GetgoChem(proc, vmodel, info, number): vmodel = Indexed() atoms = info["AtomsPerMolecule"][number] atomsread = 0 rcoords = True rbfactors = False rss = False first = True while (True): v = proc.stdout.readline().decode("utf-8") 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
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 make_channel(model, i, name=None): for a in range(len(model.atom) - 1): bd = Bond() bd.index = [a, a + 1] model.bond.append(bd) if name is None: name = "Tunnel" + str(i) cmd.load_model(model, name, state=1) cmd.set("sphere_mode", "0", name) cmd.set("sphere_color", "red", name) cmd.show("spheres", name) cmd.group("Tunnels", name) return Indexed()
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 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 parse_PDB_channel(self, file_path, name): file = open(file_path) i = 0 channelId = 1 model = Indexed() nodes = [] for line in file: if line.startswith('HETATM'): if channelId != int(line[25:30]): i += 1 model = self.make_channel(model, i, name) channelId += 1 nodes = [float(line[31:39]), float(line[39:47]), float(line[47:55]), float(line[62:68])] self.append_node(model, nodes) file.close() i += 1 self.make_channel(model, i, name)
def __init__(self, datablock): self.loops = datablock.loops self.key_value = datablock.key_value self.name = datablock.name # now build the molecule record self.model = Indexed() self.model.molecule.title = datablock.name # coordinates for state 2-N self.extra_coords = [] # by default, indicate that we want PyMOL to automatically # detect bonds based on coordinates self.model.connect_mode = 3 self.read_symmetry() if self.read_atom_site(): self.read_geom_bond() self.read_struct_conn() self.read_ss() elif self.read_chem_comp_atom(): self.read_chem_comp_bond()
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 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
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_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 removewater(self, selection='(all)'): seloutwater = Indexed() for a in selection.atom: if (a.resn != "HOH") and (a.resn != "H2O") and (a.resn != "WAT"): seloutwater.atom.append(a) return seloutwater
def execute(self, result): if result == defaults["compute_command"]: if self.testBinary() == 0: return self.showCrisscross() #input sel1index = self.listbox1.curselection()[0] sel1text = self.listbox1.get(sel1index) self.whichModelSelect = sel1text; print 'selected ' + self.whichModelSelect sel=cmd.get_model(self.whichModelSelect) cnt=0 for a in sel.atom: cnt+=1 print cnt if cnt == 0: error_dialog = Pmw.MessageDialog(self.parent,title = 'Error', message_text = 'ERROR: No molecule loaded.',) junk = error_dialog.activate() return outdir = self.binlocation.getvalue() if os.path.isfile(outdir): error_dialog = Pmw.MessageDialog(self.parent,title = 'Error', message_text = 'ERROR: Output directory is file.',) junk = error_dialog.activate() return elif not os.path.exists(outdir): self.CreateDirectory(outdir) self.stdamString = string.join(self.stdam_list, "+") # jen to zaskrtnute generatedString = "" for key in self.s: if self.s[key].get() == 1: # pak pouzit do vyberu: if key == "AA": generatedString = generatedString + "+" + self.stdamString else: generatedString = generatedString + "+" + key generatedString = generatedString[1:] print "Checked: " + generatedString mmodel = cmd.get_model(self.whichModelSelect) print self.whichModelSelect + " asize: " + str(len(mmodel.atom)) newmodel = Indexed() for matom in mmodel.atom: if generatedString.find(matom.resn) > -1: #print matom.resn newmodel.atom.append(matom) cmd.load_model(newmodel,"tmpCaverModel") #cmd.label("example","name") #fix outdir slashes outdir = outdir.replace("\\","/") if (outdir.endswith("/")): outdir = outdir[:-1] input = "%s/out.pdb" % (outdir) #cmd.save(input, self.whichModelSelect) # to by ulozilo cely model whichModelSelect. cmd.save(input, "tmpCaverModel") cmd.delete("tmpCaverModel") cesta = os.getcwd() # set ignore waters to false -- the model is already filtered by input model and aminos self.varremovewater.set(0) if WINDOWZ: #commandXYZ = "java %s -jar \"%s/modules/Caver2_1_%s/Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(), VERS, input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(), 0,self.methodvar.get(), "tun_" + self.whichModelSelect) commandXYZ = "java %s -jar \"%s\Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(),input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(),0,self.methodvar.get(), "tun_" + self.whichModelSelect) else: commandXYZ = "java %s -jar \"%s/Caver2_1.jar\" \"%s\" %f %f %f %s \"%s\" %d %d %d %s" % (JOPTS, self.pymollocation.getvalue(),input, float(self.xlocvar.get()), float(self.ylocvar.get()), float(self.zlocvar.get()), self.tunnels.getvalue(), outdir, self.varremovewater.get(),0,self.methodvar.get(), "tun_" + self.whichModelSelect) tunnels = int(self.tunnels.getvalue()) # ted vymazat v output dir vsechny soubory s path_*.py os.path.isfile(string) for i in range(tunnels): tunpy = "%s/path_%i.py" % (outdir,i) if (os.path.isfile(tunpy)): os.remove(tunpy); print commandXYZ os.system(commandXYZ) for i in range(tunnels): pathpy = "%s/path_%i.py" % (outdir, i) if os.access(pathpy,os.F_OK): view = cmd.get_view() execfile(pathpy) cmd.set_view(view) if i != 0: cmd.disable("tunnel%i" % i); else: if i == 0: error_dialog = Pmw.MessageDialog(self.parent,title = 'Error', message_text = 'Error: No tunnel was found, the starting point is probably outside of the molecule.',) junk = error_dialog.activate() break else: messa = "No more tunnels than %i were found" % (i) error_dialog = Pmw.MessageDialog(self.parent,title = 'Info', message_text = messa,) junk = error_dialog.activate() break #pass #self.deleteTemporaryFiles() else: # # Doing it this way takes care of clicking on the x in the top of the # window, which as result set to None. # if __name__ == '__main__': # # dies with traceback, but who cares # self.parent.destroy() else: #self.dialog.deactivate(result) global CAVER_BINARY_LOCATION CAVER_BINARY_LOCATION = self.binlocation.getvalue() self.dialog.withdraw()
def __init__(self): self.model = Indexed() self.atomN = 0
def GetModel(proc, info, number): vmodel = Indexed() atoms = info["AtomsPerMolecule"][number] states = info["FramesPerMolecule"][number] statecontainer = States(atoms) atomsread = 0 statesread = 0 ratoms = True rcoords = False rbfactors = False rss = False first = True while (True): v = proc.stdout.readline().decode("utf-8") 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"] at.hetatm = 1 if at.resn in resncodes.keys(): at.hetatm = 0 at.resn_code = resncodes[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) if statesread == 0: vmodel.atom[atomsread].coord = coords["Coords"] else: statecontainer.NewCoords(coords["Coords"]) # print("coords added to state!!!") #############3 atomsread = atomsread + 1 if atomsread == atoms: statesread += 1 atomsread = 0 if statesread == states: rcoords = False if info["Bfactors"]: rbfactors = True if info["SS"]: rss = True else: statecontainer.NewState() # print("NEW STATE!") ########3 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 seldom 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 #i don't like this, but I don't want to break my other plugins by changing the signature of the function #for them. Also, most pugins will only get one state anyway. if statecontainer.States() < 1: return vmodel else: return (vmodel, statecontainer)