Пример #1
0
    def testExtend(self):
        def check(v):
            stored.v = None
            cmd.do('foo', echo=0)
            self.assertEqual(stored.v, v)

        cmd.extend('foo', lambda: setattr(stored, 'v', 123))
        check(123)

        @cmd.extend
        def foo():
            stored.v = 456
        check(456)
Пример #2
0
def __init__(self):
    """
    This is the part that is automatically invoked on PyMOL startup.
    """
    self.menuBar.addmenuitem("Plugin", "command", "Voronoia", label="Voronoia", command=lambda: start_voronoia(self))

    if AUTOMATICALLY_OPEN_PYMOL_PLUGIN:
        start_voronoia(self)

    cmd.extend("packing", show_packing)
    cmd.extend("packing_zscore", show_zscore)
    cmd.extend("show_cavities", show_cavities)
    cmd.extend("show_cav_neighbors", show_cav_neighbors)
Пример #3
0
def init(save=0, fetch=0, pymolapi=0):
    '''
DESCRIPTION

    Imports all psico submodules and puts "psico" into the pymol namespace
    for GUI menus. Also enables "help psico" in the PyMOL command line.

ARGUMENTS

    save = bool: Overload "save" command with psico.exporting.save (writes
    secondary structure and crystal records to PDB header)

    fetch = bool: Overload "fetch" command with psico.importing.fetch (can
    fetch from local mirror, knows SCOP and CATH identifiers)

    pymolapi = 0/1/2: Add all psico functions to PyMOL API (pymol.cmd)
    '''
    import pymol
    from pymol import cmd

    # init all submodules
    psico = __import__(__name__, fromlist=__all__)

    # pymol namespace
    if not hasattr(pymol, 'psico'):
        pymol.psico = psico

    # pymol help
    if 'psico' not in cmd.help_only:
        cmd.help_only['psico'] = [psico]
        cmd.help_sc.append('psico')

    if save:
        cmd.extend('save', psico.exporting.save)

    if fetch:
        cmd.extend('fetch', psico.importing.fetch)

    if pymolapi:
        init_cmd(pymolapi == 2)
Пример #4
0
def __init__(self):
	print "initializing ProVAT viewer..."
	provatpath = ''
	if "PROVATPATH" not in os.environ.keys() :
		provatpath = tkFileDialog.askdirectory(title = 'Provide path to ProVAT distribution', parent=self.root)
		if not provatpath :
			print "Cannot initialize ProVAT :-("
			return
	else : provatpath = os.environ["PROVATPATH"]

	sys.path.append(provatpath)
	print 'SYS.PATH', sys.path
	from vorutil import Vorutil

	cmd.extend('remvs',remvs)
	cmd.extend('newvs',newvs)
	cmd.extend('setAlpha',setAlpha)
	cmd.extend('showvs',showvs)
	cmd.extend('makesurf', makesurf)

	print "initialized ProVAT successfully, enjoy !!"

	self.menuBar.addmenuitem('Plugin', 'command', 'ProVAT', label='ProVAT', command = lambda s=self : initProvatWin(s))
	provatData.provatframe = None
Пример #5
0
#!/usr/bin/env python
from pymol import cmd


def getrange(sel):
    minid = min(cmd.identify(sel, 0))
    maxid = max(cmd.identify(sel, 0))
    print(str(minid) + '-' + str(maxid))


cmd.extend("getrange", getrange)
Пример #6
0
	cmd.enable(cmpx)
	cmd.select(selName1, 'none')
	for (model,resi,diff) in stored.r:
		key=resi+"-"+model
		if abs(diff)>=float(cutoff):
			if key in seen: continue
			else: seen.append(key)
			rVal.append( (model,resi,diff) )
			# expand the selection here; I chose to iterate over stored.r instead of
			# creating one large selection b/c if there are too many residues PyMOL
			# might crash on a very large selection.  This is pretty much guaranteed
			# not to kill PyMOL; but, it might take a little longer to run.
			cmd.select( selName1, selName1 + " or (%s and i. %s)" % (model,resi))

	# this is how you transfer a selection to another object.
	cmd.select(selName, cmpx + " in " + selName1)
	# clean up after ourselves
	cmd.delete(selName1)
	cmd.delete(chA)
	cmd.delete(chB)
	cmd.delete(tempC)
	# show the selection
	cmd.enable(selName)
	
	# reset users settings
	cmd.set("dot_solvent", oldDS)
	
	return rVal

cmd.extend("interfaceResidues", interfaceResidues)
Пример #7
0
    fetch 1rx1, async=0
    as cartoon
    show surface
    mset 1x80
    movie.roll
    movie_fade transparency,  1, 0., 40, 1.
    movie_fade transparency, 41, 1., 80, 0.

