Ejemplo n.º 1
0
	def centeractive(self):
		if self.toggle['view']:
			cmd.set_view(self.toggle['view'])
			self.toggle['view'] = None
		else:
			self.toggle['view'] = cmd.get_view()			
			cmd.center(self.m.rdes.sel())
Ejemplo n.º 2
0
	def orient(self):
		if self.toggle['view']:
			cmd.set_view(self.toggle['view'])
			self.toggle['view'] = None
		else:
			self.toggle['view'] = cmd.get_view()
			cmd.orient(self.d.obj+" or pnt*")
Ejemplo n.º 3
0
    def Quit_Wizard(self):
        
        try:
            General_cmd.unmask_Objects(self.exc)
            cmd.set('mouse_selection_mode', self.selection_mode)

            cmd.delete(self.LigDisplay)
            cmd.refresh()
            
            cmd.deselect()
            
        except:
            pass
      
        if self.ErrorCode > 0:
            self.FlexAID.WizardError = True
        
        self.FlexAID.WizardResult = self.AnchorAtom
        self.FlexAID.ActiveWizard = None
        
        self.queue.put(lambda: self.top.AnchorRunning(False))
        self.queue.put(lambda: self.FlexAID.root.deiconify())
        self.queue.put(lambda: self.FlexAID.root.update())

        cmd.set_wizard()
        cmd.set_view(self.View)
        cmd.refresh()
Ejemplo n.º 4
0
def mysetview(look, up, pos=None, cen=None, ncp=None, fcp=None):
    Xaxis = -look.cross(up).normalized()
    Yaxis = projperp(look, up).normalized()
    Zaxis = -look.normalized()
    oldv = cmd.get_view()
    v = list(oldv)
    r = Mat(Xaxis, Yaxis, Zaxis)
    v[0] = r.xx
    v[1] = r.xy
    v[2] = r.xz
    v[3] = r.yx
    v[4] = r.yy
    v[5] = r.yz
    v[6] = r.zx
    v[7] = r.zy
    v[8] = r.zz
    if pos is not None:
        v[9:12] = pos.x, pos.y, pos.z
    if cen is not None:
        v[12:15] = cen.x, cen.y, cen.z
    if ncp is not None:
        v[15] = ncp
    if fcp is not None:
        v[16] = fcp
    cmd.set_view(v)
    return Yaxis
Ejemplo n.º 5
0
	def revert(self):
		v = cmd.get_view()
		cmd.remove(self.rdes.obj+" and not chain A")
		m = cmd.get_model(self.rdes.obj)
		n = self.oldcrd
		if not n:
			cmd.create("tmp12345",self.rnat.sel())
			cmd.align("tmp12345",self.rdes.sel())
			n = cmd.get_model("tmp12345").atom
			cmd.delete("tmp12345")
		di,ni = 0,0
		while m.atom[di].resi != str(self.rdes.resi): di += 1
		dj = di
		while m.atom[dj].resi == str(self.rdes.resi): dj += 1
		if self.oldcrd: self.oldcrd = None
		else:           self.oldcrd = m.atom[di:dj]
		m.atom = m.atom[:di] + n + m.atom[dj:]
		for i in range(di,di+len(n)):
			m.atom[i].resi  = str(self.rdes.resi)
			m.atom[i].chain = str(self.rdes.chain)
		cmd.load_model(m,self.rdes.obj,1)
		cmd.save("tmp.pdb",self.rdes.obj)
		cmd.delete(self.rdes.obj)
		cmd.load("tmp.pdb",self.rdes.obj,1)
		cmd.show('car',self.rdes.obj)
		cmd.show('lines')		
		redopent(self.rdes.obj)
		cmd.set_view(v)
		print "revert removing "+"".join(self.aas)+" from aas!"
		self.aas = [getaa('A',self.rdes.resi,self.manager.d.obj)]
Ejemplo n.º 6
0
    def Quit_Wizard(self, rv):
        
        try:
            cmd.delete(self.LigDisplay)
            cmd.delete(self.AtomDisplay)         

            cmd.deselect()

            if rv != 1:
                General.unmask_Objects(self.exc)
                cmd.set('mouse_selection_mode', self.selection_mode)
                #cmd.config_mouse('three_button_editing', 1)
      
            if rv > 0:
                self.FlexAID.WizardError = True
        
            self.FlexAID.ActiveWizard = None

            cmd.set_wizard()
            cmd.set_view(self.View)
            cmd.refresh()

            self.top.SATRunning(False)

            self.queue.put(lambda: self.top.AnchorRunning(False))
            self.queue.put(lambda: self.FlexAID.root.deiconify())
            self.queue.put(lambda: self.FlexAID.root.update())

        except:
            pass
Ejemplo n.º 7
0
def q5():
    '''
    DESCRIPTION

    Question 5:  How many axial stacks of helices does 
    the ribozyme have?
    
    The following commands created the scene for "q5": 
    
    delete all;fetch 3zp8, hammer, async=0;show cartoon, hammer;set_view (-0.5,0.18,-0.85,-0.17,-0.98,-0.11,-0.85,0.09,0.52,0.0,0.0,-167.2,-18.45,10.92,-12.11,126.37,208.02,-20.0);rock;

    To reuse of parts or all of the above commands, copy and paste the commands 
    onto the command line or into a plain text file. 
      
    These commands are sufficient for most editing tasks:  
    To edit code, positon cursor on command line with left mouse button.  
    Control-e moves the cursor to the end of the line, even when it is out of view.
    Control-a moves the cursor to the beginning of the line, even when it is out of view.    
    Up arrow key recalls last line of commands for editing.

    These commands may not be available on all systems:
    Shift-control-a selects everything from the right of the cursor to the end of the line.
    Shift-control-e selects everything to the left of the cursor to the end of the line.
    Command-f moves the cursor to the end of the current word.   
    Command-b moves the cursor to the begining of the current word.
    Control-f moves the cursor to the right by one character.   
    Control-b moves the cursor to the left by one character.
    '''
    cmd.reinitialize()
    cmd.fetch('3zp8', type='pdb', name= 'hammer', async='0')
    cmd.show_as('cartoon','hammer')
    cmd.rock()
    cmd.set_view('(-0.5,0.18,-0.85,-0.17,-0.98,-0.11,-0.85,0.09,0.52,0.0,0.0,-167.2,-18.45,10.92,-12.11,126.37,208.02,-20.0);')
    print('Enter "q5" to make the scene for question 5.')
    print('Enter "help q5" to see question 5 and the commands to make the scene.') 
Ejemplo n.º 8
0
def delete_current():
    #remove the current view from the list
    #show the previous view
    global cur_index
    global cur_view
    global views
    global actions
    global scenes
    global settings
    global models
    global frames
    global fades
 
    del views[cur_index]
    del frames[cur_index]
    if actions.has_key( cur_index ):
        del actions[cur_index]
    if scenes.has_key( cur_index ):
        del scenes[cur_index]
    if settings.has_key( cur_index ):
        del settings[cur_index]
 
    #deal with dictionaries
    actions = decKeyAbove( actions, cur_index )
    scenes = decKeyAbove( scenes, cur_index )
    settings = decKeyAbove( settings, cur_index )
    models = decKeyAbove( models, cur_index )                               
    fades = decKeyAbove( fades, cur_index )
 
    print "View number",cur_index,"deleted."
    if cur_index > 0:
        cur_index -= 1
    cur_view = views[cur_index]
    cmd.set_view( cur_view )
    print "Current view is number",cur_index
Ejemplo n.º 9
0
        def save_flip_selections():
            '''Save the user-selected flips to a new PDB object.'''
            o = main.get_object(mpobj.get())
            flipkin = self.flipkin_radio.getvalue()
            reduce_obj = o.pdb['reduce']
            flipkin_obj = o.pdb[flipkin]
            userflips_obj = o.pdb['userflips']
            # Create a new userflips object even if it already exists in case
            # previous selections have been changed.
            v = cmd.get_view()
            cmd.create(userflips_obj, reduce_obj)
            cmd.set_view(v)

            for i, v in enumerate(o.views[flipkin]):
                # If reduce value and user value are different, copy the
                # coordinates from the current flipkin molecule
                if v['reduce_chk_val'].get() != v['user_chk_val'].get():
                    # Do it the hard way, by combining objects.  This is plenty
                    # fast (we typically won't have too many flips to switch)
                    # and doesn't result in atom name mismatch errors for
                    # differently protonated HIS residues the way the
                    # load_coords method does.
                    flipped_sel = '({} and chain {} and resi {})'.format(
                            flipkin_obj, v['chain'], v['resi'])
                    userflips_sel = '({} and not (chain {} and resi {}))'.format(
                            userflips_obj, v['chain'], v['resi'])
                    combined_sel = '{} or {}'.format(
                            userflips_sel, flipped_sel)
                    v = cmd.get_view()
                    cmd.create(userflips_obj, combined_sel)
                    cmd.set_view(v)
                    msg = 'added flip for {} to {}'.format(flipped_sel,
                            userflips_obj)
                    logger.debug(msg)
            o.solo_pdb('userflips')
Ejemplo n.º 10
0
	def load(self):
		self.manager.d = self
		self.manager.m = None
		self.manager.m = None # to also set prevm = None		
		# cmd.delete(self.manager.prevd.obj)
		# cmd.delete(self.manager.prevd.pid)
		# print self.manager.d.obj
		# print self.manager.prevd.obj		
		# sys.exit()
		cmd.delete("all")
		cmd.load(self.getloadname(),self.obj,1)
		cmd.remove(self.obj+" and not chain A")
		cmd.fetch(self.pid)
		cmd.remove("het or hydro")
		cmd.color('gray',self.pid+' and elem C')
		self.scores['rms'] = cmd.align(self.pid,self.obj+" and chain A")[0]
		cmd.hide('ev')
		cmd.show('lines')
		cmd.show("car")
		#cmd.disable(self.pid)
		redopent(self.obj)
		self.recalc_design_pos()
		self.read_data_dir('avg_deg')
		self.read_data_dir('ddG')
		self.read_data_dir('rot_boltz')
		self.read_bup()
		self.read_tot_scores()
		self.read_res_scores()
		cmd.orient(self.obj+" or pnt*")
		self.manager.m = self.remembermm
		if self.manager.m: self.manager.m.focus()
		if self.remembermv: cmd.set_view(self.remembermv)
Ejemplo n.º 11
0
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()
Ejemplo n.º 12
0
    def Quit_Wizard(self):

        try:
            # Delete Sphere object
            General_cmd.unmask_Objects(self.exc)
            cmd.config_mouse(self.config_mouse)

            cmd.delete(self.SphereDisplay)
            cmd.refresh()
        except:
            pass

        # Catch error in App
        if self.ErrorCode > 0:
            self.App.WizardError = True

        # Re-enable controls
        
        self.App.ActiveWizard = None

        cmd.set_wizard()
        cmd.set_view(self.View)
        cmd.refresh()
                
        self.queue.put(lambda: self.top.SphereRunning(False))
        self.queue.put(lambda: self.top.top.root.deiconify())
        self.queue.put(lambda: self.top.top.root.update())
Ejemplo n.º 13
0
def transform_by_camera_rotation():
     view = list(cmd.get_view())
     M = view[0:3] + [-view[12]] + \
         view[3:6] + [-view[13]] + \
         view[6:9] + [-view[14]] + \
         view[12:15] + [1.]
     cmd.transform_selection('(all)', M, transpose=1)
     cmd.set_view([1,0,0,0,1,0,0,0,1] + view[9:])
Ejemplo n.º 14
0
def mkhelix(sel, t, r, n):
    v = cmd.get_view()
    for i in range(1, n):
        cmd.delete("h%i" % i)
        cmd.create("h%i" % i, sel)
        rot("h%i" % i, Vec(0, 0, 1), i * r, Vec(0, 0, 0))
        trans("h%i" % i, Vec(0, 0, i * t))
    cmd.set_view(v)
Ejemplo n.º 15
0
def mki213(N, sel = 'all'):
	v = cmd.get_view()
	cmd.delete("i213_*")
	cmd.delete('base80345769083457')
	cmd.delete('tmp80345769083457')
	c2 = com(sel)
	c3 = Vec(0, 0, 0)
	cmd.create( 'tmp80345769083457', sel)
	a2 = c2axis('tmp80345769083457')
	cmd.delete( 'tmp80345769083457')
	a3 = Vec(0, 0, 1)
	cmd.create('base80345769083457', sel+" and chain A and visible")
	seenit = []
	R2 = [rotation_matrix(a2, 0), rotation_matrix(a2, 180), ]
	R3 = [rotation_matrix(a3, 0), rotation_matrix(a3, 120), rotation_matrix(a3, 240), ]
	C = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	print a2, c2, a3, c3
	for i21 in range(2):
		for i32 in range(3 if N > 1 else 1):
			for i22 in range(2 if N > 2 else 1):
				for i33 in range(3 if N > 3 else 1):
					for i23 in range(2 if N > 4 else 1):
						for i34 in range(3 if N > 5 else 1):
							for i24 in range(2 if N > 6 else 1):
								for i35 in range(3 if N > 7 else 1):
									for i25 in range(2 if N > 8 else 1):
										test = Vec(0, 0, 0)
										test = R2[i21]*(test-c2)+c2
										test = R3[i32]*(test-c3)+c3
										test = R2[i22]*(test-c2)+c2
										test = R3[i33]*(test-c3)+c3
										test = R2[i23]*(test-c2)+c2
										test = R3[i34]*(test-c3)+c3
										test = R2[i24]*(test-c2)+c2
										test = R3[i35]*(test-c3)+c3
										test = R2[i25]*(test-c2)+c2
										#print test
										seen = False
										for xs in seenit:
											if (xs-test).length() < 0.1:
												seen = True
												break
										if seen: continue
										else: seenit.append(test)
										n = "i213_%i%i%i%i%i%i%i%i%i"%(i25, i35, i24, i34, i23, i33, i22, i32, i21)
										cmd.create(n, 'base80345769083457 and name n+ca+c')
										rot(n, a2, i21*180.0, c2)
										rot(n, a3, i32*120.0, c3)
										rot(n, a2, i22*180.0, c2)
										rot(n, a3, i33*120.0, c3)
										rot(n, a2, i23*180.0, c2)
										rot(n, a3, i34*120.0, c3)
										rot(n, a2, i24*180.0, c2)
										rot(n, a3, i35*120.0, c3)
										rot(n, a2, i25*180.0, c2)
	print len(seenit)
	cmd.delete('base80345769083457')
	cmd.set_view(v)
Ejemplo n.º 16
0
 def _load_default_scene(self):
     cmd.load('viewing-ref/ref.pse')
     cmd.set_view((
         1.0,    0.0,    0.0,
         0.0,    1.0,    0.0,
         0.0,    0.0,    1.0,
         0.0,    0.0,  -43.0,
         2.6,   -1.9,    0.0,
        36.4,   49.6,  -20.0))
Ejemplo n.º 17
0
def show_cur():
    global cur_index
    global cur_view
    global views
    cur_view = views[ cur_index ]
    cmd.set_view(cur_view)
    print "Matrix: "
    print_view( cur_view )
    print "Showing view number ",cur_index
