Example #1
0
    def testMset(self):
        # basic tet
        self.prep_movie()
        self.assertEquals(cmd.count_frames(),60)

        # test clearing
        cmd.mset()
        self.assertEquals(cmd.count_frames(),0)

        # test states and frame mapping
        cmd.mset("1x10 1 -10 10 -1")
        cmd.frame(1)
        self.assertEquals(cmd.get_frame(),1)
        self.assertEquals(cmd.get("state"),"1")
        cmd.frame(10)
        self.assertEquals(cmd.get_frame(),10)
        self.assertEquals(cmd.get("state"),"1")
        cmd.frame(12)
        self.assertEquals(cmd.get_frame(),12)
        self.assertEquals(cmd.get("state"),"2")
        cmd.frame(22)
        self.assertEquals(cmd.get_frame(),22)
        self.assertEquals(cmd.get("state"),"9")
        cmd.frame(30)
        self.assertEquals(cmd.get_frame(),30)
        self.assertEquals(cmd.get("state"),"1")
Example #2
0
    def testMset(self):
        # basic tet
        self.prep_movie()
        self.assertEquals(cmd.count_frames(), 60)

        # test clearing
        cmd.mset()
        self.assertEquals(cmd.count_frames(), 0)

        # test states and frame mapping
        cmd.mset("1x10 1 -10 10 -1")
        cmd.frame(1)
        self.assertEquals(cmd.get_frame(), 1)
        self.assertEquals(cmd.get("state"), "1")
        cmd.frame(10)
        self.assertEquals(cmd.get_frame(), 10)
        self.assertEquals(cmd.get("state"), "1")
        cmd.frame(12)
        self.assertEquals(cmd.get_frame(), 12)
        self.assertEquals(cmd.get("state"), "2")
        cmd.frame(22)
        self.assertEquals(cmd.get_frame(), 22)
        self.assertEquals(cmd.get("state"), "9")
        cmd.frame(30)
        self.assertEquals(cmd.get_frame(), 30)
        self.assertEquals(cmd.get("state"), "1")
Example #3
0
def check_selections(queue):
    """ Check if the selection made by the user changed """
    global previous_mouse_mode
    global myspace
    while True:
        # Check if the user changed the selection mode (atom/residue/chain/molecule)
        logging.debug("Current mouse selection mode : %d" %
                      int(cmd.get("mouse_selection_mode")))
        logging.debug("Number of selections: %d" %
                      len(cmd.get_names("selections")))
        if int(cmd.get("mouse_selection_mode")) == 5 and len(
                cmd.get_names("selections")) > 0:
            #logging.debug(cmd.get_names("selections")[1])
            nb_selected_objects = cmd.count_atoms('sele')
            if nb_selected_objects > 0:
                logging.info("--- Selection made by the user ---")
                logging.info(nb_selected_objects)
                cmd.iterate('(sele)', 'models.add(model)', space=myspace)
                logging.info(myspace['models'])
                tmp = set()
                # Make the list with unique items
                for i in myspace['models']:
                    if int(i) not in tmp:
                        tmp.add(int(i))
                # Check if the selection has changed
                if tmp != myspace['previous']:
                    myspace['previous'] = tmp
                    queue.put(tmp)
                else:
                    time.sleep(1)
                cmd.select('none')
        elif int(cmd.get("mouse_selection_mode")) == 1 and len(
                cmd.get_names("selections")) > 0:
            #logging.debug(cmd.get_names("selections")[0])

            nb_selected_objects = cmd.count_atoms('sele')
            if nb_selected_objects > 0:
                logging.info("--- Selection made by the user ---")
                cmd.iterate('(sele)', 'residues.add(resv)', space=myspace)
                logging.info(myspace['residues'])
                tmp = set()
                # Make the list with unique items
                for i in myspace['residues']:
                    if int(i) not in tmp:
                        tmp.add(int(i))
                # Check if the selection has changed
                if tmp != myspace['previous']:
                    myspace['previous'] = tmp
                    queue.put(tmp)
                    #cmd.delete('lb')
                else:
                    time.sleep(1)
                cmd.select('none')

        else:
            # if len(cmd.get_names("selections", enabled_only=1)) == 0:
            #     queue.put(set())
            #previous_mouse_mode = cmd.get("mouse_selection_mode")
            time.sleep(0.5)
Example #4
0
 def toggle_states(self):
     if cmd.get("all_states") == 'on':
         self.toggleStatesCaption = 'Toggle states: OFF'
         cmd.set("all_states", 0)
     elif cmd.get("all_states") == 'off':
         self.toggleStatesCaption = 'Toggle states: ON'
         cmd.set("all_states", 1)
     self.cmd.refresh_wizard()
def dump_rep(name):
    if 'PYMOL_GIT_MOD' in os.environ:
        import shutil
        try:
            shutil.copytree(
                os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'js'),
                os.path.join(os.getcwd(), 'js'))
        except OSError:
            pass

    names = cmd.get_session()['names']
    cmd.set('pdb_retain_ids', 1)

    ret = ''
    for obj in names:
        if (obj == None):
            continue
        if (obj[2] == 0):  # not visible
            continue
        if (obj[1] == 0 and obj[4] == 1 and obj[0] == name):
            ret += parseObjMol(obj)
        if (obj[1] == 0
                and obj[4] == 4):  # currently all dist objects are exported
            ret += parseDistObj(obj)

    cmd.turn('z', 180)
    view = cmd.get_view()
    cmd.turn('z', 180)
    cx = -view[12]
    cy = -view[13]
    cz = -view[14]
    cameraZ = -view[11] - 150
    fov = float(cmd.get("field_of_view"))
    fogStart = float(cmd.get("fog_start"))
    slabNear = view[15] + view[11]
    slabFar = view[16] + view[11]
    ret += "\nview:%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f" % \
        (cx, cy, cz, cameraZ, slabNear, slabFar, fogStart, fov)
    for i in range(9):
        ret += ",%.3f" % view[i]

    bgcolor = cmd.get_setting_tuple('bg_rgb')[1]
    ret += "\nbgcolor:%02x%02x%02x" % (int(255 * float(bgcolor[0])), \
                                       int(255 * float(bgcolor[1])), int(255 * float(bgcolor[2])))
    if 'PYMOL_GIT_MOD' in os.environ:
        template = open(os.path.join(os.environ['PYMOL_GIT_MOD'], 'pymol2glmol', 'imported.html')).read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)
    else:
        template = open('imported.html').read().\
            replace("###INCLUDE_PDB_FILE_HERE###", cmd.get_pdbstr(name)).\
            replace('###INCLUDE_REPRESENTATION_HERE###', ret)

    f = open(name + '.html', 'w')
    f.write(template)
    f.close()