SEE ALSO

    mdo, mappend, set
    """
    startFrame, endFrame, startVal = int(startFrame), int(endFrame), float(startVal)
    endVal = abs(1.0 - startVal) if endVal is None else float(endVal)

    if startFrame == endFrame:
        raise CmdException("start == end")

    if startFrame > endFrame:
        startFrame, endFrame = endFrame, startFrame
        startVal, endVal = endVal, startVal

    for frame in range(startFrame, endFrame + 1):
        frac = float(frame - startFrame) / (endFrame - startFrame)

        value = (1.0 - frac) * startVal + frac * endVal
        cmd.mappend(frame, "/cmd.set(%s, %f, %s)" % (repr(setting), value, repr(selection)))

cmd.extend("movie_fade", movie_fade)
cmd.auto_arg[0]["movie_fade"] = cmd.auto_arg[0]["set"]
Пример #8
0
            # hacky: register working directory with test cases
            dirname = os.path.abspath(os.path.dirname(filename))
            PyMOLTestCase.moddirs[mod.__name__] = dirname

            suite.addTest(unittest.defaultTestLoader
                    .loadTestsFromModule(mod))

        testresult = unittest.TextTestRunner(stream=out,
                resultclass=PyMOLTestResult,
                verbosity=int(verbosity)).run(suite)

        while deferred_unlink:
            os.unlink(deferred_unlink.pop())

        return len(testresult.errors) + len(testresult.failures)

    def cli():
        '''
        Test suite client application.
        '''
        if not cliargs.filenames:
            # silently do nothing
            return

        nfail = run_testfiles(**vars(cliargs))
        cmd.quit(nfail)

    cmd.extend('run_testfiles', run_testfiles)

Пример #9
0
        cmd.set_object_ttt(self.name, m, homogenous=1)

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)
cmd.extend('axes', axes)
    return (s1, s2)
 
def ccp4_contact( contactsfile, selName1 = "source", selName2 = "target" ):
    # read and parse contacts file into two lists of contact atoms and contact pair list
    s1, s2 = parseCONTACTContacts(open(contactsfile))
 
    # create a selection for the first contact list
 
    # create the PYMOL selection macros for the residues 
    resNames = [chain+"/"+residue+"/" for (type, residue, chain, atom) in s1]
    # put them in a set to remove duplicates and then join with 'or'
    resSel = " or ".join(frozenset(resNames))
    # finally select them under the new name
    cmd.select(selName1 + "_res", resSel)
 
    atomNames = [chain+"/"+residue+"/"+atom for (type, residue, chain, atom) in s1]
    atomSel = " or ".join(frozenset(atomNames))
    cmd.select(selName1 + "_atom", atomSel)
 
    # create a selection for the second contact list
 
    resNames = [chain+"/"+residue+"/" for (type, residue, chain, atom) in s2]
    resSel = " or ".join(frozenset(resNames))
    cmd.select(selName2 + "_res", resSel)
 
    atomNames = [chain+"/"+residue+"/"+atom for (type, residue, chain, atom) in s2]
    atomSel = " or ".join(frozenset(atomNames))
    cmd.select(selName2 + "_atom", atomSel)
 
cmd.extend("ccp4_contact", ccp4_contact)
Пример #11
0
	# create the axes object, draw axes with cylinders coloured red, green,
	#blue for X, Y and Z
	com = (0.0, 0.0, 0.0)
	if center_obj:
	 	com = center_of_mass.get_com(center_obj)
	u_vec = com/np.linalg.norm(com)

	print 'Origin ', com
	print 'Unit vector ', u_vec

	obj = [
	   CYLINDER, com[0] - length, com[1], com[2], com[0] + length, com[1], com[2], radius, 1, 0, 0, 1, 0, 0,
	   CYLINDER, com[0], com[1] - length, com[2], com[0], com[1] + length, com[2], radius, 0, 1, 0, 0, 1, 0, 
	   CYLINDER, com[0], com[1], com[2]  - length, com[0], com[1], com[2] + length, radius,0, 0, 1, 0, 0, 1,
	   ]
	 
	# add labels to axes object (requires pymol version 0.8 or greater, I
	# believe
	 
	cyl_text(obj,plain,[com[0] - length, com[1], com[2]],'X',0.20,axes=[[3,0,0],[0,3,0],[0,0,3]])
	cyl_text(obj,plain,[com[0], com[1] - length, com[2]],'Y',0.20,axes=[[3,0,0],[0,3,0],[0,0,3]])
	cyl_text(obj,plain,[com[0], com[1], com[2]  - length],'Z',0.20,axes=[[3,0,0],[0,3,0],[0,0,3]])
	 
	# then we load it into PyMOL
	if center_obj:
		cmd.load_cgo(obj, center_obj + '_axes')
	else:
		cmd.load_cgo(obj,  'axes')

cmd.extend('axes', plot_axis)
Пример #12
0
    height = unittouu(height, dpi)
    cmd.png(filename, width, height, dpi, ray)


def save_pdb_without_ter(filename, selection, *args, **kwargs):
    '''
DESCRIPTION

    Save PDB file without TER records. External applications like TMalign and
    DynDom stop reading PDB files at TER records, which might be undesired in
    case of missing loops.
    '''
    v = cmd.get_setting_boolean('pdb_use_ter_records')
    if v: cmd.set('pdb_use_ter_records', 0)
    cmd.save(filename, selection, *args, **kwargs)
    if v: cmd.set('pdb_use_ter_records')


## pymol command stuff

cmd.extend('save_traj', save_traj)
cmd.extend('save_pdb', save_pdb)
cmd.extend('paper_png', paper_png)

cmd.auto_arg[1].update([
    ('save_traj', cmd.auto_arg[1]['save']),
    ('save_pdb', cmd.auto_arg[1]['save']),
])

# vi:expandtab:smarttab
Пример #13
0
            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)



cmd.extend( 'lddt', do_lddt )
cmd.extend( 'lddt_interface', do_lddt_interface )
cmd.extend( 'lddt_path', set_lddt_path )


Пример #14
0
from chempy import cpv


def COM(selection='all', center=0, quiet=1):

    model = cmd.get_model(selection)
    nAtom = len(model.atom)

    COM = cpv.get_null()

    for a in model.atom:
        COM = cpv.add(COM, a.coord)
    COM = cpv.scale(COM, 1. / nAtom)

    if not int(quiet):
        print ' COM: [%8.3f,%8.3f,%8.3f]' % tuple(COM)

    if int(center):
        cmd.alter_state(1,
                        selection,
                        "(x,y,z)=sub((x,y,z), COM)",
                        space={
                            'COM': COM,
                            'sub': cpv.sub
                        })

    return COM


cmd.extend("COM", COM)
Пример #15
0
    for k, (sigma, w) in enumerate(zip(mixture.sigma, mixture.w)):
        print(' %s_%d: sigma = %6.3f, w = %.3f' % (prefix, k + 1, sigma, w))

    print(' BIC: %.2f' % (mixture.BIC))
    print(' Log Likelihood: %.2f' % (mixture.log_likelihood))


# all those have kwargs: mobile, target, mobile_state, target_state
align_methods = [
    'align', 'super', 'cealign', 'tmalign', 'theseus', 'prosmart', 'xfit'
]
align_methods_sc = cmd.Shortcut(align_methods)

# pymol commands
cmd.extend('alignwithanymethod', alignwithanymethod)
cmd.extend('tmalign', tmalign)
cmd.extend('dyndom', dyndom)
cmd.extend('gdt_ts', gdt_ts)
cmd.extend('local_rms', local_rms)
if 'extra_fit' not in cmd.keyword:
    cmd.extend('extra_fit', extra_fit)
cmd.extend('intra_theseus', intra_theseus)
cmd.extend('theseus', theseus)
cmd.extend('prosmart', prosmart)
cmd.extend('xfit', xfit)
cmd.extend('intra_xfit', intra_xfit)
cmd.extend('promix', promix)
cmd.extend('intra_promix', intra_promix)

# autocompletion
Пример #16
0
        maxY,
        minZ,  #7
        VERTEX,
        minX,
        minY,
        maxZ,  #2
        VERTEX,
        minX,
        maxY,
        maxZ,  #4
        VERTEX,
        maxX,
        minY,
        maxZ,  #6
        VERTEX,
        maxX,
        maxY,
        maxZ,  #8
        END
    ]

    boxName = "box_" + str(randint(0, 10000))
    while boxName in cmd.get_names():
        boxName = "box_" + str(randint(0, 10000))

    cmd.load_cgo(boundingBox, boxName)
    return boxName


cmd.extend("drawBoundingBox", drawBoundingBox)
Пример #17
0
        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)


cmd.extend('FocalBlur', FocalBlur)
Пример #18
0
        obj.append(cgo.NORMAL)
        obj.extend(normal)

        # need to order vertices to generate correct triangles for plane
        if cpv.dot_product(cpv.sub(pos[0], pos[1]), cpv.sub(pos[2],
                                                            pos[3])) < 0:
            vorder = [0, 1, 2, 2, 3, 0]
        else:
            vorder = [0, 1, 2, 3, 2, 1]

        # fill in the vertex data for the triangles;
        for i in vorder:
            obj.append(VERTEX)
            obj.extend(pos[i])

    # finish the CGO
    obj.append(END)

    # update the UI
    cmd.load_cgo(obj, name, state, zoom=0)
    cmd.set("cgo_transparency", transp, name)


cmd.extend("bbPlane", bbPlane)

# tab-completion of arguments
cmd.auto_arg[0]['bbPlane'] = cmd.auto_arg[1]['color']
cmd.auto_arg[1]['bbPlane'] = cmd.auto_arg[0]['color']

# vi:expandtab
Пример #19
0
  for j in range(numcol):
    print "%4d  %10.8g  %10.8g  %10.8g  %10.8g  %10.8g" % \
    (j, mean[j], stdev[j], median[j],maximum[j], minimum[j])



  count = 0

  if number != 0:
    print "Loading %d lowest energy structures: " % number
    for i in range(number):
      load_obj(data[i][0], obj, float(data[i][1]),i+1,discrete)
      count += 1
  else:
    if level != 0.0:
      print "Loading structures with energy below specified level: ",level
      limit = level
    else:
      print "Loading structures with energy below the median: ",median
      limit = median

    for i in range(len(data)):
      if float(data[i][1]) < limit:
        load_obj(data[i][0], obj, float(data[i][1]),i+1,discrete)
        count += 1

  print 'Loaded %d structures into %s' % (count, obj)


cmd.extend('load_best',load_best)
Пример #20
0
    tmatched, smatched, tmp_names = matchmaker(target, source, match)

    key = '(' + ','.join(identifiers.split()) + ',)'
    tkeys, skeys = [], []
    cmd.iterate(tmatched, 'tkeys.append(%s)' % (key), space=locals())
    cmd.iterate(smatched, 'skeys.append(%s)' % (key), space=locals())
    t2s = dict(zip(tkeys, skeys))
    cmd.alter(target, '%s = t2s.get(%s, %s)' % (key, key, key), space=locals())

    for name in tmp_names:
        cmd.delete(name)


if 'split_chains' not in cmd.keyword:
    cmd.extend('split_chains', split_chains)
cmd.extend('split_molecules', split_molecules)
cmd.extend('rmsf2b', rmsf2b)
cmd.extend('set_sequence', set_sequence)
if 'alphatoall' not in cmd.keyword:
    cmd.extend('alphatoall', alphatoall)
if 'mse2met' not in cmd.keyword:
    cmd.extend('mse2met', mse2met)
cmd.extend('polyala', polyala)
cmd.extend('stub2ala', stub2ala)
cmd.extend('remove_alt', remove_alt)
cmd.extend('dssp', dssp)
cmd.extend('stride', stride)
cmd.extend('dss_promotif', dss_promotif)
cmd.extend('sst', sst)
cmd.extend('set_phipsi', set_phipsi)
Пример #21
0
    
    cmd.color(WAT_COLOR["IPE_UNOCC"], "resn hoh and chain x" + extra)
    cmd.set("sphere_scale", "0.1", "resn hoh and chain x" + extra)
    cmd.color(WAT_COLOR["CRY_UNOCC"], "resn hoh and chain a" + extra)
    cmd.set("sphere_scale", "0.2", "resn hoh and chain a" + extra)
    cmd.show("spheres", "resn hoh" + extra)
    
    cmd.set("label_position", (0,-1.5,0))
    
    if os.path.exists(fName):
        counter = 0
        for eachLine in open(fName):
            fields = eachLine.split()
            if fields[0][:3] != "HOH": continue
            chainId = fields[0][3]
            resSeq = int(fields[0][-4:])
            selection = ("resn hoh and chain %c and resi %d" % (chainId, resSeq)) + extra
            
            if int(fields[1]) != DUMMY_WATER:
                cmd.set("sphere_scale", "0.3", selection)
                if chainId == 'A':
                    cmd.color(WAT_COLOR["CRY_OCC"], selection)
                    cmd.label(selection, '"A" + resi')
                elif chainId == 'X':
                    cmd.color(WAT_COLOR["IPE_OCC"], selection)
                    cmd.label(selection, '"X" + resi')
                counter += 1
        print "%d occupied waters colored" % counter
    
cmd.extend("occupiedWaters", occupiedWaters)
Пример #22
0
DESCRIPTION

    MMalign wrapper

    Reference: S. Mukherjee and Y. Zhang, Nucleic Acids Research 2009; 37: e83
    http://zhanglab.ccmb.med.umich.edu/MM-align/

SEE ALSO

    tmalign, tmscore
	'''
    return tmalign(mobile, target, args, exe, ter, transform, quiet=quiet)


# pymol commands
cmd.extend('alignwithanymethod', alignwithanymethod)
cmd.extend('tmalign', tmalign)
cmd.extend('tmscore', tmscore)
cmd.extend('mmalign', tmalign)

# autocompletion
cmd.auto_arg[0].update({
    'tmalign': cmd.auto_arg[0]['align'],
    'tmscore': cmd.auto_arg[0]['align'],
    'mmalign': cmd.auto_arg[0]['align'],
})
cmd.auto_arg[1].update({
    'tmalign': cmd.auto_arg[1]['align'],
    'tmscore': cmd.auto_arg[1]['align'],
    'mmalign': cmd.auto_arg[1]['align'],
})
Пример #23
0
        cmd.save(ligand_filename, ligand, state)
        cmd.save(protein_filename, protein, state)

        args = [exe, '-l', ligand_filename, '-p', protein_filename, '-t', '',
                '-o', filename, '-s', str(width), str(height)]

        if not quiet:
            print(' poseview: running...')

        process = subprocess.Popen(args,
                                   universal_newlines=True,
                                   stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
        stdout, _ = process.communicate()

        if not quiet:
            print(stdout)
            print(' poseview: done')

        if filename.endswith('.png'):
            cmd.load(filename)
        elif not quiet:
            print(' Warning: cannot load "%s" into PyMOL, unsupported file type' % (filename))

    except OSError:
        print(' Error: Cannot execute "%s", please provide full path to poseview executable' % (exe))
        raise CmdException
    finally:
        shutil.rmtree(tempdir)

cmd.extend('poseview', poseview)
Пример #24
0
    for target in targets:
        try:
            search_results = subseq_ga_search(target, data, submatrix,
                                              gapcost, minscore, firstonly)
        except Exception as e:
            logging.error("{0}".format(e))
            continue

        if search_results is not None:
            select(search_results, target, sele, method='global')

        else:
            logging.info("Nothing can be found for given target: {0}"
                         .format(target))

cmd.extend('subseq', subseq_re)
cmd.extend('subseq.local', subseq_local_alignment)
cmd.extend('subseq.global', subseq_global_alignment)
stored.id = 0


class CallCounter:
    """Decorator to determine number of calls for a method"""
    def __init__(self, method):
        self.method = method
        self.counter = 0

    def __call__(self, *args, **kwargs):
        self.counter += 1
        return self.method(*args, **kwargs)
Пример #25
0
    if not prefix:
        prefix = os.path.basename(filename).rsplit('.', 1)[0]

    for maptype in maptypes.split():
        F, P, prg = header.guessCols(maptype)
        if None in (F, P):
            print ' Warning: No %s map' % (maptype)
            continue

        name = prefix + '.' + maptype
        if not multistate:
            cmd.delete(name)

        cmd.map_generate(name, filename, F, P, 'None', 0, 0, quiet)
        if name not in cmd.get_names('objects'):
            print ' Error: Loading %s map failed.' % (maptype)
            print ' This PyMOL version might not be capable of loading MTZ files'
            raise CmdException

# commands
cmd.extend('loadall', loadall)
cmd.extend('load_traj_crd', load_traj_crd)
cmd.extend('load_traj_dcd', load_traj_dcd)
cmd.extend('load_3d', load_3d)
cmd.extend('load_aln', load_aln)
cmd.extend('load_gro', load_gro)
cmd.extend('load_mtz', load_mtz)

# vi:expandtab:smarttab
Пример #26
0
                if chain in b_dict:
                    b = b_dict[chain][resi][name]
                else:
                    b = b_dict[''][resi][name]
                return b

            stored.b = b_lookup

            #Print table
            for i in range(len(diff2)):
                print resi[0][i], name[0][i], diff2[i]

            for i in range(len(diff2)):
                sum_rmsf += diff2[i]
                try:
                    b_dict.setdefault(chain[0][i], {}).setdefault(
                        resi[0][i],
                        {})[name[0][i]] = diff2[i]**2 * 8 / 3 * math.pi**2
                except KeyError:
                    print chain[0][i], resi[0][i], name[0][i]
            cmd.alter(selection, '%s=stored.b(chain,resi,name)' % ('b'))
            mean_rmsf = sum_rmsf / len(diff2)

        # sys.stdout = orig_stdout
        # fout.close()

        print "Mean RMSF for selection: %s = %g" % (selection, mean_rmsf)


cmd.extend("rmsf_states", rmsf_states)
Пример #27
0
#-------------------------------------------------------------------------------
def disp_list():
    print(
'''
quickdisplay - list of functions. 
Enter, e.g. "help disp_ss" for more specific info.

    PURPOSE                          FUNCTION
    secondary structure cartoon......disp_ss
    ball and stick representation....disp_ball_stick
    mesh display.....................disp_mesh
    surface display..................disp_surf
    Putty b-factor sausage...........disp_putty
'''
    )
cmd.extend( "disp_list", disp_list )
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------





#-------------------------------------------------------------------------------
# PERCENTILE LIMITS (used below)
#-------------------------------------------------------------------------------
def get_b_limits(input='[0,100]', selection='all'):
    from pymol import cmd, stored
    import math
    try:
        limits=str(input)
    # Create stick residue objects
    for i in range(len(MaxNegDist)):
        name = str(i) + "_" + str(round(MaxNegDist[i][0], 1)) + "_" + shortaa(str(MaxNegDist[i][5])) + str(MaxNegDist[i][1]) + shortaa(str(MaxNegDist[i][6])) + str(MaxNegDist[i][2])
        selection = str(molecule1) + " and resi " + str(MaxNegDist[i][1]) + "+" + str(MaxNegDist[i][2]) + " or " + str(molecule2) + " and resi " + str(MaxNegDist[i][2])
        # print selection
        cmd.create(name, selection)
        if showsticks == 'yes' or showsticks == 'y':
            cmd.show("sticks", name)
    for i in range(len(MaxPosDist)):
        name = str(i) + "_" + str(round(MaxPosDist[i][0], 1)) + "_" + shortaa(str(MaxPosDist[i][5])) + str(MaxPosDist[i][1]) + shortaa(str(MaxPosDist[i][6])) + str(MaxPosDist[i][2])
        selection = str(molecule1) + " and resi " + str(MaxPosDist[i][1]) + "+" + str(MaxPosDist[i][2]) + " or " + str(molecule2) + " and resi " + str(MaxPosDist[i][2])
        # print selection
        cmd.create(name, selection)
        if showsticks == 'yes' or showsticks == 'y':
            cmd.show("sticks", name)
cmd.extend("dispmap", dispmap)


def create_nXn_matrix(n):
    return [[0.0 for x in range(n)] for x in range(n)]


def distance(array1, array2, i, j):
    i = int(i)
    j = int(j)
    dist = sqrt((array1[i][0] - array2[j][0]) ** 2 + (array1[i][1] - array2[j][1]) ** 2 + (array1[i][2] - array2[j][2]) ** 2)
    return dist


def Coord(Input):
    print(cmd.get_atom_coords(Input))
       'MET':'M',
       'PHE':'F',
       'PRO':'P',
       'SER':'S',
       'THR':'T',
       'TRP':'W',
       'TYR':'Y',
       'VAL':'V'
       } 
    return trans[three]
# ------------------------------------------------------------


# ************************************************************
# Expose to the PyMOL shell
cmd.extend('setup', setup)
cmd.extend('frag', frag)
cmd.extend('getRots', getRots)
cmd.extend('localSculpt', localSculpt)
cmd.extend('seq', seq)
# ------------------------------------------------------------

######################
# Modified avf.py
#####################
            
def writeCatSeq(variant):
    # Convenience list of variants, replacing the '+'.
    varlist = variant.split('+')

    # Initialization of the bash script
Пример #30
0
    if expression in discrete_expr:
        val_range = int(maximum - minimum + 1)
    else:
        val_range = maximum - minimum
        cmd.color(colors[0], selection)

    steps = 60 / parts
    steps_total = steps * parts

    val_start = minimum
    for p in range(parts):
        for i in range(steps):
            ii = float(i)/steps
            col_list = [colvec[p+1][j] * ii + colvec[p][j] * (1.0 - ii) for j in range(3)]
            col_name = '0x%02x%02x%02x' % (col_list[0] * 255, col_list[1] * 255, col_list[2] * 255)
            val_end = val_range * (i + 1 + p * steps) / steps_total + minimum
            if expression in discrete_expr:
                cmd.color(col_name, '(%s) and %s %d-%d' % (selection, expression, val_start, val_end))
            else:
                cmd.color(col_name, '(%s) and %s > %f' % (selection, expression, val_start))
            val_start = val_end

cmd.extend('spectrumany', spectrumany)

# tab-completion of arguments
cmd.auto_arg[0]['spectrumany'] = [ expression_sc  , 'expression'      , ', ' ]
cmd.auto_arg[1]['spectrumany'] = [ cmd.auto_arg[0]['color'][0], 'color', ' ' ]
cmd.auto_arg[2]['spectrumany'] = cmd.auto_arg[2]['spectrum']

# vi:expandtab:smarttab
Пример #31
0
        if v.startswith('['):
            return cmd.safe_list_eval(v)
        return cmd.get_atom_coords(v)

    xyz1 = get_coord(atom1)
    xyz2 = get_coord(atom2)
    normal = cpv.normalize(cpv.sub(xyz1, xyz2))

    if hlength < 0:
        hlength = radius * 3.0
    if hradius < 0:
        hradius = hlength * 0.6

    if gap:
        diff = cpv.scale(normal, gap)
        xyz1 = cpv.sub(xyz1, diff)
        xyz2 = cpv.add(xyz2, diff)

    xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2)

    obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + \
          [cgo.CONE] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + \
          [1.0, 0.0]

    if not name:
        name = cmd.get_unused_name('arrow')

    cmd.load_cgo(obj, name)

cmd.extend('cgo_arrow', cgo_arrow)
Пример #32
0
    for i in it:
        (start, stop) = i.span()
        # we found some residues, which chains are they from?
        i_chains = chains[start:stop]
        # are all residues from one chain?
        if len(set(i_chains)) != 1:
        	# now they are not, this match is not really a match, skip it
        	continue
        chain = i_chains[0]
        cmd.select(rSelName, rSelName + " or (__h and i. " + str(IDs[start]) + "-" + str(IDs[stop - 1]) + " and c. " + chain + " )")
        if int(firstOnly):
            break
    cmd.delete("__h")
    return rSelName
cmd.extend("findseq", findseq)


def checkParams(needle, haystack, selName, het, firstOnly):
    """
    This is just a helper function for checking the user input
    """
    # check Needle
    if len(needle) == 0 or type(needle) != types.StringType:
        print "Error: Please provide a string 'needle' to search for."
        print "Error: For help type 'help motifFinder'."
        return False

    # check Haystack
    if len(haystack) == 0 or type(haystack) != types.StringType:
        print "Error: Please provide valid PyMOL object or selection name"
Пример #33
0
    val_range = int(last - first + 1)
    if val_range < 2:
        print ' Error: no spectrum possible, need more than 1 state'
        raise CmdException

    for i in range(val_range):
        p = float(i) / (val_range - 1) * (len(colvec) - 1)
        p0, p1 = int(floor(p)), int(ceil(p))
        ii = (p - p0)
        col_list = [
            colvec[p1][j] * ii + colvec[p0][j] * (1.0 - ii) for j in range(3)
        ]
        col_name = '0x%02x%02x%02x' % (col_list[0] * 255, col_list[1] * 255,
                                       col_list[2] * 255)
        for s in settings:
            cmd.set(s, col_name, selection, state=i + first)


cmd.extend('spectrum_states', spectrum_states)

# tab-completion of arguments
cmd.auto_arg[0]['spectrum_states'] = cmd.auto_arg[0]['disable']
cmd.auto_arg[1]['spectrum_states'] = [
    cmd.auto_arg[0]['show'][0], 'representation', ' '
]
cmd.auto_arg[2]['spectrum_states'] = [
    cmd.auto_arg[0]['color'][0], 'color', ' '
]

# vi:expandtab:smarttab
Пример #34
0
    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()

cmd.extend('pymol2glmol', dump_rep)
cmd.auto_arg[0]['pymol2glmol'] = [cmd.object_sc, 'object', '']
Пример #35
0
    API only. Context manager to restore the current scene on exit.
    '''
    def __init__(self, **kwargs):
        self.kwargs = kwargs
    def __enter__(self):
        import random
        self.name = 'tmp_%d' % (random.randint(0, 1e8))
        cmd.scene(self.name, 'store', **self.kwargs)
    def __exit__(self, type, value, traceback):
        cmd.scene(self.name, 'recall')
        cmd.scene(self.name, 'delete')

# commands
cmd.alias('z', 'zoom visible')
cmd.alias('x', 'nice')
cmd.extend('nice', nice)
cmd.extend('cbm', cbm)
cmd.extend('cbs', cbs)
cmd.extend('spectrumany', spectrumany)
cmd.extend('spectrum_states', spectrum_states)

# tab-completion of arguments
cmd.auto_arg[0]['spectrumany'] = [ expression_sc  , 'expression'      , ', ' ]
cmd.auto_arg[1]['spectrumany'] = [ cmd.auto_arg[0]['color'][0], 'color', ' ' ]
cmd.auto_arg[2]['spectrumany'] = cmd.auto_arg[2]['spectrum']
cmd.auto_arg[0]['spectrum_states'] = cmd.auto_arg[0]['disable']
cmd.auto_arg[1]['spectrum_states'] = [ cmd.auto_arg[0]['show'][0], 'representation', ' ' ]
cmd.auto_arg[2]['spectrum_states'] = cmd.auto_arg[1]['spectrumany']

# vi:expandtab:smarttab
Пример #36
0
    selection1Dictionary = createSelectionDictionary(selection1)
    selection2Dictionary = createSelectionDictionary(selection2)

    for key in selection1Dictionary:
        if key in selection2Dictionary:
            if selection1Dictionary[key] != selection2Dictionary[key]:
                chainsAndResidues += conjunction + ' ( chain ' + key[
                    0] + ' and resi ' + key[1] + ' )'
                conjunction = ' or'

    if chainsAndResidues != '':
        cmd.do('select %s, (%s or %s) and (%s)' %
               (selection3, selection1, selection2, chainsAndResidues))


cmd.extend("diffSelections", diffSelections)

#####################################################
# MSL Stuff
import PythonMSL


def localSamplingCCD(
        system="all",
        fragSel="sele and name CA",
        bbqTable="/export/home/brettth/projectsS/code/tree/mslib/trunk/tables/PiscesBBQTable.txt",
        angle=10,
        numResults=25):
    cmd.read_pdbstr(
        PythonMSL.localSamplingCCD(cmd.get_pdbstr(system),
                                   cmd.get_pdbstr(fragSel), numResults, angle,
Пример #37
0
    # check for obsolete development version of pymolplugins
    if 'pymolplugins' in sys.modules:
        from .legacysupport import tkMessageBox
        tkMessageBox.showwarning('WARNING',
                '"pymolplugins" now integrated into PyMOL as "pymol.plugins"! '
                'Please remove the old pymolplugins module and delete ~/.pymolrc_plugins.py')

    if os.path.exists(PYMOLPLUGINSRC):
        from pymol import parsing
        parsing.run_file(PYMOLPLUGINSRC, {'__script__': PYMOLPLUGINSRC}, {})

    autoload = (pmgapp != -2)
    for parent in [startup]:
        modules = findPlugins(parent.__path__)

        for name, filename in modules.items():
            mod_name = parent.__name__ + '.' + name
            info = PluginInfo(name, filename, mod_name)
            if autoload and info.autoload:
                info.load(pmgapp)

# pymol commands
cmd.extend('plugin_load', plugin_load)
cmd.extend('plugin_pref_save', pref_save)

# autocompletion
cmd.auto_arg[0]['plugin_load'] = [ lambda: cmd.Shortcut(plugins), 'plugin', ''  ]

# vi:expandtab:smarttab:sw=4
Пример #38
0
                cara = "CA"
            if stored.resdict[b] == "GLY":
                carb = "CA"

            #cmd.distance(f"{a}_{b}_{model}",f"(/{model}//{chain}/{a}/{cara})",(f"(/{model}//{chain}/{b}/{carb})"))
            cmd.distance('{0}_{1}_{2}'.format(a, b, model),
                         '/{0}//{1}/{2}/{3}'.format(model, chain, a, cara),
                         '/{0}//{1}/{2}/{3}'.format(model, chain, b, carb))

    cmd.set('dash_color', 'cyan')
    cmd.set('dash_radius', '0.1')
    cmd.set('dash_gap', '0.05')
    print("===finished===")


cmd.extend('contactmap', contactmap)

# tab-completion of arguments
cmd.auto_arg[0].update({
    'contactmap': cmd.auto_arg[0]['zoom'],
})


def contactmap_yang(selection='',
                    chain='',
                    align='hmm2.map',
                    pcut=0.999,
                    offset=0):
    '''
DESCRIPTION
Пример #39
0
    b_dict = dict()
    for col in cmd.get_raw_alignment(aln):
        assert len(col) == 2
        b = cpv.distance(idx2coords[col[0]], idx2coords[col[1]])
        for idx in col:
            b_dict[idx] = b
    #pdb.set_trace()
    cmd.alter(seleboth, 'b = b_dict.get((model, index), -1)', space=locals())

    if doPretty:
        cmd.orient(seleboth)
        cmd.show_as('cartoon', 'byobj ' + seleboth)
        cmd.color('gray', seleboth)
        cmd.spectrum('b', 'blue_red', seleboth + ' and b > -0.5')

    if not quiet:
        print " ColorByRMSD: Minimum Distance: %.2f" % (min(b_dict.values()))
        print " ColorByRMSD: Maximum Distance: %.2f" % (max(b_dict.values()))
        print " ColorByRMSD: Average Distance: %.2f" % (sum(b_dict.values()) / len(b_dict))

    cmd.delete(aln)
    cmd.delete(seleboth)

cmd.extend('colorbyrmsd', colorbyrmsd)

# tab-completion of arguments
cmd.auto_arg[0]['colorbyrmsd'] = cmd.auto_arg[0]['align']
cmd.auto_arg[1]['colorbyrmsd'] = cmd.auto_arg[1]['align']

# vi: ts=4:sw=4:smarttab:expandtab
Пример #40
0
            + " \t\t=>\t HELIX: " + str(round(aaDict[aa][0] / sum(aaDict[aa]), 3)) + " %"
            + " \t BETA: " + str(round(aaDict[aa][1] / sum(aaDict[aa]), 3)) + " %"
            + " \t LOOP: " + str(round(aaDict[aa][2] / sum(aaDict[aa]), 3)) + " %"
        )


def countStructuresForAA(aa="ALA", elemName="all"):
    """
    Detects for a single amino acid how
    :param aa: 3 letter code amino acid
    :param elemName: all
    :return: list of counts in [helices, betasheet, loops, total amount]
    """
    structurList = [0, 0, 0]  # [H,S,L]
    objList = cmd.get_names("objects")
    obj = objList[0]  # elements (right in the protein browser in pymol)
    models = cmd.get_model(obj + " and resn " + aa + " and name CA")

    for i in models.atom:
        if i.ss == "H":
            structurList[0] += 1  # counting the Helix
        elif i.ss == "S":
            structurList[1] += 1
        else:
            structurList[2] += 1
    return structurList

#make function usable in PyMol
cmd.extend("countStructuresForAA", countStructuresForAA)
cmd.extend("countStructuresForAllAA", countStructuuresForAllAA)
Пример #41
0
    for (a,_) in ref:
        f.write("<li><a href='#%s'>%s</a>" % (a, a))
    f.write("</ul>")
    for (a, func) in ref:
        doc = func.__doc__.strip().replace("<", "&lt;")
        f.write("<hr size=1><h2 id='%s'>%s</h2>" % (a, a))
        f.write("<pre>%s</pre>" % (doc))
        f.write("<p class='api'>api: %s.%s</p>" % (func.__module__, func.__name__))
    f.write("</body></html>")
    f.close()

def write_txt_ref(filename, prefix='psico'):
    '''
DESCRIPTION

    Write psico command and its DESCRIPTION to file as plain text.

SEE ALSO

    cmd.write_html_ref
    '''
    write_html_ref(filename, prefix, 'txt_short')

cmd.extend('grepset', grepset)
cmd.extend('apropos', apropos)
cmd.extend('api_info', api_info)

cmd.auto_arg[0]['api_info'] = [ cmd.kwhash, 'command', '' ]

# vi:expandtab:smarttab
Пример #42
0
    pmgapp == -1: Autoloading but no legacyinit
    else:         Autoloading and legacyinit
    '''
    if os.path.exists(PYMOLPLUGINSRC):
        from pymol import parsing
        try:
            parsing.run_file(PYMOLPLUGINSRC, {'__script__': PYMOLPLUGINSRC},
                             {})
        except SyntaxError as e:
            colorprinting.warning(str(e))

    autoload = (pmgapp != -2)
    for parent in [startup]:
        modules = findPlugins(parent.__path__)

        for name, filename in modules.items():
            mod_name = parent.__name__ + '.' + name
            info = PluginInfo(name, filename, mod_name)
            if autoload and info.autoload:
                info.load(pmgapp)


# pymol commands
cmd.extend('plugin_load', plugin_load)
cmd.extend('plugin_pref_save', pref_save)

# autocompletion
cmd.auto_arg[0]['plugin_load'] = [lambda: cmd.Shortcut(plugins), 'plugin', '']

# vi:expandtab:smarttab:sw=4
Пример #43
0
                except CmdException:
                    print('FAILED: %s - %s' % (sele1, sele2))
                    print(restraints["ID"])
                    return 0

        else:
            if single:
                label = "NOE"

            else:
                label = "NOE_" + restraints["ID"]

            try:
                cmd.distance(label, sele1, sele2, quiet=quiet,
                             width=line_width, gap=0, label=0)

                _color_restraint(label, line_color)
            except CmdException:
                print('FAILED: %s - %s' % (sele1, sele2))
                print(restraints["ID"])
                return 0

    return 1


def _color_restraint(object_name, color="yellow"):
    cmd.set("dash_color", color, object_name)


cmd.extend("plot_noe", plot_noe)
Пример #44
0
def __init_plugin__(app):
    cmd.extend('showAlignment', showAlignment)
Пример #45
0
            refRes = node.get('residue')
            refPos = node.get('aaPosition')
            intPos = int(refPos) + 1
        except:
            print('no ref')
            continue
        # snp alleles
        for node in rs.xpath(addr % ('missense'), namespaces=ns):
            pos = node.get('aaPosition')
            assert pos == refPos
            features.add(('VARIANT', intPos, intPos, '%s -> %s (in dbSNP:rs%s)' % \
                    (refRes, node.get('residue'), rsId)))

    # make SwissProt like record
    record = Record()
    record.entry_name = seq.id
    record.sequence = str(seq.seq)
    record.features = sorted(features)
    snp_common(record, selection, label, name, quiet)

cmd.extend('snp_uniprot', snp_uniprot)
cmd.extend('snp_ncbi', snp_ncbi)

# tab-completion of arguments
cmd.auto_arg[1].update({
    'snp_uniprot'    : cmd.auto_arg[0]['zoom'],
    'snp_ncbi'       : cmd.auto_arg[0]['zoom'],
})

# vi:expandtab
Пример #46
0
    cmd.save(pname, complex_name + ' and not resn ' + ResId)
    cmd.delete(complex_name)

    # Now deal with changing to complexes.

    for complex in pdbfiles:
        # copy the file over
        #   cmd.do('set retain_order,1')
        new_complex_path = os.path.join(Complex_path, complex)
        new_ligand_path = os.path.join(Ligand_path, complex)

        # copy file
        copyfile(new_complex_path, new_ligand_path)

        # name, file extension
        complex_name, file_ext = complex.split('.')
        cmd.load(complex)

        cmd.save(complex_name + '.pdb', complex_name + ' and resn ' + ResId)
        cmd.delete(complex_name)

    # Change dir back
    os.chdir(maindir)
    return pdbfiles


cmd.extend('LigandRMSProcess', LigandRMSProcess)
cmd.extend('ComplexRMSProcess', ComplexRMSProcess)
cmd.extend('ComplexFP', ComplexFP)
cmd.extend('LigandFP', LigandFP)
Пример #47
0
License: BSD-2-Clause
'''

from pymol import cmd


def show_bumps(selection='(all)', name='bump_check', quiet=1):
    '''
DESCRIPTION

    Visualize VDW clashes

ARGUMENTS

    selection = string: atom selection {default: all}

    name = string: name of CGO object to create {default: bump_check}
    '''
    cmd.delete(name)
    cmd.create(name, selection, zoom=0)
    cmd.set('sculpt_vdw_vis_mode', 1, name)
    cmd.set('sculpt_field_mask', 0x020)  # cSculptVDW
    for state in range(1, 1 + cmd.count_states('%' + name)):
        cmd.sculpt_activate(name, state)
        strain = cmd.sculpt_iterate(name, state, cycles=0)
        if not int(quiet):
            print('VDW Strain in state %d: %f' % (state, strain))
    cmd.show_as('cgo', name)

cmd.extend('show_bumps', show_bumps)
Пример #48
0
      align_mine target=name1, files=cluster*.xyz

  """

  file_list = glob.glob(files)
  file_list.sort()
  extension = re.compile( '(^.*[\/]|\.(pdb|ent|brk|xyz))' )
  object_list = []

  rmsd = {}
  rmsd_list = []
  for i in range(len(file_list)):
    obj_name1 = extension.sub('',file_list[i])
    object_list.append(extension.sub('',file_list[i]))
    cmd.load(file_list[i],obj_name1)
    objectname = 'align_%s_on_%s' % (object_list[i],target)
    rms = cmd.align('%s '%(object_list[i]),'%s '%(target),object=objectname)

    rmsd[object_list[i]] = (rms[0],rms[1])
    rmsd_list.append((object_list[i],rms[0],rms[1]))
    cmd.delete(obj_name1)

  print ("Aligning against: %s"%(target))
  for object_name in object_list:
    print ("%s: %6.3f using %d atoms" % (object_name,rmsd[object_name][0],rmsd[object_name][1]))

  for r in rmsd_list:
    print ("%s: %6.3f using %d atoms" % r)