Ejemplo n.º 18
0
def probe_object(obj):
    '''Run Probe on the "Reduce-d" coordinates of a loaded PyMOL object.

    ARGUMENTS

        obj (str)

            Name of a loaded PyMOL object that has already been passed as an
            argument to `reduce_object()` (or `reduce_obj` from the PyMOL
            command line).

    NOTE

        Reduce_object() must be run prior to probe_object() in order to set up
        an MPObject instance in the `objects` dictionary.  Running
        probe_object() on a plain PyMOL object will fail.  Also, accordingly,
        keep in mind that the coordinates probe_object() uses are those of the
        Reduce-modified version.  For an object `myobj`, this will typically
        be `mp_myobj.myobj_reduce`.

    '''


    o = get_object(obj)

    # Clear previous results
    cmd.delete(o.pdb['probe'])  # coords
    cmd.delete(o.get_kin_cgo_group('probe'))  # cgo

    # Create the PDB to use with the 'probe' kinemage
    if o.pdb['userflips'] in cmd.get_names():
        which = 'userflips'
    else:
        which = 'reduce'
    v = cmd.get_view()
    cmd.create(o.pdb['probe'], o.pdb[which])
    cmd.set_view(v)

    pdbstr = o.get_pdbstr('probe')
    output = generate_probe_output(pdbstr)

    # Fail gracefully if probe call returns no output.
    if not output:
        msg = 'Failed to generate Probe output for {}.'.format(obj)
        logger.error(msg)
        return

    logger.info("Generated Probe output for '{}'.".format(obj))

    # Store list of dots and vectors
    o.kin['probe'] = process_probe_output(output)

    # Draw dots and vectors
    o.draw('probe')
    cmd.set_view(v)
Ejemplo n.º 19
0
def show_next():
    global cur_index
    global cur_view
    global views
    if( cur_index == len( views )-1 ):
        print "No more views."
        return
    cur_index += 1
    cur_view = views[ cur_index ]
    cmd.set_view(cur_view)
    print "Matrix: "
    print_view( cur_view )
    print "Showing view number ",cur_index
Ejemplo n.º 20
0
def show_prev():
    global cur_index
    global cur_view
    global views
    if( cur_index == 0 ):
        print "No more views."
        return
    cur_index -= 1
    cur_view = views[ cur_index ]
    cmd.set_view(cur_view)
    print "Matrix: "
    print_view( cur_view )
    print "Showing view number ",cur_index
Ejemplo n.º 21
0
	def focus(self):
		self.manager.m = self
		if self.manager.prevm: cmd.hide('sticks',self.manager.prevm.rdes.sel())
		if self.manager.prevm: cmd.color('green',self.manager.prevm.rdes.sel()+" and elem C")
		fr = self.rnat.obj+" and name n+ca+c and resi %i-%i"%(self.rnat.resi-10,self.rnat.resi+10)		
		to = self.rdes.obj+" and name n+ca+c and resi %i-%i"%(self.rdes.resi-10,self.rdes.resi+10)
		cmd.align(fr,to)
		cmd.show('sticks',self.rdes.sel())
		cmd.color('white',self.rdes.sel()+" and elem C")
		cmd.center(self.rdes.sel())
		v = list(cmd.get_view())
		v[11] = -80.0
		cmd.set_view(tuple(v))
		cmd.clip('slab',50,self.rdes.sel())
Ejemplo n.º 22
0
def go_to_view( arg=0 ):
    global cur_index
    global cur_view
    global views
    n = int( arg )
    if n < 0 or n > len(views)-1:
        print "Index out of range."
        return
    cur_index = n
    cur_view = views[n]
    cmd.set_view( cur_view )
    print "Matrix: "
    print_view( cur_view )
    print "Showing view number ", cur_index
Ejemplo n.º 23
0
def frame_scaler():
    previous_frame = None
    while True:
        frame = (yield)
        if previous_frame and frame and frame.scale_probability(previous_frame) > 0.2:
            scale_factor = frame.scale_factor(previous_frame)
            if scale_factor != 1.0:
                view = list(cmd.get_view())
                delta_z = math.log(scale_factor) * 100.0
                view[11] += delta_z
                view[15] -= delta_z
                view[16] -= delta_z
                cmd.set_view(view)
        previous_frame = frame
Ejemplo n.º 24
0
def Rotate( angleX, angleY):
	#if not CheckMaster(controller):
	#	return
	currtime = time.clock()
	global lastmovetime
	#Slowdown code vvv - don't use for right now
	if ((currtime - lastmovetime) < .01):
	        #print "derp"
		return
	view = list(cmd.get_view())
	view = rotateView(view, angleX/20, angleY/20, 0)
	cmd.set_view(view)
	#DamageGUI()
	cmd.refresh()
	lastmovetime = time.clock()
Ejemplo n.º 25
0
def hand_rotator():
    previous_frame = None
    while True:
        hand = (yield)
        if previous_frame and hand and hand.rotation_probability(previous_frame) > 0.1:
            view = list(cmd.get_view())
            matrix = hand.rotation_matrix(previous_frame)
            matrix *= Leap.Matrix(Leap.Vector(*view[0:3]),
                                  Leap.Vector(*view[3:6]),
                                  Leap.Vector(*view[6:9]))
            view[:9] = matrix.to_array_3x3()
            cmd.set_view(view)
        if hand:
            previous_frame = hand.frame
        else:
            previous_frame = None
Ejemplo n.º 26
0
def getnative():
    v = cmd.get_view()
    nats = []
    for obj in cmd.get_object_list():
        if len(obj) == 4:
            nats.append(obj)
            continue
        pid = obj[:4]
        if pid in nats:
            continue
        print "fetching native", pid
        cmd.fetch(pid)
        cmd.remove(pid + " and not chain A")
        cmd.remove(pid + " and resn HOH")
        cmd.align(pid, obj)
    cmd.set_view(v)
Ejemplo n.º 27
0
def redoA(sel="not sub", N=None):
    cmd.delete("sub*")
    cmd.hide("ev", sel + " and not chain A")
    v = cmd.get_view()
    chains = list(set(a.chain for a in cmd.get_model("name ca").atom))
    chains.sort()
    if N:
        chains = chains[:N]
    for c in chains:
        if c == "A":
            continue
        cmd.create("sub" + c, sel + " and chain A")
        cmd.align("sub" + c, sel + " and chain " + c)
        cmd.alter("sub" + c, "chain = '%s'" % c)
    color_by_chain()
    cmd.set_view(v)
    print charge(sel + " and chain A")
Ejemplo n.º 28
0
def compute_viewpoint_entropy(features, view, width, height, keepFile=''):
    
    cmd.set_view(view)

#    apply_false_color_settings()
    tmpFile = render_false_color_image(width, height, keepFile)

    e = 0.0
    if os.path.isfile(tmpFile):
        img = Image.open(tmpFile)
        e = image_entropy(img)
        # normalize by number of features
        e /= log(features + 1, 2)

        if not len(keepFile):
            os.remove(tmpFile)

    return e
Ejemplo n.º 29
0
def q6():
    '''
    DESCRIPTION

    Question 6:  What is the average distance of the Na1044
    ligand bonds? Give the residue numbers of the RNA
    nucleotides and the sodium to identify them. How many
    ligands are from RNA?
   
    The following commands created the scene for "q6":
     
    delete all;fetch 3zp8, hammer, async=0; rock;preset.ball_and_stick("all");distance ligand1, i. 1044, c. A and i. 22 and n. N7;distance ligand2, i. 1044, c. A and i. 21 and n. OP2;distance ligand3, i. 1044, i. 2121;distance ligand4, i. 1044, i. 2120;distance ligand5, i. 1044, i. 2122;distance ligand6, i. 1044, i. 2130;set_view (-0.87,0.18,-0.46,-0.39,-0.81,0.44,-0.29,0.56,0.78,-0.0,0.0,-20.47,-18.05,14.02,-18.89,17.47,23.47,-20.0);

    To reuse of parts or all of the above commands, copy and paste the commands 
    onto the command line or into a plain text file. 
      
    These commands are sufficient for most editing tasks:  
    To edit code, positon cursor on command line with left mouse button.  
    Control-e moves the cursor to the end of the line, even when it is out of view.
    Control-a moves the cursor to the beginning of the line, even when it is out of view.    
    Up arrow key recalls last line of commands for editing.

    These commands may not be available on all systems:
    Shift-control-a selects everything from the right of the cursor to the end of the line.
    Shift-control-e selects everything to the left of the cursor to the end of the line.
    Command-f moves the cursor to the end of the current word.   
    Command-b moves the cursor to the begining of the current word.
    Control-f moves the cursor to the right by one character.   
    Control-b moves the cursor to the left by one character.
    '''
    cmd.reinitialize()
    cmd.fetch('3zp8', type='pdb', name= 'hammer', async='0')
    cmd.rock()
    cmd.do('preset.ball_and_stick("all")')
    cmd.distance('Sodiumligand1',' resi 1044', 'chain A and i. 22 and n. N7')
    cmd.distance('Sodiumligand2', 'resi 1044', 'chain A and i. 21 and n. OP2')
    cmd.distance('Sodiumligand3', 'resi 1044', 'resi 2121')
    cmd.distance('Sodiumligand4', 'resi 1044', 'resi 2120')
    cmd.distance('Sodiumligand5', 'resi 1044', 'resi 2122')
    cmd.distance('Sodiumligand6', 'resi 1044', 'resi 2130')
    cmd.do('set label_size, -0.4')
    cmd.set_view('(-0.87,0.18,-0.46,-0.39,-0.81,0.44,-0.29,0.56,0.78,-0.0,0.0,-20.47,-18.05,14.02,-18.89,17.47,23.47,-20.0);')   
    print('Enter "q6" to make the scene for question 6.')
    print('Enter "help q6" to see question 6 and the commands to make the scene.') 
Ejemplo n.º 30
0
 def roving_density(self,cleanup=0):
     if not cleanup:
         try:
             cmd.load("$PYMOL_DATA/demo/il2.pdb")
             cmd.set("suspend_updates",1,quiet=1)
             cmd.remove("hydro")
             cmd.disable()
             cmd.enable("il2")
             cmd.map_new("map","gaussian","0.75","il2")
             cmd.feedback("disable","objectmesh","actions")
             cmd.set("ribbon_color","purple","il2")
             cmd.set("roving_detail",1)
             cmd.set("roving_origin",1)
             cmd.set("stick_radius",0.12,"il2")
             cmd.set("roving_sticks",0)
             cmd.set("roving_polar_contacts",0)
             cmd.set("line_width","3")
             cmd.set("roving_map1_name","map")
             cmd.isomesh("rov_m1","map",9999.0,"il2")
             cmd.color("density","rov_m1")
             
             cmd.set_view ((\
       0.132852688,   -0.729740858,    0.670686543,\
       -0.228543565,    0.635894477,    0.737154961,\
       -0.964425683,   -0.251212329,   -0.082298420,\
       0.000062190,    0.000183226,  -58.861488342,\
       13.349151611,   -1.565427899,   22.383148193,\
       55.259441376,   63.259449005,    0.000000000 ))
         finally:
             cmd.set("suspend_updates",0,quiet=1)
         cmd.refresh()
     else:
         cmd.set("roving_detail",0)
         cmd.set("roving_map1_name","")
         cmd.set("roving_polar_contacts",7)
         cmd.set("roving_sticks",6)
         cmd.delete("il2")
         cmd.delete("map")
         cmd.set("line_width",1.5)
         cmd.refresh()
         cmd.set("roving_detail",0)
         cmd.delete("rov_*")
         cmd.sync()
Ejemplo n.º 31
0
    def execute(self, result):
        if result == 'Show starting point':
            choice = int(self.var.get())
            if (choice == 0):
                startpoint = self.computecenter(self.selectionlist.getvalue())
                self.xlocvar.set(float("%.2f" % (startpoint[0])))
                self.ylocvar.set(float("%.2f" % (startpoint[1])))
                self.zlocvar.set(float("%.2f" % (startpoint[2])))
                self.var.set(1)
            else:
                if (choice == 1):
                    startpoint = (float(self.xlocvar.get()),
                                  float(self.ylocvar.get()),
                                  float(self.zlocvar.get()))
            cmd.delete("crisscross")

            self.crisscross(startpoint[0], startpoint[1], startpoint[2], 0.5,
                            "crisscross")
            return

        if result == 'Run MOLE':
            if self.checkInput(False) == False:
                return

#           self.exportvdw(self.selection.getvalue())
            choice = int(self.var.get())
            if (choice == 0):
                startpoint = self.computecenter(self.selectionlist.getvalue())
            else:
                if (choice == 1):
                    startpoint = (float(self.xlocvar.get()),
                                  float(self.ylocvar.get()),
                                  float(self.zlocvar.get()))

            print("Starting point of MOLE: %f %f %f\n" % startpoint)
            cmd.delete("crisscross")

            self.crisscross(startpoint[0], startpoint[1], startpoint[2], 0.5,
                            "crisscross")

            self.deleteTemporaryFiles()
            outdir = self.pymol_outdir.getvalue()

            for i in range(1, int(self.numbertunnels.getvalue()) + 1):
                pathpy = os.path.join(outdir, "found_001_%03d.py" % i)
                self.deleteFileIfExist(pathpy)
                cmd.delete("tunnel%03d" % i)
# Now, prepare files for MOLE
            self.prepareinput(self.selection.getvalue(), startpoint)
            tmppdb = os.path.join(outdir, "tmp.pdb")
            mole_stdout = os.path.join(outdir, "mole.stdout")
            mole_stderr = os.path.join(outdir, "mole.stderr")
            if sys.platform.startswith('win'):
                command = '%s --fi pdb --input "%s" --numinterp %d --activesiteradius %f --noclustering --selection "all" --outdir "%s" --vmd --pymol --numtun %d --x %f --y %f --z %f >"%s" 2>"%s"' % (
                    self.binlocation.getvalue(), tmppdb,
                    int(self.pymol_numinterp.getvalue()),
                    float(self.pymol_activesiteradius.getvalue()),
                    self.pymol_outdir.getvalue(),
                    int(self.numbertunnels.getvalue()), startpoint[0],
                    startpoint[1], startpoint[2], mole_stdout, mole_stderr)
                print('\nRunning command:', command)
                status = subprocess.call(command)
            else:
                #command = [self.binlocation.getvalue(),'--fi','pdb','--input',tmppdb,'--numinterp',str(int(self.pymol_numinterp.getvalue())),'--activesiteradius',str(float(self.pymol_activesiteradius.getvalue())),'--noclustering','--selection','all','--outdir',self.pymol_outdir.getvalue(),'--vmd','--pymol','--numtun',str(int(self.numbertunnels.getvalue())),'--x',str(startpoint[0]),'--y',str(startpoint[1]),'--z',str(startpoint[2])]
                # print '\nRunning command:',command
                # print '\n pyenv is:', pymol_env
                #callfunc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=pymol_env)
                #child_stdout, child_stderr = callfunc.communicate()
                # callfunc.wait()
                #status= callfunc.returncode
                # print(child_stdout)
                # print(child_stderr)

                #command = '%s --fi pdb --input "%s" --numinterp %d --activesiteradius %f --noclustering --selection "all" --outdir "%s" --vmd --pymol --numtun %d --x %f --y %f --z %f >"%s" 2>"%s"'  % (self.binlocation.getvalue(),tmppdb,int(self.pymol_numinterp.getvalue()),float(self.pymol_activesiteradius.getvalue()),self.pymol_outdir.getvalue(),int(self.numbertunnels.getvalue()),startpoint[0],startpoint[1],startpoint[2],mole_stdout, mole_stderr);
                command = '%s --fi pdb --input %s --numinterp %d --activesiteradius %f --noclustering --selection "all" --outdir %s --vmd --pymol --numtun %d --x %f --y %f --z %f' % (
                    self.binlocation.getvalue(), tmppdb,
                    int(self.pymol_numinterp.getvalue()),
                    float(self.pymol_activesiteradius.getvalue()),
                    self.pymol_outdir.getvalue(),
                    int(self.numbertunnels.getvalue()), startpoint[0],
                    startpoint[1], startpoint[2])
                print('\nRunning command:', command)
                status = subprocess.call(command, shell=True)
            print("Result from execution was: %s" % status)
            view = cmd.get_view()
            for i in range(1, int(self.numbertunnels.getvalue()) + 1):
                pathpy = os.path.join(outdir, "found_001_%03d.py" % i)
                if os.access(pathpy, os.F_OK):
                    cmd.do("run %s" % pathpy)
                    # execfile(pathpy)
                    #callfunc = subprocess.Popen(pathpy, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=pymol_env)
                    # pymol.finish_launching()
                    #child_stdout, child_stderr = callfunc.communicate()
                    #result = callfunc.returncode
                    #print("Result from execution: %s"%result)
                    # print(child_stdout)
                    # print(child_stderr)
                else:
                    print("Error: Tunnel number %d wasn't found by MOLE." % i)
                    if sys.platform.startswith('win'):
                        print("Did you set your variables??")
                        print("PATH = PATH + ;%s" % qhull_dir)
                        print("MOLEDIR = %s" % mole_dir)
                    else:
                        print("Did you set your variables??")
                        print("PATH=$PATH:%s" % qhull_dir)
                        print("export PATH")
                        print("MOLEDIR=%s" % mole_dir)
                        print("export MOLEDIR")
            cmd.set_view(view)
            pass

