def visualize_orientation(direction, center=[0, 0, 0], scale=1.0, symmetric=False, color="green", color2="red"):
    """
    Draw an arrow. Helper function for "helix_orientation" etc.
    """
    from pymol import cgo

    color_list = cmd.get_color_tuple(color)
    color2_list = cmd.get_color_tuple(color2)
    if symmetric:
        scale *= 0.5
    end = cpv.add(center, cpv.scale(direction, scale))
    radius = 0.3
    obj = [cgo.SAUSAGE]
    obj.extend(center)
    obj.extend(end)
    obj.extend([radius, 0.8, 0.8, 0.8])
    obj.extend(color_list)
    if symmetric:
        start = cpv.sub(center, cpv.scale(direction, scale))
        obj.append(cgo.SAUSAGE)
        obj.extend(center)
        obj.extend(start)
        obj.extend([radius, 0.8, 0.8, 0.8])
        obj.extend(color2_list)
    coneend = cpv.add(end, cpv.scale(direction, 4.0 * radius))
    if cmd.get_version()[1] >= 1.2:
        obj.append(cgo.CONE)
        obj.extend(end)
        obj.extend(coneend)
        obj.extend([radius * 1.75, 0.0])
        obj.extend(color_list * 2)
        obj.extend([1.0, 1.0])  # Caps
    cmd.load_cgo(obj, get_unused_name("oriVec"), zoom=0)
Пример #2
0
        def addSuccess(self, test):
            if not (self.showAll and test.timings):
                return super(PyMOLTestResult, self).addSuccess(test)

            unittest.result.TestResult.addSuccess(self, test)
            msg = 'ok (%s)' % ', '.join(
                    ('%s: %.3fs' % (m, t) if m else '%.3fs' % t)
                    for (m, t) in test.timings)
            self.stream.writeln(msg)

            filename = os.getenv("PYMOLTESTTIMINGS",
                    os.path.join(pymol_test_dir, "timings.tab"))
            with open(filename, "a") as handle:
                for i, (m, t) in enumerate(test.timings):
                    version = cmd.get_version()
                    buildinfo = version[3:] or [0, "", 0]
                    print('\t'.join([
                        '%f' % time.time(),
                        '%012x' % uuid.getnode(),
                        '%f' % t,
                        type(test).__name__ + '.' + test._testMethodName,
                        str(m or i),
                        version[0],
                        buildinfo[1],
                        '%d' % buildinfo[2],
                        platform.platform(),
                        platform.node(),
                    ]), file=handle)
Пример #3
0
        def addSuccess(self, test):
            if not (self.showAll and test.timings):
                return super(PyMOLTestResult, self).addSuccess(test)

            unittest.result.TestResult.addSuccess(self, test)
            msg = 'ok (%s)' % ', '.join(
                ('%s: %.3fs' % (m, t) if m else '%.3fs' % t)
                for (m, t) in test.timings)
            self.stream.writeln(msg)

            filename = os.getenv("PYMOLTESTTIMINGS",
                                 os.path.join(pymol_test_dir, "timings.tab"))
            with open(filename, "a") as handle:
                for i, (m, t) in enumerate(test.timings):
                    version = cmd.get_version()
                    buildinfo = version[3:] or [0, "", 0]
                    print('\t'.join([
                        '%f' % time.time(),
                        '%012x' % uuid.getnode(),
                        '%f' % t,
                        type(test).__name__ + '.' + test._testMethodName,
                        str(m or i),
                        version[0],
                        buildinfo[1],
                        '%d' % buildinfo[2],
                        platform.platform(),
                        platform.node(),
                    ]),
                          file=handle)
Пример #4
0
 def test_version(self):
     v = cmd.get_version()[:3]
     # check types
     self.assertTrue(isinstance(v[0], str))
     self.assertTrue(isinstance(v[1], float))
     self.assertTrue(isinstance(v[2], int))
     # check that major of str and float match
     self.assertEqual(int(v[0].split('.')[0]), int(v[1]))
def visualize_orientation(direction,
                          center=[0, 0, 0],
                          scale=1.0,
                          symmetric=False,
                          color='green',
                          color2='red'):
    '''
    Draw an arrow. Helper function for "helix_orientation" etc.
    '''
    from pymol import cgo
    color_list = cmd.get_color_tuple(color)
    color2_list = cmd.get_color_tuple(color2)
    if symmetric:
        scale *= 0.5
    end = cpv.add(center, cpv.scale(direction, scale))
    radius = 0.3
    obj = [cgo.SAUSAGE]
    obj.extend(center)
    obj.extend(end)
    obj.extend([
        radius,
        0.8,
        0.8,
        0.8,
    ])
    obj.extend(color_list)
    if symmetric:
        start = cpv.sub(center, cpv.scale(direction, scale))
        obj.append(cgo.SAUSAGE)
        obj.extend(center)
        obj.extend(start)
        obj.extend([
            radius,
            0.8,
            0.8,
            0.8,
        ])
        obj.extend(color2_list)
    coneend = cpv.add(end, cpv.scale(direction, 4.0 * radius))
    if cmd.get_version()[1] >= 1.2:
        obj.append(cgo.CONE)
        obj.extend(end)
        obj.extend(coneend)
        obj.extend([
            radius * 1.75,
            0.0,
        ])
        obj.extend(color_list * 2)
        obj.extend([
            1.0,
            1.0,  # Caps
        ])
    cmd.load_cgo(obj, get_unused_name('oriVec'), zoom=0)
Пример #6
0
    def testLoadPWG(self):
        if sys.version_info[0] < 3:
            import urllib2
        else:
            import urllib.request as urllib2

        content_index = b'Hello World\n'
        port = 8084
        baseurl = 'http://localhost:%d' % port

        def urlread(url):
            handle = urllib2.urlopen(url, timeout=3.0)
            try:
                return handle.info(), handle.read()
            finally:
                handle.close()

        with testing.mkdtemp() as rootdir:
            filename = os.path.join(rootdir, 'index.html')
            with open(filename, 'wb') as handle:
                handle.write(content_index)

            filename = os.path.join(rootdir, 'start.pwg')
            with open(filename, 'w') as handle:
                handle.write('root %s\n' % rootdir)
                handle.write('port %d\n' % port)
                handle.write('header add Test-Key Test-Value\n')  # new in 2.4
            cmd.load(filename)

            header, content = urlread(baseurl)
            self.assertEqual(header['Test-Key'], 'Test-Value')
            self.assertEqual(content, content_index)

            # Warning: can't call locking functions here, will dead-lock
            # get_version is non-locking since 1.7.4

            header, content = urlread(baseurl + '/apply/pymol.cmd.get_version')
            content = content.decode('ascii', errors='ignore')
            self.assertTrue(content, cmd.get_version()[0] in content)
Пример #7
0
    def testLoadPWG(self):
        if sys.version_info[0] < 3:
            import urllib2
        else:
            import urllib.request as urllib2

        content_index = b'Hello World\n'
        port = 8084
        baseurl = 'http://localhost:%d' % port

        def urlread(url):
            handle = urllib2.urlopen(url, timeout=3.0)
            try:
                return handle.read()
            finally:
                handle.close()

        with testing.mkdtemp() as rootdir:
            filename = os.path.join(rootdir, 'index.html')
            with open(filename, 'wb') as handle:
                handle.write(content_index)

            filename = os.path.join(rootdir, 'start.pwg')
            with open(filename, 'w') as handle:
                handle.write('root %s\n' % rootdir)
                handle.write('port %d\n' % port)
            cmd.load(filename)

            content = urlread(baseurl)
            self.assertEqual(content, content_index)

            # Warning: can't call locking functions here, will dead-lock
            # get_version is non-locking since 1.7.4

            content = urlread(baseurl + '/apply/pymol.cmd.get_version')
            content = content.decode('ascii', errors='ignore')
            self.assertTrue(content, cmd.get_version()[0] in content)