cmd.extend('align_mine',align_mine)
Пример #49
0
            html.append('</font><font color="' + color + '">')
            stored.color = color
        html.append(aa)
    for obj in cmd.get_object_list('(' + selection + ')'):
        for chain in cmd.get_chains('model %s and (%s)' % (obj, selection)):
            sele = 'model %s and chain "%s" and (%s)' % (obj, chain, selection)
            html.append('\n<br>&gt;%s_%s<font>' % (obj, chain))
            stored.resv = None if gapped else 0
            stored.color = None
            cmd.iterate(sele, 'callback(resv, resn, color)', space=locals())
            html.append('</font>')
    handle = open(filename, 'w')
    print('<html><body style="font-family:monospace">', file=handle)
    print(''.join(html), file=handle)
    print('</body></html>', file=handle)
    handle.close()

cmd.extend('fasta', fasta)
cmd.extend('pir', pir)
cmd.extend('save_colored_fasta', save_colored_fasta)

cmd.auto_arg[0].update({
    'fasta'          : cmd.auto_arg[0]['zoom'],
    'pir'            : cmd.auto_arg[0]['zoom'],
})
cmd.auto_arg[1].update([
    ('save_colored_fasta', cmd.auto_arg[0]['zoom']),
])

# vi: ts=4:sw=4:smarttab:expandtab
Пример #50
0
            coord1 = (m1.atom[0].coord, )
            coord2 = (m2.atom[0].coord, )

    cyl_obj = []
    for x, y in zip(coord1, coord2):
        cyl_obj.extend([CYLINDER] + x + y + [radius] + tup_color + tup_color2)

    if not object_name:
        if "link" not in cmd.get_names("objects"):
            object_name = "link"
        else:
            count = 0
            for n in cmd.get_names("objects"):
                if n[0:4] == "link":
                    count += 1

            object_name = "link" + str(count)

    else:
        count = 0
        for n in cmd.get_names("objects"):
            if n[0:len(object_name)] == object_name:
                #        print(object_name, n[0:len(object_name)])
                count += 1

        object_name = object_name  # + str(count)

    cmd.load_cgo(cyl_obj, object_name)