#	    self.deleteTemporaryFiles()
        else:
            #
            # Doing it this way takes care of clicking on the x in the top of the
            # window, which as result set to None.
            #
            if __name__ == '__main__':
                #
                # dies with traceback, but who cares
                #
                self.parent.destroy()
            else:
                # self.dialog.deactivate(result)
                global MOLE_BINARY_LOCATION
                MOLE_BINARY_LOCATION = self.binlocation.getvalue()
                self.dialog.withdraw()
Ejemplo n.º 32
0
    from dump import dump
    from pdbfile import pdbfile
    from pymol import cmd as pm

    d = dump("tmp.dump", 0)
    p = pdbfile(d)
    d.next()
    d.unscale()
    p.single(ntimestep)
    pm.load("tmp.pdb")
    pm.show("spheres", "tmp")
    #pm.zoom()
    pm.set_view("(\
     1.000000000,    0.000000000,    0.000000000,\
     0.000000000,    1.000000000,    0.000000000,\
     0.000000000,    0.000000000,    1.000000000,\
     0.000000000,    0.000000000,  -30.770051956,\
     5.363590240,    4.751065731,    0.000000000,\
    24.259342194,   37.280761719,  -20.000000000 )")
# display GUI with run/stop buttons and slider for temperature

if me == 0:
    from Tkinter import *
    tkroot = Tk()
    tkroot.withdraw()
    root = Toplevel(tkroot)
    root.title("LAMMPS GUI")

    frame = Frame(root)
    Button(frame, text="Run", command=run).pack(side=LEFT)
    Button(frame, text="Stop", command=stop).pack(side=LEFT)
Ejemplo n.º 33
0
from pymol.cgo import *
from pymol import cmd

cmd.set("cartoon_fancy_helices", 1)
cmd.set("cartoon_transparency", 0.5)
cmd.set("sphere_transparency", 0.7)
cmd.set("ray_trace_mode", 0)
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0.9)
cmd.set("ambient", 0.1)
cmd.set('''ray_opaque_background''', '''off''')

cmd.load("4xcp_hv.pdb")
cmd.color("chocolate", "4xcp_hv")
cmd.load("lig_hv_cavity_1.pdb")
cmd.color("salmon", "lig_hv_cavity_1")

cmd.set_view (\
  '''0.456030250,    0.888168931,    0.056359597,\
    -0.276825786,    0.081376061,    0.957462490,\
     0.845804632,   -0.452238709,    0.282975733,\
    -0.000969257,   -0.000390973, -118.043930054,\
    33.933498383,   32.315837860,   33.869487762,\
    83.247825623,  152.777328491,  -20.000000000''')

cmd.png("dynamics_lig_hv.png", width=500, height=400, dpi=100, ray=1)

cmd.quit()
Ejemplo n.º 34
0
def set_view(view, center, trans, volume, persp):
    '''
    view is their 4x4

    center is the centor of rotation in tranformed coordinates
    
    '''
    view = list(view)
    
    # print view[0:4]
    # print view[4:8]
    # print view[8:12]
    # print view[12:16]
    # print "\nmaestro_center: %8.3f %8.3f %8.3f"%tuple(center)
    # print "maestro_transl: %8.3f %8.3f %8.3f"%tuple(trans)

    mat = [ view[0:3], view[4:7], view[8:11] ]
    tmp = cpv.sub(center,view[12:15])
    pymol_center = cpv.transform(mat,tmp)
    
    # print "volumeX: %8.3f %8.3f"%(tuple(volume[0:2]))
    # print "volumeY: %8.3f %8.3f"%(tuple(volume[2:4]))
    # print "volumeZ: %8.3f %8.3f"%(tuple(volume[4:6]))

    # print "pymol_center: %8.3f %8.3f %8.3f"%tuple(pymol_center)

    # print persp
    if persp<0.0:
        pymol_ortho = 1.0
    else:
        pymol_ortho = 0.0

    if pymol_ortho==0.0:
        fov = 1 + 100*(persp - 1.0)/3.0
        cmd.set('field_of_view',fov)

    fov = (math.pi * float(cmd.get("field_of_view")) / 180.0)

    # unclear why we have to multiple by 1.17 to get the correct look
        
    camera_dist = 1.17 * (abs(volume[2] - volume[3])/2.0)/math.atan(fov/2.0)

    vol_center = [ (volume[0]+volume[1])/2.0,
                   (volume[2]+volume[3])/2.0,
                   (volume[4]+volume[5])/2.0 ]
    
    pymol_objective = [ trans[0] + center[0] - vol_center[0],
                        trans[1] + center[1] - vol_center[1],
                        -camera_dist ]
    
    # print "pymol_objective: %8.3f %8.3f %8.3f"%tuple(pymol_objective)

    pymol_front = center[2] + trans[2] - volume[4] - pymol_objective[2] 
    pymol_back  = center[2] + trans[2] - volume[5] - pymol_objective[2] 

    pymol_view = cmd.get_view()
    cur_view = ( view[0:3] + view[4:7] + view[8:11] +
                 pymol_objective + pymol_center +
                 [ pymol_front, pymol_back, pymol_ortho ] )

    # print cur_view

    cmd.set_view(tuple(cur_view))
Ejemplo n.º 35
0
cmd.alter('resi 752', 'b = 0.4032838548790168')
cmd.alter('resi 753', 'b = 3.905262313371594')
cmd.alter('resi 754', 'b = 2.541607835747872')
cmd.alter('resi 755', 'b = 2.527711014426134')
cmd.alter('resi 756', 'b = 6.500142836511759')
cmd.alter('resi 757', 'b = 8.246433092584747')
cmd.alter('resi 758', 'b = 5.813695418386327')
cmd.alter('resi 759', 'b = 5.238690662506715')

cmd.spectrum('b', 'white_red', 'S009')

###### SETVIEW
cmd.set_view('\
    -0.939411342,    0.224696293,    0.258875728,\
    -0.052751519,    0.651441693,   -0.756858826,\
    -0.338706851,   -0.724658728,   -0.600119412,\
     0.001423955,    0.000171021, -431.928985596,\
  1068.603637695,  -18.134885788,  381.554992676,\
   355.507598877,  508.442962646,  -20.000000000 ')

###### POSTAMBLE

cmd.select(None)
cmd.set('specular', "off")
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}_y.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.rotate('x', angle=90)
Ejemplo n.º 36
0
def animate_transition(start_view,
                       end_view,
                       nframes,
                       first_frame,
                       settings=[]):
    #print "Views"
    #print start_view,'\n',end_view

    cview = start_view[:]
    cmd.set_view(start_view)

    #get initial and final quaternions for interpolation
    #print start_view[0:9]
    #get quaternions
    qstart = rmat2quat(start_view[0:9])
    qend = rmat2quat(end_view[0:9])

    #test for long way vs. short way
    if quatdotprod(qstart, qend) < 0:
        qstart = [-q for q in qstart]

    axan_start = quat2axisangle(qstart)
    axan_end = quat2axisangle(qend)

    axan_cur = axan_start[:]
    frame_start = first_frame
    frame_end = frame_start + nframes
    doFade = 0
    doSetting = 0
    if len(settings) == 4:
        settingName, selection, startVal, endVal = settings
        settingStep = (endVal - startVal) / float(nframes)
        print "Setting step ", settingStep
        doSetting = 1
    elif len(settings) == 3:
        startVisSelection, endVisSelection, sticksOnly = settings
        settingStep = 1.0 / float(nframes)
        doFade = 1
    for f in range(frame_start, frame_end):
        #get rotmat
        #using angle axis

        for i in range(4):
            axan_cur[i] = axan_cur[i] + (axan_end[i] - axan_start[i]) / nframes
        newmat = axisangle2rmat(axan_cur)
        #print cview
        for i in range(9):
            cview[i] = newmat[i]

        mdo_cmd = "set_view (["
        for i in range(18):
            if i > 8:
                cview[i] = cview[i] + (end_view[i] - start_view[i]) / nframes
            mdo_cmd += "%12.7f," % cview[i]
        mdo_cmd = mdo_cmd[:-1] + "])"
        if doSetting:
            val = float(f - frame_start) * settingStep + startVal
            print val
            mdo_cmd += "; set %s, %f, %s" % (settingName, val, selection)
            print mdo_cmd
        #print "mdo ", mdo_cmd
        if doFade:
            val = float(f - frame_start) * settingStep
            otherVal = 1.0 - val
            mdo_cmd += "; set stick_transparency, %f, %s; set stick_transparency, %f, %s" % (
                val, startVisSelection, otherVal, endVisSelection)
            if not sticksOnly:
                #comment out surface transparency interpolation due to problem with transparent sticks in front of
                #transparent surfaces (get black holes)
                # mdo_cmd += "; set transparency, %f, %s; set transparency, %f, %s" % ( val, startVisSelection, otherVal, endVisSelection )
                mdo_cmd += "; set cartoon_transparency, %f, %s; set cartoon_transparency, %f, %s" % (
                    val, startVisSelection, otherVal, endVisSelection)
        cmd.mdo(f, mdo_cmd)
Ejemplo n.º 37
0
AXES = ['x', 'y', 'z']

GENE = '5f3b'
NUM_IMAGES = 12

# Fetch the gene from PDB
cmd.fetch(GENE, quiet=0)

# Clean Up gene representation
cmd.show("cartoon")
cmd.hide("lines")
cmd.set_view ([
    -0.090915471,   -0.583907545,    0.806714714,\
    -0.680931926,    0.627556562,    0.377493620,\
    -0.726678491,   -0.514997303,   -0.454657555,\
     0.000238538,    0.000451565, -545.061767578,\
  -100.496780396,   -9.033477783,   97.704284668,\
   -20.180725098, 1110.239257812,  -20.000000000 ])

for i in range(NUM_IMAGES):
    SITE = floor(rand() * 200)
    AXIS = AXES[floor(rand() * (len(AXES) - 1))]
    DEG = floor(10 + rand() * 38)

    if (AXIS == 'y'):
        DEG %= 15

    color_index = floor(rand() * (len(COLORS) - 1))
    color1 = COLORS[color_index][0]
    color2 = COLORS[color_index][1]
Ejemplo n.º 38
0
from pymol import cmd
cmd.bg_color('white')
cmd.select('drg', 'all')

cmd.set('valence', '1')
cmd.set_bond('stick_radius', '0.14', 'drg', 'drg')
cmd.set('sphere_scale', '0.25', 'drg')
cmd.show('sticks', 'drg')
cmd.show('spheres', 'drg')
cmd.set_view ([0.987891138,   -0.139472052,   -0.067891687,
  0.152521998,    0.793636620,    0.588958621,
 -0.028259384,   -0.592185259,    0.805302858,
  0.000017954,    0.000006792,  -52.386489868,
 -1.638074398,   -1.409737468,   -0.143483341,
-34.060420990,  138.833740234,   20.000000000])

charges = ["-0.103" ," 0.115" ," 0.016" ,"-0.082" ," 0.068" ,"-0.022" ,"-0.017" ," 0.017" ,"-0.001" ,"-0.051" ," 0.120" ,"-0.186" ," 0.163" ,"-0.115" ," 0.216" ,"-0.142" ," 0.130" ,"-0.294" ," 0.114" ,"-0.004" ," 0.102" ,"-0.098" ,"-0.004" ," 0.102" ,"-0.294" ," 0.114" ," 0.882" ,"-0.582" ,"-0.582" ,"-0.582"]
cmd.set('label_size', '22')
cmd.set('label_position', (0, 2, 2))
for i, charge in zip(range(1, 31), charges):
    cmd.label('id %s' % i, charge)

# output
cmd.set('antialias', '2')
cmd.set('direct', '0.6')
cmd.set('orthoscopic', 'on')
cmd.set('ray_trace_frames', '1')
#cmd.ray(renderer=-1)
#cmd.png('~/Downloads/charge.png', dpi=600)

Ejemplo n.º 39
0
        183, 698, 701, 190, 69, 82, 355, 627
]:
    cmd.color('red', 'resi {0} and S009'.format(r))
    cmd.show('spheres', 'resi {{0}} and S009'.format(r))

# knownAdaptiveAndTopA549
for r in [9, 684, 627, 701, 158]:
    cmd.color('magenta', 'resi {0} and S009'.format(r))
    cmd.show('spheres', 'resi {{0}} and S009'.format(r))

###### SETVIEW

cmd.set_view('\
    -0.632510662,   -0.737213850,   -0.237579703,\
     0.506035805,   -0.161099315,   -0.847335100,\
     0.586391509,   -0.656170785,    0.474955797,\
    -0.000148103,    0.000024185, -318.995605469,\
   -34.610126495,   13.929591179,   32.111713409,\
   251.499099731,  386.493469238,  -20.000000000 ')

###### POSTAMBLE

cmd.select(None)
cmd.set('specular', "off")
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}_y.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.rotate('x', angle=90)
Ejemplo n.º 40
0
cmd.set("ray_trace_mode", 0)
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0.9)
cmd.set("ambient", 0.1)
cmd.set('''ray_opaque_background''', '''off''')

cmd.load("fix_1xdx_13.pdb")
cmd.color("chocolate", "fix_1xdx_13")

cmd.load("cav_acb.pdb")
cmd.color("density", "cav_acb")
cmd.load("cav_adb.pdb")
cmd.color("density", "cav_adb")

cmd.load("ch_acb.pdb")
cmd.color("forest", "ch_acb")
cmd.load("ch_adb.pdb")
cmd.color("forest", "ch_adb")

cmd.show("spheres", "cav_a*")

cmd.set_view (\
     '''0.985927403,   -0.158083513,   -0.054349255,\
    -0.080049716,   -0.161061883,   -0.983692348,\
     0.146753371,    0.974201024,   -0.171448186,\
    -0.000008035,   -0.000002392, -104.634948730,\
     2.583818913,    5.617665291,   -4.377417088,\
   -46.898918152,  256.167358398,  -20.000000000''')

cmd.png("1xdx_cav.png", width=600, height=400, dpi=600, ray=1)
Ejemplo n.º 41
0
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0.9)
cmd.set("ambient", 0.1)
cmd.set('''ray_opaque_background''', '''off''')