Пример #8
0
def sst(selection='(all)', raw='', state=-1, quiet=1):
    '''
DESCRIPTION

    Secondary structure assignment with SST.
    http://lcb.infotech.monash.edu.au/sstweb/

SEE ALSO

    dss, dssp, stride
    '''
    try:
        import urllib2
    except ImportError:
        import urllib.request as urllib2

    state, quiet = int(state), int(quiet)

    ss_map = {
        'C': 'L',
        'E': 'S',
        'G': 'H',
        'H': 'H',
        'I': 'H',
        'g': 'H',
        'h': 'H',
        'i': 'H',
        '3': 'L',
        '4': 'L',
        '5': 'L',
        'T': 'L',
        '-': 'L',
        '|': 'L',
        ':': 'H',
    }
    ss_dict = {}
    boundary = '192.168.1.80.500.9981.1375391031.267.10'

    for model in cmd.get_object_list(selection):
        pdbstr = cmd.get_pdbstr('%s & guide & (%s)' % (model, selection),
                                state)

        body = '\r\n'.join([
            '--' + boundary,
            'Content-Disposition: form-data; name="sstverstr"',
            'Content-Type: text/plain',
            '',
            'v1.6',
            '--' + boundary,
            'Content-Disposition: file; name="pdb_file"; filename="abc.pdb"',
            'Content-Type: text/plain',
            '',
            pdbstr,
            '--' + boundary + '--',
            '',
        ])

        body = body.encode('ascii', 'ignore')

        try:
            request = urllib2.Request(
                data=body,
                url='http://lcb.infotech.monash.edu.au/sstweb2/formaction.php')
            request.add_header(
                'User-agent',
                'PyMOL ' + cmd.get_version()[0] + ' ' + cmd.sys.platform)
            request.add_header('Content-type',
                               'multipart/form-data; boundary=%s' % boundary)
            request.add_header('Content-length', len(body))
            lines = urllib2.urlopen(request).readlines()
        except urllib2.URLError:
            print(' Error: URL request failed')
            raise CmdException

        if sys.version_info[0] > 2:
            lines = (line.decode('ascii', 'ignore') for line in lines)

        lines = iter(lines)

        for line in lines:
            if line.startswith('..........RESIDUE LEVEL'):
                break
        else:
            if not quiet:
                print(' Warning: SST assignment failed')
            return

        next(lines)

        for line in lines:
            if line.startswith('...................................END'):
                break
            chain = line[2].strip()
            resi = line[3:9].strip()
            ss = line[21]
            ss_dict[model, chain, resi] = ss

    _common_ss_alter(selection, ss_dict, ss_map, raw)
Пример #9
0
def save_pdb(filename,
             selection='(all)',
             state=-1,
             symm=1,
             ss=1,
             aniso=0,
             seqres=0,
             quiet=1):
    '''
DESCRIPTION

    Save the coordinates of a selection as pdb including the
    secondary structure information and, if possible, the unit
    cell. The latter requires the selction of a single object

USAGE

    save_pdb filename, selection [, state [, symm [, ss [, aniso ]]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}
                Note: to include the unit cell information you
                need to select a single object

    state = integer: state to save {default: -1 (current state)}

    symm = 0 or 1: save symmetry info if possible {default: 1}

    ss = 0 or 1: save secondary structure info {default: 1}

    aniso = 0 or 1: save ANISO records {default: 0}

SEE ALSO

    save
    '''
    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    symm, ss = int(symm), int(ss)

    filename = cmd.exp_path(filename)
    f = open(filename, 'w')
    print('REMARK 200 Generated with PyMOL and psico'.ljust(80), file=f)

    # Write sequence
    if int(seqres):
        f.write(get_pdb_seqres(selection))

    # Write the CRYST1 line if possible
    if symm:
        try:
            obj1 = cmd.get_object_list(selection)[0]
            sym = cmd.get_symmetry(obj1)
            if len(sym) != 7:
                raise
            f.write("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-10s%4d\n" %
                    tuple(sym + [1]))
            if not quiet:
                print(' Info: Wrote unit cell and space group info')
        except:
            if not quiet:
                print(' Info: No crystal information')

    # Write secondary structure
    if ss:
        try:
            sss = get_pdb_sss(selection, state, quiet)
            if not sss:
                raise
            f.write(sss)
            if not quiet:
                print(' Info: Wrote secondary structure info')
        except:
            if not quiet:
                print(' Info: No secondary structure information')

    # Write coordinates of selection
    pdbstr = cmd.get_pdbstr(selection, state)

    # fix END records
    if state == 0 and cmd.get_version()[1] < 1.6:
        pdbstr = '\n'.join(
            line for line in pdbstr.splitlines() if line != 'END') + '\nEND\n'

    # anisotropic b-factors
    from . import pymol_version
    if int(aniso) and pymol_version < 1.6 and \
            cmd.get_model('first (%s)' % selection).atom[0].u_aniso[0] != 0.0:

        def mergeaniso():
            atom_it = iter(cmd.get_model(selection, state).atom)
            for line in pdbstr.splitlines(True):
                yield line
                if line[:6] in ['ATOM  ', 'HETATM']:
                    yield 'ANISOU' + line[6:28] + \
                            ''.join('%7.0f' % (u*1e4) for u in atom_it.next().u_aniso) + \
                            line[70:]

        pdbstr = ''.join(mergeaniso())

    f.write(pdbstr)
    f.close()

    if not quiet:
        print('Wrote PDB to \'' + filename + '\'')
Пример #10
0
def modevectors( first_obj_frame, last_obj_frame, outname="modevectors", head=1.0,tail=0.3, head_length=1.5, headrgb="1.0,1.0,1.0",tailrgb="1.0,1.0,1.0",cutoff=4.0,skip=0,cut=0.5,atom="CA",stat="show",factor=1.0):
	"""
	Authors Sean Law & Srinivasa
	Michigan State University
	slaw_(at)_msu_dot_edu
 
	Editor Sacha Yee
 
	USAGE
 
	While in PyMOL
 
	Parameter                Preset            Type    Description
	first_obj_frame          Undefined         String  Object name of the first structure.  The mode vector will propagate from this structure.  Defined by user.
	last_obj_frame           Undefined         String  Object name of the last structure.  The mode vector (arrow head) will end at this structure.  Defined by user.
	outname                  modevectors       String  Name of object to store mode vectors in.
	head                     1.0               Float   Radius for the circular base of the arrow head (cone)
	tail                     0.3               Float   Radius for the cylinder of the arrow tail (cylinder)
	head_length              1.5               Float   Length of the arrow head (from the base of the cone to the tip of cone)
	head_rgb                 1.0,1.0,1.0       String  RGB colour for the arrow head.
	tail_rgb                 1.0,1.0,1.0       String  RGB colour for the arrow tail.
	cutoff                   4.0               Float   Skips mode vectors that do not meet the cutoff distance (in Angstroms).
	skip                     0                 Integer Denotes how many atoms to skip.  No arrows will be created for skipped atoms.
	cut                      0.0               Float   Truncates all arrow tail lengths (without disturbing the arrow head) (in Angstroms).
	atom                     CA                String  Designates the atom to derive mode vectors from.
	stat                     show              String  Keeps track and prints statistics (total modevectors, skipped, cutoff).
	factor                   1.0               Float   Multiplies each mode vector length by a specified factor.
	                                                   Values between 0 and 1 will decrease the relative mode vector length.
	                                                   Values greater than 1 will increase the relative mode vector length.
 
	"""
 
	framefirst=cmd.get_model(first_obj_frame)
	framelast=cmd.get_model(last_obj_frame)
	objectname=outname
	factor=float(factor)
	arrow_head_radius=float(head)
	arrow_tail_radius=float(tail)
	arrow_head_length=float(head_length)
	cutoff=float(cutoff)
	skip=int(skip)
	cut=float(cut)
	atomtype=atom.strip('"[]()')
 
	headrgb=headrgb.strip('" []()')
	tailrgb=tailrgb.strip('" []()')
	hr,hg,hb=map(float,headrgb.split(','))
	tr,tg,tb=map(float,tailrgb.split(','))
 
	version=cmd.get_version()
	arrow=[]
	arrowhead = []
	arrowtail = []
	x1 = []
	y1 = []
	z1 = []
	x2 = []
	y2 = []
	z2 = []
	exit_flag=False
 