cmd.extend("draw_links", draw_links)
Пример #51
0
    cmd.bg_color('white')

class set_temporary(object):
    '''
DESCRIPTION

    API only. Supports the following pattern:

    >>> with set_temporary(pdb_retain_ids=1):
    ...    cmd.save('out.pdb')
    '''
    def __init__(self, *args, **kwargs):
        self.sele = kwargs.pop('selection', '')
        self.args = args + tuple(kwargs.items())
    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
    def __exit__(self, type, value, traceback):
        for k, v in self.saved:
            cmd.set(k, v, self.sele)

cmd.extend('save_settings', save_settings)
cmd.extend('paper_settings', paper_settings)

# vi:expandtab:smarttab
Пример #52
0
        atoms[0].adjacent.append(atoms[1])
        atoms[1].adjacent.append(atoms[0])
    minmax = [start, start]

    def traverse(atom, resi):
        atom.resi = resi
        atom.visited = True
        for other in atom.adjacent:
            if other.visited:
                continue
            if (atom.name, other.name) in [('C', 'N'), ("O3'", 'P')]:
                minmax[1] = resi + 1
                traverse(other, resi + 1)
            elif (atom.name, other.name) in [('N', 'C'), ('P', "O3'")]:
                minmax[0] = resi - 1
                traverse(other, resi - 1)
            elif (atom.name, other.name) not in [('SG', 'SG')]:
                traverse(other, resi)

    traverse(startatom, start)
    cmd.alter(selection,
              'resi = atom_it.next().resi',
              space={'atom_it': iter(model.atom)})
    if not quiet:
        print ' Renumber: range (%d to %d)' % tuple(minmax)