cmd.load("1xkk.pdb")
cmd.load("disp_1xkk.pdb")
cmd.load("modevectors.py")
rgb = ".8, .2, .2"
modevectors("1xkk",
            "disp_1xkk",
            outname="disp_1xkk_porky",
            head=0.5,
            tail=0.3,
            headrgb=rgb,
            tailrgb=rgb,
            cutoff=3.0)
cmd.delete("disp_1xkk")

cmd.color("slate", "1xkk")

cmd.set_view (\
     '''0.800493002,    0.201568723,   -0.564429343,\
     0.392988801,   -0.887567461,    0.240382716,\
    -0.452515632,   -0.414239049,   -0.789706230,\
    -0.000019692,    0.000001983, -167.228256226,\
    27.578765869,    7.859089851,   56.769912720,\
   125.584449768,  208.870651245,  -20.000000000''')

cmd.png("porc_1xkk.png", width=600, height=800, dpi=600, ray=1)
Ejemplo n.º 42
0
def read_moestr(contents,
                object,
                state=0,
                finish=1,
                discrete=1,
                quiet=1,
                zoom=-1,
                _self=cmd):
    moestr = contents
    name = object

    import sys
    if sys.version_info[0] > 2 and isinstance(moestr, bytes):
        moestr = moestr.decode()

    cmd = _self
    mr = MOEReader()
    mr.appendFromStr(moestr)
    split_chains = cmd.get_setting_int("moe_separate_chains")
    cmd.group(name)
    if hasattr(mr, 'system'):
        have_valences = 0
        chain_count = 0
        cmd.set_color("_aseg0", [1.0, 1.0, 1.0])
        aseg_color = cmd.get_color_index("_aseg0")
        aseg_flag = 0
        aseg_rep = {}
        model = Indexed()
        molecule = mr.system['molecule']
        if 'atoms' in molecule:
            n_atom = molecule['atoms']
            model.atom = [Atom() for x in range(n_atom)]
        residues = {}
        chains = {}
        for columns, data in molecule['attr']:
            for row in data:
                cur_atom = None
                for key, value in zip(columns, row):
                    key = key[0]
                    if key == 'ID':
                        ID = value
                    else:
                        aProp = _atom_prop_map.get(key, None)
                        if aProp != None:
                            setattr(model.atom[ID - 1], aProp, value)
                        else:
                            xyz = _atom_coord_map.get(key, None)
                            if xyz != None:
                                coord = list(model.atom[ID - 1].coord)
                                coord[xyz] = value
                                model.atom[ID - 1].coord = coord
                            elif key in _atom_vis_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'visible'):
                                    visible = atom.visible
                                else:
                                    visible = _default_visible
                                if key == 'aBondLook':
                                    if value == 'cylinder':
                                        atom.visible = 0x00000001 | visible
                                    elif value == 'line':
                                        atom.visible = 0x00000080 | visible
                                    elif value == 'none':
                                        atom.visible = -129 & Visible  # 0xFFFFFF7F
                                elif key == 'aNucleusLook':
                                    if value == 'sphere':
                                        atom.visible = 0x00000002 | visible
                                    elif value == 'small-sphere':  # need to set sphere_scale=0.2 for these atoms
                                        atom.visible = 0x00000002 | visible
                                        atom.sphere_scale = 0.2
                                    elif value == 'point':  # nonbonded
                                        atom.visible = 0x00000800 | visible
                                    elif value == 'none':
                                        atom.visible = -2067 & visible  # 0xFFFFF7ED
                                elif key == 'aHidden':
                                    atom.visible = 0
                                    atom.hidden = 1
                                if hasattr(
                                        atom, 'hidden'
                                ):  # be sure that hidden atoms aren't shown
                                    atom.visible = 0
                            elif key in _atom_color_map:
                                if key == 'aRGB':
                                    model.atom[ID - 1].trgb = value
                                elif key == 'aColorBy':
                                    model.atom[ID - 1].aColorBy = value
                            elif key in _atom_label_map:
                                atom = model.atom[ID - 1]
                                if hasattr(atom, 'label_dict'):
                                    atom.label_dict[key] = None
                                else:
                                    atom.label_dict = {key: None}
                            elif key in _residue_prop_map:
                                resi_dict = residues.get(ID, {})
                                resi_dict[key] = value
                                residues[ID] = resi_dict
                            elif key in _chain_prop_map:
                                chain_dict = chains.get(ID, {})
                                if ID not in chains:
                                    chain_count = chain_count + 1
                                    chain_dict['count'] = chain_count
                                chain_dict[key] = value
                                chains[ID] = chain_dict
        chn_keys = list(chains.keys())
        chn_keys.sort()
        res_keys = list(residues.keys())
        res_keys.sort()
        # map chain properties onto residues
        chn_resi = 0
        ch_colors = copy.deepcopy(_ch_colors)
        unique_chain_names = {}
        for chn_idx in chn_keys:
            chain_dict = chains[chn_idx]
            cName = make_valid_name(chain_dict.get('cName', ''))
            segi = cName[0:4]
            chain = cName[-1:]
            if not len(cName):
                if 'count' in chain_dict:
                    cName = "chain_" + str(chain_dict['count'])
                else:
                    cName = str(chn_idx)
            if cName not in unique_chain_names:
                unique_chain_names[cName] = cName
            else:
                cnt = 2
                while (cName + "_" + str(cnt)) in unique_chain_names:
                    cnt = cnt + 1
                newCName = cName + "_" + str(cnt)
                unique_chain_names[newCName] = cName
                cName = newCName
            chain_dict['chain_color'] = ch_colors[0]
            ch_colors = ch_colors[1:] + [ch_colors[0]]
            cResCount = chain_dict.get('cResidueCount', 0)
            for res_idx in range(chn_resi, chn_resi + cResCount):
                resi_dict = residues[res_keys[res_idx]]
                resi_dict['chain'] = chain
                resi_dict['segi'] = segi
                resi_dict['cName'] = cName
                resi_dict['chain_dict'] = chain_dict
            chn_resi = chn_resi + cResCount
        # map residue properties onto atoms
        res_atom = 0
        for res_idx in res_keys:
            resi_dict = residues[res_idx]
            rRibbonMode = resi_dict.get('rRibbonMode', 'none')
            rAtomCount = resi_dict['rAtomCount']
            rType = resi_dict.get('rType', '')
            if rAtomCount > 0:
                for at_idx in range(res_atom, res_atom + rAtomCount):
                    atom = model.atom[at_idx]
                    setattr(
                        atom, 'resi',
                        string.strip(
                            str(resi_dict.get('rUID', '')) +
                            resi_dict.get('rINS', '')))
                    setattr(atom, 'resn', resi_dict.get('rName', ''))
                    setattr(atom, 'chain', resi_dict.get('chain', ''))
                    setattr(atom, 'segi', resi_dict.get('segi', ''))
                    setattr(atom, 'custom', resi_dict.get('cName', ''))
                    # add labels
                    if hasattr(atom, 'label_dict'):
                        label = ''
                        label_dict = atom.label_dict
                        if 'aLabelElement' in label_dict:
                            label = atom.symbol
                        if 'aLabelRes' in label_dict:
                            if len(label):
                                label = label + ","
                            label = label + atom.resn + "_" + atom.resi
                        if 'aLabelName' in label_dict:
                            if len(label):
                                label = label + "."
                            label = label + atom.name
                        atom.label = label
                    if rType not in ['none', 'heme']:
                        atom.hetatm = 0  # all normal atoms
                    else:
                        atom.flags = 0x02000000  # hetatom or ligand -- ignore when surfacing

                    if rRibbonMode != 'none':
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible

                        rRibbonColorBy = resi_dict['rRibbonColorBy']
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if rRibbonColorBy in ['rgb', 'r:rgb'
                                                  ]:  # handled automatically
                                pass
                            elif rRibbonColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                rRibbonColorBy = cColorBy
                                repeat = 1

                        rRibbon_color = 0
                        rRibbon_trgb = 0xFFFFFF  # default -- white

                        # now color ribbon
                        if rRibbonColorBy == 'r:rgb':
                            rRibbon_trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'rgb':
                            rRibbon_trgb = resi_dict.get(
                                'rRibbonRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            rRibbon_trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif rRibbonColorBy == 'r:aseg':
                            rRibbon_trgb = None
                            rRibbon_color = aseg_color
                            aseg_flag = 1
                        elif rRibbonColorBy == 'tempfactor':
                            pass  # TO DO
                        elif rRibbonColorBy == 'c:number':  # per chain colors
                            rRibbon_trgb = chain_dict['chain_color']
                        if rRibbonMode in ['line', 'trace']:
                            atom.visible = 0x00000040 | visible  # PyMOL ribbon
                            if rRibbon_trgb != None:
                                atom.ribbon_trgb = rRibbon_trgb
                            else:
                                atom.ribbon_color = rRibbon_color
                            aseg_rep['ribbon'] = 1
                        else:
                            atom.visible = 0x00000020 | visible  # PyMOL cartoon
                            if rRibbon_trgb != None:
                                atom.cartoon_trgb = rRibbon_trgb
                            else:
                                atom.cartoon_color = rRibbon_color
                            aseg_rep['cartoon'] = 1

                    if hasattr(atom, 'label'):
                        if hasattr(atom, 'visible'):
                            visible = atom.visible
                        else:
                            visible = _default_visible
                        atom.visible = 0x00000028 | visible  # labels
                    if not hasattr(atom, 'aColorBy'):
                        atom.aColorBy = 'element'
                    if hasattr(atom, 'aColorBy'):
                        aColorBy = atom.aColorBy
                        repeat = 1
                        while repeat:
                            repeat = 0
                            if aColorBy == 'ribbon':
                                aColorBy = resi_dict.get('rRibbonColorBy')
                                if aColorBy == 'rgb':
                                    aColorBy = 'rib:rgb'
                                else:
                                    repeat = 1
                                # TO DO still need to handle "cartoon_color", "ribbon_color"
                            elif aColorBy == 'element':
                                if hasattr(atom, 'trgb'):
                                    del atom.trgb
                            elif aColorBy in ['rgb', 'a:rgb'
                                              ]:  # handled automatically
                                pass
                            elif aColorBy == 'residue':
                                rColorBy = resi_dict.get('rColorBy')
                                if rColorBy == 'rgb':
                                    rColorBy = 'r:rgb'
                                aColorBy = rColorBy
                                repeat = 1
                            elif aColorBy == 'chain':
                                chain_dict = resi_dict['chain_dict']
                                cColorBy = chain_dict['cColorBy']
                                if cColorBy == 'rgb':
                                    cColorBy = 'c:rgb'
                                aColorBy = cColorBy
                                repeat = 1

                        # now color atom...
                        if aColorBy == 'r:rgb':
                            atom.trgb = resi_dict.get('rRGB', 0xFFFFFF)
                        elif aColorBy == 'rib:rgb':
                            atom.trgb = resi_dict.get('rRibbonRGB', 0xFFFFFF)
                        elif aColorBy == 'c:rgb':
                            chain_dict = resi_dict['chain_dict']
                            atom.trgb = chain_dict.get('cRGB', 0xFFFFFF)
                        elif aColorBy == 'r:aseg':
                            pass  # TO DO
                        elif aColorBy == 'tempfactor':
                            pass  # TO DO
                        elif aColorBy == 'c:number':  # per chain colors
                            atom.trgb = chain_dict['chain_color']

                res_atom = res_atom + rAtomCount
        bond_list = molecule.get('bond', [])
        for bond in bond_list:
            new_bond = Bond()
            new_bond.index = [bond[0] - 1, bond[1] - 1]
            if len(bond) > 2:
                new_bond.order = bond[2]
                if bond[2] == 2:  # work around .MOE bug with triple bonds
                    if model.atom[new_bond.index[0]].hybridization == 'sp':
                        if model.atom[new_bond.index[1]].hybridization == 'sp':
                            new_bond.order = 3
                have_valences = 1
            model.bond.append(new_bond)
        if 'ViewOrientationY' in mr.system:
            vy = mr.system['ViewOrientationY']
            vz = mr.system['ViewOrientationZ']
            pos = mr.system['ViewLookAt']
            scale = mr.system['ViewScale']
            vx = cpv.cross_product(vy, vz)
            m = [cpv.normalize(vx), cpv.normalize(vy), cpv.normalize(vz)]
            m = cpv.transpose(m)
            asp_rat = 0.8  # MOE default (versus 0.75 for PyMOL)
            cmd.set("field_of_view", 25.0)
            fov = float(cmd.get("field_of_view"))
            window_height = scale * asp_rat
            dist = (0.5 * window_height) / math.atan(3.1415 *
                                                     (0.5 * fov) / 180.0)
            new_view = tuple(m[0] + m[1] + m[2] + [0.0, 0.0, -dist] + pos +
                             [dist * 0.5, dist * 1.5, 0.0])
            cmd.set_view(new_view)
            zoom = 0
        cmd.set("auto_color", 0)
        cmd.set_color("carbon", [0.5, 0.5, 0.5])  # default MOE grey

        obj_name = name + ".system"
        if split_chains < 0:  # by default, don't split chains if over 50 objects would be created
            if len(unique_chain_names) > 50:
                split_chains = 0
        if not split_chains:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=quiet,
                           zoom=zoom)
            obj_name_list = [obj_name]
        else:
            cmd.load_model(model,
                           obj_name,
                           state=state,
                           finish=finish,
                           discrete=discrete,
                           quiet=1,
                           zoom=zoom)
            obj_name_list = []
            system_name = obj_name
            for chain in unique_chain_names.keys():
                obj_name = name + "." + chain
                obj_name_list.append(obj_name)
                cmd.select("_moe_ext_tmp",
                           "custom %s" % chain,
                           domain=system_name)
                cmd.extract(obj_name, "_moe_ext_tmp", quiet=quiet, zoom=0)
                # cmd.extract(obj_name,system_name+" and text_type %s"%chain,quiet=quiet)
                cmd.delete("_moe_ext_tmp")
            if not cmd.count_atoms(system_name):
                cmd.delete(system_name)
            else:
                obj_name_list.append(system_name)
            cmd.order(name + ".*", sort=1)
        for obj_name in obj_name_list:
            cmd.set("stick_radius", 0.1, obj_name)
            cmd.set("line_width", 2.0, obj_name)
            cmd.set("label_color", "white", obj_name)
            cmd.set("nonbonded_size", 0.05,
                    obj_name)  # temporary workaround...
            if have_valences:  # if this MOE file has valences, then show em!
                cmd.set("valence", 1, obj_name)
                cmd.set("stick_valence_scale", 1.25, obj_name)
            if aseg_flag:
                cmd.dss(obj_name)
                if 'cartoon' in aseg_rep:
                    cmd.set("cartoon_color", "red",
                            obj_name + " and cartoon_color _aseg0 and ss h")
                    cmd.set("cartoon_color", "yellow",
                            obj_name + " and cartoon_color _aseg0 and ss s")
                    cmd.set(
                        "cartoon_color", "cyan",
                        obj_name + " and cartoon_color _aseg0 and not ss h+s")
                if 'ribbon' in aseg_rep:
                    cmd.set("ribbon_color", "red",
                            obj_name + " and ribbon_color _aseg0 and ss h"
                            )  # need selection op ribbon_color
                    cmd.set("ribbon_color", "yellow",
                            obj_name + " and ribbon_color _aseg0 and ss s")
                    cmd.set(
                        "ribbon_color", "cyan",
                        obj_name + " and ribbon_color _aseg0 and not ss h+s")
        if 'ViewZFront' in mr.system:
            moe_front = mr.system['ViewZFront']
            moe_width = mr.system['ViewZWidth']
            extent = cmd.get_extent(
                name)  # will this work with groups? TO DO: check!
            dx = (extent[0][0] - extent[1][0])
            dy = (extent[0][1] - extent[1][1])
            dz = (extent[0][2] - extent[1][2])
            half_width = 0.5 * math.sqrt(dx * dx + dy * dy + dz * dz)
            cmd.clip("atoms", 0.0, name)
            cur_view = cmd.get_view()
            center = (cur_view[-3] +
                      cur_view[-2]) * 0.5  # center of clipping slab
            front = center - half_width
            back = center + half_width
            width = half_width * 2
            new_view = tuple(
                list(cur_view[0:15]) + [
                    front + width * moe_front, front + width *
                    (moe_front + moe_width), 0.0
                ])
            cmd.set_view(new_view)
        if 'graphics' in mr.system:
            cgo_cnt = 1
            lab_cnt = 1
            unique_cgo_names = {}
            for graphics in mr.system['graphics']:
                cgo = []
                for gvertex in graphics.get('gvertex', []):
                    vrt = gvertex[0]
                    seg_list = gvertex[1]['seg']
                    idx = gvertex[1]['idx']
                    len_idx = len(idx)
                    if not cmd.is_list(seg_list):
                        seg_list = [seg_list] * (len_idx / seg_list)
                    last_seg = None
                    ix_start = 0
                    for seg in seg_list:
                        if seg != last_seg:
                            if last_seg != None:
                                cgo.append(END)
                            if seg == 3:
                                cgo.extend([BEGIN, TRIANGLES])
                            elif seg == 2:
                                cgo.extend([BEGIN, LINES])
                            elif seg == 1:
                                cgo.extend([BEGIN, POINTS])
                        ix_stop = seg + ix_start
                        if seg == 3:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 2:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        elif seg == 1:
                            for s in idx[ix_start:ix_stop]:
                                v = vrt[s - 1]
                                cgo.extend([
                                    COLOR, (0xFF & (v[0] >> 16)) / 255.0,
                                    (0xFF & (v[0] >> 8)) / 255.0,
                                    (0xFF & (v[0])) / 255.0
                                ])
                                if len(v) > 4:
                                    cgo.extend([NORMAL, v[4], v[5], v[6]])
                                cgo.extend([VERTEX, v[1], v[2], v[3]])
                        ix_start = ix_stop
                        last_seg = seg
                    if last_seg != None:
                        cgo.append(END)
                for gtext in graphics.get('gtext', []):
                    lab_name = name + ".label_%02d" % lab_cnt
                    exists = 0
                    for entry in gtext:
                        exists = 1
                        cmd.pseudoatom(lab_name,
                                       pos=[
                                           float(entry[1]),
                                           float(entry[2]),
                                           float(entry[3])
                                       ],
                                       color="0x%06x" % entry[0],
                                       label=entry[4])
                    if exists:
                        cmd.set('label_color', -1, lab_name)
                        lab_cnt = lab_cnt + 1
                    # TO DO -- via CGO's?

                if len(cgo):
                    cgo_name = name + "." + make_valid_name(
                        graphics.get('GTitle', 'graphics'))
                    if cgo_name not in unique_cgo_names:
                        unique_cgo_names[cgo_name] = cgo_name
                    else:
                        cnt = 2
                        while cgo_name + "_" + str(cnt) in unique_cgo_names:
                            cnt = cnt + 1
                        new_name = cgo_name + "_" + str(cnt)
                        unique_cgo_names[new_name] = new_name
                        cgo_name = new_name
                    cmd.load_cgo(cgo,
                                 cgo_name,
                                 state=state,
                                 quiet=quiet,
                                 zoom=0)
                    cgo_cnt = cgo_cnt + 1
                    cmd.set("two_sided_lighting", 1)  # global setting...
                    cmd.set("cgo_line_width", 2, cgo_name)
                    if 'GTransparency' in graphics:
                        g_trans = graphics['GTransparency']
                        if len(g_trans) >= 2:
                            if g_trans[0] != 0:
                                cmd.set('cgo_transparency',
                                        '%1.6f' % (g_trans[0] / 255.0),
                                        cgo_name)
                                cmd.set('transparency_global_sort')
        if 'meter' in mr.system:
            meter_name = name + ".meter"
            exists = 0
            for meter_block in mr.system['meter']:
                if meter_block[0][0:2] == ['type', 'atoms']:
                    for meter in meter_block[1]:
                        (type, atoms) = meter[0:2]
                        arg = tuple([meter_name] + list(
                            map(lambda x, o=name: o + " and id " + str(x - 1),
                                atoms)))
                        getattr(cmd, type)(*arg)
                        exists = 1
            if exists:
                cmd.color("green", meter_name)
