def aver_dihe(selection, a1, a2, a3, a4): states=cmd.count_states(selection); dihedrals=list(); states=cmd.count_states(selection); for i in range(1,states+1, 1): dihedrals.append(dihe(selection, a1, a2, a3, a4, state=i)); print(dihedrals);
def load_alignment(filename, object1=None, object2=None, delimiter="_"): """DESCRIPTION Structural comparison tools from the PDB website can save aligned structures as a two-model structure. This function loads such a file and splits the structures into two pymol objects for easy comparison. USAGE load_alignment filename[, object1, object2][, delimiter] ARGUMENTS filename Path to the PDB file object1 What to name the first model from the file [optional] object2 What to name the second model from the file [optional] delimiter Delimiter which separates object1 and object2 in the filename. See DETAILS. [default '_'] DETAILS The input file must contain at least two states (MODEL lines in the PDB file). Additional states are ignored. If object1 and object2 are ommitted, the script will attempt to generate them based on the filename. The extension is first removed from the filename, then the name is split around the first instance of <delimiter>. Thus, alignment files which follow the convention "object1_object2.pdb" will be properly split without additional arguments. EXAMPLES # Results in objects '1AX8.A' and '3PIV.A' load_alignment 1AX8.A_3PIV.A.pdb # Results in objects 'query' and 'target' load_alignment alignment.pdb, query, target # Results in objects '1AX8.A' and '3PIV.A' load_alignment 1AX8.A_vs_3PIV.A.pdb, delimiter="_vs_" """ # load the file, which should generate a new object num_objects = len(cmd.get_names("objects")) cmd.load(filename) objects = cmd.get_names("objects") if len(objects) != num_objects + 1: # an error occured with loading print ("Error loading file") return obj = objects[-1] if cmd.count_states(obj) >= 2: # split the object split_alignment(obj, object1, object2, delimiter) # clean up cmd.delete(obj) else: print ("Error: Expected 2 models in %s, but found %d." % filename, cmd.count_states(obj)) return
def morph_movie(morph, view, color, base_name, frameno_offset=0, morph_reverse=False): number_of_states = cmd.count_states(morph) # after this I will have each state available as its own object, called "{morphname}_000x" (padded to length of 4) # x starts with 1 --> not clear - that might depend on the numbering in the input file cmd.split_states(morph) last_frame = frameno_offset for statenum in range(0, number_of_states + 1): if morph_reverse: statenum = max(1, cmd.count_states(morph) - statenum) else: statenum = min(statenum + 1, cmd.count_states(morph)) state_name = morph + "_" + str(statenum).zfill(4) clump_representation([state_name], color, state_name), cmd.set_view(view) cmd.png(base_name + str(last_frame).zfill(3), width=1920, height=1080, ray=True) clump_cleanup([state_name], state_name) cmd.remove(state_name) last_frame += 1 return last_frame
def testCreateTargetState(self): self.create_many_states("gly", "m1", 4) cmd.frame(3) cmd.create('m2', 'm1', 0, 0) self.assertEqual(cmd.count_states('m2'), 4) cmd.delete('m2') cmd.create('m2', 'm1', 1, 0) self.assertEqual(cmd.count_states('m2'), 1) cmd.delete('m2') cmd.create('m2', 'm1', 2, 0) self.assertEqual(cmd.count_states('m2'), 2) cmd.delete('m2') cmd.create('m2', 'm1', 0, 2) self.assertEqual(cmd.count_states('m2'), 5) cmd.delete('m2') cmd.create('m2', 'm1', 1, 2) self.assertEqual(cmd.count_states('m2'), 2) cmd.delete('m2') cmd.create('m2', 'm1', 2, 2) self.assertEqual(cmd.count_states('m2'), 2) cmd.delete('m2') cmd.create('m2', 'm1', 0, -1) self.assertEqual(cmd.count_states('m2'), 4) cmd.create('m2', 'm1', 0, -1) self.assertEqual(cmd.count_states('m2'), 8) cmd.create('m2', 'm1', 2, -1) self.assertEqual(cmd.count_states('m2'), 9)
def test_assembly(self): cmd.load(self.datafile('4m4b-minimal-w-assembly.cif')) self.assertEqual(cmd.count_states(), 1) self.assertEqual(cmd.get_chains(), ['A', 'B']) cmd.delete('*') cmd.set('assembly', '1') cmd.load(self.datafile('4m4b-minimal-w-assembly.cif')) self.assertEqual(cmd.count_states(), 2) self.assertEqual(cmd.get_chains(), ['B'])
def testSaveState(self, format, pymol_version): if pymol_version > testing.PYMOL_VERSION[1]: self.skipTest("version %f" % (pymol_version)) # for rms_cur (not all formats save all identifiers) m = -1 cmd.set('retain_order') # create a multistate object cmd.fragment('ala', 'm1') cmd.create('m1', 'm1', 1, 2) cmd.create('m1', 'm1', 1, 3) cmd.translate([5, 0, 0], 'm1', state=2) cmd.translate([0, 5, 0], 'm1', state=3) n_states = cmd.count_states('m1') with testing.mktemp('.' + format) as filename: if format == 'mae' and not pymol.invocation.options.incentive_product: format = 'cms' # explicit for state in range(1, n_states + 1): cmd.delete('m2') cmd.save(filename, 'm1', state=state) cmd.load(filename, 'm2', format=format) rms = cmd.rms_cur('m1', 'm2', state, 1, matchmaker=m) self.assertAlmostEqual(rms, 0.00, delta=1e-2) # current state for state in range(1, n_states + 1): cmd.frame(state) cmd.delete('m2') cmd.save(filename, 'm1') cmd.load(filename, 'm2', 1, format=format) rms = cmd.rms_cur('m1', 'm2', state, 1, matchmaker=m) self.assertAlmostEqual(rms, 0.00, delta=1e-2) if format in ('mol', 'cms'): # no multi support return # all states cmd.delete('m2') cmd.save(filename, 'm1', state=0) cmd.load(filename, 'm2', 1, discrete=1, multiplex=0) self.assertEqual(cmd.count_states('m2'), n_states) for state in range(1, n_states + 1): rms = cmd.rms_cur('m1', 'm2 and state %d' % state, state, state, matchmaker=m) self.assertAlmostEqual(rms, 0.00, delta=1e-2)
def testMorphMulti(self): cmd.set('suspend_undo') cmd.fab('ACD', 'm1') cmd.create('m1', 'm1', 1, 2) cmd.create('m1', 'm1', 1, 3) cmd.rotate('x', 90, 'm1', 2) cmd.rotate('x', 45, 'm1', 3) steps = 5 cmd.morph('mout', 'm1', None, 0, 0, 0, steps, 'linear') self.assertEqual(steps * 2, cmd.count_states('mout')) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('mout')) cmd.morph('mo2', 'm1', None, 0, -1, 0, steps, 'linear') self.assertEqual(steps * 3, cmd.count_states('mo2')) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('mo2'))
def test_join_states(): cmd.reinitialize() cmd.load(DATA_PATH / "1nmr-frag-nohydro.pdb", "m1", multiplex=1) assert len(cmd.get_names()) == 4 assert cmd.count_states() == 1 psico.creating.join_states("m2", "m1_*", discrete=0) assert cmd.count_states("m2") == 4 assert cmd.count_discrete("m2") == 0 assert cmd.count_atoms("m2") == 241 psico.creating.join_states("m3", "m1_*", discrete=1) assert cmd.count_states("m3") == 4 assert cmd.count_discrete("m3") == 1 assert cmd.count_atoms("m3") == 241 * 4
def get_bonds_colors(resn_list, matrix, color): """obtain colors for the bonds""" matrix_colors = [] if color == 'auto': for state in range(1, cmd.count_states()+1): colors = [] for bond in matrix: stored.colors = [] cmd.iterate_state(state, 'resi %s and name c1 or resi %s and name c1' % (bond[0], bond[2]), 'stored.colors.append(color)') colors.append((stored.colors[0], stored.colors[1])) matrix_colors.append(colors) else: for state in range(1, cmd.count_states()+1): matrix_colors.append([(color, color)] * (len(resn_list)-1)) return matrix_colors
def split_states_chains_save( sel1 ): ''' Simple script to split states of NMR ensemble and then save the complex and chain A separately for each state ''' cmd.remove("resn hoh") for ind in range(1,cmd.count_states(sel1)+1): if cmd.count_states(sel1) > 1: cmd.split_states(sel1) file_prefix="{0}_{1:04d}".format(sel1, ind) else: file_prefix=sel1 cmd.save(file_prefix + "_complex.pdb", file_prefix) cmd.split_chains(file_prefix) cmd.save(file_prefix + ".pdb", file_prefix + "_A")
def get_colors_c1(resn_list, color): """obtain colors of c1 atoms""" matrix_colors = [] if color == 'auto': for state in range(1, cmd.count_states()+1): colors = [] for i, resi in enumerate(resn_list): stored.colors = [] cmd.iterate_state(state, 'resi %s and name c1' % resi, 'stored.colors.append(color)') colors.extend(stored.colors) matrix_colors.append(colors) else: for state in range(1, cmd.count_states()+1): matrix_colors.append([color] * len(resn_list)) return matrix_colors
def testIterateState(self): cmd.fragment('ala') cmd.create('ala', 'ala', 1, 2) self.assertEqual(2, cmd.count_states()) v_count = cmd.count_atoms('all') expr = 'v_xyz.append(((model,index), (x,y,z)))' # current state v_xyz = [] cmd.iterate_state(-1, 'all', expr, space=locals()) self.assertEqual(len(v_xyz), v_count) # all states v_xyz = [] cmd.iterate_state(0, 'all', expr, space=locals()) self.assertEqual(len(v_xyz), v_count * 2) # atomic=0 stored.v_xyz = [] cmd.iterate_state(1, 'all', 'stored.v_xyz.append((x,y,z))', atomic=0) self.assertEqual(len(stored.v_xyz), v_count) space = {'self': self, 'NameError': NameError, 'v_list': []} cmd.iterate_state( 1, 'all', 'v_list.append(self.assertRaises(NameError, lambda: (model, index)))', space=space) self.assertEqual(len(space['v_list']), v_count)
def gyradius(selection='(all)', state=-1, quiet=1): ''' DESCRIPTION Radius of gyration Based on: http://pymolwiki.org/index.php/Radius_of_gyration SEE ALSO centerofmass ''' from chempy import cpv state, quiet = int(state), int(quiet) if state < 0: states = [cmd.get_state()] elif state == 0: states = list(range(1, cmd.count_states(selection)+1)) else: states = [state] rg_sq_list = [] for state in states: model = cmd.get_model(selection, state) x = [i.coord for i in model.atom] mass = [i.get_mass() * i.q for i in model.atom if i.q > 0] xm = [cpv.scale(v,m) for v,m in zip(x,mass)] tmass = sum(mass) rr = sum(cpv.dot_product(v,vm) for v,vm in zip(x,xm)) mm = sum((sum(i)/tmass)**2 for i in zip(*xm)) rg_sq_list.append(rr/tmass - mm) rg = (sum(rg_sq_list)/len(rg_sq_list))**0.5 if not quiet: print(' Radius of gyration: %.2f' % (rg)) return rg
def rao_dihedrals(selection, quiet='yes'): """ rao_dihedrals Calculates the virtual torsion angles a1, a2 and a3 of a hexopyranose ring, using the definitions of Rao and co-workers, as in the book. """ stored.names=[]; states=cmd.count_states(selection); print(states); a1=[]; a2=[]; a3=[]; for i in range(1, states+1, 1): cmd.iterate_state(i, selection, 'stored.names.append(name)'); a1.append(dihe(selection, stored.names[3], stored.names[4], stored.names[1], stored.names[0], state=i)); a2.append(dihe(selection, stored.names[5], stored.names[1], stored.names[3], stored.names[4], state=i)); a3.append(dihe(selection, stored.names[1], stored.names[3], stored.names[5], stored.names[4], state=i)); av1=numpy.mean(a1); stdErr1=numpy.std(a1)/math.sqrt(states); av2=numpy.mean(a2); stdErr2=numpy.std(a2)/math.sqrt(states); av3=numpy.mean(a3); stdErr3=numpy.std(a3)/math.sqrt(states); if quiet=="no": print("a1 a2 a3"); for i in range(len(a1)): print("%.3f %.3f %.3f" %(a1[i],a2[i],a3[i])); print("Averages(Mean +/- Standard Error):\na1 a2 a3\n %.3f+/-%.3f %.3f+/-%.3f %.3f+/-%.3f" %(av1,stdErr1, av2,stdErr2, av3,stdErr3));
def get_bonds_coords(resn_list, matrix): """obtain coordinates of the atoms in the glycosidic bond""" matrix_coords = [] for state in range(1, cmd.count_states() + 1): coords = [] for bond in matrix: stored.pos = [] if bond[4] == '6': cmd.iterate_state( state, 'resi %s and name C%s or resi %s and name C%s' % (bond[0], 5, bond[2], bond[5]), 'stored.pos.append((x,y,z))') elif bond[5] == '6': cmd.iterate_state( state, 'resi %s and name C%s or resi %s and name C%s' % (bond[0], bond[4], bond[2], 5), 'stored.pos.append((x,y,z))') else: cmd.iterate_state( state, 'resi %s and name C%s or resi %s and name C%s' % (bond[0], bond[4], bond[2], bond[5]), 'stored.pos.append((x,y,z))') x1, y1, z1 = stored.pos[0] x2, y2, z2 = stored.pos[1] coords.append((x1, y1, z1, x2, y2, z2)) matrix_coords.append(coords) return matrix_coords
def hs_resize(meta_file, selection): if not is_sele(selection): raise RuntimeError( "Selection \"{}\" does not exists.".format(selection)) # Find free sele name temp_sele = _random_string() while is_sele(temp_sele): temp_sele = _random_string() states = cmd.count_states(selection=selection) for state in range(1, states + 1): stored.info = [] cmd.iterate_state(state, selection, "stored.info.append((ID, partial_charge))") for id_, partial_charge in stored.info: size = log(partial_charge / ref + 1) print(ref) print(size) cmd.select(temp_sele, "{} and id {}".format(selection, id_), state=state) cmd.set("sphere_scale", value=size, selection=temp_sele) cmd.alter(temp_sele, "b={}".format(partial_charge)) cmd.delete(temp_sele)
def pymol_mutate(file_name, chain, res_index): pymol.finish_launching() cmd.delete('all') selection = chain + '/' + res_index + '/' mutant = 'CYS' cmd.wizard("mutagenesis") pdb = file_name[:-4] cmd.load(file_name) cmd.remove('not (alt ''+A)') cmd.select('mut', 'resi ' + res_index + ' and chain ' + chain) if cmd.count_atoms('mut') == 0: return False cmd.refresh_wizard() cmd.get_wizard().set_mode(mutant) cmd.get_wizard().do_select(selection) nStates = cmd.count_states("mutation") for i in range(1, nStates + 1): cmd.get_wizard().do_select(selection) cmd.frame(i) cmd.get_wizard().apply() cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb") cmd.set_wizard() cmd.remove(file_name[:-4]) return True
def testSimple(self): cmd.fab('A', 'm1') cmd.fab('A', 'm2') v1 = 'foo' v2 = 'bar' v3 = 'com' # single state cmd.set_property('filename', v1, 'm1') self.assertTrue('foo' == v1) self.assertTrue(cmd.get_property('filename', 'm1') == v1) self.assertTrue(cmd.get_property('filename', 'm2') == None) # multiple objects cmd.set_property('filename', v1) self.assertTrue(cmd.get_property('filename', 'm2') == v1) # two states cmd.create('m1', 'm1', 1, 2) self.assertTrue(cmd.count_states() == 2) # set for all states cmd.set_property('filename', v1, 'm1') self.assertTrue(cmd.get_property('filename', 'm1', 2) == v1) # set for particular state cmd.set_property('filename', v2, 'm1', 2) self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1) self.assertTrue(cmd.get_property('filename', 'm1', 2) == v2) # set for current state cmd.frame(2) cmd.set_property('filename', v3, 'm1', -1) self.assertTrue(cmd.get_property('filename', 'm1', 1) == v1) self.assertTrue(cmd.get_property('filename', 'm1', 2) == v3)
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file,'pdb') cmd.set_title('pdb',1,os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.zoom('center',16) cmd.label("polymer and (name ca or elem P)","'//%s/%s/%s`%s/%s'%(segi,chain,resn,resi,name)") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n>1: cmd.rewind() sys.__stderr__.write(file+"\n") sys.__stderr__.flush() for a in range(1,n+1): cmd.forward() cmd.refresh() except: traceback.print_exc()
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file, 'pdb') cmd.set_title('pdb', 1, os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.show_as("ribbon") cmd.refresh() cmd.show_as("sticks") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n > 1: cmd.rewind() sys.__stderr__.write(file + "\n") sys.__stderr__.flush() for a in range(1, n + 1): cmd.forward() cmd.refresh() except: traceback.print_exc()
def com(selection,state=None,mass=None,object=None, quiet=1, **kwargs): """ DESCRIPTION Places a pseudoatom at the center of mass Author: Sean Law Michigan State University slaw (at) msu . edu SEE ALSO pseudoatom, get_com """ quiet = int(quiet) if (object == None): object = cmd.get_legal_name(selection) object = cmd.get_unused_name(object + "_COM", 0) cmd.delete(object) if (state != None): x, y, z=get_com(selection,mass=mass, quiet=quiet) if not quiet: print "%f %f %f" % (x, y, z) cmd.pseudoatom(object,pos=[x, y, z], **kwargs) cmd.show("spheres",object) else: for i in range(cmd.count_states()): x, y, z=get_com(selection,mass=mass,state=i+1, quiet=quiet) if not quiet: print "State %d:%f %f %f" % (i+1, x, y, z) cmd.pseudoatom(object,pos=[x, y, z],state=i+1, **kwargs) cmd.show("spheres", 'last ' + object)
def testLoad_idx(self): cmd.load( self.datafile( 'desmond/Bace_mapper_20143_3a51a59_e85111a_solvent_11_replica0-out.idx' )) self.assertEqual(cmd.count_states(), 210) self.assertEqual(cmd.count_atoms(), 2482)
def testIterateState(self): cmd.fragment('ala') cmd.create('ala', 'ala', 1, 2) self.assertEqual(2, cmd.count_states()) v_count = cmd.count_atoms('all') expr = 'v_xyz.append(((model,index), (x,y,z)))' # current state v_xyz = [] cmd.iterate_state(-1, 'all', expr, space=locals()) self.assertEqual(len(v_xyz), v_count) # all states v_xyz = [] cmd.iterate_state(0, 'all', expr, space=locals()) self.assertEqual(len(v_xyz), v_count * 2) # atomic=0 stored.v_xyz = [] cmd.iterate_state(1, 'all', 'stored.v_xyz.append((x,y,z))', atomic=0) self.assertEqual(len(stored.v_xyz), v_count) space = {'self': self, 'NameError': NameError, 'v_list': []} cmd.iterate_state(1, 'all', 'v_list.append(self.assertRaises(NameError, lambda: (model, index)))', space=space) self.assertEqual(len(space['v_list']), v_count)
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file,'pdb') cmd.set_title('pdb',1,os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.show_as("ribbon") cmd.refresh() cmd.show_as("sticks") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n>1: cmd.rewind() sys.__stderr__.write(file+"\n") sys.__stderr__.flush() for a in range(1,n+1): cmd.forward() cmd.refresh() except: traceback.print_exc()
def state2frame(selection, start=1): for i, x in enumerate( list( range(int(start), int(start) + cmd.count_states(selection) + 1))): cmd.frame(x) cmd.set('state', str(i + 1), selection) print("Frame => %s; and State => %s" % (str(x), str(i + 1)))
def r_gyration(selection='all', from_state=1, to_state=1, step=1, visual=True, by_state=True): """ Calculates radius of gyration for a PyMOL object Arguments: ------------------------------------------------- selection: key word. Selects and object from_state: int. First state to calculate RG to_state: int. Last state to calculate RG visual: boolean. by_state: boolean. """ states = cmd.count_states(selection) if states: fd = open('Rg.dat', 'w') radii = [] centers = [] for state in range(from_state, to_state + 1, step): model = cmd.get_model(selection, state) xyz = np.array(model.get_coord_list()) center = np.average(xyz, 0) centers.append(center) rg = np.mean(np.sum((xyz - center)**2, 1))** 0.5 fd.write('%9d%8.2f\n' % (state, rg)) radii.append(rg) try: rg_mean = sum(radii) / len(radii) centers_mean = sum(centers) / len(centers) except ZeroDivisionError: rg_mean = np.nan centers_mean = np.nan fd.write('Rg_mean = %8.2f\n' % rg_mean) fd.close() print('Rg_mean = %8.2f\n' % rg_mean) if visual: cmd.delete('sphere_rg') r, g, b = 0, 0, 1 if by_state: cmd.set('defer_updates', 'on') count = 0 for state in range(from_state, to_state + 1, step): x1, y1, z1 = tuple(centers[count]) radius = radii[count] obj = [COLOR, r, g, b, SPHERE, x1, y1, z1, radius] cmd.load_cgo(obj, 'sphere_rg', state) count += 1 cmd.set('defer_updates', 'off') # workaround. find a better way to fix the cgo persistent for # the last states for i in range(state + 1, to_state + 1): cmd.load_cgo([], 'sphere_rg', i) else: x1, y1, z1 = tuple(centers_mean) radius = rg_mean obj = [COLOR, r, g, b, SPHERE, x1, y1, z1, radius] cmd.load_cgo(obj, 'sphere_rg')
def testLoadTOP(self): ''' Data files from: http://ambermd.org/tutorials/basic/tutorial2/section6.htm ''' cmd.load(self.datafile("TRPcage.top")) cmd.load_traj(self.datafile("heat1.crd"), "TRPcage") self.assertEqual(304, cmd.count_atoms()) self.assertEqual(10, cmd.count_states())
def intra_promix(selection, K=0, prefix=None, conformers=0, guide=1, quiet=1, async_=-1, _self=cmd, **kwargs): ''' DESCRIPTION Finds rigid segments in a multi-state object. Requires CSB, https://github.com/csb-toolbox/CSB ARGUMENTS selection = string: atom selection K = integer: Number of segments {default: guess} prefix = string: Prefix of named segment selections to make SEE ALSO promix REFERENCE Mixture models for protein structure ensembles Hirsch M, Habeck M. - Bioinformatics. 2008 Oct 1;24(19):2184-92 ''' from numpy import asarray from csb.statistics import mixtures from .querying import get_ensemble_coords, get_object_name K, conformers = int(K), int(conformers) guide, quiet, async_ = int(guide), int(quiet), int(kwargs.pop('async', async_)) if async_ < 0: async_ = not quiet Mixture = mixtures.ConformerMixture if conformers else mixtures.SegmentMixture obj = get_object_name(selection) n_models = cmd.count_states(obj) if guide: selection = '(%s) and guide' % (selection) if n_models < 2: print(' Error: object needs multiple states') raise CmdException X = asarray(get_ensemble_coords(selection)) assert X.shape == (n_models, cmd.count_atoms(selection), 3) if not async_: _promix(**locals()) else: import threading t = threading.Thread(target=_promix, kwargs=locals()) t.setDaemon(1) t.start()
def get_ensemble_coords(selection): ''' DESCRIPTION API only. Returns the (nstates, natoms, 3) coordinate matrix. Considers the object rotation matrix. ''' return [get_coords(selection, state) for state in range(1, cmd.count_states(selection) + 1)]
def ens_prob(): print('\n\nEnsemble probability options') # get models, mean coords models = [] selection = 'all' for i in range(cmd.count_states(selection)): models.append(cmd.get_model(selection, state=i + 1)) for n, model in enumerate(models): residues = model.get_residues() for residue in residues: # Get individual atom info q_list = [] q_list_mc = [] q_list_sc = [] for i_seq in range(residue[0], residue[1]): # Ignore hydrogens if model.atom[i_seq].symbol != 'H': q_list.append(float(model.atom[i_seq].q)) if model.atom[i_seq].name in ['N', 'CA', 'C', 'O']: q_list_mc.append(float(model.atom[i_seq].q)) else: q_list_sc.append(float(model.atom[i_seq].q)) # Set probability per residue # Mean p if len(q_list) > 0: p_new = sum(q_list) / len(q_list) if len(q_list_mc) > 0: p_new_mc = sum(q_list_mc) / len(q_list_mc) if len(q_list_sc) > 0: p_new_sc = sum(q_list_sc) / len(q_list_sc) # # Joint p_new = q_list[0] for p in q_list[1:]: p_new *= p # # nll # p_new = math.log(q_list[0]) # for p in q_list[1:]: # p_new += math.log(max(p,0.001)) # p_new *= -1 if i_seq == residue[1] - 1: for i_seq in range(residue[0], residue[1]): if True: atom_sel = 'id ' + str( model.atom[i_seq].id) + ' and state ' + str(n + 1) atom_action = 'b = ' + str(p_new) cmd.alter(atom_sel, atom_action) else: atom_sel = 'id ' + str( model.atom[i_seq].id) + ' and state ' + str(n + 1) if model.atom[i_seq].name in ['N', 'CA', 'C', 'O']: atom_action = 'b = ' + str(p_new_mc) else: atom_action = 'b = ' + str(p_new_sc) cmd.alter(atom_sel, atom_action)
def rmsf2b(selection='all', linearscale=1.0, var='b', quiet=1): ''' DESCRIPTION Determine the root mean square fluctuation (RMSF) per atom for a multi-state object and assign b-factor ARGUMENTS selection = string: atom selection {default: name CA} linearscale = float: if linearscale <= 0, then use real b-factor equation, else use b=(rmsf*linearscale) {default: 1.0} SEE ALSO spheroid, rmsf_states.py from Robert Campbell ''' from numpy import asfarray, sqrt, pi linearscale = float(linearscale) n_atoms = cmd.count_atoms(selection) n_states = cmd.count_states(selection) if n_atoms == 0 or n_states < 2: print(' Error: not enough atoms or states') raise CmdException coords = [] cmd.iterate_state(0, selection, 'coords.append((x,y,z))', atomic=0, space={'coords': coords}) coords = asfarray(coords).reshape((cmd.count_states(selection), -1, 3)) u_sq = coords.var(0).sum(1) # var over states, sum over x,y,z b_array = sqrt(u_sq) * linearscale if linearscale > 0.0 \ else 8 * pi**2 * u_sq cmd.alter(selection, var + ' = next(b_iter)', space={ 'b_iter': iter(b_array), 'next': next }) if not int(quiet): print(' Average RMSF: %.2f' % (sqrt(u_sq).mean())) return b_array
def doubleMut(original, positions, residues): cmd.hide("everything") cmd.show("sticks") posone = positions[0][0] chainone = positions[0][1] postwo = positions[1][0] chaintwo = positions[1][1] outfile = open("forheatmap.csv", "w") #generate the protein with one mutation for a in residues: cmd.create(a, original) cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(a) sel = "/" + a + "//" + str(chainone) + "/" + str(posone) cmd.get_wizard().do_select(sel) cmd.get_wizard().apply() for m in residues: #for all the mutations generated for i in residues: #for each residue to which will be mutated name = m + "2" cmd.create(name, m) cmd.wizard("mutagenesis") cmd.do("refresh_wizard") cmd.get_wizard().set_mode(i) se = "/" + name + "//" + str(chaintwo) + "/" + str(postwo) cmd.get_wizard().do_select(se) mut_name = "mutation" if cmd.count_states(mut_name) != 1: bump_name = "_bump_check" cmd.sculpt_activate(bump_name) scores = [] for rotamer in range(1, 1 + cmd.count_states(bump_name)): score = cmd.sculpt_iterate(bump_name, rotamer, 1) scores.append(score) scores.sort(reverse=True) row = (i + "," + m + "," + str(scores[0]) + "\n") else: row = (i + "," + m + "," + "?" + "\n") outfile.write(row) outfile.close()
def testLoadCoordset(self): import numpy cmd.fragment('gly', 'm1') coords = cmd.get_coordset('m1') cmd.load_coordset(coords, 'm1', state=2) self.assertEqual(2, cmd.count_states('m1')) # data manipulation with copy=0 cmd.get_coordset('m1', copy=0)[:] += 5.0 self.assertTrue(numpy.allclose(coords + 5.0, cmd.get_coords('m1')))
def do_state(self,state): cmd=self.cmd if cmd.get("sculpting")=="on": names = cmd.get_names("all_objects") if (bump_name in names) and (obj_name in names): cmd.update(bump_name,obj_name) if self.bump_scores: state = cmd.get_state() print(' Rotamer %d/%d, strain=%.2f' % (state, cmd.count_states(obj_name), self.bump_scores[state - 1]))
def load_state_dict(self): # establish relationship between names and states # ASSUMPTION: identifiers will be unique self.state_dict = {} sd = self.state_dict so = self.object if so!=None: cnt = cmd.count_states(so) for a in range(1,cnt+1): sd[self.get_ident(so,a)] = a
def load_state_dict(self): # establish relationship between names and states # ASSUMPTION: identifiers will be unique self.state_dict = {} sd = self.state_dict so = self.object if so is not None: cnt = cmd.count_states(so) for a in range(1,cnt+1): sd[self.get_ident(so,a)] = a
def ens_prob(): print '\n\nEnsemble probability options' # get models, mean coords models = [] selection = 'all' for i in range(cmd.count_states(selection)): models.append(cmd.get_model(selection,state=i+1)) for n, model in enumerate(models): residues = model.get_residues() for residue in residues: # Get individual atom info q_list = [] q_list_mc = [] q_list_sc = [] for i_seq in range (residue[0], residue[1]): # Ignore hydrogens if model.atom[i_seq].symbol != 'H': q_list.append(float(model.atom[i_seq].q)) if model.atom[i_seq].name in ['N','CA','C','O']: q_list_mc.append(float(model.atom[i_seq].q)) else: q_list_sc.append(float(model.atom[i_seq].q)) # Set probability per residue # Mean p if len(q_list) > 0: p_new = sum(q_list) / len(q_list) if len(q_list_mc) > 0: p_new_mc = sum(q_list_mc) / len(q_list_mc) if len(q_list_sc) > 0: p_new_sc = sum(q_list_sc) / len(q_list_sc) # # Joint p_new = q_list[0] for p in q_list[1:]: p_new *= p # # nll # p_new = math.log(q_list[0]) # for p in q_list[1:]: # p_new += math.log(max(p,0.001)) # p_new *= -1 if i_seq == residue[1]-1: for i_seq in range (residue[0], residue[1]): if True: atom_sel = 'id ' + str(model.atom[i_seq].id) + ' and state ' + str(n+1) atom_action = 'b = ' + str(p_new) cmd.alter(atom_sel, atom_action) else: atom_sel = 'id ' + str(model.atom[i_seq].id) + ' and state ' + str(n+1) if model.atom[i_seq].name in ['N','CA','C','O']: atom_action = 'b = ' + str(p_new_mc) else: atom_action = 'b = ' + str(p_new_sc) cmd.alter(atom_sel, atom_action)
def get_ring_coords(resn_list, matrix): """obtain coordinates of sugar rings""" matrix_coords = [] for state in range(1, cmd.count_states()+1): coords = [] for i, resi in enumerate(resn_list): stored.coords = [] cmd.iterate_state(state, 'resi %s and name %s' % (resi, '+'.join(matrix[i])), 'stored.coords.append([x,y,z])') coords.append(stored.coords) matrix_coords.append(coords) return matrix_coords
def create(mol_name): """ create the defined molecule """ if os.path.isfile('%s_matrix.dat' % mol_name): residues, bonds = read_input('%s_matrix.dat' % mol_name) builder(residues, bonds, mol_name) to_state.set(cmd.count_states(sel0_value.get())) cmd.zoom() cmd.util.chainbow(mol_name) else: tkMessageBox.showerror("FileNotFound", "You should add residues\ before creating a molecule.")
def test(self): cmd.set('suspend_undo') cmd.fragment('gly', 'm1') cmd.remove('not ID 0+1') cmd.create('m1', 'm1', 1, 2) cmd.rotate('x', 90, 'm1', 2) steps = 5 cmd.morph('mout', 'm1', refinement=0, steps=steps, method='rigimol') self.assertEqual(steps, cmd.count_states('mout')) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('mout'))
def testMorphRigimol(self): cmd.set('suspend_undo') import epymol.rigimol cmd.fab('ACD', 'm1') cmd.create('m1', 'm1', 1, 2) cmd.rotate('x', 90, 'm1', 2) steps = 5 cmd.morph('mout', 'm1', refinement=1, steps=steps, method='rigimol') self.assertEqual(steps, cmd.count_states('mout')) self.assertEqual(cmd.count_atoms('m1'), cmd.count_atoms('mout'))
def show_bumps(selection): print selection name = 'bump_check' cmd.delete(name) cmd.create(name, selection, zoom=0) cmd.set('sculpt_vdw_vis_mode', 1, name) cmd.set('sculpt_field_mask', 0x020) # cSculptVDW for state in range(1, 1 + cmd.count_states('%' + name)): cmd.sculpt_activate(name, state) strain = cmd.sculpt_iterate(name, state, cycles=0) print('VDW Strain in state %d: %f' % (state, strain))
def getRots(site, variant): cmd.get_wizard().set_mode(variant) # Key lines # I dont know how they work, but they make it possible. # Jason wrote this: If you just write "site" instead of # "(site)", PyMOL will delete your # residue. "(site)" makes it an # anonymous selection. #print 'getRots' cmd.get_wizard().do_select("(" + str(site) + "/)") nRot = cmd.count_states("mutation") return nRot
def ens_rmsd(ens_selection, ref_selection, log_name = None): ''' DESCRIPTION Prints RMSD per structure in ensemble w.r.t. a reference structure USAGE ens_rmsd ensemble_selection, reference_selection, name, log, ARGUMENTS log = name of log file verbose = calculates structure by structure RMSD for ensemble w.r.t. a single reference structure EXAMPLE ens_rmsd ensemble_selection, reference_selection, name = 'rmsd', log 'ens.log' ''' if log_name == None: log = LogWriter(sys.stdout, 'log.txt') else: log = LogWriter(sys.stdout, log_name+'.txt') # initialize arrays ens_selection = ens_selection + ' and not resn hoh' ref_selection = ref_selection + ' and not resn hoh' rmsd_states = [] mean_coords = None number_models = cmd.count_states(ens_selection) # get models, mean coords print >> log, '\nRMSD by state' print >> log, '\n State | RMSD' for i in range(number_models): ens_coords = cmd.get_model(ens_selection,state=i+1).get_coord_list() ref_coords = cmd.get_model(ref_selection,state=1).get_coord_list() atom_sqr_dev = [] for atom in xrange(len(ref_coords)): x = ref_coords[atom] y = ens_coords[atom] atom_sqr_dev.append(distance(x,y)**2) rmsd = math.sqrt(sum(atom_sqr_dev) / len(atom_sqr_dev)) rmsd_states.append(rmsd) print >> log, ' %5d | %5.3f '%(i+1, rmsd) print_array_stats(array = rmsd_states, log = log) print '\nRMSD all states : %5.3f '%(cmd.rms(ens_selection, ref_selection))
def load(): global last1, last2 list = glob("pdb/*/*") list = map(lambda x: (random.random(), x), list) list.sort() list = map(lambda x: x[1], list) l = len(list) c = 0 for file in list: c = c + 1 try: cmd.set("suspend_updates", "1") cmd.delete("pdb") print file, last1, last2, c, "of", l last2 = last1 last1 = file cmd.load(file, "pdb") cmd.set_title("pdb", 1, os.path.split(file)[-1]) cmd.rewind() # cmd.refresh() # cmd.hide() cmd.show("cartoon") cmd.color("auto", "ss h") cmd.color("auto", "ss s") cmd.orient("pdb") cmd.color("auto", "organic and elem c") cmd.show("spheres", "organic") cmd.move("z", -50.0) sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() finally: cmd.set("suspend_updates", "0") if cmd.count_atoms(): start = time.time() if n > 1: while (time.time() - start) < cycle_time: for a in range(1, n + 1): cmd.refresh() cmd.frame(a) cmd.move("z", 2) cmd.turn("y", 1) time.sleep(0.025) sys.__stderr__.write(" %d of %d" % (c, l)) sys.__stderr__.write("\n") sys.__stderr__.flush() else: cmd.refresh() while (time.time() - start) < cycle_time: for a in range(1, n + 1): time.sleep(0.05) cmd.move("z", 1.0) cmd.turn("y", 1)
def test_set_discrete(self): import pymol cmd.fragment('ala', 'm1') cmd.create('m1', 'm1', 1, 2) self.assertEqual(0, cmd.count_discrete('*')) self.assertEqual(2, cmd.count_states()) self.assertEqual(10, cmd.count_atoms()) pymol.editing.set_discrete('m1', 1) self.assertEqual(1, cmd.count_discrete('*')) self.assertEqual(2, cmd.count_states()) self.assertEqual(20, cmd.count_atoms()) pymol.editing.set_discrete('m1', 0) self.assertEqual(0, cmd.count_discrete('*')) self.assertEqual(2, cmd.count_states()) self.assertEqual(10, cmd.count_atoms())
def testLoad_multi(self, ext, discrete): ''' Load multi-state files with discrete=0/1 and multiplex=0/1 ''' N = 10 filename = self.datafile('ligs3d.' + ext) # mutiplex=0 cmd.load(filename, discrete=discrete, multiplex=0) self.assertEqual(cmd.count_discrete('*'), discrete) self.assertEqual(cmd.count_states(), N) self.assertEqual(len(cmd.get_object_list()), 1) if ext in ['mmd']: return # mutiplex=1 cmd.delete('*') cmd.load(filename, discrete=discrete, multiplex=1) self.assertEqual(cmd.count_discrete('*'), discrete * N) self.assertEqual(cmd.count_states(), 1) self.assertEqual(len(cmd.get_object_list()), N)