cmd.extend('renumber', renumber)

# vi:expandtab:smarttab
Пример #53
0
   cmd.alter(sel+" and element C", "vdw=3.40") # 2.00 + 1.4
   cmd.alter(sel+" and element N", "vdw=4.15") # 1.75 + 1.4 + 1.0
   cmd.alter(sel+" and element O", "vdw=3.95") # 1.55 + 1.4 + 1.0
   cmd.alter(sel+" and element H", "vdw=2.40") # 1.00 + 1.4
   cmd.alter(sel+" and element P", "vdw=3.55") # 2.15 + 1.4
   cmd.alter(sel+" and element S", "vdw=3.30") # 1.90 + 1.4
   cmd.set("sphere_scale", 1.0)

def show_SASA_radii(sel="all"):
   cmd.alter(sel+" and element C", "vdw=3.40") # 2.00 + 1.4
   cmd.alter(sel+" and element N", "vdw=3.15") # 1.75 + 1.4
   cmd.alter(sel+" and element O", "vdw=2.95") # 1.55 + 1.4
   cmd.alter(sel+" and element H", "vdw=2.40") # 1.00 + 1.4
   cmd.alter(sel+" and element P", "vdw=3.55") # 2.15 + 1.4
   cmd.alter(sel+" and element S", "vdw=3.30") # 1.90 + 1.4
   cmd.set("sphere_scale", 1.0)