Example #6
0
    def testUnsetDeep(self):
        cmd.fragment('ala')
        cmd.fragment('gly')
        cmd.fragment('his')

        # global
        sphere_scale_global = 0.8
        cmd.set('sphere_scale', sphere_scale_global)
        cmd.set('stick_color', 'blue')

        # object-level
        cmd.set('sphere_scale', .5, 'ala')
        cmd.set('stick_radius', .4, 'gly')

        # atom-level
        cmd.set('sphere_scale', .3, 'index 1-3')
        cmd.set('sphere_color', 'yellow', 'index 2-4')

        # bond-level
        cmd.set('stick_radius', .6, 'elem C')
        cmd.set('stick_color', 'red', 'index 1-5')

        cmd.unset_deep()
        names = cmd.get_object_list()

        for oname in names:
            # object-level check
            for sname in ['sphere_scale', 'sphere_color']:
                self.assertEqual(cmd.get(sname), cmd.get(sname, oname))

            # atom-level check (1)
            # type float
            sname = 'sphere_scale'
            a_level_values = set()
            cmd.iterate(oname, 'a_level_values.add(s.' + sname + ')', space=locals())
            self.assertEqual(len(a_level_values), 1)
            self.assertAlmostEqual(sphere_scale_global, list(a_level_values)[0], delta=1e-4)

            # atom-level check (2)
            # type color ('default' -> None)
            sname = 'sphere_color'
            a_level_values = set()
            cmd.iterate(oname, 'a_level_values.add(s.' + sname + ')', space=locals())
            self.assertEqual(len(a_level_values), 1)
            self.assertEqual(None, list(a_level_values)[0])

        # bond-level check (None for unset settings)
        for sname in ['stick_radius', 'stick_color']:
            b_level_values = cmd.get_bond(sname, '*')
            for o_set in b_level_values:
                for b_set in o_set[1]:
                    self.assertEqual(None, b_set[2], msg=sname + ' ' + o_set[0] + ' ' + str(b_set))
Example #7
0
    def test(self):
        for i in range(100):
            cmd.pseudoatom('xxxxxxxxxx%04d' % i)

        setting = 'sphere_color'
        color = 'blue'
        name = 'xxxxxxxxxx0005'
        cmd.set(setting, color, name)
        self.assertEqual(cmd.get(setting, name), color)

        # crashes in 1.7.6.0 to 1.7.6.6
        util.color_deep('red', 'all')

        self.assertEqual(cmd.get(setting, name), 'default')
Example #8
0
    def test(self):
        for i in range(100):
            cmd.pseudoatom('xxxxxxxxxx%04d' % i)

        setting = 'sphere_color'
        color = 'blue'
        name = 'xxxxxxxxxx0005'
        cmd.set(setting, color, name)
        self.assertEqual(cmd.get(setting, name), color)

        # crashes in 1.7.6.0 to 1.7.6.6
        util.color_deep('red', 'all')

        self.assertEqual(cmd.get(setting, name), 'default')
Example #9
0
    def Start(self):
        
        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        # Display the ligand from the PDB file
        if self.DisplayLigand():
            self.FlexAID.DisplayMessage("Error while trying to display the ligand from PDB file", 1)
            self.Quit_Wizard(self.ErrorCode)
            return
                    
        # Color the Atoms based on their type
        if self.ColorByType():
            self.FlexAID.DisplayMessage("Error while coloring the ligand atoms by type", 1)
            self.Quit_Wizard(self.ErrorCode)
            return            

        # Mask everythign except modifyable object (ligand)
        self.exc = [self.LigDisplay]
        General.mask_Objects(self.exc)        

        self.selection_mode = cmd.get("mouse_selection_mode")
        cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

        # remove any possible selection before selecting atoms
        cmd.deselect()

        self.ErrorCode += 1
Example #10
0
    def __init__(self, top, queue):
        
        #print "New instance of FlexSC Wizard"

        Wizard.__init__(self)
        self.top = top
        self.queue = queue
        self.FlexAID = self.top.top

        self.FlexAID.WizardError = False

        self.TargetName = self.FlexAID.IOFile.Target
        self.TargetFlex = self.top.Vars.TargetFlex

        self.ResidueName = '...'
        self.PanelResidue = '   Residue: '
        
        # Initial view
        self.View = cmd.get_view()
        self.State = cmd.get_state()
        self.auto_zoom = cmd.get("auto_zoom")
        
        # for Quit_Wizard
        self.ErrorCode = 1
        
        self.ErrorStatus = [ "Side-chains shown in white are already set as flexible.",
                             "Side-chains shown in orange are 'active' and are ready to be added." ]
Example #11
0
def get_config_mouse():
    
    config_mouse = ''

    try:
        name = cmd.get("button_mode_name")
        
        if name[0] == '1':
            config_mouse += 'one'
        elif name[0] == '2':
            config_mouse += 'two'
        elif name[0] == '3':
            config_mouse += 'three'

        config_mouse += '_button'

        if name[0] != '1':
            if name[9:] == 'Viewing':
                config_mouse += '_viewing'
            elif name[9:] == 'Editing':
                config_mouse += '_editing'
            elif name[9:] == 'Motions':
                config_mouse += '_motions'

        return config_mouse

    except:
        return 'three_button_viewing'
Example #12
0
def cath_parse_domall(filename=''):
    ''' 
    Download "CathDomall.seqreschopping" to fetch_path (once), parse it and
    store results in global dict "cath_domains".
    '''
    if filename == '':
        fetch_path = cmd.get('fetch_path')
        if fetch_path == '.':
            import tempfile
            fetch_path = tempfile.gettempdir()
        basename = 'CathDomall.seqreschopping'
        filename = os.path.join(fetch_path, basename)
        if not os.path.exists(filename):
            import urllib2
            handle = urllib2.urlopen('http://release.cathdb.info/latest/' + basename)
            out = open(filename, 'w')
            out.write(handle.read())
            out.close()

    for line in open(os.path.expanduser(filename)):
        domid, resix = line.split()
        domain = []
        for resiy in resix.split(','):
            resi = resiy.split('-')
            domain.append((domid[4], resi[0], resi[1]))
        cath_domains[domid] = domain