#            print mr.system['meter']
    elif hasattr(mr, 'feature'):
        model = Indexed()
        cols = mr.feature[0]
        rows = mr.feature[1]
        col = {}
        cnt = 0
        for a in cols:
            col[a] = cnt
            cnt = cnt + 1
        for row in rows:
            atom = Atom()
            atom.coord = [row[col['x']], row[col['y']], row[col['z']]]
            atom.vdw = row[col['r']]
            atom.custom = row[col['expr']]
            model.atom.append(atom)
        obj_name = name + ".feature"
        cmd.load_model(model,
                       obj_name,
                       state=state,
                       finish=finish,
                       discrete=discrete,
                       quiet=quiet,
                       zoom=zoom)
        rank = 1
        for row in rows:
            cmd.color("0x%06x" % row[col['color']],
                      obj_name + " & id %d" % (rank - 1))
            rank = rank + 1
        cmd.show("mesh", obj_name)
        cmd.set("min_mesh_spacing", 0.55, obj_name)
        cmd.label(obj_name, "' '+custom")
        cmd.set("label_color", "yellow", obj_name)
    else:
        print(dir(mr))
Ejemplo n.º 43
0
    def run(self):
        my_view = cmd.get_view()
        #mark Search
        if self.mode == 'Search':
            #show message
            cmd.wizard("message", "Searching conformers...")
            cmd.refresh()
            if self.currentLabel.uid != "Rx":
                self.search()
                print "Creating Rotamers in PyMOL...",
                for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
                    self.createRotamerInPymol(aRotamer, "mW")
# 				if self.thoroughness == "painstaking" and self.currentLabel.uid == "R1":
# 					scoringWeights = {"totalContactWeight": 0.0, "typeOfContactWeight": 1.0}
# 					for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
# 						aRotamer.score(scoringWeights)
# 					self.currentLabel.ensembles["mW"].sortRotamers("chi2")
# 					numberOfRotamers = len(self.currentLabel.ensembles["mW"].rotamers)
# 					newEnsemble = ensemble.Ensemble()
# 					newEnsemble.name = "contactFit"
# 					newEnsemble.rotamers = self.currentLabel.ensembles["mW"].rotamers[0:20]
# 					self.currentLabel.ensembles["contactFit"] = newEnsemble
# 					for aRotamer in self.currentLabel.ensembles["contactFit"].rotamers:
# 						self.createRotamerInPymol(aRotamer, "contactFit")
                print "done!"

            elif self.currentLabel.uid == "Rx":
                ca1 = numpy.array(
                    cmd.get_model(self.residue1Name + " & name CA",
                                  1).get_coord_list()[0])
                ca2 = numpy.array(
                    cmd.get_model(self.residue2Name + " & name CA",
                                  1).get_coord_list()[0])
                try:
                    cb1 = numpy.array(
                        cmd.get_model(self.residue1Name + " & name CB",
                                      1).get_coord_list()[0])
                except:
                    cb1 = ca1
                try:
                    cb2 = numpy.array(
                        cmd.get_model(self.residue2Name + " & name CB",
                                      1).get_coord_list()[0])
                except:
                    cb2 = ca2

                environmentatoms = numpy.array(cmd.get_model("(%s within 10 of %s or %s) and not (%s or %s)" \
                     %(self.pickedObject1, \
                      self.residue1Name, \
                      self.residue2Name, \
                      self.residue1Name, \
                      self.residue2Name), 1).get_coord_list())
                anchor1rotamers = self.currentLabel.calculateCone(
                    ca1, cb1, environmentatoms, numberOfAtoms=8000)
                anchor2rotamers = self.currentLabel.calculateCone(
                    ca2, cb2, environmentatoms, numberOfAtoms=8000)
                solutions1 = []
                solutions2 = []
                for anchor1rotamer in anchor1rotamers:
                    anAtom = anchor1rotamer.atoms["N1"]
                    solutions1.append(anAtom.coordinate)
                for anchor2rotamer in anchor2rotamers:
                    anAtom = anchor2rotamer.atoms["N1"]
                    solutions2.append(anAtom.coordinate)

                #determine common accessible volume
                distances1 = self.currentLabel.quick_map(solutions1, cb2)
                distances2 = self.currentLabel.quick_map(solutions2, cb1)
                indices1 = numpy.where(numpy.any(distances1 > 6, axis=1))
                indices2 = numpy.where(numpy.any(distances2 > 6, axis=1))
                solutions1 = numpy.delete(solutions1, indices1, 0)
                solutions2 = numpy.delete(solutions2, indices2, 0)
                solutions = numpy.concatenate((solutions1, solutions2))

                #create resulting ensemble
                newEnsemble = ensemble.Ensemble()
                newEnsemble.name = "mW"
                id = 0
                newRotamers = []
                if len(solutions) > 0:
                    for solution in solutions:
                        newRotamer = rotamer.Rotamer()
                        thisAtom = atom.Atom()
                        thisAtom.coordinate = solution
                        thisAtom.name = "N1"
                        thisAtom.element = "N"
                        newRotamer.id = id
                        newRotamer.atoms["N1"] = thisAtom
                        id += 1
                        newRotamers.append(newRotamer)
                else:
                    print "Did not find any possible N1 locations. Are the two anchorpoints too far apart?"
                newEnsemble.rotamers = newRotamers
                self.currentLabel.ensembles[newEnsemble.name] = newEnsemble
                cmd.load(
                    "%s/labels/%s" % (self.path, self.currentLabel.pdbFile),
                    "currentLabel")
                for aRotamer in self.currentLabel.ensembles["mW"].rotamers:
                    self.createRotamerInPymol(aRotamer, "mW")
            self.numberOfLabel += 1
            self.finalCosmetics()
            #dismiss message
            cmd.wizard()

        #mark Measure
        elif self.mode == "Measure":
            cmd.wizard("message", "Calculating distances...")
            cmd.refresh()
            print "\n\n\nDistance calculation:\n"
            print "The dashed lines are the c-beta distance (green),\nand the distance between the geometric averages\nof the two ensembles (yellow).\n"
            print "The following statistics refer to the distribution\nof the individual distances between all conformers (may take a while):\n"

            #find out what the selections are
            stored.label1 = []
            stored.label2 = []
            stored.label1Coordinates = []
            stored.label2Coordinates = []
            stored.atomNames1 = []
            stored.atomNames2 = []

            #extract label info
            cmd.iterate(self.residue1Name, 'stored.label1.append(segi)')
            cmd.iterate(self.residue2Name, 'stored.label2.append(segi)')
            cmd.iterate(self.residue1Name, 'stored.atomNames1.append(name)')
            cmd.iterate(self.residue2Name, 'stored.atomNames2.append(name)')
            try:
                label1 = label.Label.fromfile("labels/%s.txt" %
                                              stored.label1[0])
                cmd.iterate_state(
                    0,
                    "%s & name %s" % (self.residue1Name, label1.spinLocation),
                    'stored.label1Coordinates.append((x,y,z))')
            except:
                cmd.iterate_state(0, "%s" % (self.residue1Name),
                                  'stored.label1Coordinates.append((x,y,z))')
            try:
                label2 = label.Label.fromfile("labels/%s.txt" %
                                              stored.label2[0])
                cmd.iterate_state(
                    0,
                    "%s & name %s" % (self.residue2Name, label2.spinLocation),
                    'stored.label2Coordinates.append((x,y,z))')
            except:
                cmd.iterate_state(0, "%s" % (self.residue2Name),
                                  'stored.label2Coordinates.append((x,y,z))')
            #calculate distances
            distances = distanceDistribution.DistanceDistribution()
            dist = distances.calculateDistanceDistribution(
                stored.label1Coordinates, stored.label2Coordinates)

            #create pseudoatom at average coordinate of each ensemble and display the distance between them
            atoms1 = numpy.array(stored.label1Coordinates)
            atoms2 = numpy.array(stored.label2Coordinates)
            avgAtoms1 = numpy.average(atoms1, axis=0)
            avgAtoms2 = numpy.average(atoms2, axis=0)
            self.createPseudoatom(avgAtoms1, "tmp_average1", 1)
            self.createPseudoatom(avgAtoms2, "tmp_average2", 1)
            cmd.distance(self.object_prefix + "avg", "tmp_average1 & name PS1",
                         "tmp_average2 & name PS1")
            cmd.delete("tmp_average1")
            cmd.delete("tmp_average2")

            #cbeta distance if cbeta is present in both selections
            #cBetaDistance = 0.0
            if any("CB" in atom for atom in stored.atomNames1) and any(
                    "CB" in atom for atom in stored.atomNames2):
                cmd.distance(self.object_prefix + "cBeta",
                             self.residue1Name + " & name CB",
                             self.residue2Name + " & name CB")
                #for some reason, cmd.distance does not return the correct distance. Although it is shown in the viewer...
                #get_distance gives the correct distance, but does not create the object in the viewer.
                cBetaDistance = cmd.get_distance(
                    self.residue1Name + " & name CB",
                    self.residue2Name + " & name CB")
                cmd.set("dash_color", "green", self.object_prefix + "cBeta")

            histogram = numpy.histogram(dist, numpy.arange(100))
            envelopePlot = numpy.zeros((100, 2))
            envelopePlot[0:99] = numpy.column_stack(
                (histogram[1][0:len(histogram[1]) - 1], histogram[0]))

            #put point in mid of bin
            envelopePlot[:, 0] += 0.5
            normEnvelopePlot = numpy.copy(envelopePlot)
            normEnvelopePlot[:, 1] = normEnvelopePlot[:, 1] / numpy.amax(
                histogram[0])

            #combine dist and histogram to single array before output
            output = numpy.column_stack((envelopePlot, normEnvelopePlot[:, 1]))
            averageDistance = numpy.average(dist)

            #make graph dictionary for mtsslPlotter
            graphtitle = "%s-%s" % (self.residue1Name, self.residue2Name)
            xlim = [0, 100]
            ylim = [0, 1]
            plotDictionary = self.makeGraphDataDictionary(
                graphtitle, "DistanceDistribution", "Distance (Angstrom)",
                "Relative Probability", output[:, 0], output[:,
                                                             2], 0, xlim, ylim)
            stored.plots.append(plotDictionary)
            print "Distribution plot added to memory. Inspect it with mtsslPlotter."

            #Copy to clipboard
            header = "Dist.   Count   Norm.Count\n"
            outputStr = header + numpy.array_str(output)
            outputStr = outputStr.replace("[", "")
            outputStr = outputStr.replace("]", "")
            self.copyStringToClipboard(outputStr)

            #Write to file
            if self.writeToFile:
                try:
                    filename = "%s-%s" % (self.residue1Name, self.residue2Name)
                    numpy.savetxt(filename + ".txt", output, delimiter='\t')
                    print "Written to file:"
                    print "%s/%s" % (os.getcwd(), filename)
                except:
                    print "Writing to file failed!"
            print self.calculateStatistics2(dist)
            try:
                if cBetaDistance > 0.0:
                    print "Cbeta distance: %3.1f" % cBetaDistance
            except:
                print "No Cbeta distance."
            cmd.wizard()

        #mark Distance Map
        elif self.mode == "Distance Map":
            #show message
            cmd.wizard("message",
                       "Calculating distance maps. Please be patient...")
            cmd.refresh()
            dm = distanceMap.DistanceMap(self.writeToFile, self.currentLabel,
                                         self.homoOligomerMode)
            if self.pickedObject1 == self.pickedObject2:
                dm.intraDistanceMap(self.pickedObject1)
            else:
                dm.interDistanceMap(self.pickedObject1, self.pickedObject2)
            print "Done!"
            cmd.wizard()

        self.cleanupAfterRun()
        cmd.set_view(my_view)