def show_Rosetta_radii(sel="all"):
   cmd.alter(sel+" and element C", "vdw=2.00")
   cmd.alter(sel+" and element N", "vdw=1.75")
   cmd.alter(sel+" and element O", "vdw=1.55")
   cmd.alter(sel+" and element H", "vdw=1.00")
   cmd.alter(sel+" and element P", "vdw=2.15")
   cmd.alter(sel+" and element S", "vdw=1.90")
   cmd.set("sphere_scale", 1.0)

cmd.extend('show_SASA_radii_expanded_polars',show_SASA_radii_expanded_polars)
cmd.extend('show_SASA_radii',show_SASA_radii)
cmd.extend('show_Rosetta_radii',show_Rosetta_radii)

    if (state != None):
        x, y, z = get_com(selection, mass=mass, quiet=quiet)
        if not quiet:
            print "%f %f %f" % (x, y, z)
        cmd.pseudoatom(object, pos=[x, y, z], **kwargs)
        cmd.show("spheres", object)
    else:
        for i in range(cmd.count_states()):
            x, y, z = get_com(selection, mass=mass, state=i + 1, quiet=quiet)
            if not quiet:
                print "State %d:%f %f %f" % (i + 1, x, y, z)
            cmd.pseudoatom(object, pos=[x, y, z], state=i + 1, **kwargs)
            cmd.show("spheres", 'last ' + object)