##############################################################
#                                                            #
# Define an object called "tail" and store the tail and  a   #
# circular base of the triangle in this object.              #
#                                                            #
##############################################################
 
	skipcount=0
	skipcounter=0
	keepcounter=0
	atom_lookup={}
	for atom in framefirst.atom:
		if atom.name == atomtype:
			if skipcount == skip:
				x1.append(atom.coord[0])
				y1.append(atom.coord[1])
				z1.append(atom.coord[2])
 
				##########################################
				#                                        #
				# Set atom_lookup for a specific atom    #
				# equal to ONE for the first input set.  #
				# This dictionary will be used as a      #
				# reference for the second set.          #
				#                                        #
				##########################################
 
				current_atom="CHAIN "+atom.chain+" RESID "\
					      +atom.resi+" RESTYPE "\
					      +atom.resn+\
					      " ATMNAME "+atom.name
#				print current_atom
				atom_lookup[current_atom]=1
 
				skipcount=0
				keepcounter+=1
			else:
#				print skipcount
				skipcount+=1
				skipcounter+=1
 
	skipcount=0
	for atom in framelast.atom:
		if atom.name == atomtype:
			if skipcount == skip:
				x2.append(atom.coord[0])
				y2.append(atom.coord[1])
				z2.append(atom.coord[2])
 
				#########################################
				#                                       #
				# Get atom information from second set  #
				# and compare with first set.  All      #
				# atoms from this second set MUST be    #
				# found in the first set!  Otherwise,   #
				# the script will exit with an error    #
				# since modevectors can only be created #
				# by calculating values from identical  #
				# sources.                              #
				#                                       #
				#########################################
 
				current_atom="CHAIN "+atom.chain+" RESID "\
					      +atom.resi+" RESTYPE "\
					      +atom.resn+\
					      " ATMNAME "+atom.name
#				print current_atom
				if current_atom not in atom_lookup:
					print "\nError: "+current_atom+" from \""\
					      +last_obj_frame+\
					      " \"is not found in \""+first_obj_frame+"\"."
					print "\nPlease check your input and/or selections and try again."
					exit_flag=True
					break
 
				skipcount=0
			else:
				skipcount+=1
 
	if exit_flag == 1:
		###########################################
		#                                         #
		# Exit script because an atom cannot be   #
		# found in both input files               #
		#                                         #
		###########################################
		return
 
	cutoff_counter=0 # Track number of atoms failing to meet the cutoff
 
	###################################################
	#                                                 #
	# Check that the two selections/PDB files contain #
	# the same number of atoms.                       #
	#                                                 #
	###################################################
 
	if len(x2) != len(x1):
		print "\nError: \""+first_obj_frame+\
		      "\" and \""+last_obj_frame+\
		      "\" contain different number of residue/atoms."
		print "\nPlease check your input and/or selections and try again."
		return
	else:
		#Continue with representing modevectors!
		#########################################
		#                                       #
		# Delete old selection or object if it  #
		# exists so that it can be overwritten  #
		#                                       #
		#########################################
		save_view=cmd.get_view(output=1,quiet=1)
		cmd.delete(name=outname)
		cmd.hide(representation="everything",selection=first_obj_frame)
		cmd.hide(representation="everything",selection=last_obj_frame)
 
 
 
	###################################################
	#                                                 #
	# Begin drawing arrow tails                       #
	#                                                 #
	###################################################
 
	arrowtail = []
	for mv in range(len(x1)):
		vectorx=x2[mv]-x1[mv]
		vectory=y2[mv]-y1[mv]
		vectorz=z2[mv]-z1[mv]
		length=sqrt(vectorx**2+vectory**2+vectorz**2)
		if length < cutoff:
			cutoff_counter+=1
			continue
		t=1.0-(cut/length)
		x2[mv]=x1[mv]+factor*t*vectorx
		y2[mv]=y1[mv]+factor*t*vectory
		z2[mv]=z1[mv]+factor*t*vectorz
		vectorx=x2[mv]-x1[mv]
		vectory=y2[mv]-y1[mv]
		vectorz=z2[mv]-z1[mv]
		length=sqrt(vectorx**2+vectory**2+vectorz**2)
		d=arrow_head_length # Distance from arrow tip to arrow base
		t=1.0-(d/length)
		tail = [
		# Tail of cylinder
		CYLINDER, x1[mv],y1[mv],z1[mv]\
		,x1[mv]+(t+0.01)*vectorx,y1[mv]+(t+0.01)*vectory,z1[mv]+(t+0.01)*vectorz\
		,arrow_tail_radius,tr,tg,tb,tr,tg,tb # Radius and RGB for each cylinder tail
		]
		arrow.extend(tail)
 
		x=x1[mv]+t*vectorx
		y=y1[mv]+t*vectory
		z=z1[mv]+t*vectorz
		dx=x2[mv]-x
		dy=y2[mv]-y
		dz=z2[mv]-z
		seg=d/100
		intfactor=int(factor)
		if version < 1.1: #Version >= 1.1 has cone primitive
			for i in range (100,0,-1): #i=100 is tip of cone
				print i
				t1=seg*i
				t2=seg*(i+1)
				radius=arrow_head_radius*(1.0-i/(100.0)) #Radius of each disc that forms cone
				head=[
				CYLINDER, x+t2*dx,y+t2*dy,z+t2*dz\
				,x+t1*dx,y+t1*dy,z+t1*dz\
				,radius,hr,hg,hb,hr,hg,hb # Radius and RGB for slice of arrow head
				]
				arrow.extend(head)
		else:
			head=[
			CONE, x, y ,z, x+d*dx, y+d*dy, z+d*dz, arrow_head_radius, 0.0, hr, hg, hb, hr, hg, hb, 1.0, 1.0 ]
			arrow.extend(head)
 
##############################################################
#                                                            #
# Load the entire object into PyMOL                          #
#                                                            #
# Print statistics if requested by user                      #
#                                                            #
##############################################################
 
	if stat == "show":
		natoms=skipcounter+keepcounter
		print "\nTotal number of atoms = "+str(natoms)
		print "Atoms skipped = "+str(skipcounter)
		if keepcounter-cutoff_counter > 0:
			print "Atoms counted = "+str(keepcounter-cutoff_counter)+" (see PyMOL object \""+outname+"\")"
		else:
			print "Atoms counted = "+str(keepcounter-cutoff_counter)+" (Empty CGO object not loaded)"	
		print "Atoms cutoff  = "+str(cutoff_counter) #Note that cutoff occurs AFTER skipping!
	if keepcounter-cutoff_counter > 0:
		cmd.load_cgo(arrow,objectname) #Ray tracing an empty object will cause a segmentation fault.  No arrows = Do not display in PyMOL!!!
	cmd.show(representation="cartoon",selection=first_obj_frame)
	cmd.cartoon("tube")
	cmd.show(representation="cartoon",selection=last_obj_frame)
	cmd.hide(representation="cartoon",selection=last_obj_frame)
	cmd.bg_color(color="white")
	cmd.set_view(save_view)
	return
Пример #11
0
Date: October 30, 2015
Version: 1.0
License: Public Domain
"""
from pymol import cmd, stored
import re
try:
    from collections import OrderedDict
    _orderedDict = True
except ImportError:
    _orderedDict = False

# PyMOL 1.7.4 introduces support for multi-letter chains, so we can afford to
# use a smaller alphabet. In earlier versions, use lower-case letters if needed
# (requires running `set ignore_case, 0`)
_long_chains = cmd.get_version()[1] >= 1.74
_default_base = 36 if _long_chains else 62

class OutOfChainsError(Exception):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return str(self.msg)

class ChainSet(object):
    """
    Base class for various methods to rename chains

    Contains _chains, which maps from the renamed chain to a tuple with the
    original (object,state,chain). All dict-like accessors work on ChainSets,
    e.g.
Пример #12
0
 def interpret_color(self, c):
     if cmd.get_version()[1] < 1:
         return cmd._interpret_color(str(c))
     return cmd._interpret_color(cmd, str(c))
'''
(c) 2010 Thomas Holder
'''

from pymol import cmd, stored, CmdException
from chempy import cpv
import math

if cmd.get_version()[1] < 1.2:

    def get_unused_name(name):
        import random
        return name + '%04d' % random.randint(0, 1000)

    STATE = 1
else:
    from pymol.cmd import get_unused_name
    STATE = -1


def _vec_sum(vec_list):
    # this is the same as
    # return numpy.array(vec_list).sum(0).tolist()
    vec = cpv.get_null()
    for x in vec_list:
        vec = cpv.add(vec, x)
    return vec