Ejemplo n.º 44
0
        183, 698, 701, 190, 69, 82, 355, 627
]:
    cmd.color('red', 'resi {0} and S009'.format(r))
    cmd.show('spheres', 'resi {{0}} and S009'.format(r))

# knownAdaptiveAndTopA549
for r in [9, 684, 627, 701, 158]:
    cmd.color('magenta', 'resi {0} and S009'.format(r))
    cmd.show('spheres', 'resi {{0}} and S009'.format(r))

###### SETVIEW

cmd.set_view('\
     0.636402488,    0.699312985,   -0.325504273,\
    -0.565354168,    0.135798618,   -0.813591778,\
    -0.524754405,    0.701796234,    0.481783271,\
     0.000000000,    0.000000000, -429.757751465,\
   -69.421409607,    7.238445282,   72.295677185,\
   338.824279785,  520.691223145,  -20.000000000 ')

###### POSTAMBLE

cmd.select(None)
cmd.set('specular', "off")
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}_y.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.rotate('x', angle=90)
Ejemplo n.º 45
0
OUTPUT_DIR = "normal_modes"

# Load structure and remove water
cmd.load(INPUT_STRUCTURE)

# Add secondary structure
cmd.dss()

# Define colors
cmd.set_color("biotite_lightgreen", [111 / 255, 222 / 255, 76 / 255])

# Set overall colors
cmd.color("biotite_lightgreen", "chain A")

# Set view
cmd.set_view(
    (0.605540633, 0.363677770, -0.707855821, -0.416691631, 0.902691007,
     0.107316799, 0.678002179, 0.229972601, 0.698157668, 0.000000000,
     0.000000000, -115.912551880, 32.098876953, 31.005725861, 78.377349854,
     89.280677795, 142.544403076, -20.000000000))

# Prepare output video frames
cmd.mset()
cmd.set("ray_shadows", 0)
if not isdir(OUTPUT_DIR):
    os.mkdir(OUTPUT_DIR)
cmd.mpng(join(OUTPUT_DIR, "img_"), mode=2, width=600, height=600)

# Render animated GIF
# convert -delay 3 -loop 0 -dispose 2 normal_modes/*.png normal_modes.gif
Ejemplo n.º 46
0
def FocalBlur(aperture=2.0, samples=10, ray=0, width=0, height=0):
    '''
DESCRIPTION

    Creates fancy figures by introducing a focal blur to the image. The object
    at the origin will be in focus.

AUTHOR

    Jarl Underhaug
    University of Bergen
    jarl_dot_underhaug_at_gmail_dot_com

    Updates by Jason Vertrees and Thomas Holder

USAGE

    FocalBlur aperture=float, samples=int, ray=0/1, width=int, height=int

EXAMPELS

    FocalBlur aperture=1, samples=100
    FocalBlur aperture=2, samples=100, ray=1, width=600, height=400
    '''

    # Formalize the parameter types
    ray = (ray in ("True", "true", 1, "1"))
    aperture, samples = float(aperture), int(samples)
    width, height = int(width), int(height)

    # Create a temporary directory
    tmpdir = mkdtemp()

    # Get the orientation of the protein and the light
    light = cmd.get('light')[1:-1]
    light = [float(s) for s in light.split(',')]
    view = cmd.get_view()

    # Rotate the protein and the light in order to create the blur
    for frame in range(samples):
        # Angles to rotate protein and light
        # Populate angles as Fermat's spiral
        theta = frame * pi * 110.0 / 144.0
        radius = 0.5 * aperture * sqrt(frame / float(samples - 1))
        x = cos(theta) * radius
        y = sin(theta) * radius
        xr = x / 180.0 * pi
        yr = y / 180.0 * pi

        # Rotate the protein
        cmd.turn('x', x)
        cmd.turn('y', y)

        # Rotate the light
        ly = light[1] * cos(xr) - light[2] * sin(xr)
        lz = light[2] * cos(xr) + light[1] * sin(xr)
        lx = light[0] * cos(yr) + lz * sin(yr)
        lz = lz * cos(yr) - lx * sin(yr)
        cmd.set('light', [lx, ly, lz])

        curFile = "%s/frame-%04d.png" % (tmpdir, frame)
        print("Created frame %i/%i (%0.0f%%)" % (frame + 1, samples, 100 *
                                                 (frame + 1) / samples))

        # Save the image to temporary directory
        if ray:
            cmd.ray(width, height)
            cmd.png(curFile)
        else:
            cmd.png(curFile, quiet=1)

        # Create the average/blured image
        try:
            avg = Image.blend(avg, Image.open(curFile), 1.0 / (frame + 1))
        except:
            avg = Image.open(curFile)

        # Return the protein and the light to the original orientation
        cmd.set('light', light)
        cmd.set_view(view)

    # Load the blured image
    avg.save('%s/avg.png' % (tmpdir))
    cmd.load('%s/avg.png' % (tmpdir))

    # Delete the temporary files
    rmtree(tmpdir)
Ejemplo n.º 47
0
from pymol.cgo import *
from pymol import cmd

cmd.set("cartoon_fancy_helices", 1)
cmd.set("cartoon_transparency", 0.7)
cmd.set("ray_trace_mode",  0)
cmd.set("two_sided_lighting", "on")
cmd.set("reflect", 0.9)
cmd.set("ambient", 0.1)
cmd.set('''ray_opaque_background''', '''off''')

cmd.load("input_pdb.pdb")
cmd.load("4_cavity_1.pdb")
cmd.set_view (\
  '''0.237595469,   -0.169580087,    0.956439614,\
     0.387604266,   -0.886297047,   -0.253433615,\
     0.890669584,    0.430938631,   -0.144854113,\
    -0.000374220,    0.000006055, -100.353157043,\
    31.699275970,   32.316436768,   33.389636993,\
    61.715843201,  138.970840454,  -20.000000000''')
cmd.png("quickstart_6.png", width=400, height=300, dpi=100, ray=1)
Ejemplo n.º 48
0
from pymol import cmd

cmd.bg_color('white')
cmd.select('drg', 'all')

cmd.set('valence', '1')
cmd.set_bond('stick_radius', '0.14', 'drg', 'drg')
cmd.set('sphere_scale', '0.25', 'drg')
cmd.show('sticks', 'drg')
cmd.show('spheres', 'drg')

cmd.set_view([0.984318674,   -0.042038180,   -0.171310961,\
     0.001240913,   -0.969511747,    0.245043248,\
    -0.176387057,   -0.241413504,   -0.954258323,\
    -0.000004895,    0.000000954,  -62.691986084,\
     1.964830756,   -0.868917644,   -0.235743612,\
    37.651191711,   87.732429504,  -20.000000000])

charges = [
    "0.152", "0.453", "-0.224", "0.343", "0.269", "0.472", "-0.447", "-0.416",
    "0.161", "0.203", "-0.055", "0.060", "0.008", "-0.007", "-0.015", "0.051",
    "0.049", "-0.218", "0.137", "-0.240", "0.140", "0.066", "0.072", "-0.062",
    "-0.006", "0.131", "-0.101", "0.152", "-0.051", "0.410", "-0.623", "0.422",
    "-0.574", "0.405", "-0.342", "0.168", "-0.031", "0.126", "-0.290", "0.158",
    "-0.190", "0.950", "-0.522", "-0.572", "-0.572"
]
cmd.set('label_size', '22')
#cmd.set('label_position', (2, 0, 0))
for i, charge in zip(range(1, 46), charges):
    cmd.label('id %s' % i, charge)
Ejemplo n.º 49
0
    def set_view(view):
        """

        :return:
        """
        return cmd.set_view(view)
Ejemplo n.º 50
0
###### SETVIEW

# cmd.set_view ('\
#      0.299299747,   -0.468806446,   -0.831047535,\
#      0.759561479,   -0.410073251,    0.504881859,\
#     -0.577481806,   -0.782342494,    0.233352542,\
#      0.000000000,    0.000000000, -405.080596924,\
#    108.490371704,  107.187545776,  105.390640259,\
#    319.368621826,  490.792572021,  -20.000000000 ')

# Zoomed to region of CTD interaction
cmd.set_view ('\
    -0.324992836,    0.298390329,    0.897407830,\
     0.532062650,   -0.726806164,    0.434348613,\
     0.781849146,    0.618635833,    0.077445090,\
     0.000000000,    0.000000000, -170.138488770,\
   108.915313721,   88.171340942,  145.125610352,\
   134.138488770,  206.138488770,  -20.000000000 ')


###### POSTAMBLE

cmd.select(None)
cmd.set('specular', "off")
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
cmd.draw(width=1000, height=1000)
cmd.png('{0}_{1}_y.png'.format(structure, metric), ray=1)
cmd.rotate('y', angle=180)
Ejemplo n.º 51
0
def modevectors(first_obj_frame,
                last_obj_frame,
                first_state=1,
                last_state=1,
                outname="modevectors",
                head=1.0,
                tail=0.3,
                head_length=1.5,
                headrgb="1.0,1.0,1.0",
                tailrgb="1.0,1.0,1.0",
                cutoff=4.0,
                skip=0,
                cut=0.5,
                atom="CA",
                stat="show",
                factor=1.0,
                notail=0):
    """
    Authors Sean Law & Srinivasa
    Michigan State University
    slaw_(at)_msu_dot_edu

    Editor Sacha Yee

    USAGE

    While in PyMOL

    Parameter                Preset            Type    Description
    first_obj_frame          Undefined         String  Object name of the first structure.  The mode vector will propagate from this structure.  Defined by user.
    last_obj_frame           Undefined         String  Object name of the last structure.  The mode vector (arrow head) will end at this structure.  Defined by user.
    first_state              1                 Integer Defines state of first object
    last_state               1                 Integer Defines state of last object
    outname                  modevectors       String  Name of object to store mode vectors in.
    head                     1.0               Float   Radius for the circular base of the arrow head (cone)
    tail                     0.3               Float   Radius for the cylinder of the arrow tail (cylinder)
    head_length              1.5               Float   Length of the arrow head (from the base of the cone to the tip of cone)
    head_rgb                 1.0,1.0,1.0       String  RGB colour for the arrow head.
    tail_rgb                 1.0,1.0,1.0       String  RGB colour for the arrow tail.
    cutoff                   4.0               Float   Skips mode vectors that do not meet the cutoff distance (in Angstroms).
    skip                     0                 Integer Denotes how many atoms to skip.  No arrows will be created for skipped atoms.
    cut                      0.0               Float   Truncates all arrow tail lengths (without disturbing the arrow head) (in Angstroms).
    atom                     CA                String  Designates the atom to derive mode vectors from.
    stat                     show              String  Keeps track and prints statistics (total modevectors, skipped, cutoff).
    factor                   1.0               Float   Multiplies each mode vector length by a specified factor.
                                                       Values between 0 and 1 will decrease the relative mode vector length.
                                                       Values greater than 1 will increase the relative mode vector length.
    notail                   0                 Integer Hides tails and only uses cones (porcupine plot)
    """

    framefirst = cmd.get_model(first_obj_frame, first_state)
    framelast = cmd.get_model(last_obj_frame, last_state)
    objectname = outname
    factor = float(factor)
    arrow_head_radius = float(head)
    arrow_tail_radius = float(tail)
    arrow_head_length = float(head_length)
    cutoff = float(cutoff)
    skip = int(skip)
    cut = float(cut)
    atomtype = atom.strip('"[]()')
    objectname = objectname.strip('"[]()')

    headrgb = headrgb.strip('" []()')
    tailrgb = tailrgb.strip('" []()')
    hr, hg, hb = list(map(float, headrgb.split(',')))
    tr, tg, tb = list(map(float, tailrgb.split(',')))

    version = cmd.get_version()[1]
    arrow = []
    arrowhead = []
    arrowtail = []
    x1 = []
    y1 = []
    z1 = []
    x2 = []
    y2 = []
    z2 = []
    exit_flag = False

    ##############################################################
    #                                                            #
    # Define an object called "tail" and store the tail and  a   #
    # circular base of the triangle in this object.              #
    #                                                            #
    ##############################################################

    skipcount = 0
    skipcounter = 0
    keepcounter = 0
    atom_lookup = {}
    for atom in framefirst.atom:
        if atom.name == atomtype:
            if skipcount == skip:
                x1.append(atom.coord[0])
                y1.append(atom.coord[1])
                z1.append(atom.coord[2])

                ##########################################
                #                                        #
                # Set atom_lookup for a specific atom    #
                # equal to ONE for the first input set.  #
                # This dictionary will be used as a      #
                # reference for the second set.          #
                #                                        #
                ##########################################

                current_atom = "CHAIN " + atom.chain + " RESID "\
                    + atom.resi + " RESTYPE "\
                    + atom.resn +\
                    " ATMNUM " + str(atom.index)
                #				print current_atom
                atom_lookup['current_atom'] = 1

                skipcount = 0
                keepcounter += 1
            else:
                #				print skipcount
                skipcount += 1
                skipcounter += 1

    skipcount = 0
    for atom in framelast.atom:
        if atom.name == atomtype:
            if skipcount == skip:
                x2.append(atom.coord[0])
                y2.append(atom.coord[1])
                z2.append(atom.coord[2])

                #########################################
                #                                       #
                # Get atom information from second set  #
                # and compare with first set.  All      #
                # atoms from this second set MUST be    #
                # found in the first set!  Otherwise,   #
                # the script will exit with an error    #
                # since modevectors can only be created #
                # by calculating values from identical  #
                # sources.                              #
                #                                       #
                #########################################

                current_atom = "CHAIN " + atom.chain + " RESID "\
                    + atom.resi + " RESTYPE "\
                    + atom.resn +\
                    " ATMNUM " + str(atom.index)
                #				print current_atom
                if 'current_atom' not in atom_lookup:
                    print("\nError: " + current_atom + " from \""\
                          + last_obj_frame +\
                          " \"is not found in \"" + first_obj_frame + "\".")
                    print(
                        "\nPlease check your input and/or selections and try again."
                    )
                    exit_flag = True
                    break

                skipcount = 0
            else:
                skipcount += 1

    if exit_flag == 1:
        ###########################################
        #                                         #
        # Exit script because an atom cannot be   #
        # found in both input files               #
        #                                         #
        ###########################################
        return

    cutoff_counter = 0  # Track number of atoms failing to meet the cutoff

    ###################################################
    #                                                 #
    # Check that the two selections/PDB files contain #
    # the same number of atoms.                       #
    #                                                 #
    ###################################################

    if len(x2) != len(x1):
        print("\nError: \"" + first_obj_frame +\
              "\" and \"" + last_obj_frame +\
              "\" contain different number of residue/atoms.")
        print("\nPlease check your input and/or selections and try again.")
        return
    else:
        # Continue with representing modevectors!
        #########################################
        #                                       #
        # Delete old selection or object if it  #
        # exists so that it can be overwritten  #
        #                                       #
        #########################################
        save_view = cmd.get_view(output=1, quiet=1)
        cmd.delete(objectname)
        cmd.hide(representation="everything", selection=first_obj_frame)
        cmd.hide(representation="everything", selection=last_obj_frame)

    ###################################################
    #                                                 #
    # Begin drawing arrow tails                       #
    #                                                 #
    ###################################################

    arrowtail = []
    for mv in range(len(x1)):
        vectorx = x2[mv] - x1[mv]
        vectory = y2[mv] - y1[mv]
        vectorz = z2[mv] - z1[mv]
        length = sqrt(vectorx**2 + vectory**2 + vectorz**2)
        if length < cutoff:
            cutoff_counter += 1
            continue
        t = 1.0 - (cut / length)
        x2[mv] = x1[mv] + factor * t * vectorx
        y2[mv] = y1[mv] + factor * t * vectory
        z2[mv] = z1[mv] + factor * t * vectorz
        vectorx = x2[mv] - x1[mv]
        vectory = y2[mv] - y1[mv]
        vectorz = z2[mv] - z1[mv]
        length = sqrt(vectorx**2 + vectory**2 + vectorz**2)
        d = arrow_head_length  # Distance from arrow tip to arrow base
        t = 1.0 - (d / length)
        if notail:
            t = 0
        tail = [
            # Tail of cylinder
            CYLINDER, x1[mv], y1[mv], z1[mv]\
            , x1[mv] + (t + 0.01) * vectorx, y1[mv] + (t + 0.01) * vectory, z1[mv] + (t + 0.01) * vectorz\
            , arrow_tail_radius, tr, tg, tb, tr, tg, tb  # Radius and RGB for each cylinder tail
        ]
        if notail == 0:
            arrow.extend(tail)

        x = x1[mv] + t * vectorx
        y = y1[mv] + t * vectory
        z = z1[mv] + t * vectorz
        dx = x2[mv] - x
        dy = y2[mv] - y
        dz = z2[mv] - z
        seg = d / 100
        intfactor = int(factor)
        if version < 1.1:  # Version >= 1.1 has cone primitive
            for i in range(100, 0, -1):  # i=100 is tip of cone
                print(i)
                t1 = seg * i
                t2 = seg * (i + 1)
                radius = arrow_head_radius * (
                    1.0 - i / (100.0))  # Radius of each disc that forms cone
                head = [
                    CYLINDER, x + t2 * dx, y + t2 * dy, z + t2 * dz\
                    , x + t1 * dx, y + t1 * dy, z + t1 * dz\
                    , radius, hr, hg, hb, hr, hg, hb  # Radius and RGB for slice of arrow head
                ]
                arrow.extend(head)
        else:
            head = [
                CONE, x, y, z, x + d * dx, y + d * dy, z + d * dz,
                arrow_head_radius, 0.0, hr, hg, hb, hr, hg, hb, 1.0, 1.0
            ]
            arrow.extend(head)