cmd.extend("com", com)


def get_com(selection, state=1, mass=None, quiet=1):
    """
DESCRIPTION
 
   Calculates the center of mass
 
   Author: Sean Law
   Michigan State University
   slaw (at) msu . edu
   """
    quiet = int(quiet)

    totmass = 0.0
Пример #55
0
    atoms1 = read_buried_unsats_from_logfile( fname1 )
    atoms2 = read_buried_unsats_from_logfile( fname2 )

    set_ats1 = set( atoms1 )
    set_ats2 = set( atoms2 )

    ats_intersect = set_ats1.intersection( set_ats2 )
    ats_1_absent_2 = set_ats1.difference( set_ats2 )
    ats_2_absent_1 = set_ats2.difference( set_ats1 )

    obj_common = []
    obj_common.extend( white )
    append_sphere_objs_from_atoms( ats_intersect, obj_common )

    obj_diff1 = []
    obj_diff1.extend( blue )
    append_sphere_objs_from_atoms( ats_1_absent_2, obj_diff1 )

    obj_diff2 = []
    obj_diff2.extend( red )
    append_sphere_objs_from_atoms( ats_2_absent_1, obj_diff2 )

    cmd.load_cgo(obj_common,'both buns',1)
    cmd.load_cgo(obj_diff1,'set1 - set2',1)
    cmd.load_cgo(obj_diff2,'set2 - set1',1)