def _mean_and_std(x):
    # this is the same as
Пример #14
0
def sst(selection='(all)', raw='', state=-1, quiet=1):
    '''
DESCRIPTION

    Secondary structure assignment with SST.
    http://lcb.infotech.monash.edu.au/sstweb/

SEE ALSO

    dss, dssp, stride
    '''
    try:
        import urllib2
    except ImportError:
        import urllib.request as urllib2

    state, quiet = int(state), int(quiet)

    ss_map = {
        'C': 'L',
        'E': 'S',
        'G': 'H',
        'H': 'H',
        'I': 'H',
        'g': 'H',
        'h': 'H',
        'i': 'H',
        '3': 'L',
        '4': 'L',
        '5': 'L',
        'T': 'L',
        '-': 'L',
        '|': 'L',
        ':': 'H',
    }
    ss_dict = {}
    boundary = '192.168.1.80.500.9981.1375391031.267.10'

    for model in cmd.get_object_list(selection):
        pdbstr = cmd.get_pdbstr('%s & guide & (%s)' % (model, selection), state)

        body = '\r\n'.join([
            '--' + boundary,
            'Content-Disposition: file; name="pdb_file"; filename="abc.pdb"',
            'Content-Type: text/plain',
            '',
            pdbstr,
            '--' + boundary + '--',
            '',
        ])

        try:
            request = urllib2.Request(
                    'http://lcb.infotech.monash.edu.au/sstweb/formaction_pdbfile.php')
            request.add_header('User-agent', 'PyMOL ' + cmd.get_version()[0] + ' ' +
                    cmd.sys.platform)
            request.add_header('Content-type', 'multipart/form-data; boundary=%s' % boundary)
            request.add_header('Content-length', len(body))
            request.add_data(body)
            lines = urllib2.urlopen(request).readlines()
        except urllib2.URLError:
            print(' Error: URL request failed')
            raise CmdException

        lines = iter(lines)

        for line in lines:
            if line.startswith('..........RESIDUE LEVEL'):
                break
        else:
            if not quiet:
                print(' Warning: SST assignment failed')
            return

        next(lines)

        for line in lines:
            if line.startswith('...................................END'):
                break
            chain = line[2].strip()
            resi = line[3:9].strip()
            ss = line[21]
            ss_dict[model,chain,resi] = ss

    _common_ss_alter(selection, ss_dict, ss_map, raw)
Пример #15
0
    import time
    import unittest
    import itertools
    import tempfile
    import argparse

    try:
        import Image
    except ImportError:
        from PIL import Image
        sys.modules['Image'] = Image

    from pymol import cmd
    from pymol.invocation import options

    PYMOL_VERSION = cmd.get_version()
    PYMOL_EDU = 'Edu' in PYMOL_VERSION[0]
    is_win64bit = "Windows" in platform.system() and sys.maxsize > 2**32

    usage = 'pymol [pymol options] %s [test options]' % (
        os.path.basename(__file__))
    parser = argparse.ArgumentParser("pymol", usage=usage)
    parser.add_argument('--xml', action='store_true')
    parser.add_argument('filenames', nargs='*', default=[])
    parser.add_argument('--out', default=sys.stdout)
    parser.add_argument('--offline', action='store_true')
    parser.add_argument('--no-mmlibs', action='store_true')
    parser.add_argument('--no-undo', action='store_true')
    parser.add_argument('--verbosity', type=int, default=2)

    have_dash_dash = __file__.startswith(sys.argv[0]) or '--run' in sys.argv
Пример #16
0
def diagnostics(filename='', compact=0, quiet=1):
    '''
DESCRIPTION

    Get system level diagnostics data

USAGE

    diagnostics [ filename ]

ARGUMENTS

    filename = str: If given, write output to text file
    '''
    import platform
    import os
    import re
    import glob
    import time
    import textwrap
    from pymol import invocation
    from pymol import cmd, CmdException

    compact, quiet = int(compact), int(quiet)

    TZ = '%+05d' % (time.timezone / 36)

    version = cmd.get_version()
    body = u'PyMOL %s\n' % version[0]

    if not compact:
        if version[3]:
            body += 'build date: %s %s\n' % (time.ctime(version[3]), TZ)
        if version[4]:
            body += 'git sha: %s\n' % version[4]

    try:
        # pymol conda package version
        condameta = glob.glob(
            os.path.join(sys.prefix, 'conda-meta',
                         'pymol-' + version[0] + '*.json'))
        if condameta:
            import json
            d = json.load(open(condameta[0]))
            body += 'conda build: %s %s\n' % (d.get('build'), d.get('schannel')
                                              or d.get('channel'))
    except BaseException as e:
        print(e)

    if not compact:
        body += '\nLicense Information:\n'

    body += 'Open-Source Build\n'

    if not compact:
        body += '\nOperating System:\n'
    body += platform.platform() + '\n'
    if platform.system() == 'Linux':
        body += platform.version() + '\n'

    if not compact:
        body += '\nOpenGL Driver:\n'
    renderer = cmd.get_renderer()
    body += str(renderer[0] or '(none)') + '\n'
    body += str(renderer[1] or '(none)') + '\n'
    body += str(renderer[2] or '(none)') + '\n'

    try:
        from pymol.Qt import QtCore
        body += '%s %s (Qt %s)\n' % (QtCore.__name__.split('.')[0],
                                     QtCore.PYQT_VERSION_STR,
                                     QtCore.QT_VERSION_STR)
    except Exception as e:
        body += '(%s)\n' % (e, )

    if not compact:
        body += '\nPython:\n'
        body += '%s\n' % sys.version
        body += 'prefix=%s\n' % _unicode(sys.prefix)
        body += 'executable=%s\n' % _unicode(sys.executable)
        body += u'filesystemencoding={}\n'.format(sys.getfilesystemencoding())

        body += '\nStartup Scripts:\n'
        pymolrc = invocation.get_user_config()
        if pymolrc:
            pymolrc = map(_unicode, pymolrc)
            body += '\n'.join(pymolrc) + '\n'
        else:
            body += '(no pymolrc file found)\n'

        body += '\nQt, Python and PyMOL Environment Variables:\n'
        for key in sorted(os.environ):
            if re.search(r'^PY|QT|^LANG',
                         key) and not (key == 'PYMOL_SCRIPTS'):
                body += u'%s=%s\n' % (key, _unicode(os.environ[key]))

        body += '\nPATH:\n'
        body += textwrap.fill(_unicode(os.getenv('PATH', '')), 78) + '\n'

        body += '\nDiagnostics collected on %s %s\n' % (time.ctime(), TZ)

    if filename:
        filename = cmd.exp_path(filename)
        if not filename.endswith('.txt'):
            raise CmdException('filename must have .txt extension')

        with open(filename, 'w') as handle:
            handle.write(body)
        print('Diagnostics written to "%s"' % filename)
    elif not quiet:
        print(body.rstrip())

    return body
Пример #17
0
A reference document with all commands can be generated with:
PyMOL> psico.helping.write_html_ref('psico-commands.html')

(c) 2010-2012 Thomas Holder <*****@*****.**>
              Steffen Schmidt <*****@*****.**>
              Max Planck Institute for Developmental Biology 

License: BSD-2-Clause
'''

__version__ = '3.4'

try:
    from pymol import cmd
    pymol_version = cmd.get_version()[1]
except:
    pymol_version = 1.6

__all__ = [
    'aaindex',
    'conservation',
    'creating',
    'editing',
    'electrostatics',
    'exporting',
    'fasta',
    'fitting',
    'geometry',
    'orientation',
    'helping',
Пример #18
0
def distancetoatom(origin='pk1',
                   cutoff=10,
                   filename=None,
                   selection='all',
                   state=0,
                   property_name='p.dist',
                   coordinates=0,
                   decimals=3,
                   sort=1,
                   quiet=1):
    '''
DESCRIPTION

    distancetoatom.py
    Described at: http://www.pymolwiki.org/Distancetoatom

    Prints all distanced between the specified atom/coordinate/center
    and all atoms within cutoff distance that are part of the selection.
    All coordinates and distances can be saved in a csv-style text file report
    and can be appended to a (custom) atom property, if defined.

USAGE

    distancetoatom [ origin [, cutoff [, filename [, selection
    [, state [, property_name [, coordinates [, decimals [, sort
    [, quiet ]]]]]]]]]]

