def pnghack(filepath, width=1024, height=768): #Workaround if cmd.png() doesn't work cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image. cmd.set('ray_shadows', 0) cmd.viewport(width, height) # Set resolution cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only cmd.mplay() # cmd.mpng needs the animation to 'run'
def makeMovie(numClusts, frameRate): real = int(numClusts)+1; fr = int(frameRate) movieSetup = "1 x" + str(real*fr) cmd.mset(movieSetup) #Load in all the system data. for x in range(0, real): # load the next system. clustName = "system-" + str(x) system = clustName + ".xyz" cmd.load(system) # Set the sphere scale and view cmd.set("sphere_scale","0.5","all") #Set the right view cmd.set_view("0.910306633, -0.382467061, 0.158301696, 0.326706469, 0.898694992, 0.292592257, -0.254171938, -0.214630708, 0.943043232, 0.000000000, 0.000000000, -99.425979614, 10.461934090, 13.087766647, 11.786855698, 80.009132385, 118.842796326, -20.000000000") #Set all the frame data for x in range(0, real): # set the current frame. frameNum = (x*fr)+1 cmd.frame(frameNum) clustName = "system-" + str(x) movieState = "hide; show spheres, " + clustName cmd.mdo(frameNum,movieState) cmd.mview("store") cmd.mview("reinterpolate") cmd.mplay()
def testGetMoviePlaying(self): self.prep_movie() cmd.mplay() self.assertEquals(cmd.get_movie_playing(), 1) cmd.mstop() self.assertEquals(cmd.get_movie_playing(), 0)
def testGetMoviePlaying(self): self.prep_movie() cmd.mplay() self.assertEquals(cmd.get_movie_playing(),1) cmd.mstop() self.assertEquals(cmd.get_movie_playing(),0)
def png_workaround(filepath, width=1200, height=800): """Workaround for (a) severe bug(s) in PyMOL preventing ray-traced images to be produced in command-line mode. Use this function in case neither cmd.ray() or cmd.png() work. """ sys.stdout = sys.__stdout__ cmd.feedback('disable', 'movie', 'everything') cmd.viewport(width, height) cmd.zoom('visible', 1.5) # Adapt the zoom to the viewport cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image. cmd.mpng(filepath, config.MODEL, config.MODEL) # Use batch png mode with 1 frame only cmd.mplay() # cmd.mpng needs the animation to 'run' cmd.refresh() originalfile = "".join([ filepath, (4 - len(str(config.MODEL))) * '0' + str(config.MODEL) + '.png' ]) newfile = "".join([filepath, '.png']) ################################################# # Wait for file for max. 1 second and rename it # ################################################# attempts = 0 while not os.path.isfile(originalfile) and attempts <= 10: sleep(0.1) attempts += 1 if os.name == 'nt': # In Windows, make sure there is no file of the same name, cannot be overwritten as in Unix if os.path.isfile(newfile): os.remove(newfile) os.rename(originalfile, newfile) # Remove frame number in filename # Check if imagemagick is available and crop + resize the images if subprocess.call("type convert", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: attempts, ecode = 0, 1 # Check if file is truncated and wait if that's the case while ecode != 0 and attempts <= 10: ecode = subprocess.call(['convert', newfile, '/dev/null'], stdout=open('/dev/null', 'w'), stderr=subprocess.STDOUT) sleep(0.1) attempts += 1 trim = 'convert -trim ' + newfile + ' -bordercolor White -border 20x20 ' + newfile + ';' # Trim the image os.system(trim) getwidth = 'w=`convert ' + newfile + ' -ping -format "%w" info:`;' # Get the width of the new image getheight = 'h=`convert ' + newfile + ' -ping -format "%h" info:`;' # Get the hight of the new image newres = 'if [ "$w" -gt "$h" ]; then newr="${w%.*}x$w"; else newr="${h%.*}x$h"; fi;' # Set quadratic ratio quadratic = 'convert ' + newfile + ' -gravity center -extent "$newr" ' + newfile # Fill with whitespace os.system(getwidth + getheight + newres + quadratic) else: sys.stderr.write( 'Imagemagick not available. Images will not be resized or cropped.' )
def png_workaround(filepath, width=1024, height=768): """Workaround for (a) severe bug(s) in PyMOL preventing ray-traced images to be produced in command-line mode. Use this function in case neither cmd.ray() or cmd.png() work. """ cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image. cmd.viewport(width, height) # Set resolution ### Workaround for raytracing in command-line mode cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only cmd.mplay() # cmd.mpng needs the animation to 'run' os.rename("".join([filepath[:-4], '0001.png']), "".join([filepath[:-4], '.png'])) # Remove frame number in filename
def convert_spin(self): '''spin the protein''' if self.argsLength > 1 and self.args[1] == 'off': cmd.mstop() cmd.mset() pymSpin = 'PyMOL: mstop; mset\n\n' else: cmd.mset('1 x180') util.mroll(1, 180, 1) cmd.mplay() pymSpin = 'PyMOL: mset 1 x180; util.mroll(1,180,1); mplay' print pymSpin
def convert_spin(self): '''spin the protein''' if self.argsLength > 1 and self.args[1] == 'off': cmd.mstop() cmd.mset() pymSpin = 'PyMOL: mstop; mset\n\n' else: cmd.mset('1 x180') util.mroll(1,180,1) cmd.mplay() pymSpin = 'PyMOL: mset 1 x180; util.mroll(1,180,1); mplay' print pymSpin
def movie(self, configurations): n = 1 cmd.feedback("disable", "executive", "actions") auto_zoom = cmd.get("auto_zoom") cmd.set("auto_zoom", 0) for conf in configurations: self._setCoordinates(conf) cmd.load_model(self.model, self.name, n) n = n + 1 cmd.set("auto_zoom", auto_zoom) cmd.feedback("enable", "executive", "actions") cmd.mplay()
def movie(self, configurations): n = 1 cmd.feedback("disable","executive","actions") auto_zoom = cmd.get("auto_zoom") cmd.set("auto_zoom", 0) for conf in configurations: self._setCoordinates(conf) cmd.load_model(self.model, self.name, n) n = n + 1 cmd.set("auto_zoom", auto_zoom) cmd.feedback("enable","executive","actions") cmd.mplay()
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 show_result(tmpdir, ligname): n = 10 # number of positions of ligand ft_file = tmpdir + "/ft.000.0.0" rm_file = tmpdir + "/rm.000.0.0" ft_data = np.loadtxt(ft_file) rm_data = np.loadtxt(rm_file) for i in range(n): num_state = i + 1 name_copy = "copy_ligand_" + str(i) cmd.copy(name_copy, ligname) tv = ft_data[i, 1:4] rm = rm_data[i].reshape((3, 3)) en = ft_data[i, 4] cmd.translate(list(tv), name_copy) cmd.rotate(list(get_axis(rm)), get_angle(rm), name_copy) cmd.create("result", name_copy, 0, num_state) cmd.delete(name_copy) result = tmpdir + "/result_dock.pdb" cmd.save(result, "result") cmd.mplay()
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 pnghack(filepath, width=1024, height=768): """Workaround if cmd.png() doesn't work""" cmd.viewport(width, height) # Set resolution cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only cmd.mplay() # cmd.mpng needs the animation to 'run'
def show_transition(start_index=0, end_index=0): #show the transition from the current view to the next view global frames global views global cur_index global actions global models if start_index == 0 and end_index == 0: if cur_index >= len(views) - 1: print "Current view is last in sequence." return start_index = cur_index end_index = cur_index + 1 else: start_index = int(start_index) end_index = int(end_index) ftot = 0 setcommand = "" i = start_index for nframes in frames[start_index:end_index]: #ftot += nframes if i in models: setcommand += " " + models[i] + " " else: setcommand += " 1 x%i" % nframes i += 1 # cmd.mset("1 x%i" % ftot) cmd.mset(setcommand) start_frame = 1 #first do all actions that happen up to this point to make sure #things look the way they should first_action = "" for i in range(start_index): if i in actions: first_action += actions[i] + ';' #print "Executing %s from actions %d" % (actions[i],i) #cmd.do( actions[i] ) if i in settings: settingName, selection, startVal, endVal = settings[i] action = "set %s, %f, %s;" % (settingName, endVal, selection) first_action += action #print "Executing %s from settings %d" % (action,i) #cmd.do( action ) if i in fades: startVisSelection, endVisSelection, sticksOnly = fades[i] action = "set stick_transparency, 0, %s; set stick_transparency, 1, %s;" % ( endVisSelection, startVisSelection) first_action += action #print "Executing %s from fades %d" % (action, i) #cmd.do( action ) for i in range(start_index, end_index): if i in settings: movs.animate_transition(views[i], views[i + 1], frames[i], start_frame, settings[i]) elif i in fades: movs.animate_transition(views[i], views[i + 1], frames[i], start_frame, fades[i]) else: movs.animate_transition(views[i], views[i + 1], frames[i], start_frame) #add an action if start_frame == 1: mdo_cmd = first_action if i in actions: mdo_cmd += actions[i] + ";" #mdo_cmd += "set_view("+str(views[i])+")" print mdo_cmd cmd.mdo(start_frame, mdo_cmd) elif i in actions: mdo_cmd = actions[i] + ";set_view(" + str(views[i]) + ")" cmd.mdo(start_frame, mdo_cmd) #print mdo_cmd start_frame += frames[i] cmd.frame(1) cmd.mplay()
self.norm[2 * a + 1][0] = self.norm[2 * a][0] self.norm[2 * a + 1][1] = self.norm[2 * a][1] self.norm[2 * a + 1][2] = self.norm[2 * a][2] def __call__(self): glColor3f(1.0, 1.0, 1.0) glVertexPointer(3, GL_FLOAT, 0, self.vert) glNormalPointer(GL_FLOAT, 0, self.norm) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glDisableClientState(GL_COLOR_ARRAY) glDrawArrays(GL_TRIANGLE_STRIP, 0, 126) def get_extent(self): return [[0.0, 0.0, -1.0], [6.3, 1.0, 1.0]] # load it into PyMOL for b in range(0, 63): cmd.load_callback(myCallback(b), 'gl03', b + 1) # give us a nice view cmd.turn('z', 20) cmd.turn('y', 20) cmd.turn('x', 20) cmd.mplay()
def reps(self, cleanup=0): rep_list = [ "lines", "sticks", "spheres", "surface", "mesh", "dots", "ribbon", "cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates", 1, quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb", "rep1") cmd.alter("rep1///1-5+8-13/", "ss='S'") cmd.cartoon("auto") cmd.hide("everything", "rep1") for a in range(2, 9): cmd.create("rep%d" % a, "rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1", 24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates", 0, quiet=1) scale = 0.5 for b in range(1, 20): cmd.set("suspend_updates", 0, quiet=1) cmd.refresh() cmd.set("suspend_updates", 1, quiet=1) xt = -3.2 yt = 1.6 for a in range(1, 5): cmd.translate([xt * scale, yt * scale, 0], object="rep%d" % a, camera=0) xt = xt + 2 yt = -yt xt = -3.2 for a in range(5, 9): cmd.translate([xt * scale, yt * scale, 0], object="rep%d" % a, camera=0) xt = xt + 2 for a in range(1, 9): cmd.origin("rep%d" % a, object="rep%d" % a) cmd.mset("1") st = ' '.join( map( lambda x, y: "rotate angle=-3,object=rep%d,axis=%s;" % (x, y), list(range(1, 9)), ['x', 'y', 'x', 'y', 'x', 'y', 'x', 'y'])) cmd.mdo(1, st) cmd.set("suspend_updates", 0, quiet=1) cmd.mplay() cgo = [] axes = [[4.5, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d" % c) pos = [(ext[0][0] + ext[1][0]) / 2, (ext[0][1] + ext[1][1]) / 2 + 14, (ext[0][2] + ext[1][2]) / 2] c = c + 1 pos[0] = pos[0] - (measure_text(plain, a, axes) / 2) wire_text(cgo, plain, pos, a, axes) cmd.set("cgo_line_width", 1.5) cmd.set("auto_zoom", 0) cmd.load_cgo(cgo, 'reps') cmd.set("auto_zoom", 1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
# counter label pdb_list = [ "HETATM%5d C UNK 1 %8.3f%8.3f%8.3f 1.00 10.00\n"%(c,2.0,0,2.0), ] cmd.read_pdbstr(''.join(pdb_list),'lab1',c,discrete=1) cmd.label("(lab1 and id %d)"%c,"'frame %d %6.3f'"%(c,math.sin(a/10.0))) cmd.hide("nonbonded","lab1") # axes labels pdb_list = [ "HETATM 1 X UNK 1 %8.3f%8.3f%8.3f 1.00 10.00\n"%(3.2,0,0), "HETATM 2 Y UNK 2 %8.3f%8.3f%8.3f 1.00 10.00\n"%(0,3.2,0), "HETATM 3 Z UNK 3 %8.3f%8.3f%8.3f 1.00 10.00\n"%(0,0,3.2),] cmd.read_pdbstr(''.join(pdb_list),'lab2') cmd.hide('(lab2)') cmd.label('lab2','name') cmd.color('white','lab2') cmd.zoom('cgo01') cmd.clip('far',-5) cmd.mplay()
def rotate_y(): cmd.mset() cmd.mset('1', '180') cmd.util.mroll('1', '180', '1') cmd.mplay()
def cheese(render_type, savefile=None, duration=5, mode='ray', width=1920, height=1080): """ DESCRIPTION loads nice settings for rendering and take a picture or records a movie of the trajectory. Before running, position the camera to have a good point of view. USAGE cheese render_type [, savefile [, duration [, mode [, width [, height]]]]] ARGUMENTS render_type = one of: - set: only load render settings - snap: take a snapshot of the current view - traj: record the whole trajectory - bullettime: make a whole revolution around the z axis savefile = file name to use to save the movie, without extension. If not given, the movie won't be save but only shown (default=None) duration = duration in seconds of the final movie (default=5) mode = set to 'draw' to disable ray tracing (default='ray') width = width of the movie in pixel (default=1920) height = height of the movie in pixel (default=1080) """ duration = int(duration) # # store settings for later restoration # store_settings.load() # cmd.sync() # settings_file = '/tmp/stir_settings.py' # cmd.do(f'store_settings {settings_file}') # load nice settings for rendering config.rendering() cmd.sync() def init_movie(): cmd.mdelete() cmd.mview('reset') frames = duration * 30 cmd.mset(f'1x{frames}') return frames # only load settings if render_type == 'set': return # take a simple picture elif render_type == 'snap': cmd.ray(width=width, height=height) # make a still movie of the whole trajectory elif render_type == 'traj': frames = init_movie() cmd.mview('store', 1, state=1) cmd.sync() states = cmd.count_states() cmd.mview('store', frames, state=states) cmd.sync() cmd.mview('reinterpolate') cmd.sync() # make a movie rotating 360 around the z axis elif render_type == 'bullettime': frames = init_movie() cmd.mview('store', 1) cmd.mview('store', frames) # TODO: moving objects seems a bit hacky. Any better solution? for obj in cmd.get_object_list(): cmd.mview('store', object=obj) cmd.sync() for i in range(4): frame = int(frames * (i + 1) / 4) cmd.frame(frame) cmd.sync() for obj in cmd.get_object_list(): cmd.rotate('z', angle=-90, camera=0, object=obj) cmd.sync() cmd.mview('store', object=obj) cmd.sync() cmd.mview('reinterpolate', object=obj, power=1) cmd.sync() cmd.mview('reinterpolate') cmd.sync() else: raise ValueError( f'{render_type} is not a valid argument. See `help cheese`.') # save if required, otherwise just play it if savefile: if render_type in ( 'traj', 'bullettime', ): cmd.viewport(width, height) movie.produce(f'{savefile}.mp4', mode=mode, encoder='ffmpeg', quality=100) elif render_type in ('snap', ): cmd.png(f'{savefile}.png', dpi=300) cmd.sync() else: if render_type in ( 'traj', 'bullettime', ): cmd.mplay() elif render_type in ('snap', ): pass
def reps(self,cleanup=0): rep_list = [ "lines","sticks","spheres","surface","mesh","dots","ribbon","cartoon" ] try: if not cleanup: cmd.disable() cmd.set("suspend_updates",1,quiet=1) cmd.load("$PYMOL_DATA/demo/pept.pdb","rep1") cmd.alter("rep1///1-5+8-13/","ss='S'") cmd.cartoon("auto") cmd.hide("everything","rep1") for a in range(2,9): cmd.create("rep%d"%a,"rep1") for x, y in enumerate(rep_list, 1): cmd.show(x, "rep%d" % y) cmd.reset() cmd.zoom("rep1",24) util.cbay("rep2") util.cbac("rep3") util.cbas("rep4") util.cbab("rep5") util.cbaw("rep6") util.cbay("rep8") cmd.set("suspend_updates",0,quiet=1) scale=0.5 for b in range(1,20): cmd.set("suspend_updates",0,quiet=1) cmd.refresh() cmd.set("suspend_updates",1,quiet=1) xt=-3.2 yt=1.6 for a in range(1,5): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 yt=-yt xt=-3.2 for a in range(5,9): cmd.translate([xt*scale,yt*scale,0],object="rep%d"%a,camera=0) xt=xt+2 for a in range(1,9): cmd.origin("rep%d"%a,object="rep%d"%a) cmd.mset("1") st = ' '.join(map(lambda x,y:"rotate angle=-3,object=rep%d,axis=%s;"%(x,y),list(range(1,9)), ['x','y','x','y','x','y','x','y'])) cmd.mdo(1,st) cmd.set("suspend_updates",0,quiet=1) cmd.mplay() cgo = [] axes = [[4.5,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]] c = 1 for a in rep_list: ext = cmd.get_extent("rep%d"%c) pos = [(ext[0][0]+ext[1][0])/2, (ext[0][1]+ext[1][1])/2+14, (ext[0][2]+ext[1][2])/2] c = c + 1 pos[0]=pos[0]-(measure_text(plain,a,axes)/2) wire_text(cgo,plain,pos,a,axes) cmd.set("cgo_line_width",1.5) cmd.set("auto_zoom",0) cmd.load_cgo(cgo,'reps') cmd.set("auto_zoom",1) else: cmd.delete("rep*") cmd.mset() cmd.mstop() except: traceback.print_exc()
def show_transition(start_index=0, end_index=0): #show the transition from the current view to the next view global frames global views global cur_index global actions global models if( start_index == 0 and end_index == 0 ): if cur_index >= len(views)-1: print "Current view is last in sequence." return start_index=cur_index end_index=cur_index+1 else: start_index = int(start_index) end_index = int(end_index) ftot = 0 setcommand = "" i = start_index for nframes in frames[start_index:end_index]: #ftot += nframes if models.has_key(i): setcommand += " " + models[i] + " " else: setcommand += " 1 x%i" % nframes i += 1 # cmd.mset("1 x%i" % ftot) cmd.mset( setcommand ) start_frame = 1 #first do all actions that happen up to this point to make sure #things look the way they should first_action = "" for i in range( 0, start_index ): if actions.has_key(i): first_action += actions[i] + ';' #print "Executing %s from actions %d" % (actions[i],i) #cmd.do( actions[i] ) if settings.has_key(i): settingName, selection, startVal, endVal = settings[i] action = "set %s, %f, %s;" % (settingName, endVal, selection) first_action += action #print "Executing %s from settings %d" % (action,i) #cmd.do( action ) if fades.has_key(i): startVisSelection, endVisSelection, sticksOnly = fades[i] action = "set stick_transparency, 0, %s; set stick_transparency, 1, %s;" % (endVisSelection, startVisSelection) first_action += action #print "Executing %s from fades %d" % (action, i) #cmd.do( action ) for i in range( start_index, end_index ): if settings.has_key(i): movs.animate_transition( views[i], views[i+1], frames[i], start_frame, settings[i] ) elif fades.has_key(i): movs.animate_transition( views[i], views[i+1], frames[i], start_frame, fades[i] ) else: movs.animate_transition( views[i], views[i+1], frames[i], start_frame ) #add an action if start_frame == 1: mdo_cmd = first_action if actions.has_key(i): mdo_cmd += actions[i]+";" #mdo_cmd += "set_view("+str(views[i])+")" print mdo_cmd cmd.mdo(start_frame, mdo_cmd) elif actions.has_key(i): mdo_cmd = actions[i]+";set_view("+str(views[i])+")" cmd.mdo(start_frame, mdo_cmd) #print mdo_cmd start_frame += frames[i] cmd.frame(1) cmd.mplay()
def play(): cmd.mplay()