def change_bfactors(bfactors): """Modify bfactors based on spatial location. Due to inconsistencies in the indexing of atoms, residues and chains between openbabel, plip and pymol, we must use coordinates to identify atoms. Arguments: bfactors: dict of dict of dicts with the mapping: x: y: z: value where value is the number we wish to assign to the atom (as the b-factor) for labelling. The x, y and z coordinates should be in the format of strings, with 1 decimal place to avoid problems with comparing floats (use '{:.1f}.format(<coord>). """ def modify_bfactor(x, y, z): """Return b factor given the x, y, z coordinates.""" x, y, z = ['{:.3f}'.format(coord) for coord in (x, y, z)] bfactor = bfactors[x][y][z] return bfactor space = {'modify_bfactor': modify_bfactor} cmd.alter_state(0, '(all)', 'b=modify_bfactor(x, y, z)', space=space, quiet=True)
def testNumeric(self): cmd.fragment('ala') cmd.alter_state(1, 'all', 'p.x, p.y, p.index = x, y, index') cmd.select('sele_p_x', 'p.x < 0') cmd.select('sele_p_y', 'p.y > 0') cmd.select('sele_p_i', 'p.index = 3') cmd.select('sele_x', 'x < 0.0') cmd.select('sele_y', 'y > 0.0') cmd.select('sele_i', 'index 3') counts = [ cmd.count_atoms('sele_p_x'), cmd.count_atoms('sele_x'), cmd.count_atoms('sele_x & sele_p_x'), ] self.assertEqual(counts[0], 8) self.assertEqual(counts[0], counts[1]) self.assertEqual(counts[0], counts[2]) counts = [ cmd.count_atoms('sele_p_y'), cmd.count_atoms('sele_y'), cmd.count_atoms('sele_y & sele_p_y'), ] self.assertEqual(counts[0], 6) self.assertEqual(counts[0], counts[1]) self.assertEqual(counts[0], counts[2]) counts = [ cmd.count_atoms('sele_i'), cmd.count_atoms('sele_p_i'), cmd.count_atoms('sele_i & sele_p_i'), ] self.assertEqual(counts[0], 1) self.assertEqual(counts[0], counts[1]) self.assertEqual(counts[0], counts[2])
def simulation(): import traceback try: while 1: for part in particle: # simplistic Euler intergration # p = p + v part[1] = (half_box + part[1] + part[5]) % box_size - half_box part[2] = (half_box + part[2] + part[6]) % box_size - half_box part[3] = (half_box + part[3] + part[7]) % box_size - half_box # v = v + pseudo-gravitational acceleration factor = max(0.1 * box_size, 0.1 * (part[1]**2 + part[2]**2 + part[3]**2)**1.5) part[5] = part[5] - part[1] / factor part[6] = part[6] - part[2] / factor part[7] = part[7] - part[3] / factor cmd.alter_state(1, "cloud", "(x,y,z) = particle[int(resi)][1:4]", space=globals()) cmd.refresh() except: traceback.print_exc()
def testStereo(self): cmd.fragment('ala') cmd.remove('hydro') # default: S configuration labels = [] cmd.iterate('name CA', 'labels.append(stereo)', space=locals()) self.assertEqual(labels, ['S']) # load R configuration (moves CB) ala_conf_R = { 'N': (-0.67690, -1.23030, -0.49050), 'CA': (-0.00090, 0.06370, -0.49050), 'C': (1.49910, -0.11030, -0.49050), 'O': (2.03010, -1.22730, -0.50150), # 'CB' : (-0.50890, 0.85570, 0.72650), # S configuration 'CB': (-0.33784, 0.82664, -1.78310), # R configuration } cmd.alter_state(1, 'ala', '(x,y,z) = ala_conf_R.get(name)', space=locals()) labels = [] cmd.iterate('name CA', 'labels.append(stereo)', space=locals()) self.assertEqual(labels, ['R'])
def superpose(self): #get the position of the selected residue's O atom stored.xyz = [] if self.currentLabel.modifiedAA: cmd.iterate_state(1, "%s & name O" % self.residue1Name, "stored.xyz.append([x,y,z])") args = [] i = 0 while i < len(self.currentLabel.atomsForSuperposition): args.append( "%s & name %s" % ("currentLabel", self.currentLabel.atomsForSuperposition[i])) args.append("%s & name %s" % (self.residue1Name, self.currentLabel.atomsForSuperposition[i])) i += 1 #print args if apply(cmd.pair_fit, args): #set the label's O atom to the stored position if self.currentLabel.modifiedAA: cmd.alter_state(1, "%s & name O" % "currentLabel", "(x,y,z)=stored.xyz.pop(0)") return True else: return False
def simulation(): import traceback try: while 1: for part in particle: # simplistic Euler intergration # p = p + v part[1] = (half_box + part[1] + part[5]) % box_size - half_box part[2] = (half_box + part[2] + part[6]) % box_size - half_box part[3] = (half_box + part[3] + part[7]) % box_size - half_box # v = v + pseudo-gravitational acceleration factor = max(0.1 * box_size, 0.1 * (part[1] ** 2 + part[2] ** 2 + part[3] ** 2) ** 1.5) part[5] = part[5] - part[1] / factor part[6] = part[6] - part[2] / factor part[7] = part[7] - part[3] / factor cmd.alter_state(1, "cloud", "(x,y,z) = particle[int(resi)][1:4]", space=globals()) cmd.refresh() except: traceback.print_exc()
def sculpt(self,cleanup=0): if not cleanup: cmd.set("suspend_updates",1,quiet=1) cmd.disable() cmd.delete("sculpt") cmd.set("sphere_scale","1.0") cmd.set("sphere_mode",5) cmd.load("$PYMOL_DATA/demo/pept.pdb","sculpt") cmd.hide("lines","sculpt") # cmd.show("sticks","sculpt") cmd.show("spheres","sculpt") # cmd.set("sphere_transparency","0.75","sculpt") # cmd.set("sphere_color","grey","sculpt") cmd.frame(1) cmd.set("auto_sculpt",1) cmd.set("sculpting",1) cmd.sculpt_activate("sculpt") cmd.set("sculpting_cycles","100") cmd.do("edit_mode") cmd.set("valence","0.05") cmd.set("suspend_updates",0,quiet=0) cmd.sculpt_iterate("sculpt") cmd.alter_state(1,"sculpt","x=x*1.5;y=y*0.1;z=z*1.5") cmd.zoom() cmd.unpick() else: cmd.set("valence","0") cmd.set("sculpting",0) cmd.set("auto_sculpt",0) cmd.delete("sculpt") cmd.mouse()
def testAlterState(self): cmd.fragment('ala') cmd.create('ala', 'ala', 1, 2) v_count = cmd.count_atoms('all') v_mock = [ list(map(float, list(range(i * 3, (i + 1) * 3)))) for i in range(v_count) ] v_xyz_1_pre = cmd.get_model('all', state=1).get_coord_list() v_xyz_2_pre = cmd.get_model('all', state=2).get_coord_list() cmd.alter_state(2, 'all', '(x,y,z) = next(xyz_iter)', space={ 'xyz_iter': iter(v_mock), 'next': next }) v_xyz_1_post = cmd.get_model('all', state=1).get_coord_list() v_xyz_2_post = cmd.get_model('all', state=2).get_coord_list() self.assertEqual(v_xyz_1_post, v_xyz_1_pre) self.assertEqual(v_xyz_2_post, v_mock)
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy. Based on: http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html ''' try: import prody except ImportError: print('Failed to import prody, please add to PYTHONPATH') raise CmdException first, last, guide = int(first), int(last), int(guide) states, factor, quiet = int(states), float(factor), int(quiet) assert first > 6 if guide: selection = '(%s) and guide and alt A+' % (selection) tmpsele = cmd.get_unused_name('_') cmd.select(tmpsele, selection) f = StringIO(cmd.get_pdbstr(tmpsele)) conf = prody.parsePDBStream(f) modes = prody.ANM() modes.buildHessian(conf, float(cutoff)) modes.calcModes(last - first + 1) if factor < 0: from math import log natoms = modes.numAtoms() factor = log(natoms) * 10 if not quiet: print(' set factor to %.2f' % (factor)) for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d' % (name, mode)) for state in range(1, states+1): xyz_it = iter(modes[mode-7].getArrayNx3() * (factor * ((state-1.0)/(states-1.0) - 0.5))) cmd.create(name, tmpsele, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = xyz_it.next() + (x,y,z)', space=locals()) cmd.delete(tmpsele) if guide: cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def sculpt(self, cleanup=0): if not cleanup: cmd.set("suspend_updates", 1, quiet=1) cmd.disable() cmd.delete("sculpt") cmd.set("sphere_scale", "1.0") cmd.set("sphere_mode", 5) cmd.load("$PYMOL_DATA/demo/pept.pdb", "sculpt") cmd.hide("lines", "sculpt") # cmd.show("sticks","sculpt") cmd.show("spheres", "sculpt") # cmd.set("sphere_transparency","0.75","sculpt") # cmd.set("sphere_color","grey","sculpt") cmd.frame(1) cmd.set("auto_sculpt", 1) cmd.set("sculpting", 1) cmd.sculpt_activate("sculpt") cmd.set("sculpting_cycles", "100") cmd.do("edit_mode") cmd.set("valence", "0.05") cmd.set("suspend_updates", 0, quiet=0) cmd.sculpt_iterate("sculpt") cmd.alter_state(1, "sculpt", "x=x*1.5;y=y*0.1;z=z*1.5") cmd.zoom() cmd.unpick() else: cmd.set("valence", "0") cmd.set("sculpting", 0) cmd.set("auto_sculpt", 0) cmd.delete("sculpt") cmd.mouse()
def cell_shift(object, dX, dY, dZ, rename=1): if rename: oldName = object.split("_") oldPre = oldName[0] oldX = int(oldName[1]) oldY = int(oldName[2]) oldZ = int(oldName[3]) newX = "_" + str(int(dX) + oldX) newY = "_" + str(int(dY) + oldY) newZ = "_" + str(int(dZ) + oldZ) newName = oldPre + newX + newY + newZ #if cmd.get_names().find(newName) != -1: # print "Symmetry partner already exists in destination position!" # quit() cmd.set_name(object, newName) object = newName stored.shift = [float(dX), float(dY), float(dZ)] stored.sgInfo = cmd.get_symmetry(object) a, b, c, alpha, beta, gamma = stored.sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) stored.fracToOrt = N.array( [[a, b * cg, c * cb], [0.0, b * sg, c * (ca - cb * cg) / sg], [0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2)]]) stored.fracToOrt = stored.fracToOrt.transpose() stored.ortToFrac = inv(stored.fracToOrt) cmd.cell_shift_helper = cell_shift_helper cmd.alter_state(1, object, "x,y,z = cmd.cell_shift_helper([x,y,z],stored.shift)")
def cell_shift(object, dX, dY, dZ, rename = 1): if rename: oldName = object.split("_") oldPre = oldName[0] oldX = int(oldName[1]) oldY = int(oldName[2]) oldZ = int(oldName[3]) newX = "_" + str(int(dX) + oldX) newY = "_" + str(int(dY) + oldY) newZ = "_" + str(int(dZ) + oldZ) newName = oldPre + newX + newY + newZ #if cmd.get_names().find(newName) != -1: # print "Symmetry partner already exists in destination position!" # quit() cmd.set_name(object, newName) object = newName stored.shift = [float(dX),float(dY),float(dZ)] stored.sgInfo = cmd.get_symmetry(object) a,b,c,alpha,beta,gamma = stored.sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) stored.fracToOrt = N.array([[a, b * cg, c * cb], [0.0, b * sg, c * (ca - cb * cg) / sg], [0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2)]]) stored.fracToOrt = stored.fracToOrt.transpose() stored.ortToFrac = inv(stored.fracToOrt) cmd.cell_shift_helper = cell_shift_helper cmd.alter_state(1, object, "x,y,z = cmd.cell_shift_helper([x,y,z],stored.shift)")
def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy. Based on: http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html ''' try: import prody except ImportError: print('Failed to import prody, please add to PYTHONPATH') raise CmdException first, last, guide = int(first), int(last), int(guide) states, factor, quiet = int(states), float(factor), int(quiet) assert first > 6 if guide: selection = '(%s) and guide and alt A+' % (selection) tmpsele = cmd.get_unused_name('_') cmd.select(tmpsele, selection) f = StringIO(cmd.get_pdbstr(tmpsele)) conf = prody.parsePDBStream(f) modes = prody.ANM() modes.buildHessian(conf, float(cutoff)) modes.calcModes(last - first + 1) if factor < 0: from math import log natoms = modes.numAtoms() factor = log(natoms) * 10 if not quiet: print(' set factor to %.2f' % (factor)) for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d' % (name, mode)) for state in range(1, states+1): xyz_it = iter(modes[mode-7].getArrayNx3() * (factor * ((state-1.0)/(states-1.0) - 0.5))) cmd.create(name, tmpsele, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = next(xyz_it) + (x,y,z)', space={'xyz_it': xyz_it, 'next': next}) cmd.delete(tmpsele) if guide: cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def test_atom_state_settings_3f(self, f, data): m1 = "pseudo01" lp1, lp2 = lp = map(f, data) cmd.pseudoatom(m1) cmd.pseudoatom(m1) cmd.create(m1, m1, 1, 2) stored.pos = {} stored.lp1 = lp1 stored.lp2 = lp2 stored.origp = None # get origp (should be 0.,0.,0. cmd.alter("(index 1)", "stored.origp = s['label_placement_offset']") # change atom-state setting to lp1 for atom in both states cmd.alter_state(0, "(index 1)", "s['label_placement_offset']=stored.lp1") # change atom-level setting for all atoms to something else cmd.alter("all", "s['label_placement_offset']=stored.lp2") # get atom-state settings cmd.iterate_state(0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']") # atom-state setting should be lp1 for atom 1 self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)]) self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)]) # atom setting should override to lp2 for atom 2 in both states self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 1, 2)]) self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 2, 2)]) # unset all atom-level settings, atom-state settings should still exist cmd.alter("all", "s['label_placement_offset']=None") stored.pos = {} cmd.iterate_state(0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']") self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)]) self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)]) self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 1, 2)]) self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 2, 2)])
def update(self): self.center = cmd.get_position() cmd.alter_state(0, self.center_name, "(x, y, z) = p", space={'p': self.center}) cmd.isomesh(self.name, self.map_name, self.level, self.center_name, carve=self.radius)
def update_structure(pose_name): '''Update the structure of the pose.''' pose = poses[pose_name] for i in range(1, pose.size() + 1): for j in range(1, pose.residue(i).natoms() + 1): name = pose.residue(i).atom_name(j) xyz = pose.residue(i).xyz(j) cmd.alter_state( 1, '{0} and res {1} and n. {2}'.format(pose_name, i, name), '(x, y, z)=({0}, {1}, {2})'.format(xyz.x, xyz.y, xyz.z))
def testAtomStateLevelSettingsOnRemove(self): if cmd.get_setting_int('suspend_undo'): self.skipTest("need suspend_undo=0") cmd.load(self.datafile("1molecule.mae")) cmd.load(self.datafile("1molecule.mae")) cmd.label("index 10", "'Test Label'") plv = [ 5., 0., 0.] cmd.alter_state(1, "index 10", "s.label_placement_offset = %s" % plv) cmd.remove("index 10") cmd.undo() stored.offset = None cmd.iterate_state(1, "index 10", "stored.offset = list(s.label_placement_offset)") self.assertEqual(stored.offset, plv)
def testAlterState(self): self.load_big_example_multistate() v_count = cmd.count_atoms() * cmd.count_states() assert v_count > 10**5 xyz = [] with self.timing('i', 5.0): cmd.iterate_state(0, 'all', 'xyz.append((x,y,z))', space=locals()) self.assertEqual(v_count, len(xyz)) with self.timing('a', 5.0): cmd.alter_state(0, 'all', '(x,y,z) = next(xyz_rev)', space={'xyz_rev': reversed(xyz), 'next': next}) cmd.iterate_state(0, 'last all', 'stored.xyz = (x,y,z)') self.assertEqual(stored.xyz, xyz[0])
def createRotamerInPymol(self, rotamer, ensembleName): atomNames = self.currentLabel.atomNames for atomName in atomNames: thisAtom = rotamer.atoms[atomName] stored.xyz = [] stored.xyz = thisAtom.coordinate try: cmd.alter_state(1, "%s & name %s " % ("currentLabel", atomName), "(x,y,z)=stored.xyz") except: print "Could not alter coordinate" cmd.alter("%s & name %s " % ("currentLabel", atomName), "segi='%s'" % self.currentLabel.uid) cmd.create( "%s_%s_%s" % (self.residue1Name, self.currentLabel.identifier, ensembleName), "currentLabel", 1, rotamer.id + 1)
def testAlterState(self): cmd.fragment('ala') cmd.create('ala', 'ala', 1, 2) v_count = cmd.count_atoms('all') v_mock = [list(map(float, list(range(i*3, (i+1)*3)))) for i in range(v_count)] v_xyz_1_pre = cmd.get_model('all', state=1).get_coord_list() v_xyz_2_pre = cmd.get_model('all', state=2).get_coord_list() cmd.alter_state(2, 'all', '(x,y,z) = next(xyz_iter)', space={'xyz_iter': iter(v_mock), 'next': next}) v_xyz_1_post = cmd.get_model('all', state=1).get_coord_list() v_xyz_2_post = cmd.get_model('all', state=2).get_coord_list() self.assertEqual(v_xyz_1_post, v_xyz_1_pre) self.assertEqual(v_xyz_2_post, v_mock)
def COM(selection='all', center=0, quiet=1): model = cmd.get_model(selection) nAtom = len(model.atom) COM = cpv.get_null() for a in model.atom: COM = cpv.add(COM, a.coord) COM = cpv.scale(COM, 1./nAtom) if not int(quiet): print ' COM: [%8.3f,%8.3f,%8.3f]' % tuple(COM) if int(center): cmd.alter_state(1, selection, "(x,y,z)=sub((x,y,z), COM)", space={'COM': COM, 'sub': cpv.sub}) return COM
def simulation(): state = 1 import traceback try: while state < n_states: state = state + 1 for part in particle: # simplistic Euler intergration # p = p + v part[1] = (half_box + part[1] + part[5]) % box_size - half_box part[2] = (half_box + part[2] + part[6]) % box_size - half_box part[3] = (half_box + part[3] + part[7]) % box_size - half_box # v = v + pseudo-gravitational acceleration factor = max(0.1 * box_size, 0.1 * (part[1]**2 + part[2]**2 + part[3]**2)**1.5) part[5] = part[5] - part[1] / factor part[6] = part[6] - part[2] / factor part[7] = part[7] - part[3] / factor # copy initial coordinates to a new state cmd.create("cloud", "cloud", 1, state) # update the new state coordinates cmd.alter_state(state, "cloud", "(x,y,z) = particle[int(resi)][1:4]", space=globals()) cmd.forward() cmd.refresh() # don't hog the CPU entirely sleep(0.01) cmd.mplay() except: traceback.print_exc()
def COM(selection='all', center=0, quiet=1): model = cmd.get_model(selection) nAtom = len(model.atom) COM = cpv.get_null() for a in model.atom: COM = cpv.add(COM, a.coord) COM = cpv.scale(COM, 1. / nAtom) if not int(quiet): print ' COM: [%8.3f,%8.3f,%8.3f]' % tuple(COM) if int(center): cmd.alter_state(1, selection, "(x,y,z)=sub((x,y,z), COM)", space={'COM': COM, 'sub': cpv.sub}) return COM
def centroid(selection='all', center=0, quiet=1): model = cmd.get_model(selection) nAtom = len(model.atom) centroid = cpv.get_null() for a in model.atom: centroid = cpv.add(centroid, a.coord) centroid = cpv.scale(centroid, 1. / nAtom) if not int(quiet): print ' centroid: [%8.3f,%8.3f,%8.3f]' % tuple(centroid) if int(move): cmd.alter_state(1, selection, "(x,y,z)=sub((x,y,z), centroid)", space={'centroid': centroid, 'sub': cpv.sub}) return centroid
def test_atom_state_settings_3f(self, f, data): m1 = "pseudo01" lp1, lp2 = lp = map(f, data) cmd.pseudoatom(m1) cmd.pseudoatom(m1) cmd.create(m1, m1, 1, 2) stored.pos = {} stored.lp1 = lp1 stored.lp2 = lp2 stored.origp = None # get origp (should be 0.,0.,0. cmd.alter("(index 1)", "stored.origp = s['label_placement_offset']") # change atom-state setting to lp1 for atom in both states cmd.alter_state(0, "(index 1)", "s['label_placement_offset']=stored.lp1") # change atom-level setting for all atoms to something else cmd.alter("all", "s['label_placement_offset']=stored.lp2") # get atom-state settings cmd.iterate_state( 0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']" ) # atom-state setting should be lp1 for atom 1 self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)]) self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)]) # atom setting should override to lp2 for atom 2 in both states self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 1, 2)]) self.assertEqual(tuple(lp2), stored.pos['%s-%s-%s' % (m1, 2, 2)]) # unset all atom-level settings, atom-state settings should still exist cmd.alter("all", "s['label_placement_offset']=None") stored.pos = {} cmd.iterate_state( 0, "all", "stored.pos['%s-%s-%s' % (model, state, index)]=s['label_placement_offset']" ) self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 1, 1)]) self.assertEqual(tuple(lp1), stored.pos['%s-%s-%s' % (m1, 2, 1)]) self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 1, 2)]) self.assertEqual(tuple(stored.origp), stored.pos['%s-%s-%s' % (m1, 2, 2)])
def test2667(self): cmd.fragment('ala', 'm1') cmd.alter_state(1, '%m1', 's.label_placement_offset = [1., 0., 0.]') with testing.mktemp('.pse') as filename: cmd.save(filename) cmd.set_name('m1', 'm2') cmd.load(filename, partial=1) # now we have two copies (m1 m2). If unique ids are converted upon # loading, then there will be no settings cross-leaking. Otherwise # changing m1 settings will affect m2. cmd.alter_state(1, '%m1', 's.label_placement_offset = [0., 1., 0.]') m2_setting = [] cmd.iterate_state(1, 'first %m2', 'm2_setting.append(s.label_placement_offset)', space=locals()) self.assertArrayEqual([1., 0., 0.], m2_setting[0], 0.001)
def simulation(): state = 1 import traceback try: while state < n_states: state = state + 1 for part in particle: # simplistic Euler intergration # p = p + v part[1] = (half_box + part[1] + part[5]) % box_size - half_box part[2] = (half_box + part[2] + part[6]) % box_size - half_box part[3] = (half_box + part[3] + part[7]) % box_size - half_box # v = v + pseudo-gravitational acceleration factor = max(0.1*box_size, 0.1*(part[1]**2+part[2]**2+part[3]**2)**1.5) part[5] = part[5] - part[1] / factor part[6] = part[6] - part[2] / factor part[7] = part[7] - part[3] / factor # copy initial coordinates to a new state cmd.create("cloud","cloud",1,state) # update the new state coordinates cmd.alter_state(state,"cloud","(x,y,z) = particle[int(resi)][1:4]",space=globals()) cmd.forward() cmd.refresh() # don't hog the CPU entirely sleep(0.01) cmd.mplay() except: traceback.print_exc()
def testStereo(self): cmd.fragment('ala') cmd.remove('hydro') # default: S configuration labels = [] cmd.iterate('name CA', 'labels.append(stereo)', space=locals()) self.assertEqual(labels, ['S']) # load R configuration (moves CB) ala_conf_R = { 'N' : (-0.67690, -1.23030, -0.49050), 'CA' : (-0.00090, 0.06370, -0.49050), 'C' : ( 1.49910, -0.11030, -0.49050), 'O' : ( 2.03010, -1.22730, -0.50150), # 'CB' : (-0.50890, 0.85570, 0.72650), # S configuration 'CB' : (-0.33784, 0.82664, -1.78310), # R configuration } cmd.alter_state(1, 'ala', '(x,y,z) = ala_conf_R.get(name)', space=locals()) labels = [] cmd.iterate('name CA', 'labels.append(stereo)', space=locals()) self.assertEqual(labels, ['R'])
def testAlterState(self): self.load_big_example_multistate() v_count = cmd.count_atoms() * cmd.count_states() assert v_count > 10**5 xyz = [] with self.timing('i', 5.0): cmd.iterate_state(0, 'all', 'xyz.append((x,y,z))', space=locals()) self.assertEqual(v_count, len(xyz)) with self.timing('a', 5.0): cmd.alter_state(0, 'all', '(x,y,z) = next(xyz_rev)', space={ 'xyz_rev': reversed(xyz), 'next': next }) cmd.iterate_state(0, 'last all', 'stored.xyz = (x,y,z)') self.assertEqual(stored.xyz, xyz[0])
def centroid(selection='all', center=0, quiet=1): model = cmd.get_model(selection) nAtom = len(model.atom) centroid = cpv.get_null() for a in model.atom: centroid = cpv.add(centroid, a.coord) centroid = cpv.scale(centroid, 1. / nAtom) if not int(quiet): print(' centroid: [%8.3f,%8.3f,%8.3f]' % tuple(centroid)) if int(center): cmd.alter_state(1, selection, "(x,y,z)=sub((x,y,z), centroid)", space={ 'centroid': centroid, 'sub': cpv.sub }) return centroid
def ens_rmsf(selection, rmsf_spectrum = False, mean_structure = False, mean_per_resi = True, log_name = None): ''' DESCRIPTION Generates and colors structure by RMSF statistics, calculated from mulistate ensembles USAGE ens_rmsf selection, sigma_rmsf_spectrum, mean_structure, histogram_number_bins, log_name ARGUMENTS sigma_rmsf_spectrum = overwrite q col with sigma RMSF (per atom), color by q mean_structure = generate new single state structure with mean coords histogram_number_bins = number of bins for output histograms log_name = name of log file EXAMPLE ens_rmsf protein, True, True, 25, 'ens_rmsf.log' ''' if log_name == None: log = LogWriter(sys.stdout, 'log.txt') else: log = LogWriter(sys.stdout, log_name+'.txt') print >> log, "\nEnsemble RMSF" print >> log, "N.B. waters excluded" print >> log, "N.B. B column information from first model" print >> log, "Rmsf (Angstrom) [w.r.t mean structure]" print >> log, "B_atom (Angstrom^2) [atomic Bfactor used in simulation]" print >> log, "B_rmsf (Angstrom^2) [rmsf converted to Bfactor]" # initialize arrays selection = selection + ' and not resn hoh' models = [] mean_coords = None number_models = cmd.count_states(selection) r_number_models = 1.0 / number_models # get models, mean coords for i in range(number_models): models.append(cmd.get_model(selection,state=i+1)) coords_for_mean = map( lambda x: [x[0]*r_number_models,x[1]*r_number_models,x[2]*r_number_models],models[i].get_coord_list()) if mean_coords == None: mean_coords = coords_for_mean else: n = [] for mean, for_mean in zip(mean_coords, coords_for_mean): mean = map(sum, zip(mean,for_mean)) n.append(mean) mean_coords = n # calculate RMSF w.r.t. mean structure rmsf_coord = [0.0]*len(mean_coords) for i in range(number_models): coord_array = models[i].get_coord_list() for i_seq, xyz in enumerate(coord_array): rmsf_coord[i_seq] += distance(xyz, mean_coords[i_seq])**2 rmsf_coord = map(lambda x: (x / number_models)**0.5, rmsf_coord) # Generate new model object with average xyz coord if mean_structure: mean_structure_name = 'mean_xyz_'+selection cmd.create(mean_structure_name, selection, 1) stored.xyz = map(lambda v:[v[0],v[1],v[2]],mean_coords) cmd.alter_state(1, mean_structure_name,'(x,y,z) = stored.xyz.pop(0)') # convert to B factor (A^2) rmsf_as_b_coord = map(lambda x: x**2 * ((8.0 * math.pi**2) / 3.0), rmsf_coord) # get atomic b factor info atom_b = [at.b for at in models[0].atom] b_atom_plus_b_rsmf = map(sum,zip(atom_b,rmsf_as_b_coord)) # Colour by rmsf if rmsf_spectrum: # cmd.color('grey', 'all') # cmd.alter('all','q=0') atom = models[0].atom for n, atom in enumerate(models[0].atom): atom_sel = 'id ' + str(atom.id) atom_action = 'q = ' + str(rmsf_sigma[n]) cmd.alter(atom_sel,atom_action) print "\n\nQ infomation updated with RMSF sigma\n" cmd.spectrum('q',selection = selection) if mean_structure: cmd.spectrum('q', selection = mean_structure_name) else: for n, atom in enumerate(models[0].atom): atom_sel = 'id ' + str(atom.id) atom_action = 'q = ' + str(rmsf_coord[n]) cmd.alter(atom_sel,atom_action) print "\n\nQ infomation updated with RMSF (Angstrom)\n" cmd.spectrum('q',selection = selection) # array stats print >> log, '\nB_atom (A^2): ' print_array_stats(array = atom_b, log = log) print >> log, '\nRmsf (A): ' print_array_stats(array = rmsf_coord, log = log) print >> log, '\nB_rmsf (A^2): ' print_array_stats(array = rmsf_as_b_coord, log = log) print >> log, '\nB_atom + B_rmsf (A^2):' print_array_stats(array = b_atom_plus_b_rsmf, log = log) # individual atom stats print >> log, '\n\n Resi | Name | Chain | Rmsf | B_rmsf | B_atom | B_rmsf+B_atom\n' for i_seq, b_factor in enumerate(atom_b): print >> log, ' %7s %7s %7s | %8.3f | %8.3f %8.3f | %8.3f'%( models[0].atom[i_seq].resi, models[0].atom[i_seq].name, models[0].atom[i_seq].chain, rmsf_coord[i_seq], rmsf_as_b_coord[i_seq], b_factor, b_atom_plus_b_rsmf[i_seq]) if mean_per_resi: print >> log, '\nMean per residue' # update atom to include info for n, atom in enumerate(models[0].atom): atom.rmsf = rmsf_coord[n] atom.b_rmsf = rmsf_as_b_coord[n] atom.b_atom_plus_b_rsmf = atom.b + atom.b_rmsf print >> log, ' Resi Resn | Atoms | Atom_rmsf | B_atom B_rmsf B_atom+B_rmsf' def print_mean_residue(): print >> log, ' %4s %5s| %3d | %8.3f | %8.3f %8.3f %8.3f '%( current_resi, current_resn, len(res_b), sum(res_rmsf) / len(res_rmsf), sum(res_b) / len(res_b), sum(res_b_rmsf) / len(res_b_rmsf), sum(res_b_atom_plus_b_rsmf) / len(res_b_atom_plus_b_rsmf) ) current_resi = models[0].atom[0].resi current_resn = models[0].atom[0].resn res_rmsf = [] res_b = [] res_b_rmsf = [] res_b_atom_plus_b_rsmf = [] for atom in models[0].atom: if atom.resi == current_resi: assert atom.resn == current_resn res_rmsf.append(atom.rmsf) res_b.append(atom.b) res_b_rmsf.append(atom.b_rmsf) res_b_atom_plus_b_rsmf.append(atom.b_atom_plus_b_rsmf) else: print_mean_residue() current_resi = atom.resi current_resn = atom.resn res_rmsf = [atom.rmsf] res_b = [atom.b] res_b_rmsf = [atom.b_rmsf] res_b_atom_plus_b_rsmf = [atom.b_atom_plus_b_rsmf] print_mean_residue()
def avgStates(object='all',object_sel=None,first=1,last=0,newobj=None,fitverdict='no',\ verb=0,pairs=1,writefiles=1): ''' ARGUMENTS: object (string [defaults to 'all']): Starting PyMOL molecular object consisting of >1 states to be averaged object_sel (string [defaults to "name CA"]): An optional subset of atoms on which to operate (e.g., "name CA and resi 20-50") first (int [defaults to 1]): number of the first state to include in averaging last (int [defaults to last state]): Number of the last state to include in averaging. A value of '0' (zero) means use the last state in the object. newobj (string [defaults to name of object with string "_avg_AtoZ" appended, where A and Z are the numbers of the first and last frames included in the averaging]): Desired name of the new output pymol object (i.e., averaged structure) fitverdict (string [defaults to "no", any value != "no" is taken as a "yes"]): Use the pymol function intra_fit() to fit all the states of "object & object_sel" before calculating the average structure and RMSDs?? 'no' = NO, !'no' = yes verb (int [defaults to 0]): Verbosity level of output. 0 = quiet, !0 = verbose (e.g., write position-specific RMSDs to standard output). pairs (int [default 1]): Also calculate average pairwise RMSD for each residue position?? 0 = no, !0 = yes writefiles (int [default 1]): Write the calculated RMSD data to plaintext files?? 0 = no, !0 = yes NOTES: The state specified as 'first' is taken as the reference state for the (optional) intra_fit() alignment. If no selection is given, the string "and name CA" will be appended to the object and the averaging and rmsd calculations will be restricted to "object and name CA" (i.e., C-alpha atoms). To avoid this default behavior, specify a valid pymol atom selection for the object_sel argument (e.g., "name CA" or "name CA and resi 20-50" or whatever). ''' object = str(object) object_sel = str(object_sel) first=int(first) last=int(last) num_states_tot = cmd.count_states(object) if last<1: last=num_states_tot num_states2avg = last - first + 1 if newobj==None or newobj=='': newobj = "%s_avg_%dto%d"%(object,first,last) cmd.create(newobj,object,first,1) if writefiles: print '%s'%('-'*80) datfileprefix = '%s_%dto%d'%(replace(object,' ','_'),first,last) avg_rmsd_file = datfileprefix + '.avg_rmsd.dat' avg_file = open(avg_rmsd_file,'w') print 'Opened "%s" file for writing residue-specific RMSDs to average structure...'%avg_rmsd_file if pairs: pair_rmsd_file = datfileprefix + '.pair_rmsd.dat' pair_file = open(pair_rmsd_file,'w') print 'Opened "%s" file for writing averaged residue-specific pairwise RMSDs...'%pair_rmsd_file print '%s'%('-'*80) else: avg_file = open('/dev/null','w') # just do this instead of evaluating conditionals each time if pairs: pair_file = open('/dev/null','w') # through the atom loops (below)... obj_sel_string = (lambda o,s: (o and s and "%s and %s"%(o,s)) or \ (o and not s and "%s and name CA"%o))(object,object_sel) newobj_sel_string = (lambda o,s: (o and s and "%s and %s"%(o,s)) or \ (o and not s and "%s and name CA"%o))(newobj,object_sel) print '%s'%('-'*80) print 'Averaging %d states [%d, %d] of object "%s" (%d total states) to get new single-state object "%s"...' \ % (num_states2avg,first,last,obj_sel_string,num_states_tot,newobj) print '%s'%('-'*80) tmpobject='%s_tmp4avg_%dto%d'%(object,first,last) i=0 for eachstate in range(first,last+1): i+=1 # because pymol states are indexed starting from 1 (not 0) cmd.create(tmpobject,obj_sel_string,eachstate,i) if fitverdict != 'no': print "-> proceeding WITH FITTING to reference state..." tmpobject_intrafit_rmsds = cmd.intra_fit(tmpobject,1) if verb: print ' intrafit_rmsds = ', print tmpobject_intrafit_rmsds else: print "-> proceeding WITHOUT FITTING to reference state..." # create an atom index map between original (complete) object and subset to be averaged: atindex_map = [None] for at in cmd.get_model(newobj_sel_string,1).atom: atindex_map.append(at.index) if verb: print "-> atom index_map = ", print atindex_map newobj_chempy = cmd.get_model(tmpobject,1) for at in newobj_chempy.atom: this_at_idx = at.index sum_x = sum_y = sum_z = 0.0 avg_x = avg_y = avg_z = 0.0 state_coords=[] rmsd_sum = rmsd = 0.0 for s in range(1,num_states2avg+1): this_x = cmd.get_model(tmpobject,s).atom[this_at_idx-1].coord[0] this_y = cmd.get_model(tmpobject,s).atom[this_at_idx-1].coord[1] this_z = cmd.get_model(tmpobject,s).atom[this_at_idx-1].coord[2] sum_x += this_x sum_y += this_y sum_z += this_z state_coords.append([this_x,this_y,this_z]) avg_x = sum_x / num_states2avg avg_y = sum_y / num_states2avg avg_z = sum_z / num_states2avg cmd.alter_state(1,'%s and id %d'%(newobj,atindex_map[this_at_idx]),'x=%f'%avg_x) cmd.alter_state(1,'%s and id %d'%(newobj,atindex_map[this_at_idx]),'y=%f'%avg_y) cmd.alter_state(1,'%s and id %d'%(newobj,atindex_map[this_at_idx]),'z=%f'%avg_z) # position-specific RMSDs with respect to average structure: for somept in state_coords: rmsd_sum += pow(calcDist(somept,[avg_x,avg_y,avg_z]),2.0) rmsd = sqrt(rmsd_sum / num_states2avg) # DEBUG: # DEBUG print 'newobj = %s / id = %d / b = %0.3f'%(newobj,atindex_map[this_at_idx],rmsd) cmd.alter('%s and id %d'%(newobj,atindex_map[this_at_idx]),'b=%0.3f'%rmsd) if verb: print '"%s" index = %d'%(obj_sel_string,this_at_idx) print 'rmsd = %0.3f'%rmsd avg_file.write('%d\t%0.3f\n'%(atindex_map[this_at_idx],rmsd)) # position-specific RMSDs averaged pairwise over the bundle: if pairs: for at in newobj_chempy.atom: this_at_idx = at.index loop_counter = 0 running_sum = 0.0 for s1 in range(1,num_states2avg+1): for s2 in range(s1+1,num_states2avg+1): #DB print 'computing position %d, %d x %d'%(this_at_idx,s1,s2) pos1 = [ cmd.get_model(tmpobject,s1).atom[this_at_idx-1].coord[0], cmd.get_model(tmpobject,s1).atom[this_at_idx-1].coord[1], cmd.get_model(tmpobject,s1).atom[this_at_idx-1].coord[2] ] pos2 = [ cmd.get_model(tmpobject,s2).atom[this_at_idx-1].coord[0], cmd.get_model(tmpobject,s2).atom[this_at_idx-1].coord[1], cmd.get_model(tmpobject,s2).atom[this_at_idx-1].coord[2] ] loop_counter += 1 running_sum += pow(calcDist(pos1,pos2),2.0) # print '%s'%('.'*s2) pairwise_rmsd = sqrt(running_sum / loop_counter) if verb: print 'calculated pairwise RMSD for %d pairs at position %d = %0.3f' % \ (loop_counter,atindex_map[this_at_idx],pairwise_rmsd) pair_file.write('%d\t%0.3f\n'%(atindex_map[this_at_idx],pairwise_rmsd)) if writefiles: avg_file.close() if pairs: pair_file.close()
from pymol import cmd from pymol import stored stored.xyz = [] cmd.iterate_state(1,"pept","stored.xyz.append([x,y,z])") # at this point, stored.xyz is a native Python array holding # the coordinates, which you can modify as required stored.xyz = map(lambda v:[-v[1],v[0],v[2]],stored.xyz) # and now you can update the internal coordinate sets cmd.alter_state(1,"pept","(x,y,z)=stored.xyz.pop(0)")
def do_library(self): cmd = self.cmd pymol = cmd._pymol if not ( (cmd.count_atoms("(%s) and name n" % src_sele) == 1) and (cmd.count_atoms("(%s) and name c" % src_sele) == 1) and (cmd.count_atoms("(%s) and name o" % src_sele) == 1) ): self.clear() return 1 cmd.feedback("push") cmd.feedback("disable", "selector", "everythin") cmd.feedback("disable", "editor", "actions") self.prompt = ["Loading rotamers..."] pymol.stored.name = "residue" cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi') self.res_text = pymol.stored.name cmd.select("_seeker_hilight", src_sele) auto_zoom = cmd.get_setting_text("auto_zoom") cmd.set("auto_zoom", "0", quiet=1) cmd.frame(0) cmd.delete(frag_name) if self.auto_center: cmd.center(src_sele, animate=-1) self.lib_mode = self.mode if self.lib_mode == "current": pymol.stored.resn = "" cmd.iterate("(%s and n;ca)" % src_sele, "stored.resn=resn") rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn) if (self.c_cap != "none") or (self.n_cap != "none") or (self.hyd != "auto"): self.lib_mode = rot_type # force fragment-based load else: cmd.create(frag_name, src_sele, 1, 1) if self.c_cap == "open": cmd.remove("%s and name OXT" % frag_name) if self.lib_mode != "current": rot_type = self.lib_mode frag_type = self.lib_mode if (self.n_cap == "posi") and (frag_type[0:3] != "NT_"): if not (cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) &! r. ace" % (src_sele, src_sele))): # use N-terminal fragment frag_type = "NT_" + frag_type if (self.c_cap == "nega") and (frag_type[0:3] != "CT_"): if not (cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele))): # use C-terminal fragment frag_type = "CT_" + frag_type if rot_type[0:3] in ["NT_", "CT_"]: rot_type = rot_type[3:] rot_type = _rot_type_xref.get(rot_type, rot_type) cmd.fragment(string.lower(frag_type), frag_name) # trim off hydrogens if self.hyd == "none": cmd.remove("(" + frag_name + " and hydro)") elif self.hyd == "auto": if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") # copy identifying information cmd.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain") cmd.alter("(%s)" % frag_name, "chain=stored.chain") cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi") cmd.alter("(%s)" % frag_name, "resi=stored.resi") cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi") cmd.alter("(%s)" % frag_name, "segi=stored.segi") cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss") cmd.alter("(%s)" % frag_name, "ss=stored.ss") # move the fragment if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and ( cmd.count_atoms("(%s and n;cb)" % src_sele) == 1 ): cmd.pair_fit( "(%s and n;ca)" % frag_name, "(%s and n;ca)" % src_sele, "(%s and n;cb)" % frag_name, "(%s and n;cb)" % src_sele, "(%s and n;c)" % frag_name, "(%s and n;c)" % src_sele, "(%s and n;n)" % frag_name, "(%s and n;n)" % src_sele, ) else: cmd.pair_fit( "(%s and n;ca)" % frag_name, "(%s and n;ca)" % src_sele, "(%s and n;c)" % frag_name, "(%s and n;c)" % src_sele, "(%s and n;n)" % frag_name, "(%s and n;n)" % src_sele, ) # fix the carbonyl position... cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list") if cmd.count_atoms("(%s and n;oxt)" % src_sele): cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list") elif cmd.count_atoms("(%s and n;oxt)" % frag_name): # place OXT if no template exists angle = cmd.get_dihedral( "(%s and n;n)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;c)" % frag_name, "(%s and n;o)" % frag_name, ) cmd.protect("(%s and n;o)" % frag_name) cmd.set_dihedral( "(%s and n;n)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;c)" % frag_name, "(%s and n;oxt)" % frag_name, 180.0 + angle, ) cmd.deprotect(frag_name) # fix the hydrogen position (if any) if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1: if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1: cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]") cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list") elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1: # position hydro based on location of the carbonyl angle = cmd.get_dihedral( "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1 ) cmd.set_dihedral( "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, "(%s and n;h)" % frag_name, 180.0 + angle, ) cmd.delete(tmp_sele1) # add c-cap (if appropriate) if self.c_cap in ["amin", "nmet"]: if not cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)): if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1: if self.c_cap == "amin": editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh") elif self.c_cap == "nmet": editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme") if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name): cmd.h_fix("n;n & bound_to (n;c & (%s))" % frag_name) # trim hydrogens if self.hyd == "none": cmd.remove("(" + frag_name + " and hydro)") elif self.hyd == "auto": if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") # add n-cap (if appropriate) if self.n_cap in ["acet"]: if not cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)): if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1: if self.n_cap == "acet": editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace") if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name): cmd.h_fix("n;n & (%s)" % frag_name) # trim hydrogens if self.hyd == "none": cmd.remove("(" + frag_name + " and hydro)") elif self.hyd == "auto": if cmd.count_atoms("(" + src_sele + ") and hydro") == 0: cmd.remove("(" + frag_name + " and hydro)") cartoon = cmd.count_atoms("(%s and n;ca and rep cartoon)" % src_sele) > 0 sticks = cmd.count_atoms("(%s and n;ca and rep sticks)" % src_sele) > 0 cmd.delete(obj_name) key = rot_type lib = None if self.dep == "dep": try: result = cmd.phi_psi("%s" % src_sele) if len(result) == 1: (phi, psi) = result[result.keys()[0]] (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10)))) key = (rot_type, phi, psi) if not self.dep_library.has_key(key): (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20)))) key = (rot_type, phi, psi) if not self.dep_library.has_key(key): (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60)))) key = (rot_type, phi, psi) lib = self.dep_library.get(key, None) except: pass if lib == None: key = rot_type lib = self.ind_library.get(key, None) if (lib != None) and self.dep == "dep": print " Mutagenesis: no phi/psi, using backbone-independent rotamers." if lib != None: state = 1 for a in lib: cmd.create(obj_name, frag_name, 1, state) if state == 1: cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele)) if rot_type == "PRO": cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele) for b in a.keys(): if b != "FREQ": cmd.set_dihedral( "(%s & n;%s)" % (mut_sele, b[0]), "(%s & n;%s)" % (mut_sele, b[1]), "(%s & n;%s)" % (mut_sele, b[2]), "(%s & n;%s)" % (mut_sele, b[3]), a[b], state=state, ) else: cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100)) if rot_type == "PRO": cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele) state = state + 1 cmd.delete(frag_name) print " Mutagenesis: %d rotamers loaded." % len(lib) if self.bump_check: cmd.delete(bump_name) cmd.create( bump_name, "(((byobj %s) within 6 of (%s and not name n+c+ca+o+h+ha)) and (not (%s)))|(%s)" % (src_sele, mut_sele, src_sele, mut_sele), singletons=1, ) cmd.color("gray50", bump_name + " and elem c") cmd.set("seq_view", 0, bump_name, quiet=1) cmd.hide("everything", bump_name) if (cmd.select(tmp_sele1, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1 ): cmd.bond(tmp_sele1, tmp_sele2) if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and ( cmd.select(tmp_sele2, "(n;N and (%s in %s))" % (bump_name, mut_sele)) == 1 ): cmd.bond(tmp_sele1, tmp_sele2) cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.protect("%s and not (%s in (%s and not name n+c+ca+o+h+ha))" % (bump_name, bump_name, mut_sele)) cmd.sculpt_activate(bump_name) cmd.show("cgo", bump_name) # draw the bumps cmd.set("sculpt_vdw_vis_mode", 1, bump_name) state = 1 for a in lib: cmd.sculpt_iterate(bump_name, state=state) state = state + 1 cmd.delete(mut_sele) else: cmd.create(obj_name, frag_name, 1, 1) print " Mutagenesis: no rotamers found in library." cmd.set("seq_view", 0, obj_name, quiet=1) pymol.util.cbaw(obj_name) cmd.hide("(" + obj_name + ")") cmd.show(self.rep, obj_name) cmd.show("lines", obj_name) # neighbor always show lines if cartoon: cmd.show("cartoon", obj_name) if sticks: cmd.show("sticks", obj_name) cmd.set("auto_zoom", auto_zoom, quiet=1) cmd.delete(frag_name) cmd.frame(0) cmd.unpick() cmd.feedback("pop")
def avg_states(object='all', object_sel=None, first=1, last=0, newobj=None, fitverdict='no', verb=0, pairs=1, writefiles=1): """ ARGUMENTS: object (string [defaults to 'all']): Starting PyMOL molecular object consisting of >1 states to be averaged object_sel (string [defaults to "name CA"]): An optional subset of atoms on which to operate (e.g., "name CA and resi 20-50") first (int [defaults to 1]): number of the first state to include in averaging last (int [defaults to last state]): Number of the last state to include in averaging. A value of '0' (zero) means use the last state in the object. newobj (string [defaults to name of object with string "_avg_AtoZ" appended, where A and Z are the numbers of the first and last frames included in the averaging]): Desired name of the new output pymol object (i.e., averaged structure) fitverdict (string [defaults to "no", any value != "no" is taken as a "yes"]): Use the pymol function intra_fit() to fit all the states of "object & object_sel" before calculating the average structure and RMSDs?? 'no' = NO, !'no' = yes verb (int [defaults to 0]): Verbosity level of output. 0 = quiet, !0 = verbose (e.g., write position-specific RMSDs to standard output). pairs (int [default 1]): Also calculate average pairwise RMSD for each residue position?? 0 = no, !0 = yes writefiles (int [default 1]): Write the calculated RMSD data to plaintext files?? 0 = no, !0 = yes NOTES: The state specified as 'first' is taken as the reference state for the (optional) intra_fit() alignment. If no selection is given, the string "and name CA" will be appended to the object and the averaging and rmsd calculations will be restricted to "object and name CA" (i.e., C-alpha atoms). To avoid this default behavior, specify a valid pymol atom selection for the object_sel argument (e.g., "name CA" or "name CA and resi 20-50" or whatever). """ pair_file = None object = str(object) object_sel = str(object_sel) first = int(first) last = int(last) num_states_tot = cmd.count_states(object) if last < 1: last = num_states_tot num_states2avg = last - first + 1 if newobj is None or newobj == '': newobj = "%s_avg_%dto%d" % (object, first, last) cmd.create(newobj, object, first, 1) if writefiles: print('%s' % ('-' * 80)) datfileprefix = '%s_%dto%d' % (replace(object, ' ', '_'), first, last) avg_rmsd_file = datfileprefix + '.avg_rmsd.dat' avg_file = open(avg_rmsd_file, 'w') print('Opened "%s" file for writing residue-specific RMSDs to ' 'average structure...' % avg_rmsd_file) if pairs: pair_rmsd_file = datfileprefix + '.pair_rmsd.dat' pair_file = open(pair_rmsd_file, 'w') print('Opened "%s" file for writing averaged residue-specific ' 'pairwise RMSDs...' % pair_rmsd_file) print('%s' % ('-' * 80)) else: # just do this instead of evaluating conditionals each time avg_file = open('/dev/null', 'w') if pairs: pair_file = open('/dev/null', 'w') # through the atom loops (below)... obj_sel_string = (lambda o, sel: (o and sel and "%s and %s" % (o, sel)) or (o and not sel and "%s and name CA" % o))(object, object_sel) newobj_sel_string = (lambda o, sel: (o and sel and "%s and %s" % (o, sel)) or (o and not sel and "%s and name CA" % o))(newobj, object_sel) print('%s' % ('-' * 80)) print( 'Averaging %d states [%d, %d] of object "%s" (%d total states) ' 'to get new single-state object "%s"...' % (num_states2avg, first, last, obj_sel_string, num_states_tot, newobj)) print('%s' % ('-' * 80)) tmpobject = '%s_tmp4avg_%dto%d' % (object, first, last) i = 0 for eachstate in range(first, last + 1): i += 1 # because pymol states are indexed starting from 1 (not 0) cmd.create(tmpobject, obj_sel_string, eachstate, i) if fitverdict != 'no': print("-> proceeding WITH FITTING to reference state...") tmpobject_intrafit_rmsds = cmd.intra_fit(tmpobject) if verb: print(' intrafit_rmsds = ', ) print(tmpobject_intrafit_rmsds) else: print("-> proceeding WITHOUT FITTING to reference state...") # create an atom index map between original (complete) object and subset # to be averaged: atindex_map = [None] for at in cmd.get_model(newobj_sel_string).atom: atindex_map.append(at.index) if verb: print("-> atom index_map = ", ) print(atindex_map) newobj_chempy = cmd.get_model(tmpobject) for at in newobj_chempy.atom: this_at_idx = at.index sum_x = sum_y = sum_z = 0.0 # avg_x = avg_y = avg_z = 0.0 state_coords = [] # rmsd_sum = rmsd = 0.0 rmsd_sum = 0.0 for s in range(1, num_states2avg + 1): this_x = cmd.get_model(tmpobject, s).atom[this_at_idx - 1].coord[0] this_y = cmd.get_model(tmpobject, s).atom[this_at_idx - 1].coord[1] this_z = cmd.get_model(tmpobject, s).atom[this_at_idx - 1].coord[2] sum_x += this_x sum_y += this_y sum_z += this_z state_coords.append([this_x, this_y, this_z]) avg_x = sum_x / num_states2avg avg_y = sum_y / num_states2avg avg_z = sum_z / num_states2avg cmd.alter_state( 1, '{0:s} and id {1:d}'.format(newobj, atindex_map[this_at_idx]), 'x=%f' % avg_x) cmd.alter_state( 1, '{0:s} and id {1:d}'.format(newobj, atindex_map[this_at_idx]), 'y=%f' % avg_y) cmd.alter_state( 1, '{0:s} and id {1:d}'.format(newobj, atindex_map[this_at_idx]), 'z=%f' % avg_z) # position-specific RMSDs with respect to average structure: for somept in state_coords: rmsd_sum += pow(calcDist(somept, [avg_x, avg_y, avg_z]), 2.0) rmsd = sqrt(rmsd_sum / num_states2avg) # DEBUG: # DEBUG print('newobj = %sel / id = %d / b = %0.3f' # %(newobj,atindex_map[this_at_idx],rmsd) cmd.alter( '{0:s} and id {1:d}'.format(newobj, atindex_map[this_at_idx]), 'b=%0.3f' % rmsd) if verb: print('"%s" index = %d' % (obj_sel_string, this_at_idx)) print('rmsd = %0.3f' % rmsd) avg_file.write('{0:d}\t{1:0.3f}\n'.format(atindex_map[this_at_idx], rmsd)) # position-specific RMSDs averaged pairwise over the bundle: if pairs: for at in newobj_chempy.atom: this_at_idx = at.index loop_counter = 0 running_sum = 0.0 for s1 in range(1, num_states2avg + 1): for s2 in range(s1 + 1, num_states2avg + 1): # print('computing position %d, %d x %d'%(this_at_idx,s1,s2) pos1 = [ cmd.get_model(tmpobject, s1).atom[this_at_idx - 1].coord[0], cmd.get_model(tmpobject, s1).atom[this_at_idx - 1].coord[1], cmd.get_model(tmpobject, s1).atom[this_at_idx - 1].coord[2] ] pos2 = [ cmd.get_model(tmpobject, s2).atom[this_at_idx - 1].coord[0], cmd.get_model(tmpobject, s2).atom[this_at_idx - 1].coord[1], cmd.get_model(tmpobject, s2).atom[this_at_idx - 1].coord[2] ] loop_counter += 1 running_sum += pow(calcDist(pos1, pos2), 2.0) pairwise_rmsd = sqrt(running_sum / loop_counter) if verb: print('calculated pairwise RMSD for {0:d} pairs at ' 'position {0:d} = {1:0.3f}'.format( loop_counter, atindex_map[this_at_idx], pairwise_rmsd)) pair_file.write('{0:d}\t{1:0.3f}\n'.format( atindex_map[this_at_idx], pairwise_rmsd)) if writefiles: avg_file.close() if pairs: pair_file.close() cmd.delete(tmpobject) return newobj
def GenNM(obj, nmids, mode, inp=None, amp=50., nframes=20, dump_file=False, \ prmtop=None): nmids=[int(i) for i in nmids.split()] amp = float(amp) nframes=int(nframes) mode=int(mode) stored.NMA = {} stored.NMA[obj] = {} if mode==1: if not inp: print "Please specify cpptraj covariance matrix file" return 0 if (not prmtop): print "Please specify prmtop file for proper mass reweighing of vectors." return 0 print "Attempting to read mwcov matrix %s" %inp mwcvmat=genfromtxt(inp) print "Diagonalizing covariance matrix." w,v = linalg.eig(mwcvmat) #sort from largest eigenvvalue to smallest si=argsort(w)[::-1] w=w[si] v=v[:,si] #convert to cm-1 for i in range(len(w)): if w[i]<0: w[i]= -108.587*sqrt(-0.6/w[i]) elif w[i]>0: w[i]= 108.587*sqrt(0.6/w[i]) else: w[i]=0 #get masses and un-mass weigh the modes m=raf.prmtop(prmtop).Get_Masses() m=[[i]*3 for i in m] m=[item for sublist in m for item in sublist] for vec in range(v.shape[1]): v[:,vec]=v[:,vec]/sqrt(m) #store stored.NMA[obj]['w'] = w stored.NMA[obj]['v'] = v elif mode==2: if not inp: print "Please specify evecs frequency/eigenvector file" return 0 print "Attempting to read evecs file %s" %inp stored.NMA[obj]['w'], stored.NMA[obj]['v'] = ReadEvecs(inp) elif mode==3: if not inp: print "Please specify pickled normal mode object" return 0 print "Attempting to read pickle file %s" %inp stored.NMA[obj]=pickle.load( open(inp,"rb")) if dump_file: print "Dumping eigenvalues and modes to pickle file." pickle.dump(stored.NMA[obj], open(dump_file,"wb") ) w = stored.NMA[obj]['w'] v = stored.NMA[obj]['v'] print "%7s%20s%20s" % ('NMID', 'f Hz', 'f cm^-1') for i in range(min(w.size,20)): print "%7d%20.5e\t%20.5f" % (i, w[i]*2.99792458e10, w[i]), if i in nmids: print "*" else: print "" for nmid in nmids: newobj = "%s-nm_%d" % (obj, nmid) cmd.delete(newobj) nm = real(v[:,nmid]) nm *= amp/sqrt((nm**2).sum()) for ifr in range(nframes): cmd.create(newobj, obj, 1, ifr+1) stored.nm = nm*sin(2.*pi*ifr/nframes) cmd.alter_state(ifr+1, newobj, "x,y,z = x+stored.nm[(ID-1)*3], y+stored.nm[(ID-1)*3+1], z+stored.nm[(ID-1)*3+2]")
def do_library(self): cmd=self.cmd pymol=cmd._pymol if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and (cmd.count_atoms("(%s) and name C"%src_sele)==1) and (cmd.count_atoms("(%s) and name O"%src_sele)==1)): self.clear() return 1 cmd.feedback("push") cmd.feedback("disable","selector","everythin") cmd.feedback("disable","editor","actions") self.prompt = [ 'Loading rotamers...'] self.bump_scores = [] state_best = 0 pymol.stored.name = 'residue' cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi') self.res_text = pymol.stored.name cmd.select("_seeker_hilight",src_sele) auto_zoom = cmd.get_setting_text('auto_zoom') cmd.set('auto_zoom',"0",quiet=1) cmd.frame(0) cmd.delete(frag_name) if self.auto_center: cmd.center(src_sele,animate=-1) self.lib_mode = self.mode if self.lib_mode=="current": pymol.stored.resn="" cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn") rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn) if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'): self.lib_mode = rot_type # force fragment-based load else: cmd.create(frag_name,src_sele,1,1) if self.c_cap=='open': cmd.remove("%s and name OXT"%frag_name) if self.lib_mode!='current': rot_type = self.lib_mode frag_type = self.lib_mode if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'): if not ( cmd.count_atoms( "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"% (src_sele,src_sele))): # use N-terminal fragment frag_type ="NT_"+frag_type if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'): if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"% (src_sele,src_sele))): # use C-terminal fragment frag_type ="CT_"+frag_type if rot_type[0:3] in [ 'NT_', 'CT_' ]: rot_type = rot_type[3:] rot_type = _rot_type_xref.get(rot_type, rot_type) cmd.fragment(frag_type.lower(), frag_name, origin=0) # trim off hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") # copy identifying information cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space) cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space) # move the fragment if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and (cmd.count_atoms("(%s & name CB)"%src_sele)==1)): cmd.pair_fit("(%s & name CA)"%frag_name, "(%s & name CA)"%src_sele, "(%s & name CB)"%frag_name, "(%s & name CB)"%src_sele, "(%s & name C)"%frag_name, "(%s & name C)"%src_sele, "(%s & name N)"%frag_name, "(%s & name N)"%src_sele) else: cmd.pair_fit("(%s & name CA)"%frag_name, "(%s & name CA)"%src_sele, "(%s & name C)"%frag_name, "(%s & name C)"%src_sele, "(%s & name N)"%frag_name, "(%s & name N)"%src_sele) # fix the carbonyl position... cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]") cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list") if cmd.count_atoms("(%s & name OXT)"%src_sele): cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]") cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list") elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists angle = cmd.get_dihedral("(%s & name N)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name C)"%frag_name, "(%s & name O)"%frag_name) cmd.protect("(%s & name O)"%frag_name) cmd.set_dihedral("(%s & name N)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name C)"%frag_name, "(%s & name OXT)"%frag_name,180.0+angle) cmd.deprotect(frag_name) # fix the hydrogen position (if any) if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1: if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1: cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele, "stored.list=[x,y,z]") cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name, "(x,y,z)=stored.list") elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1: # position hydro based on location of the carbonyl angle = cmd.get_dihedral("(%s & name C)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name N)"%frag_name, tmp_sele1) cmd.set_dihedral("(%s & name C)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name N)"%frag_name, "(%s & name H)"%frag_name,180.0+angle) cmd.delete(tmp_sele1) # add c-cap (if appropriate) if self.c_cap in [ 'amin', 'nmet' ]: if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"% (src_sele,src_sele)): if cmd.count_atoms("name C & (%s)"%(frag_name))==1: if self.c_cap == 'amin': editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh') elif self.c_cap == 'nmet': editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme') if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name): cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") # add n-cap (if appropriate) if self.n_cap in [ 'acet' ]: if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "% (src_sele,src_sele)): if cmd.count_atoms("name N & (%s)"%(frag_name))==1: if self.n_cap == 'acet': editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace') if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name): cmd.h_fix("name N & (%s)"%frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0) sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0) cmd.delete(obj_name) key = rot_type lib = None if self.dep == 'dep': try: result = cmd.phi_psi("%s"%src_sele) if len(result)==1: (phi,psi) = list(result.values())[0] (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10)))) key = (rot_type,phi,psi) if key not in self.dep_library: (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20)))) key = (rot_type,phi,psi) if key not in self.dep_library: (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60)))) key = (rot_type,phi,psi) lib = self.dep_library.get(key,None) except: pass if lib == None: key = rot_type lib = self.ind_library.get(key,None) if (lib!= None) and self.dep == 'dep': print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.') if lib != None: state = 1 for a in lib: cmd.create(obj_name,frag_name,1,state) if state == 1: cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) if rot_type=='PRO': cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele) for b in a.keys(): if b!='FREQ': cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]), "(%s & n;%s)"%(mut_sele,b[1]), "(%s & n;%s)"%(mut_sele,b[2]), "(%s & n;%s)"%(mut_sele,b[3]), a[b],state=state) else: cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100)) if rot_type=='PRO': cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele) state = state + 1 cmd.delete(frag_name) print(" Mutagenesis: %d rotamers loaded."%len(lib)) if self.bump_check: cmd.delete(bump_name) cmd.create(bump_name, "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"% (src_sele,mut_sele,src_sele,mut_sele),singletons=1) cmd.color("gray50",bump_name+" and elem C") cmd.set("seq_view",0,bump_name,quiet=1) cmd.hide("everything",bump_name) if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"% (bump_name,src_sele)) == 1) and (cmd.select(tmp_sele2, "(name C & (%s in %s))"% (bump_name,mut_sele)) == 1)): cmd.bond(tmp_sele1,tmp_sele2) if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"% (bump_name,src_sele)) == 1) and (cmd.select(tmp_sele2,"(name N & (%s in %s))"% (bump_name,mut_sele)) == 1)): cmd.bond(tmp_sele1,tmp_sele2) cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"% (bump_name,bump_name,mut_sele)) cmd.sculpt_activate(bump_name) cmd.show("cgo",bump_name) # draw the bumps cmd.set("sculpt_vdw_vis_mode",1,bump_name) state = 1 score_best = 1e6 for a in lib: score = cmd.sculpt_iterate(bump_name, state, 1) self.bump_scores.append(score) if score < score_best: state_best = state score_best = score state = state + 1 cmd.delete(mut_sele) else: cmd.create(obj_name,frag_name,1,1) print(" Mutagenesis: no rotamers found in library.") cmd.set("seq_view",0,obj_name,quiet=1) pymol.util.cbaw(obj_name) cmd.hide("("+obj_name+")") cmd.show(self.rep,obj_name) cmd.show('lines',obj_name) #neighbor always show lines if cartoon: cmd.show("cartoon",obj_name) if sticks: cmd.show("sticks",obj_name) cmd.set('auto_zoom',auto_zoom,quiet=1) cmd.delete(frag_name) cmd.frame(state_best) cmd.unpick() cmd.feedback("pop")
def optAlign( sel1, sel2 ): """ optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections. Example: optAlign MOL1 and i. 20-40, MOL2 and i. 102-122 Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMol based upon your selections. By default, this program will optimally align the ALPHA CARBONS of the selections provided. To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below. @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ cmd.reset() # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # -- CUT HERE sel1 += " and N. CA" sel2 += " and N. CA" # -- CUT HERE # Get the selected coordinates. We # align these coords. cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # get molecule name mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] # Get all molecule coords. We do this because # we have to rotate the whole molcule, not just # the aligned selection cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") # check for consistency assert len(stored.sel1) == len(stored.sel2) L = len(stored.sel1) assert L > 0 # must alway center the two proteins to avoid # affine transformations. Center the two proteins # to their selections. COM1 = numpy.sum(stored.sel1,axis=0) / float(L) COM2 = numpy.sum(stored.sel2,axis=0) / float(L) stored.sel1 -= COM1 stored.sel2 -= COM2 # Initial residual, see Kabsch. E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0) # # This beautiful step provides the answer. V and Wt are the orthonormal # bases that when multiplied by each other give us the rotation matrix, U. # S, (Sigma, from SVD) provides us with the error! Isn't SVD great! V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1)) # we already have our solution, in the results from SVD. # we just need to check for reflections and then produce # the rotation. V and Wt are orthonormal, so their det's # are +/-1. reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt)))) if reflect == -1.0: S[-1] = -S[-1] V[:,-1] = -V[:,-1] RMSD = E0 - (2.0 * sum(S)) RMSD = numpy.sqrt(abs(RMSD / L)) #U is simply V*Wt U = numpy.dot(V, Wt) # rotate and translate the molecule stored.sel2 = numpy.dot((stored.mol2 - COM2), U) stored.sel2 = stored.sel2.tolist() # center the molecule stored.sel1 = stored.mol1 - COM1 stored.sel1 = stored.sel1.tolist() # let PyMol know about the changes to the coordinates cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)") cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)") print "RMSD=%f" % RMSD # make the alignment OBVIOUS cmd.hide('everything') cmd.show('ribbon', sel1 + ' or ' + sel2) cmd.color('gray70', mol1 ) cmd.color('paleyellow', mol2 ) cmd.color('red', 'visible') cmd.show('ribbon', 'not visible') cmd.center('visible') cmd.orient() cmd.zoom('visible')
def simpAlign( mat1, mat2, name1, name2, mol1=None, mol2=None, align=0, L=0 ): """ optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections. Example: optAlign MOL1 and i. 20-40, MOL2 and i. 102-122 Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMol based upon your selections. By default, this program will optimally align the ALPHA CARBONS of the selections provided. To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below. @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ # check for consistency assert(len(mat1) == len(mat2)) # must alway center the two proteins to avoid # affine transformations. Center the two proteins # to their selections. COM1 = numpy.sum(mat1,axis=0) / float(L) COM2 = numpy.sum(mat2,axis=0) / float(L) mat1 = mat1 - COM1 mat2 = mat2 - COM2 # Initial residual, see Kabsch. E0 = numpy.sum( numpy.sum(mat1 * mat1,axis=0),axis=0) + numpy.sum( numpy.sum(mat2 * mat2,axis=0),axis=0) # # This beautiful step provides the answer. V and Wt are the orthonormal # bases that when multiplied by each other give us the rotation matrix, U. # S, (Sigma, from SVD) provides us with the error! Isn't SVD great! V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(mat2), mat1)) # we already have our solution, in the results from SVD. # we just need to check for reflections and then produce # the rotation. V and Wt are orthonormal, so their det's # are +/-1. reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt)))) if reflect == -1.0: S[-1] = -S[-1] V[:,-1] = -V[:,-1] RMSD = E0 - (2.0 * sum(S)) RMSD = numpy.sqrt(abs(RMSD / L)) if ( align == 0 ): return RMSD; assert(mol1 != None) assert(mol2 != None) #U is simply V*Wt U = numpy.dot(V, Wt) # rotate and translate the molecule mat2 = numpy.dot((mol2 - COM2), U) + COM1 stored.sel2 = mat2.tolist() # let PyMol know about the changes to the coordinates cmd.alter_state(1,name2,"(x,y,z)=stored.sel2.pop(0)") print "NumAligned=%d" % L print "RMSD=%f" % RMSD
def affineStretch(selection, stretch): # stretch molecule using affine transformations stored.altered = [] cmd.iterate_state(1, selector.process(selection), f"stored.altered.append([x,{stretch}*y,z])") cmd.alter_state(1, selection, "(x,y,z) = stored.altered.pop(0)")
# Load frames cmd.set('all_states', 0) print "Loading frames..." for iteration in range(niterations): # Set coordinates print "iteration %8d / %8d" % (iteration, niterations) positions = (10.0 * ncfile.variables['positions'][iteration, replica, :, :]).squeeze() positions[:,:] = positions[pdb_mapping,:] xyz = positions.tolist() xyz_iter = iter(xyz) #cmd.load_model(model, 'complex', state=iteration+1) #cmd.frame(iteration+1) #model = cmd.get_model('complex', state=1) #cmd.load_model(model, 'complex', state=iteration+1) cmd.create('complex', 'complex', 1, iteration+1) cmd.alter_state(iteration+1, 'complex', '(x,y,z) = xyz_iter.next()', space=locals()) #for pdb_index in range(natoms): #if (pdb_index % 100)==0: print pdb_index #model_index = model_mapping[pdb_index] #model.atom[model_index].coord = (10 * ncfile.variables['positions'][iteration, replica, pdb_index, :]).squeeze().tolist() #for k in range(3): # model.atom[model_index].coord[k] = float(ncfile.variables['positions'][iteration, replica, pdb_index, k]) * 10.0 # convert to angstroms #cmd.load_model(model, 'complex', state=iteration+1) #cmd.load_model(model, 'complex') print "done" # Align all states cmd.intra_fit('all')
def updateColor(self): selection = 'all' stored.atoms_charge = [] stored.atoms_colors = [] cmd.map_new('chargyc_map', selection="(all)") if not self.colorNeutral: tkMessageBox.showerror("Error", "Set Neutral Color, Please") return if not self.colorNegative: tkMessageBox.showerror("Error", "Set Negative Color, Please") return if not self.colorPositive: tkMessageBox.showerror("Error", "Set Positive Color, Please") return cmd.iterate_state(1, '(' + selection + ')', 'stored.atoms_charge.append(partial_charge)') _i = 0 minValue = None maxValue = None while _i < len(stored.atoms_charge): color = [] if _i == 0: maxValue = stored.atoms_charge[_i] minValue = stored.atoms_charge[_i] if(stored.atoms_charge[_i] > maxValue): maxValue = stored.atoms_charge[_i] if stored.atoms_charge[_i] < minValue: minValue = stored.atoms_charge[_i] _i += 1 self.minNegativeLbl["text"] = 'Min Found: ' + str(round(minValue, 3)) self.maxPositiveLbl["text"] = 'Max Found: ' + str(round(maxValue, 3)) if(self.scaleNegative == 0.0 and self.scalePositive == 0.0): self.scaleNegative = round(minValue, 3) self.scalePositive = round(maxValue, 3) self.sclSelectNegative.delete(0, "end") self.sclSelectPositive.delete(0, "end") self.sclSelectNegative.insert(0, round(minValue, 3)) self.sclSelectPositive.insert(0, round(maxValue, 3)) else: self.scaleNegative = float(self.sclSelectNegative.get()) self.scalePositive = float(self.sclSelectPositive.get()) minValue = float(self.sclSelectNegative.get()) maxValue = float(self.sclSelectPositive.get()) self.scaleLbl["text"] = 'Scale: ' + str( self.scaleNegative) + ' to ' + str(self.scalePositive) middleValue = 0 if(maxValue < 0): maxValue = 0 if(minValue > 0): minValue = 0 _i = 0 while _i < len(stored.atoms_charge): color = [] cmd.set_color("neutral_color", self.colorNeutral[0]) cmd.set_color("positive_color", self.colorPositive[0]) cmd.set_color("negative_color", self.colorNegative[0]) if(stored.atoms_charge[_i] >= middleValue): if(stored.atoms_charge[_i] == middleValue): cmd.set_color(str(_i) + "_color", self.colorNeutral[0]) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorPositive[0], maxValue, stored.atoms_charge[_i] if stored.atoms_charge[_i] < maxValue else maxValue)) else: cmd.set_color(str(_i) + "_color", self.getColor( self.colorNeutral[0], self.colorNegative[0], abs(minValue), abs(stored.atoms_charge[_i]) if abs(stored.atoms_charge[_i]) < abs(minValue) else abs(minValue))) index = cmd.get_color_index(str(_i) + "_color") stored.atoms_colors.append(index) _i += 1 cmd.alter_state(1, '(' + selection + ')', "color=stored.atoms_colors.pop(0)") cmd.ramp_new('chargy_ramp', 'chargyc_map', range=[self.scaleNegative, ((self.scaleNegative+self.scalePositive)/2.0), self.scalePositive], color=['negative_color', 'neutral_color', 'positive_color'])
def eigenfacs_iter(mode): x = modes[mode-1].array return iter(x.take(z, 0)) for mode in range(first, min(last, len(modes)) + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print ' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1]) for state in range(1, states+1): cmd.create(name, selection, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(myit.next(), myfac))', space={'cpv': cpv, 'myit': eigenfacs_iter(mode), 'myfac': 1e2 * factor * ((state-1.0)/(states-1.0) - 0.5)}) cmd.delete(selection) if model == 'calpha': cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*') def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy.
def optAlignRNA( sel1, sel2 ): """ optAlignRNA performs the Kabsch alignment algorithm upon the C1' carbons of two selections. Example: optAlignRNA 1JU7 and i. 1-16 and n. C1', 1CLL and i. 4-146 and n. C1' Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMOL based upon your selections. This function can be run in a for loop to fit multiple structures with a common prefix name: for x in cmd.get_names(): optAlignRNA(x, "1JU7_0001") or get the rmsds for all combinations, do the following: [[optAlignRNA(x, y) for x in cmd.get_names()] for y in cmd.get_names()] """ cmd.reset() # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # -- CUT HERE sel1 += " and N. C1'" sel2 += " and N. C1'" # -- CUT HERE # Get the selected coordinates. We # align these coords. cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # get molecule name mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] # Get all molecule coords. We do this because # we have to rotate the whole molcule, not just # the aligned selection cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") # check for consistency assert len(stored.sel1) == len(stored.sel2) L = len(stored.sel1) assert L > 0 # must alway center the two proteins to avoid # affine transformations. Center the two proteins # to their selections. COM1 = numpy.sum(stored.sel1,axis=0) / float(L) COM2 = numpy.sum(stored.sel2,axis=0) / float(L) stored.sel1 -= COM1 stored.sel2 -= COM2 # Initial residual, see Kabsch. E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0) # # This beautiful step provides the answer. V and Wt are the orthonormal # bases that when multiplied by each other give us the rotation matrix, U. # S, (Sigma, from SVD) provides us with the error! Isn't SVD great! V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1)) # we already have our solution, in the results from SVD. # we just need to check for reflections and then produce # the rotation. V and Wt are orthonormal, so their det's # are +/-1. reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt)))) if reflect == -1.0: S[-1] = -S[-1] V[:,-1] = -V[:,-1] RMSD = E0 - (2.0 * sum(S)) RMSD = numpy.sqrt(abs(RMSD / L)) #U is simply V*Wt U = numpy.dot(V, Wt) # rotate and translate the molecule stored.sel2 = numpy.dot((stored.mol2 - COM2), U) stored.sel2 = stored.sel2.tolist() # center the molecule stored.sel1 = stored.mol1 - COM1 stored.sel1 = stored.sel1.tolist() # let PyMol know about the changes to the coordinates cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)") cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)") #print("Moved: %s Reference: %s RMSD = %f" % mol1, mol2, RMSD) print("% s, % s,% 5.3f" % (mol1, mol2, RMSD)) # make the alignment OBVIOUS cmd.hide("everything") cmd.show("ribbon", sel1 + " or " + sel2) cmd.color("gray70", mol1 ) cmd.color("magenta", mol2 ) cmd.color("red", "visible") cmd.show("ribbon", "not visible") cmd.center("visible") cmd.orient() cmd.zoom("visible")
def _normalmodes(selection, cutoff, force, mass, first, last, choose, substruct, blocksize, exe, diag_exe, prefix, states, factor, clean, quiet, wiz=None): import tempfile, subprocess, os, shutil, sys from chempy import cpv cutoff, force = float(cutoff), float(force) first, last, blocksize = int(first), int(last), int(blocksize) clean, quiet = int(clean), int(quiet) exe = cmd.exp_path(exe) diag_exe = cmd.exp_path(diag_exe) tempdir = tempfile.mkdtemp() if not quiet: print ' normalmodes: Temporary directory is', tempdir try: sele_name = cmd.get_unused_name('__pdbmat') except AttributeError: sele_name = '__pdbmat' try: filename = os.path.join(tempdir, 'mobile.pdb') commandfile = os.path.join(tempdir, 'pdbmat.dat') cmd.select(sele_name, '(%s) and not hetatm' % (selection)) cmd.save(filename, sele_name) f = open(commandfile, 'w') f.write('''! pdbmat file Coordinate FILENAME = %s MATRIx FILENAME = matrix.sdijb INTERACtion DISTance CUTOF = %.3f INTERACtion FORCE CONStant = %.3f Origin of MASS values = %s Output PRINTing level = 0 MATRix FORMat = BINA ''' % (filename, cutoff, force, mass.upper())) f.close() if not quiet: print ' normalmodes: running', exe, '...' if wiz is not None: wiz.message[1] = 'running pdbmat' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) natoms = len(open(os.path.join(tempdir, 'pdbmat.xyzm')).readlines()) if natoms != cmd.count_atoms(sele_name): print 'Error: pdbmat did not recognize all atoms' raise CmdException commandfile = os.path.join(tempdir, 'diagrtb.dat') f = open(commandfile, 'w') f.write('''! diagrtb file MATRIx FILENAME = matrix.sdijb COORdinates filename = pdbmat.xyzm Eigenvector OUTPut filename= diagrtb.eigenfacs Nb of VECTors required = %d EigeNVALues chosen = %s Type of SUBStructuring = %s Nb of residues per BLOck = %d Origin of MASS values = %s Temporary files cleaning = ALL MATRix FORMat = BINA Output PRINting level = 0 ''' % (last, choose.upper(), substruct.upper(), blocksize, mass.upper())) f.close() exe = diag_exe if not quiet: print ' normalmodes: running', exe, '...' if wiz is not None: wiz.message[1] = 'running diagrtb' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) eigenfacs, frequencies = parse_eigenfacs( os.path.join(tempdir, 'diagrtb.eigenfacs'), last) if wiz is not None: wiz.message[1] = 'generating objects' cmd.refresh_wizard() states = int(states) factor = float(factor) if factor < 0: factor = natoms**0.5 for mode in range(first, last+1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print ' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1]) for state in range(1, states+1): cmd.create(name, sele_name, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(myit.next(), myfac))', space={'cpv': cpv, 'myit': iter(eigenfacs[mode-1]), 'myfac': factor * (state - (states+1)/2.0)}) # if CA only selection, show ribbon trace if natoms == cmd.count_atoms('(%s) and name CA' % sele_name): cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') # store results if not hasattr(stored, 'nma_results'): stored.nma_results = [] stored.nma_results.append({ 'facs': eigenfacs, 'freq': frequencies, 'sele': sele_name, }) except OSError: print 'Cannot execute "%s", please provide full path to executable' % (exe) except CmdException, e: print ' normalmodes: failed!', e
def display_graphpool(pdb_id, pdb_path): ''' ''' # Load PDB cmd.bg_color('white') cmd.load(pdb_path + pdb_id[:-2] + '.pdb') cmd.split_chains(pdb_id[:-2]) for name in cmd.get_names('objects', 0, '(all)'): if not name.endswith(pdb_id[-1].upper()) and name.startswith( pdb_id[:4]): cmd.delete(name) else: zero_residues(name) cmd.reset() pdb_id2 = pdb_id + 'copy' cmd.create(pdb_id2, pdb_id) cmd.color('grey', pdb_id) cmd.hide('everything', pdb_id) cmd.show_as('lines', pdb_id + ' and (name ca)') cmd.set('line_width', 5) cmd.set_bond('line_width', 5, pdb_id + ' and (name ca)') cmd.show('spheres', pdb_id + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id + ' and name ca') data = cmd.get_coords(selection=pdb_id + ' and name ca', state=1) data_ = [] cmd.set('dash_color', 'marine') cmd.set('dash_width', 1.0) j = 55 for i in range(len(data)): if i % 2 == 0 and i + 1 < len(data): data[i] = np.mean(data[i:i + 2], axis=0) data[i + 1] = np.array([10000, 10000, 10000]) #cmd.distance('d'+str(i)+str(j), pdb_id + ' and name ca and res ' + str(i), pdb_id + ' and name ca and res ' + str(j)) #cmd.hide('labels', 'd'+str(i)+str(j)) cmd.color('red', pdb_id2) cmd.hide('everything', pdb_id2) cmd.show_as('lines', pdb_id2 + ' and (name ca)') cmd.set('line_width', 5) cmd.set_bond('line_width', 5, pdb_id2 + ' and (name ca)') cmd.show('spheres', pdb_id2 + ' and name ca') cmd.set('sphere_transparency', 0.0, pdb_id2 + ' and name ca') cmd.set('sphere_scale', 0.5, pdb_id2 + ' and name ca') for i in range(len(data)): if i % 2 == 0 and i + 1 < len(data): cmd.alter_state(1, pdb_id2 + ' and name ca and res ' + str(i), '(x,y,z)=' + str(tuple(data[i]))) else: cmd.hide('spheres', pdb_id2 + ' and name ca and res ' + str(i)) pdb_id3 = pdb_id + 'copy2' cmd.create(pdb_id3, pdb_id2) cmd.color('red', pdb_id3) cmd.hide('everything', pdb_id3) cmd.show_as('lines', pdb_id3 + ' and (name ca)') cmd.set('line_width', 5) cmd.set_bond('line_width', 5, pdb_id3 + ' and (name ca)') cmd.show('spheres', pdb_id3 + ' and name ca') cmd.set('sphere_transparency', 0.8, pdb_id3 + ' and name ca') for i in range(len(data)): if i % 2 == 0 and i + 1 < len(data): cmd.set('sphere_scale', np.random.uniform(1.0, 4.5), pdb_id3 + ' and name ca and res ' + str(i)) else: cmd.hide('spheres', pdb_id2 + ' and name ca and res ' + str(i))
def _normalmodes(selection, cutoff, force, mass, first, last, choose, substruct, blocksize, exe, diag_exe, prefix, states, factor, clean, quiet, wiz=None): import tempfile, subprocess, os, shutil, sys from chempy import cpv cutoff, force = float(cutoff), float(force) first, last, blocksize = int(first), int(last), int(blocksize) clean, quiet = int(clean), int(quiet) exe = cmd.exp_path(exe) diag_exe = cmd.exp_path(diag_exe) tempdir = tempfile.mkdtemp() if not quiet: print(' normalmodes: Temporary directory is', tempdir) try: sele_name = cmd.get_unused_name('__pdbmat') except AttributeError: sele_name = '__pdbmat' try: filename = os.path.join(tempdir, 'mobile.pdb') commandfile = os.path.join(tempdir, 'pdbmat.dat') cmd.select(sele_name, '(%s) and not hetatm' % (selection)) cmd.save(filename, sele_name) f = open(commandfile, 'w') f.write('''! pdbmat file Coordinate FILENAME = %s MATRIx FILENAME = matrix.sdijb INTERACtion DISTance CUTOF = %.3f INTERACtion FORCE CONStant = %.3f Origin of MASS values = %s Output PRINTing level = 0 MATRix FORMat = BINA ''' % (filename, cutoff, force, mass.upper())) f.close() if not quiet: print(' normalmodes: running', exe, '...') if wiz is not None: wiz.message[1] = 'running pdbmat' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, universal_newlines=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) try: natoms = len( open(os.path.join(tempdir, 'pdbmat.xyzm')).readlines()) except Exception as e: print(e) natoms = cmd.count_atoms(sele_name) if natoms != cmd.count_atoms(sele_name): print('Error: pdbmat did not recognize all atoms') raise CmdException commandfile = os.path.join(tempdir, 'diagrtb.dat') f = open(commandfile, 'w') f.write('''! diagrtb file MATRIx FILENAME = matrix.sdijb COORdinates filename = %s Eigenvector OUTPut filename= diagrtb.eigenfacs Nb of VECTors required = %d EigeNVALues chosen = %s Type of SUBStructuring = %s Nb of residues per BLOck = %d Origin of MASS values = %s Temporary files cleaning = ALL MATRix FORMat = BINA Output PRINting level = 0 ''' % (filename, last, choose.upper(), substruct.upper(), blocksize, mass.upper())) f.close() exe = diag_exe if not quiet: print(' normalmodes: running', exe, '...') if wiz is not None: wiz.message[1] = 'running diagrtb' cmd.refresh_wizard() process = subprocess.Popen([exe], cwd=tempdir, universal_newlines=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) for line in process.stdout: if not quiet: sys.stdout.write(line) eigenfacs, frequencies = parse_eigenfacs( os.path.join(tempdir, 'diagrtb.eigenfacs'), last) if wiz is not None: wiz.message[1] = 'generating objects' cmd.refresh_wizard() states = int(states) factor = float(factor) if factor < 0: factor = natoms**0.5 for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1])) for state in range(1, states + 1): cmd.create(name, sele_name, 1, state, zoom=0) cmd.alter_state( state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(next(myit), myfac))', space={ 'cpv': cpv, 'myit': iter(eigenfacs[mode - 1]), 'next': next, 'myfac': factor * (state - (states + 1) / 2.0) }) # if CA only selection, show ribbon trace if natoms == cmd.count_atoms('(%s) and name CA' % sele_name): cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') # store results if not hasattr(stored, 'nma_results'): stored.nma_results = [] stored.nma_results.append({ 'facs': eigenfacs, 'freq': frequencies, 'sele': sele_name, }) except OSError: print('Cannot execute "%s", please provide full path to executable' % (exe)) except CmdException as e: print(' normalmodes: failed!', e) finally: if clean: shutil.rmtree(tempdir) elif not quiet: print(' normalmodes: Working directory "%s" not removed!' % (tempdir)) # cmd.delete(sele_name) if wiz is not None: cmd.set_wizard_stack( [w for w in cmd.get_wizard_stack() if w != wiz])
for mode in range(first, min(last, len(modes)) + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1])) for state in range(1, states + 1): cmd.create(name, selection, 1, state, zoom=0) cmd.alter_state( state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(myit.next(), myfac))', space={ 'cpv': cpv, 'myit': eigenfacs_iter(mode), 'myfac': 1e2 * factor * ((state - 1.0) / (states - 1.0) - 0.5) }) cmd.delete(selection) if model == 'calpha': cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*') def normalmodes_prody(selection, cutoff=15,
def normalmodes_mmtk(selection, cutoff=12.0, ff='Deformation', first=7, last=10, prefix='mmtk', states=7, factor=-1, quiet=1): ''' DESCRIPTION Fast normal modes for large proteins using an elastic network model (CA only) Based on: http://dirac.cnrs-orleans.fr/MMTK/using-mmtk/mmtk-example-scripts/normal-modes/ ''' try: import MMTK except ImportError: print('Failed to import MMTK, please add to PYTHONPATH') raise CmdException selection = selector.process(selection) cutoff = float(cutoff) first, last = int(first), int(last) states, factor, quiet = int(states), float(factor), int(quiet) from math import log from chempy import cpv from MMTK import InfiniteUniverse from MMTK.PDB import PDBConfiguration from MMTK.Proteins import Protein from MMTK.NormalModes import NormalModes from MMTK.ForceFields import DeformationForceField, CalphaForceField from MMTK.FourierBasis import FourierBasis, estimateCutoff from MMTK.NormalModes import NormalModes, SubspaceNormalModes model = 'calpha' ff = ff.lower() if 'deformationforcefield'.startswith(ff): forcefield = DeformationForceField(cutoff=cutoff / 10.) elif 'calphaforcefield'.startswith(ff): forcefield = CalphaForceField(cutoff=cutoff / 10.) elif 'amber94forcefield'.startswith(ff): from MMTK.ForceFields import Amber94ForceField forcefield = Amber94ForceField() model = 'all' else: raise NotImplementedError('unknown ff = ' + str(ff)) if not quiet: print(' Forcefield:', forcefield.__class__.__name__) if model == 'calpha': selection = '(%s) and polymer and name CA' % (selection) f = StringIO(cmd.get_pdbstr(selection)) conf = PDBConfiguration(f) items = conf.createPeptideChains(model) universe = InfiniteUniverse(forcefield) universe.protein = Protein(*items) nbasis = max(10, universe.numberOfAtoms() / 5) cutoff, nbasis = estimateCutoff(universe, nbasis) if not quiet: print(" Calculating %d low-frequency modes." % nbasis) if cutoff is None: modes = NormalModes(universe) else: subspace = FourierBasis(universe, cutoff) modes = SubspaceNormalModes(universe, subspace) natoms = modes.array.shape[1] frequencies = modes.frequencies if factor < 0: factor = log(natoms) if not quiet: print(' set factor to %.2f' % (factor)) if True: # cmd.count_atoms(selection) != natoms: import tempfile, os from MMTK import DCD filename = tempfile.mktemp(suffix='.pdb') sequence = DCD.writePDB(universe, None, filename) z = [a.index for a in sequence] selection = cmd.get_unused_name('_') cmd.load(filename, selection, zoom=0) os.remove(filename) if cmd.count_atoms(selection) != natoms: print('hmm... still wrong number of atoms') def eigenfacs_iter(mode): x = modes[mode - 1].array return iter(x.take(z, 0)) for mode in range(first, min(last, len(modes)) + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d with freq. %.6f' % \ (name, mode, frequencies[mode-1])) for state in range(1, states + 1): cmd.create(name, selection, 1, state, zoom=0) cmd.alter_state( state, name, '(x,y,z) = cpv.add([x,y,z], cpv.scale(next(myit), myfac))', space={ 'cpv': cpv, 'myit': eigenfacs_iter(mode), 'next': next, 'myfac': 1e2 * factor * ((state - 1.0) / (states - 1.0) - 0.5) }) cmd.delete(selection) if model == 'calpha': cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def symset(prefix="sym", object=-1, x=0, y=0, z=0, opList=[]): if object == -1: object = cmd.get_names()[0] cell = [float(x), float(y), float(z)] view = cmd.get_view() cmd.show("lines", object) sgInfo = cmd.get_symmetry(object) raw_ops = [] for s in sgtbx.space_group_info(sgInfo[6]).group(): raw_ops.append(str(s)) if len(opList) == 0: for i in range(len(raw_ops)): opList.append(i) opMatrices = [] vars = ["x", "y", "z"] #CREATE 4X4 MATRICES FOR SYMMETRY OPERATORS for i, raw_op in enumerate(raw_ops): ops = raw_op.split(",") matrix = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]] for j in range(len(ops)): for k in range(len(vars)): index = ops[j].find(vars[k]) if index != -1: if index == 0: matrix[k][j] = 1 elif ops[j][index - 1] == "-": matrix[k][j] = -1 else: matrix[k][j] = 1 index = ops[j].find("/") if index != -1: matrix[3][j] = float(ops[j][index - 1]) / float( ops[j][index + 1]) opMatrices.append(matrix) a, b, c, alpha, beta, gamma = sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) fracToOrt = N.array([[a, b * cg, c * cb, 0.0], [0.0, b * sg, c * (ca - cb * cg) / sg, 0.0], [ 0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2), 0.0 ], [0.0, 0.0, 0.0, 1.0]]) fracToOrt = fracToOrt.transpose() ortToFrac = inv(fracToOrt) stored.atoms = [] cmd.iterate_state(1, object, "stored.atoms.append([x,y,z,1])") stored.atoms = N.array(stored.atoms) fracCoords = N.dot(stored.atoms, ortToFrac) for i in opList: try: op = opMatrices[i] except: print("Bad symmetry partner numbers. Try again.") quit() copy = "%s%02d_%d_%d_%d" % (prefix, i, x, y, z) cmd.copy(copy, object) newCoordsFrac = N.dot(fracCoords, op) stored.newCoords = N.dot(newCoordsFrac, fracToOrt) stored.j = 0 cmd.alter_state( 1, copy, "x,y,z = stored.newCoords[stored.j][0], stored.newCoords[stored.j][1], stored.newCoords[stored.j][2]; stored.j = stored.j + 1" ) xSum = ySum = zSum = 0.0 for a, b, c in newCoordsFrac: xSum += a ySum += b zSum += c center = N.array([xSum, ySum, zSum]) center = center / len(stored.newCoords) shift = [ cell[0] - math.floor(center[0]), cell[1] - math.floor(center[1]), cell[2] - math.floor(center[2]) ] cell_shift(copy, shift[0], shift[1], shift[2], 0) ''' #COPIES COORDINATES OF EACH ATOM TO CORRESPONDING ONE IN GIVEN SYMMETRY PARTNER #cmd.alter_state(1, copy, "x,y,z = cmd.sym_partner([x,y,z], stored.tmpOp)") #MOVES SYMMETRY PARTNER TO PROPER LATTICE COORDINATES AND CORRECTS FOR NATIVE LATTICE POSITION ERROR #stored.xSum,stored.ySum,stored.zSum = 0.0,0.0,0.0 #atoms = cmd.count_atoms(copy) #cmd.iterate_state(1, copy, "stored.xSum = stored.xSum + x; stored.ySum = stored.ySum + y; stored.zSum = stored.zSum + z") #xMean = stored.xSum / atoms #yMean = stored.ySum / atoms #zMean = stored.zSum / atoms #xError, yError, zError = N.dot(N.array([xMean,yMean,zMean]), stored.ortToFrac) #dX,dY,dZ = cell[0]-math.floor(xError), cell[1]-math.floor(yError), cell[2]-math.floor(zError) #cell_shift(copy,dX,dY,dZ, 0) ''' cmd.hide("everything", object) cmd.set_view(view)
def do_library(self): cmd=self.cmd pymol=cmd._pymol if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and (cmd.count_atoms("(%s) and name C"%src_sele)==1) and (cmd.count_atoms("(%s) and name O"%src_sele)==1)): self.clear() return 1 cmd.feedback("push") cmd.feedback("disable","selector","everythin") cmd.feedback("disable","editor","actions") self.prompt = [ 'Loading rotamers...'] self.bump_scores = [] state_best = 0 pymol.stored.name = 'residue' cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi') self.res_text = pymol.stored.name cmd.select("_seeker_hilight",src_sele) auto_zoom = cmd.get_setting_text('auto_zoom') cmd.set('auto_zoom',"0",quiet=1) cmd.frame(0) cmd.delete(frag_name) if self.auto_center: cmd.center(src_sele,animate=-1) self.lib_mode = self.mode if self.lib_mode=="current": pymol.stored.resn="" cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn") rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn) if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'): self.lib_mode = rot_type # force fragment-based load else: cmd.create(frag_name,src_sele,1,1) if self.c_cap=='open': cmd.remove("%s and name OXT"%frag_name) if self.lib_mode!='current': rot_type = self.lib_mode frag_type = self.lib_mode if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'): if not ( cmd.count_atoms( "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"% (src_sele,src_sele))): # use N-terminal fragment frag_type ="NT_"+frag_type if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'): if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"% (src_sele,src_sele))): # use C-terminal fragment frag_type ="CT_"+frag_type if rot_type[0:3] in [ 'NT_', 'CT_' ]: rot_type = rot_type[3:] rot_type = _rot_type_xref.get(rot_type, rot_type) cmd.fragment(frag_type.lower(), frag_name, origin=0) # trim off hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") # copy identifying information cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space) cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space) # move the fragment if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and (cmd.count_atoms("(%s & name CB)"%src_sele)==1)): cmd.pair_fit("(%s & name CA)"%frag_name, "(%s & name CA)"%src_sele, "(%s & name CB)"%frag_name, "(%s & name CB)"%src_sele, "(%s & name C)"%frag_name, "(%s & name C)"%src_sele, "(%s & name N)"%frag_name, "(%s & name N)"%src_sele) else: cmd.pair_fit("(%s & name CA)"%frag_name, "(%s & name CA)"%src_sele, "(%s & name C)"%frag_name, "(%s & name C)"%src_sele, "(%s & name N)"%frag_name, "(%s & name N)"%src_sele) # fix the carbonyl position... cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]") cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list") if cmd.count_atoms("(%s & name OXT)"%src_sele): cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]") cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list") elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists angle = cmd.get_dihedral("(%s & name N)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name C)"%frag_name, "(%s & name O)"%frag_name) cmd.protect("(%s & name O)"%frag_name) cmd.set_dihedral("(%s & name N)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name C)"%frag_name, "(%s & name OXT)"%frag_name,180.0+angle) cmd.deprotect(frag_name) # fix the hydrogen position (if any) if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1: if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1: cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele, "stored.list=[x,y,z]") cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name, "(x,y,z)=stored.list") elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1: # position hydro based on location of the carbonyl angle = cmd.get_dihedral("(%s & name C)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name N)"%frag_name, tmp_sele1) cmd.set_dihedral("(%s & name C)"%frag_name, "(%s & name CA)"%frag_name, "(%s & name N)"%frag_name, "(%s & name H)"%frag_name,180.0+angle) cmd.delete(tmp_sele1) # add c-cap (if appropriate) if self.c_cap in [ 'amin', 'nmet' ]: if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"% (src_sele,src_sele)): if cmd.count_atoms("name C & (%s)"%(frag_name))==1: if self.c_cap == 'amin': editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh') elif self.c_cap == 'nmet': editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme') if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name): cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") # add n-cap (if appropriate) if self.n_cap in [ 'acet' ]: if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "% (src_sele,src_sele)): if cmd.count_atoms("name N & (%s)"%(frag_name))==1: if self.n_cap == 'acet': editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace') if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name): cmd.h_fix("name N & (%s)"%frag_name) # trim hydrogens if (self.hyd == 'none'): cmd.remove("("+frag_name+" and hydro)") elif (self.hyd == 'auto'): if cmd.count_atoms("("+src_sele+") and hydro")==0: cmd.remove("("+frag_name+" and hydro)") cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0) sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0) cmd.delete(obj_name) key = rot_type lib = None if self.dep == 'dep': try: result = cmd.phi_psi("%s"%src_sele) if len(result)==1: (phi,psi) = list(result.values())[0] (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10)))) key = (rot_type,phi,psi) if key not in self.dep_library: (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20)))) key = (rot_type,phi,psi) if key not in self.dep_library: (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60)))) key = (rot_type,phi,psi) lib = self.dep_library.get(key,None) except: pass if lib is None: key = rot_type lib = self.ind_library.get(key,None) if (lib is not None) and self.dep == 'dep': print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.') if lib is not None: state = 1 for a in lib: cmd.create(obj_name,frag_name,1,state) if state == 1: cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) if rot_type=='PRO': cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele) for b in a.keys(): if b!='FREQ': cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]), "(%s & n;%s)"%(mut_sele,b[1]), "(%s & n;%s)"%(mut_sele,b[2]), "(%s & n;%s)"%(mut_sele,b[3]), a[b],state=state) else: cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100)) if rot_type=='PRO': cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele) state = state + 1 cmd.delete(frag_name) print(" Mutagenesis: %d rotamers loaded."%len(lib)) if self.bump_check: cmd.delete(bump_name) cmd.create(bump_name, "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"% (src_sele,mut_sele,src_sele,mut_sele),singletons=1) cmd.color("gray50",bump_name+" and elem C") cmd.set("seq_view",0,bump_name,quiet=1) cmd.hide("everything",bump_name) if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"% (bump_name,src_sele)) == 1) and (cmd.select(tmp_sele2, "(name C & (%s in %s))"% (bump_name,mut_sele)) == 1)): cmd.bond(tmp_sele1,tmp_sele2) if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"% (bump_name,src_sele)) == 1) and (cmd.select(tmp_sele2,"(name N & (%s in %s))"% (bump_name,mut_sele)) == 1)): cmd.bond(tmp_sele1,tmp_sele2) cmd.delete(tmp_sele1) cmd.delete(tmp_sele2) cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"% (bump_name,bump_name,mut_sele)) cmd.sculpt_activate(bump_name) cmd.show("cgo",bump_name) # draw the bumps cmd.set("sculpt_vdw_vis_mode",1,bump_name) state = 1 score_best = 1e6 for a in lib: score = cmd.sculpt_iterate(bump_name, state, 1) self.bump_scores.append(score) if score < score_best: state_best = state score_best = score state = state + 1 cmd.delete(mut_sele) else: cmd.create(obj_name,frag_name,1,1) print(" Mutagenesis: no rotamers found in library.") cmd.set("seq_view",0,obj_name,quiet=1) pymol.util.cbaw(obj_name) cmd.hide("("+obj_name+")") cmd.show(self.rep,obj_name) cmd.show('lines',obj_name) #neighbor always show lines if cartoon: cmd.show("cartoon",obj_name) if sticks: cmd.show("sticks",obj_name) cmd.set('auto_zoom',auto_zoom,quiet=1) cmd.delete(frag_name) cmd.frame(state_best) cmd.unpick() cmd.feedback("pop")
from random import random, seed print "BEGIN-LOG" seed(123) print "the 1st random number should be %8.3f\notherwise the rest of the test is meaningless...\n" % pymol.random() pymol.random = random cmd.load("dat/pept.pdb", "ref") for a in xrange(1, 11): cmd.create("trg", "ref", 1, a, quiet=0) cmd.alter_state(a, "trg", "x=x+random()/2") cmd.alter_state(a, "trg", "y=y+random()/2") cmd.alter_state(a, "trg", "z=z+random()/2", quiet=0) cmd.frame(1) print "%8.3f" % cmd.fit("ref", "trg") # asdf for a in xrange(1, 14): print a, print "%8.3f" % cmd.fit("ref and resi %d" % a, "trg"), print "%8.3f" % cmd.rms("ref", "trg"), print "%8.3f" % cmd.rms_cur("ref", "trg")
def symset(prefix = "sym", object = -1, x=0,y=0,z=0, opList = []): if object == -1: object = cmd.get_names()[0] cell = [float(x),float(y),float(z)] view = cmd.get_view() cmd.show("lines", object) sgInfo = cmd.get_symmetry(object) raw_ops = [] for s in sgtbx.space_group_info(sgInfo[6]).group(): raw_ops.append(str(s)) if (len(opList) == 0): for i in range(len(raw_ops)): opList.append(i) opMatrices = [] vars = ["x","y","z"] i = 0 j = 0 k = 0 #CREATE 4X4 MATRICES FOR SYMMETRY OPERATORS for raw_op in raw_ops: ops = raw_op.split(",") matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] for j in range(len(ops)): for k in range(len(vars)): index = ops[j].find(vars[k]) if index != -1: if index == 0: matrix[k][j] = 1 elif ops[j][index - 1] == "-": matrix[k][j] = -1 else: matrix[k][j] = 1 index = ops[j].find("/") if index != -1: matrix[3][j] = float(ops[j][index - 1]) / float(ops[j][index + 1]) opMatrices.append(matrix) i=i+1 a,b,c,alpha,beta,gamma = sgInfo[0:6] ca = math.cos(math.radians(alpha)) cb = math.cos(math.radians(beta)) cg = math.cos(math.radians(gamma)) sb = math.sin(math.radians(beta)) sg = math.sin(math.radians(gamma)) fracToOrt = N.array([[a, b * cg, c * cb, 0.0], [0.0, b * sg, c * (ca - cb * cg) / sg, 0.0], [0.0, 0.0, c * sb * math.sqrt(1.0 - ((cb * cg - ca) / (sb * sg))**2), 0.0], [0.0,0.0,0.0,1.0]]) fracToOrt = fracToOrt.transpose() ortToFrac = inv(fracToOrt) stored.atoms = [] cmd.iterate_state(1,object,"stored.atoms.append([x,y,z,1])") stored.atoms = N.array(stored.atoms) fracCoords = N.dot(stored.atoms,ortToFrac) for i in opList: try: op = opMatrices[i] except: print "Bad symmetry partner numbers. Try again." quit() if i > 9: copy = prefix + str(i) + "_" + str(x) + "_" + str(y) + "_" + str(z) else: copy = prefix + "0" + str(i) + "_" + str(x) + "_" + str(y) + "_" + str(z) cmd.copy(copy, object) newCoordsFrac = N.dot(fracCoords, op) stored.newCoords = N.dot(newCoordsFrac, fracToOrt) stored.j = 0 cmd.alter_state(1,copy,"x,y,z = stored.newCoords[stored.j][0], stored.newCoords[stored.j][1], stored.newCoords[stored.j][2]; stored.j = stored.j + 1") xSum=ySum=zSum=0.0 for k in range(len(newCoordsFrac)): xSum = newCoordsFrac[k][0] + xSum ySum = newCoordsFrac[k][1] + ySum zSum = newCoordsFrac[k][2] + zSum center = N.array([xSum,ySum,zSum]) center = center/len(stored.newCoords) shift = [-math.floor(center[0]) + cell[0], -math.floor(center[1]) + cell[1], -math.floor(center[2]) + cell[2]] cell_shift(copy,shift[0],shift[1],shift[2],0) ''' #COPIES COORDINATES OF EACH ATOM TO CORRESPONDING ONE IN GIVEN SYMMETRY PARTNER #cmd.alter_state(1, copy, "x,y,z = cmd.sym_partner([x,y,z], stored.tmpOp)") #MOVES SYMMETRY PARTNER TO PROPER LATTICE COORDINATES AND CORRECTS FOR NATIVE LATTICE POSITION ERROR #stored.xSum,stored.ySum,stored.zSum = 0.0,0.0,0.0 #atoms = cmd.count_atoms(copy) #cmd.iterate_state(1, copy, "stored.xSum = stored.xSum + x; stored.ySum = stored.ySum + y; stored.zSum = stored.zSum + z") #xMean = (stored.xSum / atoms) #yMean = (stored.ySum / atoms) #zMean = (stored.zSum / atoms) #xError, yError, zError = N.dot(N.array([xMean,yMean,zMean]), stored.ortToFrac) #dX,dY,dZ = -math.floor(xError) + cell[0], -math.floor(yError) + cell[1], -math.floor(zError) + cell[2] #cell_shift(copy,dX,dY,dZ, 0) ''' cmd.hide("everything", object) cmd.set_view(view)
for iteration in range(niterations): # Set coordinates print "iteration %8d / %8d" % (iteration, niterations) positions = ( 10.0 * ncfile.variables['positions'][iteration, replica, :, :]).squeeze() positions = positions[pdb_mapping, :] xyz = positions.tolist() xyz_iter = iter(xyz) #cmd.load_model(model, 'complex', state=iteration+1) #cmd.frame(iteration+1) #model = cmd.get_model('complex', state=1) #cmd.load_model(model, 'complex', state=iteration+1) cmd.create('complex', 'complex', 1, iteration + 1) cmd.alter_state(iteration + 1, 'complex', '(x,y,z) = xyz_iter.next()', space=locals()) #for pdb_index in range(natoms): #if (pdb_index % 100)==0: print pdb_index #model_index = model_mapping[pdb_index] #model.atom[model_index].coord = (10 * ncfile.variables['positions'][iteration, replica, pdb_index, :]).squeeze().tolist() #for k in range(3): # model.atom[model_index].coord[k] = float(ncfile.variables['positions'][iteration, replica, pdb_index, k]) * 10.0 # convert to angstroms #cmd.load_model(model, 'complex', state=iteration+1) #cmd.load_model(model, 'complex') print "done" # Align all states cmd.intra_fit('all')
def optAlign( sel1, sel2 ): """ optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections. Example: optAlign MOL1 and i. 20-40, MOL2 and i. 102-122 Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA Two RMSDs are returned. One comes from the Kabsch algorithm and the other from PyMol based upon your selections. By default, this program will optimally align the ALPHA CARBONS of the selections provided. To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below. @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ cmd.reset() # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # now put the coordinates into a list # partials # -- REMOVE ALPHA CARBONS sel1 = sel1 + " and N. CA" sel2 = sel2 + " and N. CA" # -- REMOVE ALPHA CARBONS cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # full molecule mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") K = kabsch() U, T1, T2, RMSD, c1, c2 = K.align(stored.sel1, stored.sel2, []) stored.mol2 = map(lambda v:[T2[0]+((v[0]*U[0][0])+(v[1]*U[1][0])+(v[2]*U[2][0])),T2[1]+((v[0]*U[0][1])+(v[1]*U[1][1])+(v[2]*U[2][1])),T2[2]+((v[0]*U[0][2])+(v[1]*U[1][2])+(v[2]*U[2][2]))],stored.mol2) #stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1) stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1) cmd.alter_state(1,mol1,"(x,y,z)=stored.mol1.pop(0)") cmd.alter_state(1,mol2,"(x,y,z)=stored.mol2.pop(0)") cmd.alter( 'all',"segi=''") cmd.alter('all', "chain=''") print "RMSD=%f" % cmd.rms_cur(sel1, sel2) print "MY RMSD=%f" % RMSD cmd.hide('everything') cmd.show('ribbon', sel1 + ' or ' + sel2) cmd.color('gray70', mol1 ) cmd.color('paleyellow', mol2 ) cmd.color('red', 'visible') cmd.show('ribbon', 'not visible') cmd.center('visible') cmd.orient() cmd.zoom('visible')