ARGUMENTS

    NAME        TYPE    FUNCTION
    origin:     <list>  defines the coordinates for the origin and can be:
                <str>   1. a list with coordinates [x,y,z]
                        2. a single atom selection string {default='pk1'}
                        3. a multi-atom selection string (center will be used)
    cutoff      <float> sets the maximum distance {default: 10}
    filename    <str>   filename for optional output report. {default=None}
                        set to e.g. 'report.txt' to create a report
                        (omit or set to '', None, 0 or False to disable)
    selection   <str>   can be used to define/limit the measurment to specific
                        sub-selections {default='all'}
    state       <int>   object state, {default=0} # = current
    property_name <str> the distance will be stored in this property {p.dist}
                        set "" to disable
    coordinates <int>   toggle whether atom coordinated will be reported {0}
    decimals    <int>   decimals for coordinates and distance:
                        default = 3 # = max. PDB resolution
    sort        <int>   Sorting by distance?
                         1: ascending (default)
                         0: no sorting (by names)
                        -1: descending
    quiet       <bool>  toggle verbosity
    '''
    # keyword check
    try:
        selection = '(%s)' % selection
        ori = get_coord(origin)
        if not ori:
            print("distancetoatom: aborting - check input for 'origin'!")
            return False
        cutoff = abs(float(cutoff))
        filename = str(filename)
        state = abs(int(state))
        if (not int(state)):
            state = cmd.get_state()
        cmd.set('state', state)  # distance by state
        property_name = str(property_name)
        decimals = abs(int(decimals))
        sort = int(sort)
        coordinates = bool(int(coordinates))
        quiet = bool(int(quiet))
    except:
        print('distancetoatom: aborting - input error!')
        return False

    # round origin
    ori = [round(x, decimals) for x in ori]

    # report?
    if filename in ['', '0', 'False', 'None']:
        filename = False
    else:
        try:
            report = open(filename, 'w')  # file for writing
        except:
            print('distancetoatom: Unable to open report file! - Aborting!')
            return False

    # temporary name for pseudoatom
    tempname = cmd.get_unused_name('temp_name')
    tempsel = cmd.get_unused_name('temp_sel')

    #origin
    cmd.pseudoatom(object=tempname, resi=1, pos=ori)

    # select atoms within cutoff
    cmd.select(
        tempsel, '(%s around %f) and (%s) and state %d' %
        (tempname, cutoff, selection, state))
    cmd.delete(tempname)

    # single atom ori and part of selection
    # avoid double reporting!
    single_atom_ori = False
    try:
        if cmd.count_atoms('(%s) and (%s) and (%s)' %
                           (selection, tempsel, origin)) == 1:
            single_atom_ori = True
    except:
        pass
    # pass= coordinates or multi-atom or single, not selected --> report ori

    # atom list
    stored.temp = []
    cmd.iterate(
        tempsel,
        'stored.temp.append([model, segi, chain, resn, resi, name, alt])')

    # custom properties? # conditional disabling
    if (property_name == ''): property_name = False
    if ((cmd.get_version()[1] < 1.7) and (property_name not in ['b', 'q'])):
        property_name = False

    # calculate the distances, creating list
    distance_list = []
    if (not single_atom_ori):
        distance_list.append(
            ['ORIGIN: ' + str(origin), ori[0], ori[1], ori[2], 0.0])
    for atom in stored.temp:
        atom_name = (
            '/%s/%s/%s/%s`%s/%s`%s' %
            (atom[0], atom[1], atom[2], atom[3], atom[4], atom[5], atom[6]))
        atom_xyz = [round(x, decimals) for x in cmd.get_atom_coords(atom_name)]
        atom_dist = round(cpv.distance(ori, atom_xyz), decimals)
        distance_list.append(
            [atom_name, atom_xyz[0], atom_xyz[1], atom_xyz[2], atom_dist])
        # create property with distance (can be used for coloring, labeling etc)
        if property_name:
            try:
                cmd.alter(atom_name, '%s=%f' % (property_name, atom_dist))
            except:
                # I'm not sure alter raises exceptions if the property is illegal
                property_name = False

    # sort list, if selected
    if sort > 0: distance_list.sort(key=lambda dist: dist[4])
    elif sort < 0: distance_list.sort(key=lambda dist: dist[4], reverse=True)
    # add header
    distance_list = [[
        'Atom Macro ID', 'x-coord', 'y-coord', 'z-coord', 'distance_to_origin'
    ]] + distance_list

    if ((not quiet) and (filename)):
        # Hijack stdout to print to file and console
        class logboth(object):
            def __init__(self, *files):
                self.files = files

            def write(self, obj):
                for f in self.files:
                    f.write(obj)

        originalstdout = sys.stdout
        sys.stdout = logboth(sys.stdout, report)

    for entry in distance_list:
        if coordinates:
            output = '%s, %s, %s, %s, %s' % (
                entry[0], entry[1], entry[2], entry[3], entry[4])  #csv style
        else:
            output = '%s, %s' % (entry[0], entry[4])  #csv style
        if (not quiet):
            print(output)
        elif filename:
            report.write(output + '\n')

    # restore regular stdout
    if ((not quiet) and (filename)): sys.stdout = originalstdout
    # close file
    if filename: report.close()

    if (not quiet):
        if property_name:
            print('Distances saved to property: %s' % str(property_name))
        else:
            print('Distances NOT saved to property (illegal custom property)')

    # remove temp. selection
    cmd.delete(tempsel)

    # return list for potential use:
    if coordinates:
        if len(distance_list) > 2:  # prevents crash if list is otherwise empty
            distance_list2 = list(map(distance_list.__getitem__, [1, 4]))
            return distance_list2
        else:
            return distance_list
    else:
        return distance_list
Пример #19
0
    import time
    import unittest
    import itertools
    import tempfile
    import argparse

    try:
        import Image
    except ImportError:
        from PIL import Image
        sys.modules['Image'] = Image

    from pymol import cmd
    from pymol.invocation import options

    PYMOL_VERSION = cmd.get_version()
    PYMOL_EDU = 'Edu' in PYMOL_VERSION[0]
    is_win64bit = "Windows" in platform.system() and sys.maxsize > 2**32

    usage = 'pymol [pymol options] %s [test options]' % (os.path.basename(__file__))
    parser = argparse.ArgumentParser("pymol", usage=usage)
    parser.add_argument('--xml', action='store_true')
    parser.add_argument('filenames', nargs='*', default=[])
    parser.add_argument('--out', default=sys.stdout)
    parser.add_argument('--offline', action='store_true')
    parser.add_argument('--no-mmlibs', action='store_true')
    parser.add_argument('--verbosity', type=int, default=2)

    have_dash_dash = __file__.startswith(sys.argv[0]) or '--run' in sys.argv
    cliargs = parser.parse_known_args(None if have_dash_dash else [])[0]
Пример #20
0
def save_pdb(filename, selection="(all)", state=-1, symm=1, ss=1, aniso=0, quiet=1):
    """
DESCRIPTION

    Save the coordinates of a selection as pdb including the
    secondary structure information and, if possible, the unit
    cell. The latter requires the selction of a single object

USAGE

    save_pdb filename, selection [, state [, symm [, ss [, aniso ]]]]

ARGUMENTS

    filename = string: file path to be written

    selection = string: atoms to save {default: (all)}
                Note: to include the unit cell information you
                need to select a single object

    state = integer: state to save {default: -1 (current state)}

    symm = 0 or 1: save symmetry info if possible {default: 1}

    ss = 0 or 1: save secondary structure info {default: 1}

    aniso = 0 or 1: save ANISO records {default: 0}

SEE ALSO

    save
    """
    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    symm, ss = int(symm), int(ss)

    filename = cmd.exp_path(filename)
    f = open(filename, "w")
    print >> f, "REMARK 200 Generated with PyMOL and psico".ljust(80)

    # Write the CRYST1 line if possible
    if symm:
        try:
            obj1 = cmd.get_object_list(selection)[0]
            sym = cmd.get_symmetry(obj1)
            if len(sym) != 7:
                raise
            f.write("CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-10s%4d\n" % tuple(sym + [1]))
            if not quiet:
                print " Info: Wrote unit cell and space group info"
        except:
            if not quiet:
                print " Info: No crystal information"

    # Write secondary structure
    if ss:
        try:
            sss = get_pdb_sss(selection, state, quiet)
            if not sss:
                raise
            f.write(sss)
            if not quiet:
                print " Info: Wrote secondary structure info"
        except:
            if not quiet:
                print " Info: No secondary structure information"

    # Write coordinates of selection
    pdbstr = cmd.get_pdbstr(selection, state)

    # fix END records
    if state == 0 and cmd.get_version()[1] < 1.6:
        pdbstr = "\n".join(line for line in pdbstr.splitlines() if line != "END") + "\nEND\n"

    # anisotropic b-factors
    if int(aniso) and cmd.get_model("first (%s)" % selection).atom[0].u_aniso[0] != 0.0:

        def mergeaniso():
            atom_it = iter(cmd.get_model(selection, state).atom)
            for line in pdbstr.splitlines(True):
                yield line
                if line[:6] in ["ATOM  ", "HETATM"]:
                    yield "ANISOU" + line[6:28] + "".join("%7.0f" % (u * 1e4) for u in atom_it.next().u_aniso) + line[
                        70:
                    ]

        pdbstr = "".join(mergeaniso())

    f.write(pdbstr)
    f.close()

    if not quiet:
        print "Wrote PDB to '" + filename + "'"
Пример #21
0
Date: October 30, 2015
Version: 1.0
License: Public Domain
"""
from pymol import cmd, stored
import re
try:
    from collections import OrderedDict
    _orderedDict = True
except ImportError:
    _orderedDict = False

# PyMOL 1.7.4 introduces support for multi-letter chains, so we can afford to
# use a smaller alphabet. In earlier versions, use lower-case letters if needed
# (requires running `set ignore_case, 0`)
_long_chains = cmd.get_version()[1] >= 1.74
_default_base = 36 if _long_chains else 62


class OutOfChainsError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return str(self.msg)


class ChainSet(object):
    """
    Base class for various methods to rename chains
Пример #22
0
def diagnostics(filename='', compact=0, quiet=1):
    '''