Example #13
0
def axes(name='axes'):
    '''
DESCRIPTION

    Puts coordinate axes to the lower left corner of the viewport.
    '''
    from pymol import cgo

    auto_zoom = cmd.get('auto_zoom')
    cmd.set('auto_zoom', 0)

    w = 0.06 # cylinder width
    l = 0.75 # cylinder length
    h = 0.25 # cone hight
    d = w * 1.618 # cone base diameter

    obj = [cgo.CYLINDER, 0.0, 0.0, 0.0,   l, 0.0, 0.0, w, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
           cgo.CYLINDER, 0.0, 0.0, 0.0, 0.0,   l, 0.0, w, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
           cgo.CYLINDER, 0.0, 0.0, 0.0, 0.0, 0.0,   l, w, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
           cgo.CONE,   l, 0.0, 0.0, h+l, 0.0, 0.0, d, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0,
           cgo.CONE, 0.0,   l, 0.0, 0.0, h+l, 0.0, d, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0,
           cgo.CONE, 0.0, 0.0,   l, 0.0, 0.0, h+l, d, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]

    PutCenterCallback(name, 1).load()
    cmd.load_cgo(obj, name)

    cmd.set('auto_zoom',auto_zoom)
Example #14
0
def cath_parse_domall(filename=""):
    """ 
    Download "CathDomall.seqreschopping" to fetch_path (once), parse it and
    store results in global dict "cath_domains".
    """
    if filename == "":
        fetch_path = cmd.get("fetch_path")
        if fetch_path == ".":
            import tempfile

            fetch_path = tempfile.gettempdir()
        basename = "CathDomall.seqreschopping"
        filename = os.path.join(fetch_path, basename)
        if not os.path.exists(filename):
            import urllib2

            handle = urllib2.urlopen("http://release.cathdb.info/latest/" + basename)
            out = open(filename, "w")
            out.write(handle.read())
            out.close()

    for line in open(os.path.expanduser(filename)):
        domid, resix = line.split()
        domain = []
        for resiy in resix.split(","):
            resi = resiy.split("-")
            domain.append((domid[4], resi[0], resi[1]))
        cath_domains[domid] = domain
Example #15
0
    def displayPartition(self):

        auto_zoom = cmd.get("auto_zoom")

        try:
            cmd.delete(self.PartitionDisplay)
            cmd.refresh()
        except:
            pass
            
        try:
            cmd.set("auto_zoom", 0)
            
            cmd.load(self.TempPartition, self.PartitionDisplay, format='pdb')
            cmd.refresh()

            cmd.hide('everything', self.PartitionDisplay)
            cmd.refresh()

            cmd.show('surface', self.PartitionDisplay)
            cmd.refresh()

            cmd.color('grey60', self.PartitionDisplay)
            cmd.refresh()
            
            General_cmd.Oscillate(self.Cleft.CleftName, 0.0)

        except:
            self.top.DisplayMessage("  ERROR: An error occured while displaying the partitionned cleft", 1)

        cmd.set("auto_zoom", auto_zoom)
Example #16
0
def get_SASA(pdbfile, pdb1='pdb1'):
    ## set
    cmd.load(pdbfile, pdb1)
    oldDS = cmd.get("dot_solvent")
    cmd.h_add()
    cmd.flag("ignore", "none")
    cmd.set("dot_solvent", 1)
    cmd.set("dot_density", 2)
    cmd.set("solvent_radius", 3)

    ## calculate
    area = cmd.get_area(pdb1, load_b=1)
    stored.r = []
    cmd.iterate(pdb1, 'stored.r.append((model,chain,resi,resn,name,b))')
    areas = {}
    for model, chain, idx, char, name, sasa in stored.r:
        if idx == '653':
            print chain, idx, char, name, sasa
        base = areas.get((chain, idx, char), 0)
        if (char == 'A' and name == 'N1') or (char == 'C' and name == 'N3'):
            base += float(sasa)
        areas[(chain, idx, char)] = base

    ## reset
    cmd.set("dot_solvent", oldDS)
    cmd.delete(pdb1)
    print pdbfile, area, sum(areas.values())
    return areas
Example #17
0
    def displayPartition(self):

        auto_zoom = cmd.get("auto_zoom")

        try:
            cmd.delete(self.PartitionDisplay)
            cmd.refresh()
        except:
            pass
            
        try:
            cmd.set("auto_zoom", 0)
            
            cmd.load(self.TempPartition, self.PartitionDisplay, format='pdb')
            cmd.refresh()

            cmd.hide('everything', self.PartitionDisplay)
            cmd.refresh()

            cmd.show('surface', self.PartitionDisplay)
            cmd.refresh()

            cmd.color('grey60', self.PartitionDisplay)
            cmd.refresh()
            
            General_cmd.Oscillate(self.Cleft.CleftName, 0.0)

        except:
            self.top.DisplayMessage("  ERROR: An error occured while displaying the partitionned cleft", 1)

        cmd.set("auto_zoom", auto_zoom)
Example #18
0
def cath_parse_domall(filename=''):
    ''' 
    Download "CathDomall.seqreschopping" to fetch_path (once), parse it and
    store results in global dict "cath_domains".
    '''
    if filename == '':
        fetch_path = cmd.get('fetch_path')
        if fetch_path == '.':
            import tempfile
            fetch_path = tempfile.gettempdir()
        basename = 'CathDomall.seqreschopping'
        filename = os.path.join(fetch_path, basename)
        if not os.path.exists(filename):
            try:
                import urllib2
            except ImportError:
                import urllib.request as urllib2
            handle = urllib2.urlopen('http://release.cathdb.info/latest/' +
                                     basename)
            out = open(filename, 'w')
            out.write(handle.read())
            out.close()

    for line in open(os.path.expanduser(filename)):
        domid, resix = line.split()
        domain = []
        for resiy in resix.split(','):
            resi = resiy.split('-')
            domain.append((domid[4], resi[0], resi[1]))
        cath_domains[domid] = domain