##############################################################
#                                                            #
# Load the entire object into PyMOL                          #
#                                                            #
# Print statistics if requested by user                      #
#                                                            #
##############################################################

    if stat == "show":
        natoms = skipcounter + keepcounter
        print("\nTotal number of atoms = " + str(natoms))
        print("Atoms skipped = " + str(skipcounter))
        if keepcounter - cutoff_counter > 0:
            print("Atoms counted = " + str(keepcounter - cutoff_counter) +
                  " (see PyMOL object \"" + objectname + "\")")
        else:
            print("Atoms counted = " + str(keepcounter - cutoff_counter) +
                  " (Empty CGO object not loaded)")
        print("Atoms cutoff  = " +
              str(cutoff_counter))  # Note that cutoff occurs AFTER skipping!
    if keepcounter - cutoff_counter > 0:
        cmd.delete(objectname)
        cmd.load_cgo(
            arrow, objectname
        )  # Ray tracing an empty object will cause a segmentation fault.  No arrows = Do not display in PyMOL!!!
    cmd.show(representation="cartoon", selection=first_obj_frame)
    if (first_obj_frame != last_obj_frame):
        cmd.show(representation="cartoon", selection=last_obj_frame)
        cmd.hide(representation="cartoon", selection=last_obj_frame)
    cmd.bg_color(color="white")
    cmd.set_view(save_view)
    return
Ejemplo n.º 52
0
def mvSinViewTravel(frames=1,
                    old_view=(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
                              0, 0),
                    new_view=(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                              0, 0)):
    """
	Generate progressive view matrices to move the camera smoothly
	from the current view to a new view provided as an argument.

         frames - frames for the journey 
	 old_view - old view
         new_view - PyMol view matrix that defines the view at the end 
	of the sequence
	"""
    framestates = getFrameStates(frames)
    nframes = len(framestates)
    ff = float(1.0 / nframes)

    #	print ( "view : (" + "%8.3f, "*17 + "%8.3f)" ) % (old_view)
    #       print "oldtran : %8.3f %8.3f %8.3f" % (old_view[12], old_view[13], old_view[14])

    #       capture new zoom/clip parameters
    ozc1 = new_view[11]
    ozc2 = new_view[15]
    ozc3 = new_view[16]

    #		save for later since in sin smoothing need to do zoom/clip parameters
    #		step by step also instead of a constant step size
    nv11 = new_view[11]
    nv15 = new_view[15]
    nv16 = new_view[16]

    #       calculate shift in zoom/clip parameters
    #	dzc1 = (ozc1 - old_view[11]) * ff
    #	dzc2 = (ozc2 - old_view[15]) * ff
    #	dzc3 = (ozc3 - old_view[16]) * ff

    ozc1 = old_view[11]
    ozc2 = old_view[15]
    ozc3 = old_view[16]

    #       capture new translation vector component
    ox = new_view[12]
    oy = new_view[13]
    oz = new_view[14]

    #       calculate shift vector
    dx = ox - old_view[12]
    dy = oy - old_view[13]
    dz = oz - old_view[14]

    dx = dx * ff
    dy = dy * ff
    dz = dz * ff

    ox = old_view[12]
    oy = old_view[13]
    oz = old_view[14]

    #       capture old and new rotation matrix components in quaternion form

    #       m[0][0] = v[0]  m[0][1] = v[1]  m[0][2] = v[2]
    #       m[1][0] = v[3]  m[1][1] = v[4]  m[1][2] = v[5]
    #       m[2][0] = v[6]  m[2][1] = v[7]  m[2][2] = v[8]

    qx1, qy1, qz1, qw1 = quaternion(old_view)
    qx2, qy2, qz2, qw2 = quaternion(new_view)

    #       calc cosine
    cosom = qx1 * qx2 + qy1 * qy2 + qz1 * qz2 + qw1 * qw2

    limit = 0.001
    if cosom > 1.0 + limit:
        raise ValueError, "Cosine of omega way out of range (positive)"
    elif cosom > 1.0:
        print "Warning: cosom corrected from ", cosom, "to",
        cosom = 1.0
        print cosom

    if cosom < -1.0 - limit:
        raise ValueError, "Cosine of omega way out of range (negative)"
    elif cosom < -1.0:
        print "Warning: cosom corrected from ", cosom, "to",
        cosom = 1.0
        print cosom

#       adjust signs
    if (cosom < 0.0):
        cosom = -cosom
        to0 = -qx2
        to1 = -qy2
        to2 = -qz2
        to3 = -qw2
    else:
        to0 = qx2
        to1 = qy2
        to2 = qz2
        to3 = qw2

#       calc coefficients
    omega = acos(cosom)
    sinom = sin(omega)
    if sinom == 0.0:
        sinom = limit
        print "Warning: sinom corrected!"

#       restore old view
    cmd.set_view(("%8.3f, " * 17 + "%8.3f") % tuple(old_view))

    #       loop interpolating over nframes generating interpolated quaternion
    j = 1
    prev = 1.0
    sum = 0.0
    a = 0
    for fs in framestates:
        #for a in range(nframes+1):
        scale0 = sin(
            (1.0 - float(sin((math.pi / 2) *
                             (2 * a * ff - 1)) / 2 + 0.5)) * omega) / sinom
        scale1 = sin((float(sin((math.pi / 2) *
                                (2 * a * ff - 1)) / 2 + 0.5) * omega)) / sinom
        #print a,scale0,scale1
        rx = scale0 * qx1 + scale1 * to0
        ry = scale0 * qy1 + scale1 * to1
        rz = scale0 * qz1 + scale1 * to2
        rw = scale0 * qw1 + scale1 * to3

        # convert back to matrix
        x2 = rx + rx
        y2 = ry + ry
        z2 = rz + rz
        xx = rx * x2
        xy = rx * y2
        xz = rx * z2
        yy = ry * y2
        yz = ry * z2
        zz = rz * z2
        wx = rw * x2
        wy = rw * y2
        wz = rw * z2

        nv0 = 1.0 - (yy + zz)
        nv3 = xy - wz
        nv6 = xz + wy

        nv1 = xy + wz
        nv4 = 1.0 - (xx + zz)
        nv7 = yz - wx

        nv2 = xz - wy
        nv5 = yz + wx
        nv8 = 1.0 - (xx + yy)

        # update translation vector
        ox = ox + dx
        oy = oy + dy
        oz = oz + dz

        # for sin smoothing need difference between this step and next step:
        diff = (sin(math.pi / 2 *
                    ((a + 1) * 2 * ff - 1)) - sin(math.pi / 2 *
                                                  (a * 2 * ff - 1))) / 2
        if diff < 0:
            print("diff adjusted from negative")
            diff = 0
        #       calculate shift in zoom/clip parameters
        dzc1 = (nv11 - old_view[11]) * diff
        dzc2 = (nv15 - old_view[15]) * diff
        dzc3 = (nv16 - old_view[16]) * diff

        # update zoom/clip parameters

        ozc1 = ozc1 + dzc1
        ozc2 = ozc2 + dzc2
        ozc3 = ozc3 + dzc3
        #mv.movie.append((fs[0],fs[1],"color %s, %s"%(tmpc,selection)))

        mv.movie.append(
            (fs[0], fs[1],
             "set_view (%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f)"
             % (nv0, nv1, nv2, nv3, nv4, nv5, nv6, nv7, nv8, old_view[9],
                old_view[10], ozc1, ox, oy, oz, ozc2, ozc3, old_view[17])))

        a = a + 1
Ejemplo n.º 53
0
cmd.load("ch_ecf.pdb")
cmd.color("blue", "ch_ecf")

cmd.load("ch_edf.pdb")
cmd.color("blue", "ch_edf")

cmd.load("ecf_1.pdb")
cmd.color("forest", "ecf_1")

cmd.load("edf_1.pdb")
cmd.color("forest", "edf_1")

cmd.hide("spheres")
cmd.hide("sticks")
cmd.show("nonbonded")
cmd.show("lines", "ch_ecf")
cmd.show("lines", "ch_edf")

cmd.set_view (\
  '''0.030933606,    0.584483027,    0.810812235,\
    -0.455680430,   -0.713744700,    0.531896412,\
     0.889600039,   -0.385925800,    0.244258434,\
     0.000140842,   -0.000561976, -111.916397095,\
   -57.852790833,  -77.408004761,  -41.355598450,\
  -151.198226929,  375.676757812,  -20.000000000''')

cmd.png("lc8.png", width=500, height=400, dpi=200, ray=1)

cmd.quit()
Ejemplo n.º 54
0
    print('Processing pdbs to wrl representations')
    # Save surface representations from pymol to .wrl files

    files = glob.glob(bsPDBDir + '*.pdb')

    for i, f in enumerate(files):
        if i % 100 == 0:
            print("Processing binding site PBD file number " + str(i) +
                  ' of ' + str(len(files)))
        fOut = f.split('/')[-1]
        fOut = fOut.split('_')
        fOut = '_'.join(fOut[:-1])
        cmd.load(f)
        cmd.set('surface_quality', '0')
        cmd.show_as('surface', 'all')
        cmd.set_view('1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,300,1')
        cmd.save(wrlDir + fOut + '.wrl')
        cmd.delete('all')

    print(
        'DONE!\nVDW surfaces for each binding site residue pdb file saved to '
        + LecGly.homeDir[:-1] + wrlDir[1:])
    # ######################################################

    # print('\n\nExtracting points from wrl files and saving to mol2 files...\n')
    # # Get surface points from .wrl files and save to .mol2 files
    # files = os.listdir(wrlDir)
    # for i,f in enumerate(files):
    #     if i % 100 == 0: print("Processing wrl file number " + str(i) + ' of ' + str(len(files)))
    #     pnts = []
    #     pnts = getPntsFromWRL(wrlDir + f)
Ejemplo n.º 55
0
    def display_box(self, box, cylinder_size, prot):
        view = cmd.get_view()
        if prot == 'target':
            name = 'Target_box'
            color = [1.00, 1.00, 1.00]
        else:
            name = 'Off-Target_box'
            color = [0.50, 0.78, 0.50]
        obj = []
        # build cgo object
        for i in range(2):
            for k in range(2):
                for j in range(2):
                    if i != 1:
                        obj.append(CYLINDER)
                        obj.extend([box[0][i], box[1][j], box[2][k]])
                        obj.extend([box[0][i + 1], box[1][j], box[2][k]])
                        obj.append(cylinder_size)
                        obj.extend(color)
                        obj.extend(color)
                        obj.append(COLOR)
                        obj.extend(color)
                        obj.append(SPHERE)
                        obj.extend(
                            [box[0][i], box[1][j], box[2][k], cylinder_size])

                    if j != 1:
                        obj.append(CYLINDER)
                        obj.extend([box[0][i], box[1][j], box[2][k]])
                        obj.extend([box[0][i], box[1][j + 1], box[2][k]])
                        obj.append(cylinder_size)
                        obj.extend(color)
                        obj.extend(color)
                        obj.append(COLOR)
                        obj.extend(color)
                        obj.append(SPHERE)
                        obj.extend([
                            box[0][i], box[1][j + 1], box[2][k], cylinder_size
                        ])
                    if k != 1:
                        obj.append(CYLINDER)
                        obj.extend([box[0][i], box[1][j], box[2][k]])
                        obj.extend([box[0][i], box[1][j], box[2][k + 1]])
                        obj.append(cylinder_size)
                        obj.extend(color)
                        obj.extend(color)
                        obj.append(COLOR)
                        obj.extend(color)
                        obj.append(SPHERE)
                        obj.extend([
                            box[0][i], box[1][j], box[2][k + 1], cylinder_size
                        ])
        axes = [[2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 2.0]]
        xpos = [box[0][1] + (box[0][1] - box[0][0]) / 5., box[1][0], box[2][0]]
        cyl_text(obj, plain, xpos, 'X', 0.10, axes=axes)
        ypos = [box[0][0], box[1][1] + (box[1][1] - box[1][0]) / 5, box[2][0]]
        cyl_text(obj, plain, ypos, 'Y', 0.10, axes=axes)
        zpos = [box[0][0], box[1][0], box[2][1] + (box[2][1] - box[2][0]) / 5]
        cyl_text(obj, plain, zpos, 'Z', 0.10, axes=axes)
        cmd.load_cgo(obj, name)
        cmd.set_view(view)