DESCRIPTION

    Get system level diagnostics data

USAGE

    diagnostics [ filename ]

ARGUMENTS

    filename = str: If given, write output to text file
    '''
    import time
    from pymol import invocation
    from pymol import cmd, CmdException

    compact, quiet = int(compact), int(quiet)

    TZ = '%+05d' % (time.timezone / 36)

    version = cmd.get_version()
    body = u'PyMOL %s\n' % version[0]

    if not compact:
        if version[3]:
            body += 'build date: %s %s\n' % (time.ctime(version[3]), TZ)
        if version[4]:
            body += 'git sha: %s\n' % version[4]

    body += diagnostics_conda(version[0])

    if not compact:
        body += '\nLicense Information:\n'

    body += 'Open-Source Build\n'

    body += diagnostics_platform()

    if not compact:
        body += '\nOpenGL Driver:\n'
    renderer = cmd.get_renderer()
    body += str(renderer[0] or '(none)') + '\n'
    body += str(renderer[1] or '(none)') + '\n'
    body += str(renderer[2] or '(none)') + '\n'

    body += diagnostics_qt()

    if not compact:
        body += diagnostics_python()

        body += '\nStartup Scripts:\n'
        pymolrc = invocation.get_user_config()
        if pymolrc:
            pymolrc = map(_unicode, pymolrc)
            body += '\n'.join(pymolrc) + '\n'
        else:
            body += '(no pymolrc file found)\n'

        body += diagnostics_env_vars()

        body += '\nDiagnostics collected on %s %s\n' % (time.ctime(), TZ)

    if filename:
        filename = cmd.exp_path(filename)
        if not filename.endswith('.txt'):
            raise CmdException('filename must have .txt extension')

        with open(filename, 'w') as handle:
            handle.write(body)
        print('Diagnostics written to "%s"' % filename)
    elif not quiet:
        print(body.rstrip())

    return body
Пример #23
0
 def interpret_color(self, c):
     if cmd.get_version()[1] < 1:
         return cmd._interpret_color(str(c))
     return cmd._interpret_color(cmd, str(c))
def distancetoatom(
origin='pk1',
cutoff=10,
filename=None,
selection='all',
state=0,
property_name='p.dist',
coordinates=0,
decimals=3,
sort=1,
quiet=1
):
    '''
DESCRIPTION

    distancetoatom.py
    Described at: http://www.pymolwiki.org/Distancetoatom

    Prints all distanced between the specified atom/coordinate/center
    and all atoms within cutoff distance that are part of the selection.
    All coordinates and distances can be saved in a csv-style text file report
    and can be appended to a (custom) atom property, if defined.

USAGE

    distancetoatom [ origin [, cutoff [, filename [, selection
    [, state [, property_name [, coordinates [, decimals [, sort
    [, quiet ]]]]]]]]]]