Example #19
0
 def Load_ProcConvLigand(self, LigandFile, ObjectName, Zoom):
     
     Error = 0
     
     try:
         cmd.delete(ObjectName)
         cmd.refresh()
     except:
         pass
     
     auto_zoom = cmd.get("auto_zoom")
     
     try:
         cmd.set("auto_zoom", 0)                
         cmd.load(LigandFile, ObjectName, state=1)
         cmd.refresh()
             
         if Zoom:
             cmd.zoom(ObjectName)
             cmd.refresh()
     except:
         self.DisplayMessage('  ERROR: Could not load the ligand file in PyMOL', 1)
         Error = 1
     
     cmd.set("auto_zoom", auto_zoom)
     
     return Error
Example #20
0
    def Start(self):

        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        cmd.window('show')
        # self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        self.ErrorCode = 1

        try:
            self.selection_mode = cmd.get("mouse_selection_mode")
            cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

            # Mask objects
            self.exc = [self.LigDisplay]
            General_cmd.mask_Objects(self.exc)

            self.ErrorCode = 0
            
        except:
            self.queue.put(lambda: self.FlexAID.DisplayMessage("  ERROR: Could not start the Anchor Atom wizard", 1))
            self.queue.put(lambda: self.FlexAID.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display the ligand from the PDB file
        if self.DisplayLigand() or self.RefreshDisplay():
            self.queue.put(lambda: self.FlexAID.DisplayMessage("  ERROR: Could not display the ligand", 1))
            self.queue.put(lambda: self.FlexAID.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return
        
        # remove any possible selection before selecting atoms
        cmd.deselect()
Example #21
0
    def __init__(self, top, queue, ResSeq, LigandPath):
        
        #print "New instance of flexbond Class.\n"

        Wizard.__init__(self)

        self.top = top
        self.queue = queue
        self.FlexAID = self.top.top
        self.FlexAID.WizardError = False

        self.ResSeq = ResSeq
        
        self.dictFlexBonds = self.FlexAID.IOFile.Vars.dictFlexBonds
        self.dictNeighbours = self.FlexAID.IOFile.Vars.dictNeighbours

        self.RefLigand = LigandPath

        self.View = cmd.get_view()
        self.State = cmd.get_state()
        self.auto_zoom = cmd.get("auto_zoom")
        
        self.pick_count = 0
        
        self.panelForceBond = 'Adv.: Force bond OFF'
        self.Force = False

        self.point1 = list()
        self.point2 = list()

        self.atom1 = list()
        self.atom2 = list()

        self.ErrorStatus = [ "Flexible bonds of the ligand are shown in orange.",
                             "Selected flexible bonds of the ligand are shown in white." ]
Example #22
0
    def Load_ProcConvLigand(self, LigandFile, ObjectName, Zoom):

        Error = 0

        try:
            cmd.delete(ObjectName)
            cmd.refresh()
        except:
            pass

        auto_zoom = cmd.get("auto_zoom")

        try:
            cmd.set("auto_zoom", 0)
            cmd.load(LigandFile, ObjectName, state=1)
            cmd.refresh()

            if Zoom:
                cmd.zoom(ObjectName)
                cmd.refresh()
        except:
            self.DisplayMessage(
                '  ERROR: Could not load the ligand file in PyMOL', 1)
            Error = 1

        cmd.set("auto_zoom", auto_zoom)

        return Error
Example #23
0
def _get_aaindex1():
    '''
    Get a global AAindex instance for "fetch_path/aaindex1"
    '''
    global _aaindex1
    if _aaindex1 is None:
        _aaindex1 = AAindex(1, cmd.get('fetch_path'), 0)
    return _aaindex1
Example #24
0
def _get_aaindex1():
    '''
    Get a global AAindex instance for "fetch_path/aaindex1"
    '''
    global _aaindex1
    if _aaindex1 is None:
        _aaindex1 = AAindex(1, cmd.get('fetch_path'), 0)
    return _aaindex1
Example #25
0
 def __enter__(self):
     self.saved = []
     for k, v in self.args:
         v_saved = cmd.get(k, self.sele)
         if v != v_saved:
             self.saved.append((k, v_saved))
             cmd.set(k, v, self.sele)
     return self
Example #26
0
def fetch_eppic_sync(pdbCode,iface=0,name=None,state=0,entropies=None,logfn=None,**kwargs):
	"Synchronously fetch eppic interface(s)"
	fetchpath=cmd.get('fetch_path')
	if logfn is None:
		def logfn(m):
			print(m)

	try:
		if entropies is not None:
			entropies = int(entropies)
	except ValueError:
		pass

	if not pdbCode:
		logfn( "No PDB given")
		return

	fetched = []

	if iface: #Single interface
		filename=os.path.join(fetchpath, "%s-%s.pdb"%(pdbCode,iface))
		if name is None:
			name = "{}-{}".format(pdbCode,iface)
		#Download interface
		check_fetch = load_eppic(pdbCode,iface,filename,logfn)
		if check_fetch:
			cmd.load(filename,name,state,format="pdb",**kwargs)
			fetched.append(name)

			if entropies is not None:
				show_entropies(name,entropies)
			cmd.util.color_chains(name)
		else:
			logfn("No PDB or Interface Found")
	else: # All interfaces
		if name is None:
			name = "{}-{{}}".format(pdbCode)
		iface=1
		check_fetch = True
		while check_fetch:
			filename=os.path.join(fetchpath, "%s-%d.pdb"%(pdbCode,iface))
			objname = name.format(iface)
			check_fetch = load_eppic(pdbCode,iface,filename,logfn)
			if check_fetch:
				cmd.load(filename,objname,state,format="pdb",**kwargs)
				fetched.append(objname)

				if entropies is not None:
					show_entropies(objname,entropies)
				cmd.util.color_chains(objname)
				iface+=1
			else:
				if iface==1:
					logfn( "No PBD or Interface Found")
					logfn("No PDB or Interface Found")
	
	return fetched
Example #27
0
    def testMdelete(self):
        cmd.mset("1x10 1 -10 10 -1")

        # 1-10 = state 1
        # 11-20 = states 1..10
        # 21-30 = states 10..1

        cmd.mdelete(count=10, frame=11)
        # simple delete
        self.assertEquals(cmd.count_frames(),20)

        # test state mapping
        cmd.frame(1)
        self.assertEquals(cmd.get("state"),"1")
        cmd.frame(11)
        self.assertEquals(cmd.get("state"),"10")
        cmd.frame(20)
        self.assertEquals(cmd.get("state"),"1")
Example #28
0
def settings(**kwargs):
    """Set options temporarily."""
    orig = {}
    for key, value in kwargs.items():
        orig[key] = pm.get(key)
        pm.set(key, value)
    yield
    for key, value in orig.items():
        pm.set(key, value)
Example #29
0
    def testMdelete(self):
        cmd.mset("1x10 1 -10 10 -1")

        # 1-10 = state 1
        # 11-20 = states 1..10
        # 21-30 = states 10..1

        cmd.mdelete(count=10, frame=11)
        # simple delete
        self.assertEquals(cmd.count_frames(), 20)

        # test state mapping
        cmd.frame(1)
        self.assertEquals(cmd.get("state"), "1")
        cmd.frame(11)
        self.assertEquals(cmd.get("state"), "10")
        cmd.frame(20)
        self.assertEquals(cmd.get("state"), "1")
Example #30
0
    def __init__(self, selection=None, name=None, symbols='', state=-1):
        try:
            from pymol.plugins import get_pmgapp
            pmgapp = get_pmgapp()
        except ImportError:
            pmgapp = None

        if pmgapp is not None:
            rootframe = Tkinter.Toplevel(pmgapp.root)
            parent = rootframe
        else:
            rootframe = Tkinter.Tk()
            parent = rootframe

        rootframe.title(' Dynamic Angle Plotting ')
        rootframe.protocol("WM_DELETE_WINDOW", self.close_callback)

        canvas = SimplePlot(parent, width=320, height=320)
        canvas.bind("<Button-2>", canvas.pickWhich)
        canvas.bind("<Button-3>", canvas.pickWhich)
        canvas.pack(side=Tkinter.LEFT, fill="both", expand=1)
        canvas.axis(xint=150,
                    xlabels=[-180, -120, -60, 0, 60, 120, 180],
                    ylabels=[
                        -180, -150, -120, -90, -60, -30, 0, 30, 60, 90, 120,
                        150, 180
                    ])

        if symbols == 'ss':
            canvas.symbols = 1

        if name is None:
            try:
                name = cmd.get_unused_name('DynoRama')
            except AttributeError:
                name = 'DynoRamaObject'

        self.rootframe = rootframe
        self.canvas = canvas
        self.name = name
        self.lock = 0
        self.state = state

        if name != 'none':
            auto_zoom = cmd.get('auto_zoom')
            cmd.set('auto_zoom', 0)
            cmd.load_callback(self, name)
            cmd.set('auto_zoom', auto_zoom)
            canvas.bind("<ButtonPress-1>", canvas.down)
            canvas.bind("<ButtonRelease-1>", canvas.up)
            canvas.bind("<Motion>", canvas.drag)

        if selection is not None:
            self.start(selection)

        if with_mainloop and pmgapp is None:
            rootframe.mainloop()
Example #31
0
 def testResume(self):
     with testing.mktemp('.pml') as logfile:
         with open(logfile, 'w') as f:
             print('bg yellow', file=f)
         cmd.resume(logfile)
         self.assertEqual('yellow', cmd.get('bg_rgb'))
         cmd.log('hello world')
         cmd.log_close()
         lines = [_f for _f in map(str.strip, open(logfile)) if _f]
         self.assertEqual(lines, ['bg yellow', 'hello world'])
 def do_state(self,state):
     cmd=self.cmd
     if cmd.get("sculpting")=="on":
         names = cmd.get_names("all_objects")
         if (bump_name in names) and (obj_name in names):
             cmd.update(bump_name,obj_name)
     if self.bump_scores:
         state = cmd.get_state()
         print(' Rotamer %d/%d, strain=%.2f' % (state,
                 cmd.count_states(obj_name), self.bump_scores[state - 1]))
Example #33
0
 def testResume(self):
     with testing.mktemp('.pml') as logfile:
         with open(logfile, 'w') as f:
             print('bg yellow', file=f)
         cmd.resume(logfile)
         self.assertEqual('yellow', cmd.get('bg_rgb'))
         cmd.log('hello world')
         cmd.log_close()
         lines = [_f for _f in map(str.strip, open(logfile)) if _f]
         self.assertEqual(lines, ['bg yellow', 'hello world'])
Example #34
0
 def do_state(self,state):
     cmd=self.cmd
     if cmd.get("sculpting")=="on":
         names = cmd.get_names("all_objects")
         if (bump_name in names) and (obj_name in names):
             cmd.update(bump_name,obj_name)
     if self.bump_scores:
         state = cmd.get_state()
         print(' Rotamer %d/%d, strain=%.2f' % (state,
                 cmd.count_states(obj_name), self.bump_scores[state - 1]))
Example #35
0
 def testResume(self):
     with testing.mktemp('.pml') as logfile:
         with open(logfile, 'w') as f:
             print >> f, 'bg yellow'
         cmd.resume(logfile)
         self.assertEqual('yellow', cmd.get('bg_rgb'))
         cmd.log('hello world')
         cmd.log_close()
         lines = filter(None, map(str.strip, open(logfile)))
         self.assertEqual(lines, ['bg yellow', 'hello world'])
Example #36
0
def smooth_map_from_xyz(name,
                        selection,
                        contour_level,
                        grid_spacing,
                        bfactor=100,
                        gaussRes=3,
                        grid_buffer=2,
                        state=0):
    """Creates a map object from a selection with xyz coordinates (e.g. a PDB or XYZ object)
    and draws a smooth isosurface at the specified contour level.

    Parameters
    ----------

    name : str
        name of the map
    selection : xyz object
        loaded PDB or XYZ file
    contour_level : float
        contour level (in sigma units)
    grid_spacing : float
        spacing between grid points (in A)
    bfactor : int
        temperature factor; higher numbers generates smoother surfaces
    gaussRes : int, optional=3
        Gaussian resolution; higher numbers generate smoother surfaces
    grid_buffer : float, optional=2
        buffer for map
    state : int, optional=0
        0: use all states independently with independent extents (default)
        -3: combine all states (ACVs) into a single map

    Notes
    ----
    If a map for each ACV of a multi-model PDB file should be generated,
    the PDB file must be loaded with the flag discrete=1 (load as discrete objects
    to allow each ACV to have different numbers of grid points.
    (see also https://www.pymolwiki.org/index.php/Discrete_objects)

    """
    name_surf = name + "_isosurf"
    name_map = name + "_map"
    bfactor_str = "b={:d}".format(int(bfactor))
    cmd.alter(selection, bfactor_str)
    cmd.alter(selection, bfactor_str)
    gaussRes_default = cmd.get("gaussian_resolution")
    cmd.set("gaussian_resolution", gaussRes)
    cmd.map_new(name_map, "gaussian", grid_spacing, selection, state=state)
    cmd.isosurface(name_surf,
                   name_map,
                   contour_level,
                   selection,
                   buffer=grid_buffer)
    cmd.set("gaussian_resolution", gaussRes_default)
    cmd.disable(selection)
Example #37
0
 def fetch_emd(self):
     if self.emd_id is not None:
         fetch_path = cmd.get('fetch_path')
         urlstr = 'ftp://ftp.wwpdb.org/pub/emdb/structures/EMD-%s/map/emd_%s.map.gz' % (
             self.emd_id, self.emd_id)
         emd_filename = '%s/emd_%s.map.gz' % (fetch_path, self.emd_id)
         if not os.path.exists(emd_filename):
             urllib.request.urlretrieve(urlstr, emd_filename)
         cmd.load(emd_filename)
         self.fill_map_list()
         self.load_isosurface(self.current_mrc)
    def __init__(self, selection=None, name=None, symbols='', state=-1):
        try:
            from pymol.plugins import get_pmgapp
            pmgapp = get_pmgapp()
        except ImportError:
            pmgapp = None

        if pmgapp is not None:
            rootframe = Tkinter.Toplevel(pmgapp.root)
            parent = rootframe
        else:
            rootframe = Tkinter.Tk()
            parent = rootframe

        rootframe.title(' Dynamic Angle Plotting ')
        rootframe.protocol("WM_DELETE_WINDOW", self.close_callback)

        canvas = SimplePlot(parent, width=320, height=320)
        canvas.bind("<Button-2>", canvas.pickWhich)
        canvas.bind("<Button-3>", canvas.pickWhich)
        canvas.pack(side=Tkinter.LEFT, fill="both", expand=1)
        canvas.axis(xint=150,
                    xlabels=[-180, -120, -60, 0, 60, 120, 180],
                    ylabels=[-180, -150, -120, -90, -60, -30, 0, 30, 60, 90, 120, 150, 180])

        if symbols == 'ss':
            canvas.symbols = 1

        if name is None:
            try:
                name = cmd.get_unused_name('DynoRama')
            except AttributeError:
                name = 'DynoRamaObject'

        self.rootframe = rootframe
        self.canvas = canvas
        self.name = name
        self.lock = 0
        self.state = state

        if name != 'none':
            auto_zoom = cmd.get('auto_zoom')
            cmd.set('auto_zoom', 0)
            cmd.load_callback(self, name)
            cmd.set('auto_zoom', auto_zoom)
            canvas.bind("<ButtonPress-1>", canvas.down)
            canvas.bind("<ButtonRelease-1>", canvas.up)
            canvas.bind("<Motion>", canvas.drag)

        if selection is not None:
            self.start(selection)

        if with_mainloop and pmgapp is None:
            rootframe.mainloop()
Example #39
0
def rpcGet(prop, obj):
    """ executes a PyMol get command
 
   return value is either the result of the command or the empty string
 
  """
    res = cmd.get(prop, obj)
    if res is not None:
        return res
    else:
        return ''
Example #40
0
File: rpc.py Project: jandom/rdkit
def rpcGet(prop, obj):
  """ executes a PyMol get command
 
   return value is either the result of the command or the empty string
 
  """
  res = cmd.get(prop, obj)
  if res is not None:
    return res
  else:
    return ''
Example #41
0
def push():
    """save current state to disk"""
    global settings_stack

    push_session()

    settings = {}
    for key in FALSE_COLOR_SETTINGS:
        settings[key] = cmd.get(key)

    settings_stack.append(settings)
Example #42
0
 def movie(self, configurations):
     n = 1
     cmd.feedback("disable", "executive", "actions")
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     for conf in configurations:
         self._setCoordinates(conf)
         cmd.load_model(self.model, self.name, n)
         n = n + 1
     cmd.set("auto_zoom", auto_zoom)
     cmd.feedback("enable", "executive", "actions")
     cmd.mplay()
Example #43
0
 def movie(self, configurations):
     n = 1
     cmd.feedback("disable","executive","actions")
     auto_zoom = cmd.get("auto_zoom")
     cmd.set("auto_zoom", 0)
     for conf in configurations:
         self._setCoordinates(conf)
         cmd.load_model(self.model, self.name, n)
         n = n + 1
     cmd.set("auto_zoom", auto_zoom)
     cmd.feedback("enable","executive","actions")
     cmd.mplay()
Example #44
0
 def test_cgo_lighting_setting(self, has_normal):
     objname = 'simpletri'
     obj = []
     if has_normal:
         obj.extend([NORMAL, 0., 0., 1.])
     obj.extend([
         BEGIN, TRIANGLES, COLOR, 1.0, 0., 0., VERTEX, 0.0, 0.0, 0.0,
         VERTEX, 1.0, 0.0, 0.0, VERTEX, 0.0, 1.0, 0.0, END
     ])
     cmd.load_cgo(obj, objname, 1)
     cgo_lighting = cmd.get('cgo_lighting', objname)
     self.assertEqual(int(cgo_lighting), int(has_normal))
Example #45
0
            def run(self):
                try:
                    conn = httplib.HTTPSConnection(self.nodeobj.data['server'], self.nodeobj.data['port']) #, timeout=5
                    
                    conn.request("POST", self.nodeobj.data['uri'], str(post_data))
                    response = conn.getresponse()
                    response_data = response.read()
                    conn.close()
                except:
                    print "WARNING: showContentService cannot communicate with server '", self.nodeobj.data['server'], " at port ", self.nodeobj.data['port']
                    return
                try:
                    retobj = json.loads(response_data)
                except:
                    print "WARNING: showContentService: reading bad response_data=", response_data
                    return False

                suspend_undo = cmd.get("suspend_undo")

                success = True
                for jobname, resultsjob in retobj:
                    output_files = resultsjob["OUTPUTFILES"]
                    output_file_base64, output_file_ext = output_files["<output_file_1>"]
                    outFileName = '%s/_outputfile%s' % (tmp_dir, output_file_ext)
                    binary_to_file(outFileName, output_file_base64)
                    try:
                        success = process_output[output_file_ext](outFileName, suspend_undo) and success
                    except:
                        print "Error: process_output: output_file_ext=", output_file_ext
                        success = False
                print "success=", success
                if not success:
                    dialog1 = Pmw.MessageDialog(serverobj.dialog.component('hull'),
                                                title = 'Service: Unreadable Outputs',
                                                message_text = 'Some output molecules were not loaded.' )
                    dialog1.iconname('Service: Unreadable Outputs')
                    dialog1.activate()
                
                if serverobj._localscriptvar.get() in local_scripts_data_by_name:
                    scripts_data = local_scripts_data_by_name[serverobj._localscriptvar.get()]
                    print "should be executing this script scripts_data=", scripts_data, " object_list=", object_list
                    import imp
                    mod = imp.new_module(scripts_data[1])
                    execfile(scripts_data[2], mod.__dict__)
                    at = getattr(mod, scripts_data[3])
                    print "at=", at
                    at(object_list)

                serverobj._statusvar.set("Finished running %s molecules with service %s on %s" % (len(object_list), service_name, server_name))
                print "_runServiceDialog done: ret=", ret
                print "\tserverobj._sourcevar=", serverobj._sourcevar.get()
Example #46
0
    def Start(self):

        self.queue.put(lambda: self.FlexAID.root.withdraw())
        cmd.window('hide')
        cmd.window('show')
        # self.queue.put(lambda: cmd.window('show'))
        cmd.refresh_wizard()

        self.ErrorCode = 1        

        try:
            #self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")
            self.selection_mode = cmd.get("mouse_selection_mode")
            cmd.set("mouse_selection_mode", 0) # set selection mode to atomic

            # Mask objects
            self.exc = [self.LigDisplay, self.PossFlexDisplay, self.SelFlexDisplay]
            General_cmd.mask_Objects(self.exc)

            self.ErrorCode = 0

        except:
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not start the Flexible Bonds wizard", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display the ligand from the PDB file
        if self.DisplayLigand():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the ligand", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display all Possible Flexible Bonds
        if self.show_FlexibleBonds():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the flexible bonds", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return

        # Display all Selected Flexible Bonds
        if self.show_SelectedBonds():
            self.queue.put(lambda: self.top.DisplayMessage("  ERROR: Could not display the selected flexible bonds", 1))
            self.queue.put(lambda: self.top.DisplayMessage("         The wizard will abort prematurely", 1))
            self.Quit_Wizard()
            return
        
        # remove any possible selection before selecting atoms
        cmd.deselect()
        cmd.unpick()
Example #47
0
    def Display_BindingSite(self):

        auto_zoom = cmd.get("auto_zoom")
        cmd.set("auto_zoom", 0)

        self.Delete_BindingSite()

        try:
            if self.Vars.BindingSite.Type == 1:

                cmd.pseudoatom(self.BindingSiteDisplay,
                               pos=self.Vars.BindingSite.Sphere.Center,
                               vdw=self.Vars.BindingSite.Sphere.Radius,
                               state=1)
                cmd.refresh()

                cmd.hide('everything', self.BindingSiteDisplay)
                cmd.refresh()

                cmd.show('spheres', self.BindingSiteDisplay)
                cmd.refresh()

                cmd.set('sphere_transparency', 0.7, self.BindingSiteDisplay)
                cmd.color('purpleblue', self.BindingSiteDisplay)
                cmd.refresh()

            elif self.Vars.BindingSite.Type == 2 and self.Vars.BindingSite.listClefts:
                self.Generate_CleftBindingSite()

                cmd.load(self.CleftTmpPath, self.BindingSiteDisplay, state=1)
                cmd.refresh()

                cmd.hide('everything', self.BindingSiteDisplay)
                cmd.refresh()

                cmd.show('mesh', self.BindingSiteDisplay)
                cmd.refresh()

                cmd.alter(self.BindingSiteDisplay, 'vdw=2.00')
                cmd.rebuild(self.BindingSiteDisplay)
                cmd.color('purpleblue', self.BindingSiteDisplay)
                cmd.refresh()
            # cmd.color('purpleblue', self.BindingSiteDisplay)
            # cmd.refresh()

        except:
            self.DisplayMessage("  ERROR: while displaying the binding-site",
                                2)

        cmd.set("auto_zoom", auto_zoom)
Example #48
0
def genAV(obstacles, attachment, linker_length=20.0, linker_diameter=2.0, dye_radius=3.5, disc_step=0.9, name=None, state=1, stripsc=True, allowed_sphere_radius=0.0, smoothSurf=True):

  source = np.array(cmd.get_model(attachment, state).get_coord_list())
  if (source.shape[0]!=1):
    print('attachment selection must contain exactly one atom, selected: {}'.format(source.shape[0]))
    return
  source=source.reshape(3)

  srcAt = cmd.get_model(attachment, state).atom[0]
  srcModelName = cmd.get_names('objects',0,attachment)[0]

  obstacles = '(' + obstacles + ') and not (' + attachment + ')'
  if stripsc and isAA(srcAt.resn):
    obstacles += ' and not (' + srcModelName
    if len(srcAt.chain)>0:
      obstacles += ' and chain ' + srcAt.chain
    obstacles+=' and resi '+srcAt.resi+' and sidechain'+')'
  if allowed_sphere_radius > 0.0:
    obstacles+=' and not (({}) around {})'.format(attachment, allowed_sphere_radius)

  xyzRT=np.zeros((1,4))
  nAtoms=cmd.count_atoms(obstacles)
  if nAtoms>0:
    atoms=cmd.get_model(obstacles, state).atom
    nAtoms=len(atoms)
    xyzRT=np.zeros((nAtoms,4))
    for i,at in enumerate(atoms):
      xyzRT[i]=[at.coord[0],at.coord[1],at.coord[2],at.vdw]

  av1=ll.dyeDensityAV1(xyzRT.T,source,linker_length, linker_diameter, dye_radius, disc_step)
  m=avToModel(av1)
  if len(m.atom)==0:
    print('Failed: Empty AV. Is attachment position buried?')
    return
  if name is None:
    name = srcModelName + '_'
    if len(srcAt.chain)>0:
      name += srcAt.chain + '-'
    name +=  srcAt.resi + '-' + srcAt.name
  cmd.load_model(m, name)

  if smoothSurf:
    surfName=name+'_surf'
    mapName=name+'_map'
    gRes=cmd.get('gaussian_resolution')
    cmd.set('gaussian_resolution',3.0)
    cmd.map_new(mapName,'gaussian', 1.0, name, 6)
    cmd.isosurface(surfName,mapName,0.9)
    cmd.set('gaussian_resolution',gRes)
    cmd.disable(name)
Example #49
0
    def testMadd(self):
        # test clearing
        self.prep_movie()
        self.assertEquals(cmd.count_frames(),60)

        # test states and frame mapping
        cmd.madd("1x10 1 -10 10 -1")
        self.assertEquals(cmd.count_frames(),90)
        
        cmd.frame(1)
        self.assertEquals(cmd.get_frame(),1)
        self.assertEquals(cmd.get("state"),"1")
        cmd.frame(10)
        self.assertEquals(cmd.get_frame(),10)
        self.assertEquals(cmd.get("state"),"1")
        cmd.frame(72)
        self.assertEquals(cmd.get_frame(),72)
        self.assertEquals(cmd.get("state"),"2")
        cmd.frame(82)
        self.assertEquals(cmd.get_frame(),82)
        self.assertEquals(cmd.get("state"),"9")
        cmd.frame(90)
        self.assertEquals(cmd.get_frame(),90)
        self.assertEquals(cmd.get("state"),"1")
Example #50
0
def save_settings(filename='~/.pymolrc-settings.py', quiet=1):
    '''
DESCRIPTION
 
    Dumps all settings with non-default values to ~/.pymolrc-settings.py
 
    Feature Request: Save settings for later use - ID: 1009951
    https://sourceforge.net/tracker/?func=detail&aid=1009951&group_id=4546&atid=354546
    '''
    from pymol.setting import get_name_list
    quiet = int(quiet)
    if not filename.endswith('.py'):
        print('Warning: filename should end with ".py"')
    # temporatily load default settings and remember them
    cmd.reinitialize('store_defaults')
    cmd.reinitialize('original_settings')
    original = [(name, cmd.get(name)) for name in get_name_list()]
    cmd.reinitialize('settings')
    # dump to file
    filename = cmd.exp_path(filename)
    f = open(filename, 'w')
    print('# AUTOGENERATED FILE', file=f)
    print('from pymol import cmd, invocation', file=f)
    print('if invocation.options.show_splash:', end=' ', file=f) # no newline
    print('    print "Loading settings from",', repr(filename), file=f)
    count = 0
    for name, o_value in original:
        value = cmd.get(name)
        if value != o_value:
            print('cmd.set("%s", %s)' % (name, repr(value)), file=f)
            if not quiet:
                print('set %s, %s # default: %s' % (name, value, o_value))
            count += 1
    f.close()
    if not quiet:
        print('Dumped %d settings to %s' % (count, filename))
Example #51
0
    def testMadd(self):
        # test clearing
        self.prep_movie()
        self.assertEquals(cmd.count_frames(), 60)

        # test states and frame mapping
        cmd.madd("1x10 1 -10 10 -1")
        self.assertEquals(cmd.count_frames(), 90)

        cmd.frame(1)
        self.assertEquals(cmd.get_frame(), 1)
        self.assertEquals(cmd.get("state"), "1")
        cmd.frame(10)
        self.assertEquals(cmd.get_frame(), 10)
        self.assertEquals(cmd.get("state"), "1")
        cmd.frame(72)
        self.assertEquals(cmd.get_frame(), 72)
        self.assertEquals(cmd.get("state"), "2")
        cmd.frame(82)
        self.assertEquals(cmd.get_frame(), 82)
        self.assertEquals(cmd.get("state"), "9")
        cmd.frame(90)
        self.assertEquals(cmd.get_frame(), 90)
        self.assertEquals(cmd.get("state"), "1")
Example #52
0
    def test(self):
        cmd.set('opaque_background')
        with testing.mktemp('tmp.pse') as session_filename:
            with testing.mktemp('bg.png') as bg_image_filename:
                cmd.bg_color('red')
                cmd.png(bg_image_filename)
                cmd.bg_color('blue')
                cmd.set('bg_image_filename', bg_image_filename)
                cmd.save(session_filename)

            cmd.load(session_filename)
        x = cmd.get('bg_image_filename')
        self.assertTrue(x.startswith('data:'))
        self.assertImageHasColor('red', delta=4,
                msg='bg_image_filename=data: not rendered')
Example #53
0
 def eval_color(v):
     try:
         if not v:
             v=eval(cmd.get('bg_rgb'))
             v=list(map(sum, list(zip(v,[-1,-1,-1]))))
             v=list(map(abs, v))
             if v[0]==v[1]==v[2]==0.5: # grey
                 v=[0,0,0]
             return v
         if isinstance(v, list):
             return v[0:3]
         if not isinstance(v, str):
             return v[0:3]
         if v.startswith('['):
             return cmd.safe_list_eval(v)[0:3]
         return list(cmd.get_color_tuple(v))
     except:
         return [random.random(),random.random(),random.random()]
Example #54
0
def _get_solvent_radius(selection, state):
    '''Get object-state level solvent_radius'''
    radius = [None]

    try:
        cmd.iterate_state(state,
            'first ({})'.format(selection),
            'radius[0] = s.solvent_radius',
            space=locals())

        if radius[0] is not None:
            # Note: One of my test cases failed with radius 2.75, rounding
            # to one digit worked
            return '{:.1}'.format(radius[0])
    except:
        print('Using global solvent_radius')

    return cmd.get('solvent_radius')
Example #55
0
    def fetch_scop_async(sid, name, state, ver, url, file, **kwargs):
        fetch_path = cmd.get("fetch_path")
        if name is None:
            name = sid

        filename = file or os.path.join( fetch_path, "%s.pdb"%sid )
        if not os.path.isfile(filename):
            try:
                fullURL = "%s/ver=%s&id=%s&output=text" %(url,ver,sid)
                #print "Fetching %s"%fullURL
                result = urllib.urlretrieve(fullURL,filename)
                if not check_format(result):
                    print "Error-fetch-scop: unable to load '%s'"%sid
                    if os.path.isfile(filename):
                        os.remove(filename)
                    return
            except IOError, err:
                print str(err)
                return