Ejemplo n.º 56
0
def inner_lddt(interface=False):

    # Save the camera
    save_view = cmd.get_view(output=1, quiet=1)

    pdbname = cmd.get_object_list()[0]

    file_path = os.path.join(my_lddt_path, pdbname + ".npz")

    if ( not os.path.exists(file_path) ):
        print("Could not find npz file: %s"%file_path)
        return

    dat = np.load(file_path)

    ### Stuff from Nao

    digitizations = [-20.0, -15.0, -10.0, -4.0, -2.0, -1.0, -0.5, 0.5, 1.0, 2.0, 4.0, 10.0, 15.0, 20.0]
    masses = [digitizations[0]]+[(digitizations[i]+digitizations[i+1])/2 for i in range(len(digitizations)-1)]+[digitizations[-1]]

    def get_lddt(estogram, mask, center=7, weights=[1,1,1,1]):  
        # Remove diagonal from the mask.
        mask = np.multiply(mask, np.ones(mask.shape)-np.eye(mask.shape[0]))
        # Masking the estogram except for the last cahnnel
        masked = np.transpose(np.multiply(np.transpose(estogram, [2,0,1]), mask), [1,2,0])

        p0 = np.sum(masked[:,:,center], axis=-1)
        p1 = np.sum(masked[:,:,center-1]+masked[:,:,center+1], axis=-1)
        p2 = np.sum(masked[:,:,center-2]+masked[:,:,center+2], axis=-1)
        p3 = np.sum(masked[:,:,center-3]+masked[:,:,center+3], axis=-1)
        p4 = np.sum(mask, axis=-1)

        p4[p4==0] = 1
        # Only work on parts where interaction happen
        output = np.divide((weights[0]*p0 + weights[1]*(p0+p1) + weights[2]*(p0+p1+p2) + weights[3]*(p0+p1+p2+p3))/np.sum(weights), p4)
        return output

    #####

    # if interface, mask out the binder and the target to get individual lddts
    if ( interface ):

        blen = len(cmd.get_coords('name CA and chain A', 1))

        mask2 = np.zeros(dat['mask'].shape)
        mask2[:blen, blen:] = 1
        mask2[blen:, :blen] = 1

        my_lddt = get_lddt(dat['estogram'].transpose([1,2,0]), np.multiply(dat['mask'], mask2))

    else:

        my_lddt = get_lddt(dat['estogram'].transpose([1,2,0]), dat['mask'])


    print("========== Mean LDDT: %.2f"%np.mean(my_lddt))


    # colorspace for lddt visualization
    max_color = 121
    min_color = 0

    # interpolate on RGB so we don't see every color in between
    # set saturation to 0.5 so that we can distinguish from cylinders
    max_rgb = colorsys.hsv_to_rgb(max_color/360, 0.5, 1)
    min_rgb = colorsys.hsv_to_rgb(min_color/360, 0.5, 1)

    max_lddt = 1.0
    min_lddt = 0.5

    # color each residue the corresponding lddt color
    for seqpos in range(1, len(dat['mask'])):
        this_lddt = my_lddt[seqpos-1]
     
        r = np.interp(this_lddt, [min_lddt, max_lddt], [min_rgb[0], max_rgb[0]]) * 255
        g = np.interp(this_lddt, [min_lddt, max_lddt], [min_rgb[1], max_rgb[1]]) * 255
        b = np.interp(this_lddt, [min_lddt, max_lddt], [min_rgb[2], max_rgb[2]]) * 255

        color = "0x%02x%02x%02x"%(int(r), int(g), int(b))

        colorCPK("resi %i"%seqpos, color)

        # cmd.color(color, "resi %i"%seqpos,)


    # get 1 indexed ca positions
    cas = np.r_[ [[0, 0, 0]], cmd.get_coords('name CA', 1)]

    # max radius of cylinders (A)
    max_rad = 0.25

    # standard cylinder drawing function. color in HSV
    def get_cyl(start, end, rad_frac=1.0, color=[360, 0, 1]):

        rgb = colorsys.hsv_to_rgb(color[0]/360, color[1], color[2])

        radius = max_rad * rad_frac
        cyl = [
            # Tail of cylinder
            cgo.CYLINDER, start[0], start[1], start[2]
            , end[0], end[1], end[2]
            , radius, rgb[0], rgb[1], rgb[2], rgb[0], rgb[1], rgb[2]  # Radius and RGB for each cylinder tail
        ]

        return cyl


    def obj_exists(sele):
       return sele in cmd.get_names("objects")


    # clear out the old ones if we ran this twice
    for name in cmd.get_names("objects"):
        if (name.startswith("esto_res")):
            cmd.delete(name)


    estogram = np.transpose(dat['estogram'], [1, 2, 0])

    # parameters for cylinder colors
    # Since the lddt calculation maxes out at 4, we do so too
    # Also, fade near-0 to white so that we don't see sharp edges
    close_range_colors = [58, 0]
    far_range_colors = [167, 296]
    max_range = 4
    white_fade = 0.2

    # interpolate in hue space so that we do see all colors in-between
    def dist_to_color(dist):
        dist = np.clip(dist, -max_range, max_range)
        # dist = 2
        if ( dist < 0 ):
            bounds = close_range_colors
            dist = - dist
        else:
            bounds = far_range_colors

        hue = np.interp(dist, [0, max_range], bounds)
        sat = np.interp(dist, [0, white_fade], [0, 1])

        return [hue, sat, 1]

    # Mask is how likely the model things two residues are within 15A of each other
    # Don't draw cylinders for super distant residues
    min_mask = 0.1

    # actually draw the cylinders
    for seqpos in range(1, len(cas)):

        # pull out the estogram and mask for this position
        esto = estogram[seqpos-1] # shape (N x 15)
        mask = dat['mask'][seqpos-1] # shape (N)

        this_cgo = []

        for other in range(1, len(cas)):
            mask_edge = mask[other-1]
            if ( mask_edge < min_mask ):
                continue

            # estogram is a histogram of distances
            # this method comes directly from nao and takes the "center_of_mass" of that histogram
            esto_dist = np.sum(esto[other-1]*masses)

            color = dist_to_color(esto_dist)

            this_cgo += get_cyl(cas[seqpos], cas[other], rad_frac=mask_edge, color=color)

        if ( len(this_cgo) > 0):

            name = "esto_res%i"%seqpos
            cmd.load_cgo(this_cgo, name)
            cmd.disable(name)


    # disables all estograms and then enables the ones you've selected
    def enable_selected():
        selected = list(set([int(x.resi) for x in cmd.get_model("sele").atom]))

        for name in cmd.get_names("objects"):
            if (name.startswith("esto_res")):
                cmd.disable(name)

        for seqpos in selected:
            name = "esto_res%i"%seqpos
            cmd.enable(name)

        cmd.delete("sele")


    cmd.set_key( 'CTRL-C' , enable_selected )

    # restore the camera
    cmd.set_view(save_view)
Ejemplo n.º 57
0
def ribbon_ride(selection="mol",
                fperm="40",
                zbuff="30",
                halfslab="6",
                frequency="1"):
    # clear various movie memories, frames, caches
    cmd.do("mclear")
    cmd.do("mvClear")
    cmd.do("mset")
    cmd.do("frame 1")

    # get current view, just to inherit some flags like orthoscopic and ?
    # from how the user was looking at the world
    # that being said, most of the 18 view matrix arguments will be set de novo
    # by this routine
    old_view = cmd.get_view()

    fperm = int(fperm)
    frequency = int(frequency)
    zbuff = int(zbuff)
    halfslab = int(halfslab)

    #frame of reference vector...rotations are relative to this
    start = (0, 0, -1)

    # parse mol selection to get array of Calpha coordinates
    cmd.create("calpha", "/" + selection + "////CA")
    calpha = cmd.get_model("calpha")
    # break calpha up so it only includes every xth atom, where x is frequency
    # passed in by user
    totalcount = len(calpha.atom)

    #define working list size
    listsizecorrect = 0
    if (totalcount % frequency):
        listsizecorrect = 1
    workinglist = [0] * (totalcount / frequency + listsizecorrect)
    lpcount = 0
    indexcount = 0
    for a in calpha.atom:
        # now only add this atom to the working array if our counter%frequency is 0
        # i.e. is evenly divisible by the frequency
        if (lpcount % frequency == 0):
            workinglist[indexcount] = (a.coord[0], a.coord[1], a.coord[2])
            indexcount = indexcount + 1
        lpcount = lpcount + 1

    lpcount = 0
    lastx = 0
    target = (0, 0, 0)
    for b in workinglist:
        #cx=a.coord[0]
        #cy=a.coord[1]
        #cz=a.coord[2]
        cx = b[0]
        cy = b[1]
        cz = b[2]

        # calculate vector to next Calpha
        if (lastx):
            vx = cx - lastx
            vy = cy - lasty
            vz = cz - lastz
            target = (vx, vy, vz)
        #print "cx - lastx is: " + `cx` + " - " + `lastx`
        lastx = cx
        lasty = cy
        lastz = cz
        #print "target vector is: " + `target`
        #debugging control point
        #	if (lpcount==1000):
        #		print "breaking!"
        #		break
        if (lpcount > 0):
            #print "We're in!"
            maga = math.sqrt(start[0] * start[0] + start[1] * start[1] +
                             start[2] * start[2])
            magb = math.sqrt(target[0] * target[0] + target[1] * target[1] +
                             target[2] * target[2])
            #print "mag a is " + `maga`
            #print "mag b is " + `magb`

            # normalize the target view vector b
            target = normvec(target, magb)
            #print "normalized target view vector is: " + `target`

            magb = math.sqrt(target[0] * target[0] + target[1] * target[1] +
                             target[2] * target[2])
            #print "magnitude should now be one: " + `magb`
            magb = 1

            #calculate cross product
            cprod = cross_product(start, target)
            #print "cross product is " + `cprod`

            magcross = math.sqrt(cprod[0] * cprod[0] + cprod[1] * cprod[1] +
                                 cprod[2] * cprod[2])
            #print "mag cross is " + `magcross`

            # calculate dot product
            dprod = (start[0] * target[0] + start[1] * target[1] +
                     start[2] * target[2])
            #print "dot product is " + `dprod`

            # get angle between vectors
            sintheta = magcross / (maga * magb)
            theta1 = asin(sintheta)
            theta2 = math.pi - theta1

            costheta = dprod / (maga * magb)
            theta3 = acos(costheta)
            theta4 = -theta3

            # have to check which solution of asin is correct by comparing with acos results
            diff1 = theta1 - theta3
            diff2 = theta2 - theta3
            diff3 = theta1 - theta4
            diff4 = theta2 - theta4
            diff1 = abs(diff1)
            diff2 = abs(diff2)
            diff3 = abs(diff3)
            diff4 = abs(diff4)
            if (diff1 < 0.01):
                theta = theta1

            elif (diff2 < 0.01):
                theta = theta2

            elif (diff3 < 0.01):
                theta = theta1

            elif (diff4 < 0.01):
                theta = theta2

            else:
                theta = 0

    # convert this rotation vector (cprod) and angle (theta) to quaternion form
            quat1 = vecang2quat(cprod, theta)

            #normalize the quat
            quat1 = normquat(quat1)

            # now convert the quaternion to a matrix
            mat = quat2mat(quat1)

            #print "new view matrix is " + `mat`
            cmd.set_view(
                ("%8.3f, " * 17 + "%8.3f") %
                (mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6],
                 mat[7], mat[8], 0, 0, -zbuff, cx, cy, cz, zbuff - halfslab,
                 zbuff + halfslab - 2, old_view[17]))
            new = cmd.get_view()
            if (lpcount == 0):
                original = new
            start_frame = (lpcount - 1) * fperm
            end_frame = start_frame + fperm
            framerange = "%s-%s" % (start_frame, end_frame)
            mvViewTravel(framerange, old_view, new)
            old_view = new
        lpcount = lpcount + 1
    cmd.do("movie")
Ejemplo n.º 58
0
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)
Ejemplo n.º 59
0
                        obj + ' )')


# checks if the argument is the envelope protein
if sys.argv[1] == "E":
    #loads in the pdb file
    cmd.load("../pdb/7k3g.pdb")
    #calls the coloring function
    yrb()
    #shows the surface
    cmd.hide("all")
    cmd.show("surface")
    cmd.set_view("\
         0.545077741,    0.838331640,   -0.009660738,\
         0.245126382,   -0.170380458,   -0.954402864,\
        -0.801753283,    0.517852783,   -0.298365384,\
         0.000000000,    0.000000000, -220.324935913,\
         25.228977203,    0.014108658,    0.018569946,\
         184.920150757,  255.729721069,  -20.000000000")
    os.system('mkdir -p ./images/E')
    cmd.png("./images/E/envelope_protein_1.png")
    cmd.load("./pdb/7k3g.pdb")
    yrb()
    cmd.hide("all")
    cmd.show("surface")
    cmd.set_view("\
         0.001396583,    0.035106514,    0.999381900,\
         0.997273207,    0.073681392,   -0.003983754,\
        -0.073777318,    0.996663272,   -0.034911018,\
         0.000000000,    0.000000000, -220.324935913,\
       25.228977203,    0.014108658,    0.018569946,\
Ejemplo n.º 60
0
    def draw(self, kin_group, dot_mode=0):
        '''Draw the Kinemage dots and clashes.'''
        logger.debug('Drawing Kinemage {}...'.format(self))
        view = cmd.get_view()

        # Set group_auto_mode for easier naming
        gam = cmd.get('group_auto_mode')
        cmd.set('group_auto_mode', 2)

        # Speed up CGO sphere rendering
        if dot_mode == 0:
            cmd.set('cgo_use_shader', 0)
            cmd.set('cgo_sphere_quality', 0)

        # Create dict to store cgolists to be extended
        cgolists = {}

        # Populate a Pointmaster code lookup dict
        pm_lookup = {}
        for pm in self.pointmasters():
            if pm['code'] not in pm_lookup.keys():
                pm_lookup[pm['code']] = pm['label']

        # Get CGO from dotlists
        for dotlist in self.dotlists():
            # Skip non-contact dotlists (if there is such a thing)
            if dotlist[0].dotlist_name != 'x':
                continue

            try:
                dg = dotlist[0].group[0]
            except TypeError:
                dg = 'no_group'  # probe output typically doesn't have a group

            ds = dotlist[0].subgroup[1]
            dm = dotlist[0].master
            for dot in dotlist:
                dpm = pm_lookup[dot.pm]
                dcgo = dot.get_cgo(dot_mode)
                dname = '{}.{}.{}.{}'.format(dg, ds, dm, dpm)
                try:
                    # Extend existing cgo list
                    cgolists[dname].extend(dcgo)
                except KeyError:
                    # Create new cgo list
                    cgolists[dname] = dcgo

        # Get CGO from vectorlists
        # TODO combine this with the dotlist version into a separate function
        for vectorlist in self.vectorlists():
            # Skip non-clash vectorlists (e.g. coordinates)
            if vectorlist[0].vectorlist_name != 'x':
                continue

            try:
                vg = vectorlist[0].group[0]
            except TypeError:
                vg = 'no_group'  # probe output typically doesn't have a group

            vs = vectorlist[0].subgroup[1]
            vm = vectorlist[0].master
            for vector in vectorlist:
                vpm = pm_lookup[vector.pm[0]]  # 2 stored, use first
                vcgo = vector.get_cgo()
                vname = '{}.{}.{}.{}'.format(vg, vs, vm, vpm)
                try:
                    # Extend existing cgo list
                    cgolists[vname].extend(vcgo)
                except KeyError:
                    # Create new cgo list
                    cgolists[vname] = vcgo

        # Create CGO objects
        for name, cgolist in cgolists.items():
            objname = '{}.{}'.format(kin_group, name)
            logger.debug('loading cgo for object {}'.format(objname))
            cmd.load_cgo(cgolist, objname)

        # Restore initial view.
        cmd.set_view(view)

        # Restore initial group_auto_mode setting
        cmd.set('group_auto_mode', gam)

        logger.debug('Finished drawing Kinemage.')