ARGUMENTS

    NAME        TYPE    FUNCTION
    origin:     <list>  defines the coordinates for the origin and can be:
                <str>   1. a list with coordinates [x,y,z]
                        2. a single atom selection string {default='pk1'}
                        3. a multi-atom selection string (center will be used)
    cutoff      <float> sets the maximum distance {default: 10}
    filename    <str>   filename for optional output report. {default=None}
                        set to e.g. 'report.txt' to create a report
                        (omit or set to '', None, 0 or False to disable)
    selection   <str>   can be used to define/limit the measurment to specific
                        sub-selections {default='all'}
    state       <int>   object state, {default=0} # = current
    property_name <str> the distance will be stored in this property {p.dist}
                        set "" to disable
    coordinates <int>   toggle whether atom coordinated will be reported {0}
    decimals    <int>   decimals for coordinates and distance:
                        default = 3 # = max. PDB resolution
    sort        <int>   Sorting by distance?
                         1: ascending (default)
                         0: no sorting (by names)
                        -1: descending
    quiet       <bool>  toggle verbosity
    '''
    # keyword check
    try:
        selection = '(%s)'%selection
        ori=get_coord(origin)
        if not ori:
            print "distancetoatom: aborting - check input for 'origin'!"
            return False
        cutoff = abs(float(cutoff))
        filename = str(filename)
        state = abs(int(state))
        if (not int(state)):
            state=cmd.get_state()
        cmd.set('state', state) # distance by state
        property_name = str(property_name)
        decimals = abs(int(decimals))
        sort = int(sort)
        coordinates=bool(int(coordinates))
        quiet=bool(int(quiet))
    except:
        print 'distancetoatom: aborting - input error!'
        return False

    # round origin
    ori = [round(x,decimals) for x in ori]

    # report?
    if filename in ['', '0', 'False', 'None']:
        filename=False
    else:
        try:
            report=open(filename,'w') # file for writing
        except:
            print 'distancetoatom: Unable to open report file! - Aborting!'
            return False

    # temporary name for pseudoatom
    tempname = cmd.get_unused_name('temp_name')
    tempsel = cmd.get_unused_name('temp_sel')

    #origin
    cmd.pseudoatom(object=tempname, resi=1, pos=ori)

    # select atoms within cutoff
    cmd.select(tempsel, '(%s around %f) and (%s) and state %d' %(tempname, cutoff, selection, state))
    cmd.delete(tempname)

    # single atom ori and part of selection
    # avoid double reporting!
    single_atom_ori=False
    try:
        if cmd.count_atoms('(%s) and (%s) and (%s)'%(selection, tempsel, origin))==1:
            single_atom_ori=True
    except: pass
    # pass= coordinates or multi-atom or single, not selected --> report ori

    # atom list
    stored.temp=[]
    cmd.iterate(tempsel, 'stored.temp.append([model, segi, chain, resn, resi, name, alt])')

    # custom properties? # conditional disabling
    if (property_name==''): property_name=False
    if ((cmd.get_version()[1]<1.7) and (property_name not in ['b','q'])):
        property_name=False

    # calculate the distances, creating list
    distance_list=[]
    if (not single_atom_ori):
        distance_list.append(['ORIGIN: '+str(origin), ori[0], ori[1], ori[2], 0.0])
    for atom in stored.temp:
        atom_name = ('/%s/%s/%s/%s`%s/%s`%s'%(atom[0], atom[1], atom[2], atom[3], atom[4], atom[5], atom[6]))
        atom_xyz = [round(x, decimals) for x in cmd.get_atom_coords(atom_name)]
        atom_dist = round(cpv.distance(ori, atom_xyz), decimals)
        distance_list.append([atom_name,atom_xyz[0],atom_xyz[1],atom_xyz[2], atom_dist])
        # create property with distance (can be used for coloring, labeling etc)
        if property_name:
            try:
                cmd.alter(atom_name, '%s=%f'%(property_name, atom_dist))
            except:
                # I'm not sure alter raises exceptions if the property is illegal
                property_name=False

    # sort list, if selected
    if sort>0: distance_list.sort(key=lambda dist: dist[4])
    elif sort<0: distance_list.sort(key=lambda dist: dist[4], reverse=True)
    # add header
    distance_list=[['Atom Macro ID',
                    'x-coord',
                    'y-coord',
                    'z-coord',
                    'distance_to_origin']
                ]+distance_list

    if ((not quiet) and (filename)):
        # Hijack stdout to print to file and console
        class logboth(object):
            def __init__(self, *files):
                self.files = files
            def write(self, obj):
                for f in self.files:
                    f.write(obj)
        originalstdout = sys.stdout
        sys.stdout = logboth(sys.stdout, report)

    for entry in distance_list:
        if coordinates:
            output= '%s, %s, %s, %s, %s' %(entry[0],entry[1],entry[2],entry[3],entry[4]) #csv style
        else:
            output= '%s, %s' %(entry[0],entry[4]) #csv style
        if (not quiet):
            print output
        elif filename:
            report.write(output+'\n')

    # restore regular stdout
    if ((not quiet) and (filename)): sys.stdout = originalstdout
    # close file
    if filename: report.close()

    if (not quiet):
        if property_name: print 'Distances saved to property: %s' %str(property_name)
        else: print 'Distances NOT saved to property (illegal custom property)'
Пример #25
0
def startup_pymod(app=None):
    """
    Executed when clicking on the 'PyMod' item in PyMOL's plugin menu.
    """

    if has_gui is None:
        print(
            "\n# No GUI library (either Tkinter or Qt bindings) was found. PyMod"
            " can not be launched.")
        return None

    # Check if a PyMod main window is already open.
    if pyqt_found:
        try:
            for widget in QtWidgets.QApplication.instance().topLevelWidgets():
                if hasattr(widget,
                           "is_pymod_main_window") and widget.isVisible():
                    title = "PyMod Error"
                    message = (
                        "PyMod is already running. Please close its main"
                        " window or restart PyMOL in order to launch it again."
                    )
                    showerror(title, message)
                    return None
        except Exception as e:
            pass

    # Checks if Python 3 is available.
    if python_version != 3:
        title = "Python Version Error"
        message = "PyMod %s requires Python 3. Your current Python version is %s." % (
            __pymod_version__, python_micro_version)
        showerror(title, message)
        return None

    # Checks the PyMOL version.
    pymol_version = float(".".join(cmd.get_version()[0].split(".")[0:2]))
    if pymol_version < 2.3:
        title = "PyMOL Version Error"
        message = "PyMod %s requires a PyMOL version of 2.3 or higher. Your current PyMOL version is %s." % (
            __pymod_version__, pymol_version)
        showerror(title, message)
        return None

    # Checks for PyQt.
    if not pyqt_found:
        title = "Import Error"
        message = "PyQt5 is not installed on your system. Please install it in order to use PyMod."
        showerror(title, message)
        return None

    # Checks if NumPy and Biopython (PyMod core Python dependencies) are present before launching
    # PyMod.
    if not numpy_found:
        title = "Import Error"
        message = "NumPy is not installed on your system. Please install it in order to use PyMod."
        showerror(title, message)
        return None
    if not biopython_found:
        title = "Import Error"
        message = "Biopython is not installed on your system. Please install it in order to use PyMod."
        showerror(title, message)
        return None

    # Adds to the sys.path the directory where the PyMod module is located.
    pymod_plugin_dirpath = os.path.dirname(__file__)
    if os.path.isdir(pymod_plugin_dirpath):
        sys.path.append(pymod_plugin_dirpath)

    # Attempts to import MODELLER from the default sys.path.
    modeller_spec = util.find_spec("modeller")

    parallel_modeller = False  # A flag, when set as 'True' MODELLER parallel jobs can be used.

    # MODELLER can be imported.
    if modeller_spec is not None:
        parallel_modeller = True

    # MODELLER can not be imported. Tries to import it from a PyMod conda
    # pseudo-environment.
    else:

        # Adds to the sys.path the PyMod conda environment directory. Used to import
        # modules fetched by conda within PyMod.
        from pymod_lib import pymod_os_specific

        pymod_env_dirpath = pymod_os_specific.get_pymod_cfg_paths()[3]

        # Checks if a directory for a PyMod conda pseudo-environment exists.
        if os.path.isdir(pymod_env_dirpath):

            if sys.platform in ("linux", "darwin"):
                conda_lib_dirpath_list = [
                    os.path.join(pymod_env_dirpath, "lib",
                                 "python%s" % python_minor_version),
                    os.path.join(pymod_env_dirpath, "lib",
                                 "python%s" % python_minor_version,
                                 "lib-dynload"),
                    os.path.join(pymod_env_dirpath, "lib",
                                 "python%s" % python_minor_version,
                                 "site-packages")
                ]
                path_extend_list = []

            elif sys.platform == "win32":
                dll_dirpath = os.path.join(pymod_env_dirpath, "Lib",
                                           "site-packages")
                conda_lib_dirpath_list = [
                    os.path.join(pymod_env_dirpath, "Library", "modeller",
                                 "modlib"), dll_dirpath
                ]

                path_extend_list = [
                    os.path.join(pymod_env_dirpath, "Scripts"),
                    pymod_env_dirpath, dll_dirpath
                ]

            else:
                conda_lib_dirpath_list = []
                path_extend_list = []

            # Add the environment directories to the sys.path of Python.
            for conda_lib_dirpath in conda_lib_dirpath_list:
                sys.path.append(conda_lib_dirpath)
            # Also add new directories to the PATH to use the MODELLER DLLs.
            if path_extend_list:
                os.environ["PATH"] += os.pathsep.join(path_extend_list)
            os.environ[
                "HDF5_DISABLE_VERSION_CHECK"] = "1"  # Prevents problems with hdf5 libraries versions.

            # Edit the 'modslave.py' file of MODELLER in the PyMod environment directory
            # (the user's original MODELLER files will remain untouched) so that the
            # MODELLER version installed in the PyMod environment directory can be
            # used to run parallel jobs. This operation will be performed only once,
            # that is, the first time PyMod is launched after MODELLER has been
            # installed through the GUI of the plugin.
            try:

                # Gets the installation directory of MODELLER. This can be acquired
                # also if the MODELLER key is not valid.
                from modeller import config

                modeller_bin_dirpath = os.path.join(config.install_dir, "bin")
                modslave_filepath = os.path.join(modeller_bin_dirpath,
                                                 "modslave.py")
                modslave_bak_filepath = os.path.join(modeller_bin_dirpath,
                                                     "modslave.py.bak")

                # Checks if the modslave file is present.
                if os.path.isfile(modslave_filepath):

                    # Checks if the backup modslave file is present (if it already
                    # exists, then PyMod has already modified the original modslave
                    # file).
                    if not os.path.isfile(modslave_bak_filepath):

                        print(
                            "\n# Configuring the MODELLER modslave.py in the PyMod environment."
                        )
                        print("- modslave.py file found at: %s" %
                              modslave_filepath)

                        # Build a backup copy of the original modslave file.
                        print("- Backing up the modslave.py file.")
                        shutil.copy(modslave_filepath, modslave_bak_filepath)

                        # Gets the content from the old modslave file.
                        with open(modslave_filepath, "r") as m_fh:
                            modfile_lines = m_fh.readlines()

                        insert_idx = 1
                        for line_idx, line in enumerate(modfile_lines):
                            if line.startswith("import sys"):
                                print("- Found insert line")
                                insert_idx = line_idx + 1
                                break

                        # This will add the paths above also to the 'modslave.py'
                        # file, so that MODELLER can be imported in child processes.
                        import_lines = [
                            '\n# Added by the PyMod installer.\n',
                            'import os\n', 'import sys\n\n',
                            'conda_lib_dirpath_list = %s\n' %
                            repr(conda_lib_dirpath_list),
                            'path_extend_list = %s\n\n' %
                            repr(path_extend_list),
                            'for path in conda_lib_dirpath_list:\n',
                            '    sys.path.append(path)\n',
                            'os.environ["PATH"] += os.pathsep.join(path_extend_list)\n',
                            'os.environ["HDF5_DISABLE_VERSION_CHECK"] = "1"\n',
                            '# End of the code inserted by PyMod.\n'
                        ]

                        modfile_lines = modfile_lines[:
                                                      insert_idx] + import_lines + modfile_lines[
                                                          insert_idx:]

                        # Edits the modslave file.
                        with open(modslave_filepath, "w") as m_fh:
                            m_fh.writelines(modfile_lines)

                        print("- Finishing.")

                    parallel_modeller = True

            except Exception as e:
                print(
                    "- Could not import MODELLER from the PyMod environment: %s."
                    % e)

    # Actually launches PyMod.
    from pymod_lib import pymod_main

    pymod_main.pymod_launcher(app=app,
                              pymod_plugin_name=pymod_plugin_name,
                              pymod_version=__pymod_version__,
                              pymod_revision=__revision__,
                              parallel_modeller=parallel_modeller)
Пример #26
0
A reference document with all commands can be generated with:
PyMOL> psico.helping.write_html_ref('psico-commands.html')

(c) 2010-2012 Thomas Holder <*****@*****.**>
              Steffen Schmidt <*****@*****.**>
              Max Planck Institute for Developmental Biology

License: BSD-2-Clause
'''