cmd.extend("buried_unsats_from_logfile", buried_unsats_from_logfile )
cmd.extend("contrast_unsats_logfile", contrast_unsats_logfile )
Пример #56
0
            print("Unknown mode", mode)


def ccp4_ncont(contactsfile, selName1="source", selName2="target"):
    # read and parse contacts file into two lists of contact atoms and contact pair list
    s1, s2, pairs = parseNCONTContacts(open(contactsfile))
    # create a selection for the first contact list

    # create the PYMOL selection macros for the residues
    resNames = [chain + "/" + residue + "/" for (type, chain, residue, atom) in s1]
    # put them in a set to remove duplicates and then join with 'or'
    resSel = " or ".join(frozenset(resNames))
    # finally select them under the new name
    cmd.select(selName1 + "_res", resSel)

    atomNames = [chain + "/" + residue + "/" + atom for (type, chain, residue, atom) in s1]
    atomSel = " or ".join(frozenset(atomNames))
    cmd.select(selName1 + "_atom", atomSel)

    # create a selection for the second contact list

    resNames = [chain + "/" + residue + "/" for (type, chain, residue, atom) in s2]
    resSel = " or ".join(frozenset(resNames))
    cmd.select(selName2 + "_res", resSel)

    atomNames = [chain + "/" + residue + "/" + atom for (type, chain, residue, atom) in s2]
    atomSel = " or ".join(frozenset(atomNames))
    cmd.select(selName2 + "_atom", atomSel)

cmd.extend("ccp4_ncont", ccp4_ncont)
Пример #57
0
                try:
                    aa1 = to_one_letter_code[a1[0][0]]
                    aa2 = to_one_letter_code[a2[0][0]]
                    u_sum += matrix[i].get(aa1, aa2)
                    count += 1
                except:
                    print('Failed for', a1[0], a2[0])

    value = float(u_sum) / twoN
    if not quiet:
        print('PMF: %.4f (%d contacts, %d residues)' % (value, count, twoN))
    return value

try:
    from pymol import cmd
    cmd.extend('aaindex2b', aaindex2b)
    cmd.extend('pmf', pmf)

    def pymol_auto_arg_update():
        aaindexkey_sc = cmd.Shortcut(_aaindex.keys())
        cmd.auto_arg[0].update({
            'aaindex2b': [aaindexkey_sc, 'aaindexkey', ', '],
            'pmf': [aaindexkey_sc, 'aaindexkey', ', '],
        })
        cmd.auto_arg[1].update({
            'aaindex2b': [cmd.selection_sc, 'selection', ''],
        })
        cmd.auto_arg[2].update({
            'pmf': [cmd.selection_sc, 'selection', ''],
        })
        cmd.auto_arg[3].update({
Пример #58
0
    if len(high_sel) > 0:
        cmd.show_as('dashes', HBO_name)
        cmd.color('green', HBO_name)
        high_sel.sort()


    if not quiet:
        hb.sort(lambda x,y:(cmp(x[0][1],y[0][1])))
        print "--------------------------------------------------------------------"
        print "------------------------------Results ------------------------------"
        print "--------------------------------------------------------------------"
        print "           Donor             |            Aceptor           |"
        print "    Object   Chain Residue   |     Object   Chain Residue   | # wrappers  wrapping"
        for line in low_sel:
            print line[1]
        for line in mean_sel:
            print line[1]
        for line in high_sel:
            print line[1]
        print '\nProtein global statistics:'
        print '\nz-score wrappers = %6.2f\nz-score hydrogen bonds = %6.2f\n' % (z_score_wrappers, z_score_hb)
    elif not quiet and len(hb) != 0:
        print '\n - no dehydrons were found - '
        print '\nz-score hydrogen bonds = %6.2f\n' % (z_score_hb)
    else:
        print '\n - no hydrogen bonds were found - '

cmd.extend('wrappy', dehydron)

# vi:expandtab:smarttab
Пример #59
0
        if v.startswith('['):
            return cmd.safe_list_eval(v)
        return cmd.get_atom_coords(v)

    xyz1 = get_coord(atom1)
    xyz2 = get_coord(atom2)
    normal = cpv.normalize(cpv.sub(xyz1, xyz2))

    if hlength < 0:
        hlength = radius * 3.0
    if hradius < 0:
        hradius = hlength * 0.6

    if gap:
        diff = cpv.scale(normal, gap)
        xyz1 = cpv.sub(xyz1, diff)
        xyz2 = cpv.add(xyz2, diff)

    xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2)

    obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + \
          [cgo.CONE] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + \
          [1.0, 0.0]

    if not name:
        name = cmd.get_unused_name('arrow')

    cmd.load_cgo(obj, name)

cmd.extend('cgo_arrow', cgo_arrow)
    r = cmd.get_raw_alignment(aln)

    if names == ():
        known_objs = []
        map(known_objs.extend, map(lambda x: map(lambda y: y[0], x), r))
        known_objs = set(known_objs)

        # highest number of matches seen
        M = max(map(len, r)) + 1
    else:
        known_objs = set(names)
        M = len(known_objs) + 1

    for obj in known_objs:
        _self.alter(obj, "b=0.0")

    for af in r:
        c = float(1.0 + len(af)) / float(M)
        for y in af:
            _self.alter("%s and index %s" % (y[0], y[1]), "b=c", space={'c': c})

    if as_putty != 0:
        for obj in known_objs:
            _self.show_as("cartoon", "%s" % obj)
            _self.cartoon("putty", "%s" % obj)
            _self.spectrum('b', color, obj)
            _self.sort()
            _self.rebuild()
    return None
cmd.extend("color_by_conservation", color_by_conservation)