def testMAEsaveLoadSessions(self): cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props='*') allpropdata = {} objs = cmd.get_object_list() for obj in objs: props = cmd.get_property_list(obj) allpropdata[obj] = {} for prop in props: allpropdata[obj][prop] = cmd.get_property(prop, obj) with testing.mktemp('.pse') as psefilename: cmd.save(psefilename) cmd.load(psefilename) # this is to fail the test on purpose # cmd.set_property('i_m_ct_format', 3, '1d_smiles.mol_13') objs = cmd.get_object_list() for obj in objs: props = cmd.get_property_list(obj) # test to make sure there are no extra properties or not enough properties self.assertEqual(set(props), set(allpropdata[obj].keys())) # test to make sure all property values are the same for prop in props: try: self.assertTrue(allpropdata[obj][prop] == cmd.get_property(prop, obj)) except: self.fail('properties are not the same: obj=%s prop=%s' % (obj, prop))
def _test_recall(self): cmd.scene('s1', 'recall') cmd.ray(1, 1) # force scene update self.assertEqual(['m3'], cmd.get_object_list('(visible)')) self.assertEqual(['m3'], cmd.get_object_list('(enabled)')) cmd.enable('g1') cmd.ray(1, 1) # force scene update self.assertEqual(['m1', 'm3'], cmd.get_object_list('(visible)')) self.assertEqual(['m1', 'm3'], cmd.get_object_list('(enabled)'))
def alignallrms(sele): r = {} for i in cmd.get_object_list(): r[i] = cmd.align("fr52re", i)[0] for k, v in r.items(): if v < 2: print k, v
def get_alignment_coords(name, active_only=0, state=-1, quiet=0): ''' DESCRIPTION API only function. Returns a dictionary with items (object name, Nx3 coords list) N is the number of alignment columns without gaps. EXAMPLE import numpy from psico.multistuff import * from psico.querying import * extra_fit('name CA', cycles=0, object='aln') x = get_alignment_coords('aln') m = numpy.array(x.values()) ''' active_only, state, quiet = int(active_only), int(state), int(quiet) aln = cmd.get_raw_alignment(name, active_only) object_list = cmd.get_object_list(name) idx2coords = dict() cmd.iterate_state(state, name, 'idx2coords[model,index] = (x,y,z)', space={'idx2coords': idx2coords}) allcoords = dict((model, []) for model in object_list) for pos in aln: if len(pos) != len(object_list): continue for model,index in pos: allcoords[model].append(idx2coords[model,index]) return allcoords
def testMAEloadSomePropertiesEmptyList(self): props = [] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertIsNone(allprops)
def loadFitnessFactors (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"): # adapted from http://www.pymolwiki.org/index.php/Load_new_B-factors """ Replaces B-factors with a list of fitness factor values contained in a plain txt file usage: loadFitnessFactors mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new Fitness-factors' file (default=1) source = name of the file containing new Fitness-factor values (default=newFitnessFactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadFitnessFactors 1LVM and chain A """ obj=cmd.get_object_list(mol)[0] cmd.alter(mol,"b=-1.0") inFile = open(source, 'r') counter=int(startaa) fitnessFacts=[] for line in inFile.readlines(): fitnessFact=float(line) fitnessFacts.append(fitnessFact) cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%fitnessFact) counter=counter+1 if visual=="Y": cmd.show_as("cartoon",mol) cmd.cartoon("putty", mol) # cmd.set("cartoon_putty_scale_min", min(fitnessFacts),obj) # cmd.set("cartoon_putty_scale_max", max(fitnessFacts),obj) cmd.set("cartoon_putty_transform", 0,obj) cmd.set("cartoon_putty_radius", 0.2,obj) cmd.spectrum("b","red_white_blue", "%s and n. CA " %mol) cmd.ramp_new("count", obj, [min(fitnessFacts), (min(fitnessFacts)+max(fitnessFacts))/2, max(fitnessFacts)], color = ["blue", "white", "red"]) cmd.recolor()
def pir(selection='(all)', wrap=70): ''' DESCRIPTION Print sequence in PIR format SEE ALSO fasta ''' from . import one_letter from chempy import cpv wrap = int(wrap) for obj in cmd.get_object_list('(' + selection + ')'): seq = [] prev_coord = None model = cmd.get_model('/%s////CA and guide and (%s)' % (obj, selection)) for atom in model.atom: if prev_coord is not None and cpv.distance(atom.coord, prev_coord) > 4.0: seq.append('/\n') prev_coord = atom.coord seq.append(one_letter.get(atom.resn, 'X')) seq.append('*') print('>P1;%s' % (obj)) print('structure:%s:%s:%s:%s:%s::::' % (obj, model.atom[0].resi,model.atom[0].chain, model.atom[-1].resi,model.atom[-1].chain)) if wrap < 1: print(''.join(seq)) continue for i in range(0, len(seq), wrap): print(''.join(seq[i:i+wrap]))
def stride(selection="(all)", exe="stride", raw="", state=-1, quiet=1): """ DESCRIPTION Secondary structure assignment with STRIDE. http://webclu.bio.wzw.tum.de/stride/ SEE ALSO dss, dssp """ from subprocess import Popen, PIPE import tempfile, os state, quiet = int(state), int(quiet) ss_map = {"C": "L", "B": "S", "b": "S", "E": "S", "T": "L", "G": "H", "H": "H"} tmpfilepdb = tempfile.mktemp(".pdb") ss_dict = dict() for model in cmd.get_object_list(selection): cmd.save(tmpfilepdb, "%s and (%s)" % (model, selection), state) try: process = Popen([exe, tmpfilepdb], stdout=PIPE) except OSError: print "Error: Cannot execute exe=" + exe raise CmdException for line in process.stdout: if not line.startswith("ASG"): continue chain = line[9].strip("-") resi = line[11:16].strip() ss = line[24] ss_dict[model, chain, resi] = ss os.remove(tmpfilepdb) _common_ss_alter(selection, ss_dict, ss_map, raw)
def testMAEloadSomePropertiesDontExist(self): props = ['s_knime_origin_file_name', 's_knime_origin_hostname', 'dontexist'] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertIsNotNone(allprops)
def testMAEloadSomeProperties(self): props = ['s_knime_origin_file_name', 's_knime_origin_hostname'] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertEqual(len(props), len(allprops))
def mutate_all(selection, new_resn, inplace=1, sculpt=0, *args, **kwargs): ''' DESCRIPTION Mutate all residues in selection. By default do mutation in-place (unlike the 'mutate' command which by default works on a copy). FOR SCULPTING ONLY SUPPORTS SELECTIONS WITHIN THE SAME MODEL! SEE ALSO mutate ''' inplace, sculpt = int(inplace), int(sculpt) if sculpt and len(cmd.get_object_list('(' + selection + ')')) > 1: print(' Error: Sculpting in multiple models not supported') raise CmdException kwargs.pop('_self', None) sele_list = set() cmd.iterate(selection, 'sele_list.add("/%s/%s/%s/%s" % (model, segi, chain, resi))', space={'sele_list': sele_list}) for sele in sele_list: mutate(sele, new_resn, inplace, sculpt and not inplace, *args, **kwargs) if sculpt and inplace: sculpt_relax('(' + ' '.join(sele_list) + ')', 0, sculpt == 2)
def loadBfacts (mol,startaa=1,source="/Users/student/Box Sync/PUBS/Pymol-practice.txt", visual="Y"): """ Replaces B-factors with a list of values contained in a plain txt file usage: loadBfacts mol, [startaa, [source, [visual]]] mol = any object selection (within one single object though) startaa = number of first amino acid in 'new B-factors' file (default=1) source = name of the file containing new B-factor values (default=newBfactors.txt) visual = redraws structure as cartoon_putty and displays bar with min/max values (default=Y) example: loadBfacts 1LVM and chain A """ obj=cmd.get_object_list(mol)[0] cmd.alter(mol,"b=-1.0") inFile = open(source, 'r') counter=int(startaa) bfacts=[] for line in inFile.readlines(): bfact=float(line) bfacts.append(bfact) cmd.alter("%s and resi %s and n. CA"%(mol,counter), "b=%s"%bfact) counter=counter+1 if visual=="Y": cmd.show_as("cartoon",mol) cmd.cartoon("putty", mol) cmd.set("cartoon_putty_scale_min", min(bfacts),obj) cmd.set("cartoon_putty_scale_max", max(bfacts),obj) cmd.set("cartoon_putty_transform", 0,obj) cmd.set("cartoon_putty_radius", 0.2,obj) cmd.spectrum("b","rainbow", "%s and n. CA " %mol) cmd.ramp_new("count", obj, [min(bfacts), max(bfacts)], "rainbow") cmd.recolor()
def chainbow_obj(selection="(all)"): """DESCRIPTION Colors each chain as a rainbow from N (blue) to C (red) USAGE chainbow_obj [selection] ARGUMENTS selection = the objects to be colored NOTES Any objects present in the selection will be recolored completely. There is no way to color only part of an object. EXAMPLES AUTHOR Spencer Bliven """ for object in cmd.get_object_list(selection): util.chainbow(object)
def testLoadNoProperties(self, molfilename): cmd.set('load_object_props_default', '') cmd.load(self.datafile(molfilename), 'test') objs = cmd.get_object_list() for obj in objs: prop_list= cmd.get_property_list(obj) self.assertEquals(prop_list, None)
def testMAEchempy(self, molfilename): cmd.load(self.datafile(molfilename), 'test', object_props='*', atom_props='*') objs = cmd.get_object_list() for obj in objs: idxToVal = {} natoms = cmd.count_atoms(obj) for i in range(natoms): idxToVal[i+1] = i*10 cmd.set_atom_property('test_prop', i*10, "index %d and %s" % (i+1, obj)) model = cmd.get_model(obj) # test to make sure the properties that exist are the same prop_list= cmd.get_property_list(obj) mol_prop_list = [x[0] for x in model.molecule_properties] self.assertEqual(set(prop_list), set(mol_prop_list)) # need to test whether the values are the same for prop, val in model.molecule_properties: propval = cmd.get_property(prop, obj) self.assertEqual(propval, val) self.assertEqual(natoms, len(model.atom)) # need to test values of all atom properties, including the ones that were set above stored.prop_lookup = {} cmd.iterate(obj, "stored.prop_lookup[index-1] = properties.all") idx = 0 for at in model.atom: for prop in at.atom_properties.keys(): val = at.atom_properties[prop] self.assertEqual(val, stored.prop_lookup[idx][prop]) idx += 1
def iterate_plot(selection, expr_y, expr_x=None, scatter=0, filename=None, space=None, quiet=1): ''' DESCRIPTION Plot atomic properties. ARGUMENTS selection = string: atom selection expr_y = string: python expression for y values expr_x = string: python expression for x values {default: None} scatter = 0/1: make line plot or scatter plot {default: 0, line plot} EXAMPLE # C-alpha b-factors iterate_plot name CA, b, resv ''' from . import matplotlib_fix from matplotlib.pyplot import figure scatter, quiet = int(scatter), int(quiet) if space is None: space = {'cmd': cmd, 'stored': cmd.pymol.stored} if cmd.is_string(selection): if selection.startswith('['): sele_list = selection[1:-1].split(',') else: sele_list = ['(%s) and (%s)' % (model, selection) for model in cmd.get_object_list('(' + selection + ')')] else: sele_list = selection fig = figure() plt = fig.add_subplot(111) for selection in sele_list: space['_values'] = y_values = [] cmd.iterate(selection, '_values.append(' + expr_y + ')', space=space) if expr_x is None: x_values = range(len(y_values)) else: space['_values'] = x_values = [] cmd.iterate(selection, '_values.append(' + expr_x + ')', space=space) color = get_model_color(selection) if scatter: plt.scatter(x_values, y_values, c=color) else: plt.plot(x_values, y_values, c=color) _showfigure(fig, filename, quiet)
def intra_theseus(selection, state=1, cov=0, cycles=200, exe='theseus', preserve=0, quiet=1): ''' DESCRIPTION Fits all states of an object to an atom selection with maximum likelihood. THESEUS: Maximum likelihood multiple superpositioning http://www.theseus3d.org ARGUMENTS selection = string: atoms to fit state = integer: keep transformation of this state unchanged {default: 1} cov = 0/1: 0 is variance weighting, 1 is covariance weighting (slower) {default: 0} SEE ALSO intra_fit, intra_rms_cur ''' import tempfile, os state, cov, cycles = int(state), int(cov), int(cycles) preserve, quiet = int(preserve), int(quiet) tempdir = tempfile.mkdtemp() filename = os.path.join(tempdir, 'mobile.pdb') cmd.save(filename, selection, 0) exe = cmd.exp_path(exe) args = [exe, '-a0', '-c' if cov else '-v', '-i%d' % cycles, filename] translations = [] rotations = [] translations, rotations = _run_theseus(args, tempdir, preserve, quiet) matrices = [R[0:3] + [-t[0]] + R[3:6] + [-t[1]] + R[6:9] + [-t[2], 0,0,0, 1] for (R, t) in zip(rotations, translations)] # intra fit states obj_list = cmd.get_object_list('(' + selection + ')') for i, m in enumerate(matrices): for obj in obj_list: cmd.transform_object(obj, m, i+1, transpose=1) # fit back to given state if 0 < state <= len(matrices): m = list(matrices[state-1]) for i in [3,7,11]: m[i] *= -1 for obj in obj_list: cmd.transform_object(obj, m, 0) if not quiet: print(' intra_theseus: %d states aligned' % (len(matrices)))
def testMAEchempy(self): cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props='*') objs = cmd.get_object_list() for obj in objs: model = cmd.get_model(obj) prop_list= cmd.get_property_list(obj) mol_prop_list = map(lambda x: x[0], model.molecule_properties) self.assertEqual(set(prop_list), set(mol_prop_list))
def prosmart(mobile, target, mobile_state=1, target_state=1, exe='prosmart', transform=1, object=None, quiet=0): ''' DESCRIPTION ProSMART wrapper. http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/ ''' import subprocess, tempfile, os, shutil, glob quiet = int(quiet) tempdir = tempfile.mkdtemp() mobile_filename = os.path.join(tempdir, 'mobile.pdb') target_filename = os.path.join(tempdir, 'target.pdb') cmd.save(mobile_filename, mobile, state=mobile_state) cmd.save(target_filename, target, state=target_state) exe = cmd.exp_path(exe) args = [exe, '-p1', mobile_filename, '-p2', target_filename, '-a'] xglob = lambda x: glob.glob(os.path.join(tempdir, 'ProSMART_Output/Output_Files', x)) try: subprocess.check_call(args, cwd=tempdir) transfiles = xglob('Superposition/Transformations/*/*.txt') with open(transfiles[0]) as f: f = iter(f) for line in f: if line.startswith('ROTATION'): matrix = [list(map(float, next(f).split())) + [0] for _ in range(3)] elif line.startswith('TRANSLATION'): matrix.append([-float(v) for v in next(f).split()] + [1]) break if int(transform): matrix = [v for m in matrix for v in m] assert len(matrix) == 4*4 for model in cmd.get_object_list('(' + mobile + ')'): cmd.transform_object(model, matrix, state=0) if object: from .importing import load_aln alnfiles = xglob('Residue_Alignment_Scores/*/*.txt') alnfiles = [x for x in alnfiles if not x.endswith('_clusters.txt')] load_aln(alnfiles[0], object, mobile, target) except OSError: print(' Error: Cannot execute "%s", please provide full path to prosmart executable' % (exe)) raise CmdException finally: shutil.rmtree(tempdir) if not quiet: print(' prosmart: done')
def extra_fit(selection='(all)', reference=None, method='align', zoom=1, quiet=0, _self=cmd, **kwargs): ''' DESCRIPTION Like "intra_fit", but for multiple objects instead of multiple states. ARGUMENTS selection = string: atom selection of multiple objects {default: all} reference = string: reference object name {default: first object in selection} method = string: alignment method (command that takes "mobile" and "target" arguments, like "align", "super", "cealign" {default: align} ... extra arguments are passed to "method" SEE ALSO alignto, cmd.util.mass_align, align_all.py from Robert Campbell ''' zoom, quiet = int(zoom), int(quiet) sele_name = cmd.get_unused_name('_') cmd.select(sele_name, selection) # for speed models = cmd.get_object_list(sele_name) if reference is None: reference = models[0] models = models[1:] elif reference in models: models.remove(reference) else: cmd.select(sele_name, reference, merge=1) if cmd.is_string(method): if method in cmd.keyword: method = cmd.keyword[method][0] else: print('Unknown method:', method) raise CmdException for model in models: x = method(mobile='%s and model %s' % (sele_name, model), target='%s and model %s' % (sele_name, reference), **kwargs) if not quiet: if cmd.is_sequence(x): print('%-20s RMS = %8.3f (%d atoms)' % (model, x[0], x[1])) elif isinstance(x, float): print('%-20s RMS = %8.3f' % (model, x)) elif isinstance(x, dict) and 'RMSD' in x: natoms = x.get('alignment_length', 0) suffix = (' (%s atoms)' % natoms) if natoms else '' print('%-20s RMS = %8.3f' % (model, x['RMSD']) + suffix) else: print('%-20s' % (model,)) if zoom: cmd.zoom(sele_name) cmd.delete(sele_name)
def symexpcell(prefix='mate', object=None, a=0, b=0, c=0): ''' DESCRIPTION Creates all symmetry-related objects for the specified object that occur with their bounding box center within the unit cell. USAGE symexpcell prefix, object, [a, b, c] ARGUMENTS prefix = string: prefix of new objects object = string: object for which to create symmetry mates a, b, c = integer: create neighboring cell {default: 0,0,0} SEE ALSO symexp, http://www.pymolwiki.org/index.php/SuperSym ''' if object is None: object = cmd.get_object_list()[0] sym = cmd.get_symmetry(object) cell_edges = sym[0:3] cell_angles = sym[3:6] spacegroup = sym[6] basis = cellbasis(cell_angles, cell_edges) basis = numpy.matrix(basis) extent = cmd.get_extent(object) center = sum(numpy.array(extent)) * 0.5 center = numpy.matrix(center.tolist() + [1.0]).T center_cell = basis.I * center extra_shift = [[float(i)] for i in (a,b,c)] i = 0 matrices = xray.sg_sym_to_mat_list(spacegroup) for mat in matrices: i += 1 mat = numpy.matrix(mat) shift = numpy.floor(mat * center_cell) mat[0:3,3] -= shift[0:3,0] mat[0:3,3] += extra_shift mat = basis * mat * basis.I mat_list = list(mat.flat) name = '%s%d' % (prefix, i) cmd.create(name, object) cmd.transform_object(name, mat_list) cmd.color(i+1, name)
def sort_dcoms(subs): N = len(subs) / 2 for i in range(1, N + 1): assert "tmp%iA" % i in cmd.get_object_list() for i in range(1, N + 1): assert "tmp%iB" % i in cmd.get_object_list() coms = [com(s) for s in subs] tmp = [(coms[0].distance(x), i) for i, x in enumerate(coms)] tmp.sort() td = tmp[2][0] - tmp[1][0] < tmp[3][0] - tmp[2][0] ring = [tmp[1 if td else 2][1], 0, tmp[2 if td else 3][1]] while len(ring) < N: tmp = [(coms[ring[-1]].distance(x), i) for i, x in enumerate(coms)] tmp.sort() assert (tmp[2][0] - tmp[1][0] < tmp[3][0] - tmp[2][0]) == td v1 = tmp[1 if td else 2][1] v2 = tmp[2 if td else 3][1] assert ring[-2] in (v1, v2) ring.append(v1 if v2 == ring[-2] else v2) # print ring # print [subs[i] for i in ring] namemap = {} for i, r in enumerate(ring): assert not subs[r] in namemap namemap[subs[r]] = "sub%iA" % (i + 1) tmp = [(coms[r].distance(x), j) for j, x in enumerate(coms)] tmp.sort() # print r, [subs[x[1]] for x in tmp] sub_partner = subs[tmp[3 if td else 1][1]] assert not sub_partner in namemap namemap[sub_partner] = "sub%iB" % (i + 1) assert len(set(namemap.keys())) == 2 * N for i in range(1, N + 1): assert "tmp%iA" % i in cmd.get_object_list() for i in range(1, N + 1): assert "tmp%iB" % i in cmd.get_object_list() chains = {} for i in range(N): chains["sub%iA" % (i + 1)] = string.uppercase[2 * N + 0] chains["sub%iB" % (i + 1)] = string.uppercase[2 * N + 1] for k in namemap: cmd.set_name(k, namemap[k]) cmd.alter(namemap[k], "chain = '%s'" % chains[namemap[k]]) for i in chains: assert i in cmd.get_object_list()
def bondzn(): for o in cmd.get_object_list(): print "add zn bonds for", o for r, c in getres(o + " and elem ZN"): cmd.bond( "(%s and resi %s and chain %s)" % (o, r, c), "(%s and resn HIS and elem N) within 2.5 of (%s and resi %s and chain %s)" % (o, o, r, c), ) break
def testLoadNoAtomProperties(self, molfilename): cmd.load(self.datafile(molfilename), 'test', object_props='*') objs = cmd.get_object_list() for obj in objs: stored.prop_lookup = {} self.assertEquals(cmd.count_atoms(obj) > 0, True) cmd.iterate(obj, "stored.prop_lookup[index-1] = properties.all") for i in stored.prop_lookup.keys(): self.assertEquals(len(stored.prop_lookup[i]), 0)
def setchains(sele="all"): aa = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" i = 0 for o in enumerate(cmd.get_object_list()): for c in cmd.get_chains(): cmd.alter("chain %s and %s" % (c, o), "chain='%s'" % aa[i % len(aa)]) i += 1 return
def apbs_surface(selection='all', maximum=None, minimum=None, map_name=None, ramp_name=None, grid=0.5, quiet=1): ''' DESCRIPTION Show electrostatic potential on surface (calculated with APBS). Important: surface_color is a object property, so when calculating surface potential for different selections and visualize them all together, you should first split them into separate objects. USAGE apbs_surface [ selection [, maximum [, minimum ]]] EXAMPLE fetch 2x19, async=0 split_chains apbs_surface 2x19_A, 10 apbs_surface 2x19_B, 10 SEE ALSO map_new_apbs, APBS Tools Plugin, isosurface, gradient, util.protein_vacuum_esp ''' quiet = int(quiet) if ramp_name is None: ramp_name = cmd.get_unused_name('ramp') if map_name is None: map_name = cmd.get_unused_name('map') map_new_apbs(map_name, selection, float(grid), quiet=quiet) if maximum is not None: maximum = float(maximum) minimum = -maximum if minimum is None else float(minimum) kwargs = {'range': [minimum, (minimum + maximum) * 0.5, maximum]} else: kwargs = {'selection': selection} cmd.ramp_new(ramp_name, map_name, **kwargs) object_names = cmd.get_object_list('(' + selection + ')') for name in object_names: cmd.set('surface_color', ramp_name, name) cmd.show('surface', selection) cmd.set('surface_solvent', 0) cmd.set('surface_ramp_above_mode', 1)
def extra_fit(selection='(all)', reference=None, method='align', zoom=1, quiet=0, _self=cmd, **kwargs): ''' DESCRIPTION Like "intra_fit", but for multiple objects instead of multiple states. ARGUMENTS selection = string: atom selection of multiple objects {default: all} reference = string: reference object name {default: first object in selection} method = string: alignment method (command that takes "mobile" and "target" arguments, like "align", "super", "cealign" {default: align} ... extra arguments are passed to "method" SEE ALSO alignto, cmd.util.mass_align, align_all.py from Robert Campbell ''' zoom, quiet = int(zoom), int(quiet) sele_name = cmd.get_unused_name('_') cmd.select(sele_name, selection) # for speed models = cmd.get_object_list(sele_name) if reference is None: reference = models[0] models = models[1:] elif reference in models: models.remove(reference) else: cmd.select(sele_name, reference, merge=1) if cmd.is_string(method): if method in cmd.keyword: method = cmd.keyword[method][0] else: print('Unknown method:', method) raise CmdException for model in models: x = method(mobile='%s and model %s' % (sele_name, model), target='%s and model %s' % (sele_name, reference), **kwargs) if not quiet: if cmd.is_sequence(x): print('%-20s RMS = %8.3f (%d atoms)' % (model, x[0], x[1])) elif isinstance(x, float): print('%-20s RMS = %8.3f' % (model, x)) if zoom: cmd.zoom(sele_name) cmd.delete(sele_name)
def dss_promotif(selection="all", exe="", raw="", state=-1, quiet=1): """ DESCRIPTION Secondary structure assignment with PROMOTIF. http://www.rubic.rdg.ac.uk/~gail/#Software SEE ALSO dss, dssp, stride """ from subprocess import Popen, PIPE import tempfile, os, shutil state, quiet = int(state), int(quiet) ss_map = {"B": "S", "E": "S", "H": "H", "G": "H"} exe = cmd.exp_path(exe) if not exe: from . import which motifdir = os.environ.get("motifdir") exe = which("p_sstruc3", "p_sstruc2", "promotif.scr", path=[motifdir] if motifdir else None) tmpdir = tempfile.mkdtemp() tmpfilepdb = os.path.join(tmpdir, "xxxx.pdb") tmpfilesst = os.path.join(tmpdir, "xxxx.sst") ss_dict = dict() try: for model in cmd.get_object_list("(" + selection + ")"): cmd.save(tmpfilepdb, "model %s and (%s)" % (model, selection), state) process = Popen([exe, tmpfilepdb], cwd=tmpdir, stdin=PIPE) process.communicate(tmpfilepdb + os.linesep) with open(tmpfilesst) as handle: for line in handle: if line.startswith(" num seq.no"): break for line in handle: if not line.strip(): break chain = line[6].strip("-") resi = line[7:12].strip() ss = line[23] ss_dict[model, chain, resi] = ss os.remove(tmpfilesst) except OSError: print " Error: Cannot execute exe=" + exe raise CmdException finally: shutil.rmtree(tmpdir) _common_ss_alter(selection, ss_dict, ss_map, raw)
def runStride(self): """ """ # delete old results self.sel_obj_list = [] self.stride_rlt_dict = {} self.SSE_res_dict = {} self.SSE_sel_dict = {} pdb_fn = None sel_name = None sel = self.pymol_sel.get() if len(sel) > 0: # if any pymol selection/object is specified all_sel_names = cmd.get_names('all') # get names of all selections if sel in all_sel_names: if cmd.count_atoms(sel) == 0: err_msg = 'ERROR: The selection %s is empty.' % (sel,) print('ERROR: %s' % (err_msg,)) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = sel # no selection/object with the input name is found # we assume either a single-word selector or # some other selection-expression is uesd else: print('The selection/object you specified is not found.') print('Your input will be interpreted as a selection-expression.') tmpsel = self.randomSeleName(prefix='your_sele_') cmd.select(tmpsel, sel) if cmd.count_atoms(tmpsel) == 0: cmd.delete(tmpsel) err_msg = 'ERROR: The selection %s is empty.' % (sel,) print('ERROR: %s' % (err_msg,)) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = tmpsel else: # what structure do you want Stride to work on? err_msg = 'No PyMOL selection/object specified!' print('ERROR: %s' % (err_msg,)) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False # each object in the selection is treated as an independent struc objlist = cmd.get_object_list(sel_name) self.ss_asgn_prog = 'Stride' print('Starting %s ...' % (self.ss_asgn_prog, )) for objname in objlist: self.sel_obj_list.append('%s and %s' % (sel_name, objname)) self.runStrideOneObj(self.sel_obj_list[-1]) return True
def runStride(self): """ """ # delete old results self.sel_obj_list = [] self.stride_rlt_dict = {} self.SSE_res_dict = {} self.SSE_sel_dict = {} pdb_fn = None sel_name = None sel = self.pymol_sel.get() if len(sel) > 0: # if any pymol selection/object is specified all_sel_names = cmd.get_names('all') # get names of all selections if sel in all_sel_names: if cmd.count_atoms(sel) == 0: err_msg = 'ERROR: The selection %s is empty.' % (sel, ) print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = sel # no selection/object with the input name is found # we assume either a single-word selector or # some other selection-expression is uesd else: print 'The selection/object you specified is not found.' print 'Your input will be interpreted as a selection-expression.' tmpsel = self.randomSeleName(prefix='your_sele_') cmd.select(tmpsel, sel) if cmd.count_atoms(tmpsel) == 0: cmd.delete(tmpsel) err_msg = 'ERROR: The selection %s is empty.' % (sel, ) print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False else: sel_name = tmpsel else: # what structure do you want Stride to work on? err_msg = 'No PyMOL selection/object specified!' print 'ERROR: %s' % (err_msg, ) tkMessageBox.showinfo(title='ERROR', message=err_msg) return False # each object in the selection is treated as an independent struc objlist = cmd.get_object_list(sel_name) self.ss_asgn_prog = 'Stride' print 'Starting %s ...' % (self.ss_asgn_prog, ) for objname in objlist: self.sel_obj_list.append('%s and %s' % (sel_name, objname)) self.runStrideOneObj(self.sel_obj_list[-1]) return True
def testDirtyDelete(self): cmd.pseudoatom('m1') cmd.pseudoatom('m2') cmd.group('g1', 'm1 m2') cmd.set_wizard(MockWizard()) cmd.draw() v = cmd.get_object_list('(g1)') self.assertEqual(v, ['m1', 'm2'])
def __init__(self): filein = "log" suffix = "pylog" try: filein = "%s" % (cmd.get_object_list()[0]) except: print("Warning: Can't properly name the .%s file." % suffix) # Create the log file at the input path self.start_time = timeit.default_timer() self.log = open(filein + "." + suffix, 'a+')
def updateList(self): self.listbox1.delete(0, Tkinter.END) #fill with data self.listbox1.insert(0,"all") self.listbox1.selection_set(0, 0) # Default sel tindex = 1; for item in cmd.get_object_list(): self.listbox1.insert(tindex,str(item)) tindex = tindex + 1; self.inputAnalyse()
def pymol_xform(name, xform): """TODO: Summary Args: name (TYPE): Description xform (TYPE): Description """ from pymol import cmd assert name in cmd.get_object_list() cmd.transform_object(name, xform.flatten())
def theseus(mobile, target, match='align', cov=0, cycles=200, mobile_state=1, target_state=1, exe='theseus', preserve=0, quiet=1): ''' DESCRIPTION Structural superposition of two molecules with maximum likelihood. THESEUS: Maximum likelihood multiple superpositioning http://www.theseus3d.org ARGUMENTS mobile = string: atom selection for mobile atoms target = string: atom selection for target atoms match = string: in, like, align, none or the name of an alignment object (see "local_rms" help for details) {default: align} cov = 0/1: 0 is variance weighting, 1 is covariance weighting (slower) {default: 0} SEE ALSO align, super, cealign ''' import tempfile, os cov, cycles = int(cov), int(cycles) mobile_state, target_state = int(mobile_state), int(target_state) preserve, quiet = int(preserve), int(quiet) tempdir = tempfile.mkdtemp() mobile_filename = os.path.join(tempdir, 'mobile.pdb') target_filename = os.path.join(tempdir, 'target.pdb') mm = MatchMaker(mobile, target, match) cmd.save(mobile_filename, mm.mobile, mobile_state) cmd.save(target_filename, mm.target, target_state) exe = cmd.exp_path(exe) args = [exe, '-a0', '-c' if cov else '-v', '-i%d' % cycles, mobile_filename, target_filename] translations, rotations = _run_theseus(args, tempdir, preserve, quiet) matrices = [R[0:3] + [i*t[0]] + R[3:6] + [i*t[1]] + R[6:9] + [i*t[2], 0,0,0, 1] for (R, t, i) in zip(rotations, translations, [-1,1])] obj_list = cmd.get_object_list('(' + mobile + ')') for obj in obj_list: cmd.transform_object(obj, matrices[0], 0, transpose=1) cmd.transform_object(obj, matrices[1], 0) if not quiet: print(' theseus: done')
def getRMSD(directory="temp"): # If the directory exists if os.path.exists(directory): files = [ f for f in listdir(directory) if isfile(join(directory, f)) and ( f.split(".")[-1] == "log" or f.split(".")[-1] == "out") and len(f.split(".")) > 1 ] # load all the pdb files for file in files: filesplit = file.split(".") full_file_name = join(directory, "%s_OPT.pdb" % filesplit[0]) cmd.load(full_file_name, "%s_copy" % cmd.get_object_list()[0]) # calculate for the reference object RMSD = cmd.intra_fit("%s_copy" % cmd.get_object_list()[0], 0) #print RMSD energies = [] for i in range(len(files)): out = getoutData(join(directory, files[i])) energies.append(out.ENERGY) # scale and convert hartree to J/mol. Then calculate Boltzman distribution hartree_to_Jmol = 2600 * 1000 # hartree to J/mol Jmol_to_kcalmol = 0.24 / 1000 # J/mol to kcal/mol min_energy = min(energies) for i in range(len(energies)): energies[i] = (energies[i] - min_energy) * hartree_to_Jmol * Jmol_to_kcalmol #write csv output = open("RMSD.csv", 'w') output.write("Structure;Energy;RMSD\n") message = "%s;%.4f;%.4f\n" % ( files[0], energies[0], 0 ) # RMSD = -1 for the same structure by default, but in our case 0 is more meningful output.write(message) for i in range(1, len(files)): message = "%s;%.4f;%.4f\n" % (files[i], energies[i], RMSD[i]) output.write(message) # terminate output.close() else: print("FATAL ERROR: Specified directory doesn't exist [%s]" % directory)
def testMAEloadSomePropertiesDontExist(self): props = [ 's_knime_origin_file_name', 's_knime_origin_hostname', 'dontexist' ] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertIsNotNone(allprops)
def builder(residues, bonds, mol_name): """Using the list generated by read_input connects monosacharides in a single oligosaccharide""" cmd.set('suspend_updates', 'on') cmd.feedback('disable', 'executive', 'actions') every_object = cmd.get_object_list('all') if mol_name in every_object: cmd.delete(mol_name) every_object.remove(mol_name) if every_object: sel = 'not (' + ' or '.join(every_object) + ') and' else: sel = '' for i in range(0, len(residues)): res_name = residues[i] cmd.load(os.path.join(path, 'db_glycans', '%s.pdb' % res_name)) cmd.set_name(res_name, i) #rename object (necessary to avoid repeating names) cmd.alter(i, 'resi = %s' % i) #name residues for further referencing cmd.sort(i) for i in range(0, len(bonds)): resi_i, resi_j, atom_i, atom_j = bonds[i][0], bonds[i][2], bonds[i][ 4], bonds[i][5] if atom_i > atom_j: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_j, atom_j, atom_j)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_i, atom_i)) cmd.fuse('%s (resi %s and name O%s)' % (sel, resi_i, atom_i), '%s (resi %s and name C%s)' % (sel, resi_j, atom_j), mode=2) else: cmd.remove('%s (resi %s and name O%s+H%so)' % (sel, resi_i, atom_i, atom_i)) cmd.remove('%s (resi %s and name H%so)' % (sel, resi_j, atom_j)) cmd.fuse('%s (resi %s and name C%s)' % (sel, resi_i, atom_i), '%s (resi %s and name O%s)' % (sel, resi_j, atom_j), mode=2) cmd.delete('%s' % i) cmd.copy(mol_name, '%s' % resi_j) cmd.delete('%s' % resi_j) for i in range(0, len(bonds)): set_phi(mol_name, bonds[i], -60) set_psi(mol_name, bonds[i], 120) cmd.delete('pk1') cmd.delete('pk2') cmd.delete('pkbond') cmd.delete('pkmol') if babel: fast_min(mol_name, 5000) minimize(mol_name) else: fast_min(mol_name, 5000) cmd.feedback('enable', 'executive', 'actions') cmd.set('suspend_updates', 'off')
def gv(): all_objs = cmd.get_names("objects",enabled_only=0) for i in cmd.get_object_list(): cmd.hide("everything", i) cmd.show("cartoon", i) cmd.set("cartoon_flat_sheets", 0) #cmd.show("surface", i) cmd.show("lines", i) if i != 'peptide_on_target-keep': cmd.show("stick", "resname CYS and not name c+n+o") cmd.hide("everything", "symbol H")
def sculpt_relax(selection, backbone=1, neighbors=0, model=None, cycles=100, state=0, quiet=1): ''' DESCRIPTION Relax the given selection. SO FAR ONLY SUPPORTS SELECTIONS WITHIN THE SAME MODEL! Do 100 iterations, 75 of them with all terms but low VDW weights, and 25 with only local geometry terms. With default VDW weights and atom clashes, the structure gets distorted very easily! USAGE sculpt_relax selection [, backbone [, neighbors [, model [, cycles ]]]] ''' from pymol import selector backbone, neighbors = int(backbone), int(neighbors) cycles, state, quiet = int(cycles), int(state), int(quiet) sele = selector.process(selection) org = cmd.get_object_list(sele)[0] if model is None: model = org elif model != org: sele = sele.replace('(%s)' % org, '(%s)' % model) cmd.protect() cmd.deprotect(sele) if not backbone: cmd.protect('name CA+C+N+O+OXT') cmd.sculpt_activate(model, state) cmd.set('sculpt_vdw_weight', 0.25, model) # Low VDW forces cmd.set('sculpt_field_mask', 0x1FF, model) # Default if neighbors: cmd.sculpt_iterate(model, state, int(cycles * 0.25)) cmd.deprotect('byres (%s within 6.0 of (%s))' % (model, sele)) if not backbone: cmd.protect('name CA+C+N+O+OXT') cmd.sculpt_iterate(model, state, cycles=int(cycles * 0.50)) else: cmd.sculpt_iterate(model, state, int(cycles * 0.75)) cmd.set('sculpt_field_mask', 0x01F, model) # Local Geometry Only cmd.sculpt_iterate(model, state, int(cycles * 0.25)) cmd.unset('sculpt_vdw_weight', model) cmd.unset('sculpt_field_mask', model) cmd.sculpt_deactivate(model) cmd.deprotect()
def alignall(sel="", obj=None): l = cmd.get_object_list() if not obj: obj = l[0] if obj not in l: print "ERROR object", obj, "not found!!!" return for o in l: if o == obj: continue cmd.do("align " + o + " and (" + sel + ")," + obj + " and (" + sel + ")") return
def write_sele(filename, selection_name='', selection='sele', resolution='atom'): """ Append selection to file and overwrite section if existing Parameters ---------- filename : str file to create/append and write selection selection_name : str, optional name of selection to write (i.e. 'QM'/'NOFIX') default taken from selection argument selection : str, optional name of a PyMOL selection object (def: 'sele') resolution : {'atom', 'residue', 'subsystem'}, optional minimum entity size to treat not whole at writting (def: 'atom') """ selection_name = selection_name.upper() or selection.upper() # check selection exists if not selection in cmd.get_names('selections'): raise CmdException(f"Selection '{selection}' not found", "pyDYNAMON") # get selection with DynnConfigSele structure natoms = 0 sele = dict() obj_list = cmd.get_object_list(selection) for obj in obj_list: model = cmd.get_model(selection + " and " + obj) natoms += model.nAtom for a in model.atom: segi = str(a.segi) resi = int(a.resi) name = str(a.name) sele.setdefault(segi, {}) if resolution == 'subsystem': continue sele[segi].setdefault(resi, []) if resolution == 'residue': continue sele[segi][resi].append(name) # read file to overwrite a section if already exists dynn = DynnConfigSele() dynn.read_selection(filename) # assign to object and write dynn.selection[selection_name] = sele dynn.write_selection(filename, resolution='atom') print( f" pyDYNAMON: {selection_name} with {natoms} written to \"{os.path.abspath(filename)}\"" )
def _monitoringThread(): global pymolViewingMols global showing from pymol import cmd import time def _view(mol, viewname): topo = tempname(suffix=".cif") xtc = tempname(suffix=".xtc") mol.write(topo) mol.write(xtc) cmd.delete(viewname) cmd.load(topo, viewname) cmd.load_traj(xtc, viewname, state=1) cmd.dss() # Guess SS os.remove(topo) os.remove(xtc) showing[viewname] = True curr_mols = {key: val.copy() for key, val in pymolViewingMols.items()} for viewname in curr_mols: _view(curr_mols[viewname], viewname) while True: # print("KEYS", curr_mols.keys()) new_keys = np.setdiff1d(list(pymolViewingMols.keys()), list(curr_mols.keys())) for viewname in new_keys: curr_mols[viewname] = pymolViewingMols[viewname].copy() _view(curr_mols[viewname], viewname) # print("viewed new mol") for viewname in curr_mols: if not mol_equal(curr_mols[viewname], pymolViewingMols[viewname], _logger=False): curr_mols[viewname] = pymolViewingMols[viewname].copy() _view(curr_mols[viewname], viewname) # print("updated existing mol") time.sleep(_checkFrequency) # Check if molecule which was showing before does not exist in viewer anymore # If it doesn't remove it from our lists here to clean-up pymol_objects = cmd.get_object_list("all") todelete = [] for key in showing: if key not in pymol_objects: todelete.append(key) for key in todelete: del showing[key] del curr_mols[key] del pymolViewingMols[key]
def collect(cls): for id in range(0, 50): obj_mask = "consensus.{id:03}.*".format(id=id) objs = fnmatch.filter(pm.get_object_list(), obj_mask) if len(objs) == 0: break if len(objs) > 1: raise Exception(f"Too much objects found: {', '.join(objs)}") obj = objs[0] pm.flag("ignore", obj, "clear", True) coords = pm.get_coords(obj) yield Cluster(id, obj, coords)
def testSymexp(self): cmd.load(self.datafile('1oky.pdb.gz'), 'm1') n = cmd.count_atoms() cmd.symexp('s', 'm1', '%m1 & resi 283', 20.0) x = cmd.get_object_list() self.assertEqual(x, [ 'm1', 's01000000', 's03000000', 's04000000', ]) self.assertEqual(n * 4, cmd.count_atoms())
def split_chains(obj=None, color=1): if obj is None: obj = cmd.get_object_list()[0] chains = cmd.get_chains(obj) for chain in chains: new_obj = obj+"_"+chain cmd.create(new_obj, f"{obj} and chain {chain}") cmd.color('atomic', new_obj) cmd.center(obj) cmd.delete(obj) if int(color) == 1: util.color_objs(f"elem c and {obj}_*")
def testMAEName(self): import gzip from epymol import mae name = 'a.b.c' filename = 'PYMOL-771-example.mae.gz' contents = gzip.open(filename).read() mae.read_maestr(contents, name) v = cmd.get_object_list() self.assertEqual(v, [name])
def apply(self): ''' Permanently applies the mutation upon the selected residue Overrides method from Wizard class ''' cmd = self.cmd if self._status == Status.NO_SELECTION: return #Remove all atoms that are not in the sugar/phosphate group #Needed for non-canonical bases cmd.select("_tmp_sele_invert", "(none)") for a in self._sugar_phos_atoms: cmd.select("_tmp_sele_invert", "_tmp_sele_invert | (%s & name %s)" % (SRC_SELE, a)) cmd.select("_tmp_sele_invert", "%s and not _tmp_sele_invert" % SRC_SELE) cmd.remove("_tmp_sele_invert") try: new_name = cmd.get_object_list(SRC_SELE)[0] except IndexError: print(" Mutagenesis: object not found.") return frag_name_three = self._mode_labels[self.mode] frag_name_one = self._base3_to_1[frag_name_three.lower()] # FUSE cmd.fuse( "%s & name %s" % (FRAG_NAME, self._frag_N_atom_name), "/%s/%s/%s/%s & name %s" % (new_name, self._stored.identifiers[0], self._stored.identifiers[1], self._stored.identifiers[2], self._src_Cp_atom_name), 1) #Check to see if DNA dnaPrefix = '' if cmd.count_atoms("%s & name O2'" % SRC_SELE) == 0: dnaPrefix = 'D' cmd.alter( "/%s/%s/%s/%s" % (new_name, self._stored.identifiers[0], self._stored.identifiers[1], self._stored.identifiers[2]), "(resn) = '%s%s'" % (dnaPrefix, frag_name_one.upper()), space=self._space) cmd.unpick() self.clear()
def consurfdb(code, chain='A', selection=None, palette='red_white_blue', quiet=1): ''' DESCRIPTION Color by evolutionary conservation. Writes scores to b-factor. Fetches pre-calculated conservation profile from ConSurf-DB. http://consurfdb.tau.ac.il/ USAGE consurfdb code [, chain [, selection [, palette ]]] EXAMPLE fetch 1ubq, async=0 consurfdb 3nhe, B, 1ubq SEE ALSO load_consurf ''' try: import urllib2 except ImportError: import urllib.request as urllib2 code = code.upper() url = 'http://bental.tau.ac.il/new_ConSurfDB/DB/%s/%s/r4s.res' % (code, chain) try: handle = urllib2.urlopen(url) except urllib2.HTTPError: print(' error: no pre-calculated profile for %s/%s' % (code, chain)) raise CmdException if selection is None: object_list = cmd.get_object_list() if code not in object_list: if code.lower() in object_list: code = code.lower() else: from .importing import fetch fetch(code, async=0) selection = '%s and chain %s' % (code, chain) load_consurf(handle, selection, palette, quiet)
def interface_analyse_multi(dist=10): cmd.disable('all') all_objects = cmd.get_object_list() for obj in all_objects: print 'analysing', obj interface_analyser(obj, dist, animate=False) cmd.disable(obj) cmd.disable(obj + '_h.bonds') cmd.do('order *, yes') cmd.zoom(all_objects[0], animate=-1) cmd.orient(all_objects[0], animate=-1) cmd.enable(all_objects[0]) cmd.enable(all_objects[0] + '_h.bonds')
def alignvis(): l = [k for k, v in cmd.get_vis().items() if v[0]] l.sort() b = l[0] toprint = "" for i in l[1:]: if cmd.align(i, b)[0] > 2: if toprint == "": for jj, j in enumerate(cmd.get_object_list()): if j.startswith(i): toprint = str(jj + 1) cmd.delete(i) print "NEXT:", toprint
def testCopyObjectProperties(self): cmd.load(self.datafile('1molecule.mae'), 'test', object_props='*') objs = cmd.get_object_list() for obj in objs: obj_copy = '%s_copy' % obj cmd.create(obj_copy, obj, copy_properties=True) props1 = cmd.get_property_list(obj) props2 = cmd.get_property_list(obj_copy) self.assertEqual(set(props1), set(props2)) for prop in props1: prop1 = cmd.get_property(prop, obj) prop2 = cmd.get_property(prop, obj_copy) self.assertEqual(prop1, prop2)
def testLoad_multi(self, ext, discrete): ''' Load multi-state files with discrete=0/1 and multiplex=0/1 ''' N = 10 filename = self.datafile('ligs3d.' + ext) # mutiplex=0 cmd.load(filename, discrete=discrete, multiplex=0) self.assertEqual(cmd.count_discrete('*'), discrete) self.assertEqual(cmd.count_states(), N) self.assertEqual(len(cmd.get_object_list()), 1) if ext in ['mmd']: return # mutiplex=1 cmd.delete('*') cmd.load(filename, discrete=discrete, multiplex=1) self.assertEqual(cmd.count_discrete('*'), discrete * N) self.assertEqual(cmd.count_states(), 1) self.assertEqual(len(cmd.get_object_list()), N)
def zero_residues_sub(sel1, start=0, end=0, offset=0, chains=0): """ DESCRIPTION Renumbers the residues so that the given residue range starts at zero, or offset USAGE zero_residues_sub selection, start, end [, offset [, chains ]] EXAMPLES zero_residues_sub protName, 0, 10 # first residue is 0 zero_residues_sub protName, 0, 10, 5 # first residue is 5 zero_residues_sub protName, 0, 10, chains=1 # each chain starts at 0 zero_residues_sub * """ offset = int(offset) # variable to store the offset stored.first = None # get the names of the proteins in the selection names = [ '(model %s and (%s))' % (p, sel1) for p in cmd.get_object_list('(' + sel1 + ')') ] if int(chains): names = [ '(%s and chain %s)' % (p, chain) for p in names for chain in cmd.get_chains(p) ] # for each name shown for p in names: # get this offset ok = cmd.iterate("first %s and polymer and n. CA" % p, "stored.first=resv") # don't waste time if we don't have to #if not ok or stored.first == offset: if not ok: continue # reassign the residue numbers p = p + " and resi " + start + "-" + end cmd.alter("%s" % p, "resi=str(int(resi)-%s)" % str(int(start) - offset)) # update pymol cmd.rebuild()
def find_mutations_multi(ref, names, sel_prefix=''): """find_mutations_multi :param ref: reference object to compare all others to :param names: name regex to choose :param sel_prefix: a prefix to add to the selections """ if cmd.count_atoms(ref) == 0: print '%s is empty' % ref return obj_lst = cmd.get_object_list('(%s)' % names) print obj_lst for obj in obj_lst: find_mutations(ref, obj, '%smuts_%s_%s' % (sel_prefix, ref, obj))