__version__ = '3.2'

try:
    from pymol import cmd
    pymol_version = cmd.get_version()[1]
except:
    pymol_version = 1.6

__all__ = [
    'aaindex',
    'contactmap',
    'contactmap_yang',
    'conservation',
    'creating',
    'editing',
    'electrostatics',
    'exporting',
    'fasta',
    'fitting',
    'geometry',
Пример #27
0
'''
Orientation, displacement and angle measurments of helices and domains.

(c) 2010-2012 Thomas Holder, MPI for Developmental Biology

License: BSD-2-Clause
'''

from pymol import cmd, CmdException
from chempy import cpv

if cmd.get_version()[1] < 1.2:
    # legacy support to run this script standalone with PyMOL 0.99
    def get_unused_name(name):
        import random
        return name + '%04d' % random.randint(0, 1000)
    STATE = 1
else:
    from pymol.cmd import get_unused_name
    STATE = -1

def _vec_sum(vec_list):
    # this is the same as
    # return numpy.array(vec_list).sum(0).tolist()
    vec = cpv.get_null()
    for x in vec_list:
        vec = cpv.add(vec, x)
    return vec

def _common_orientation(selection, center, vec, visualize=1, scale=1.0, quiet=1):
    if visualize:
Пример #28
0
    def __init__(self, root, top, menuindex, Project_Dir, Install_Dir,
                 NRGsuite_Dir, OSid, PyMOL, Name, WINDOWWIDTH, WINDOWHEIGHT,
                 RootPrefs):

        self.Name = Name
        self.OSid = OSid
        self.PyMOL = PyMOL
        self.pymol_major_version = int(cmd.get_version()[0][0])

        self.NRGsuite_Dir = NRGsuite_Dir
        self.Install_Dir = Install_Dir
        self.Project_Dir = Project_Dir

        self.Folders = [self.NRGsuite_Dir]
        if self.Project_Dir:
            self.Folders.append(self.Project_Dir)

        self.Set_Folders()
        self.Validate_Folders()

        self.Prefs = RootPrefs

        self.Color_Green = '#CCFFCC'
        self.Color_Grey = '#EDEDED'
        self.Color_Gray = '#EDEDED'
        self.Color_Blue = '#6699FF'
        self.Color_Red = '#FF9999'
        self.Color_White = '#FFFFFF'
        self.Color_Black = '#000000'

        self.root = root
        self.root.title(self.Name)

        self.top = top

        self.menuindex = menuindex
        if self.menuindex != -1:
            self.Disable_MenuItem()

        self.WINDOWWIDTH = WINDOWWIDTH
        self.WINDOWHEIGHT = WINDOWHEIGHT

        #self.root.geometry()   # Interface DIMENSIONS
        #self.root.maxsize(WINDOWWIDTH,WINDOWHEIGHT)
        self.root.minsize(self.WINDOWWIDTH, self.WINDOWHEIGHT)
        self.root.protocol('WM_DELETE_WINDOW', self.Quit)

        General.CenterWindow(self.root, self.WINDOWWIDTH, self.WINDOWHEIGHT)

        #==================================================================================
        #                 SET the default fonts of the interface
        #==================================================================================

        FontType = self.Prefs.GetFontType()
        FontSize = self.Prefs.GetFontSize()

        self.font_Title = tkFont.Font(family=FontType,
                                      size=FontSize,
                                      weight=tkFont.BOLD)
        self.font_Title_H = tkFont.Font(family=FontType,
                                        size=FontSize + 1,
                                        weight=tkFont.BOLD)
        self.font_Text = tkFont.Font(family=FontType, size=FontSize)
        self.font_Text_H = tkFont.Font(family=FontType, size=FontSize + 1)
        self.font_Text_I = tkFont.Font(family=FontType,
                                       size=FontSize,
                                       slant=tkFont.ITALIC)
        self.font_Text_U = tkFont.Font(family=FontType,
                                       size=FontSize,
                                       underline=True)

        self.ChildWindow = None
        self.ActiveFrame = None
        self.Run = None

        self.ProcessError = False
        self.ProcessRunning = False
        self.ProcessParsing = False
        self.ProcessDone = False
        self.ParseState = 10
        self.SimulateState = -1

        self.fMain = Frame(self.root)
        self.fMain.pack(expand=True)

        self.Def_Vars()
        self.Init_Vars()

        self.Frame_Main()

        self.Build_Tabs()
        self.MakeMenuBar()

        self.After_Init()

        self.Clean()
Пример #29
0
def modevectors(first_obj_frame,
                last_obj_frame,
                first_state=1,
                last_state=1,
                outname="modevectors",
                head=0.5,
                tail=0.1,
                head_length=0.3,
                headrgb="0,0,0",
                tailrgb="0.0,0.0,0.0",
                cutoff=4.0,
                skip=0,
                cut=0.5,
                atom="CA",
                stat="show",
                factor=1.0,
                notail=1):
    """
    Authors Sean Law & Srinivasa
    Michigan State University
    slaw_(at)_msu_dot_edu

    Editor Sacha Yee

    USAGE

    While in PyMOL

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

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

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

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

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

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

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

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

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

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

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

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

                skipcount = 0
            else:
                skipcount += 1

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

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

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

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

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

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

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


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

    if stat == "show":
        natoms = skipcounter + keepcounter
        print("\nTotal number of atoms = " + str(natoms))
        print("Atoms skipped = " + str(skipcounter))
        if keepcounter - cutoff_counter > 0:
            print("Atoms counted = " + str(keepcounter - cutoff_counter) +
                  " (see PyMOL object \"" + objectname + "\")")
        else:
            print("Atoms counted = " + str(keepcounter - cutoff_counter) +
                  " (Empty CGO object not loaded)")
        print("Atoms cutoff  = " +
              str(cutoff_counter))  # Note that cutoff occurs AFTER skipping!
    if keepcounter - cutoff_counter > 0:
        cmd.delete(objectname)
        cmd.load_cgo(
            arrow, objectname
        )  # Ray tracing an empty object will cause a segmentation fault.  No arrows = Do not display in PyMOL!!!
    cmd.show(representation="cartoon", selection=first_obj_frame)
    if (first_obj_frame != last_obj_frame):
        cmd.show(representation="cartoon", selection=last_obj_frame)
        cmd.hide(representation="cartoon", selection=last_obj_frame)
    cmd.bg_color(color="white")
    cmd.set_view(save_view)
    return
Пример #30
0
 def test_version(self):
     v = cmd.get_version()
     # check that all elements of v are the same, need to remove "." and strip trailing 0's
     s = set(map(lambda s: str(s).replace('.', '').rstrip('0'), v))
     self.assertEqual(len(s), 1)