Esempio n. 1
0
def extra_fit(selection='(all)',
              reference=None,
              method='align',
              zoom=1,
              quiet=0,
              _self=cmd,
              **kwargs):
    '''
DESCRIPTION

    Like "intra_fit", but for multiple objects instead of
    multiple states.

ARGUMENTS

    selection = string: atom selection of multiple objects {default: all}

    reference = string: reference object name {default: first object in selection}

    method = string: alignment method (command that takes "mobile" and "target"
    arguments, like "align", "super", "cealign" {default: align}

    ... extra arguments are passed to "method"

SEE ALSO

    alignto, cmd.util.mass_align, align_all.py from Robert Campbell
    '''
    zoom, quiet = int(zoom), int(quiet)
    models = cmd.get_object_list('(%s)' % selection)
    if reference is None:
        reference = models[0]
        models = models[1:]
    elif reference in models:
        models.remove(reference)
    if cmd.is_string(method):
        if method in cmd.keyword:
            method = cmd.keyword[method][0]
        else:
            print('Unknown method ' + str(method))
            raise CmdException
    for model in models:
        x = method(mobile='(%s) and model %s' % (selection, model),
                   target='(%s) and model %s' % (selection, reference),
                   **kwargs)
        if not quiet:
            if cmd.is_sequence(x):
                print('%-20s RMS = %8.3f (%d atoms)' % (model, x[0], x[1]))
            elif isinstance(x, float):
                print('%-20s RMS = %8.3f' % (model, x))
            elif _self.is_dict(x) and 'RMSD' in x:
                natoms = x.get('alignment_length', 0)
                suffix = (' (%s atoms)' % natoms) if natoms else ''
                print('%-20s RMS = %8.3f' % (model, x['RMSD']) + suffix)
            else:
                print('%-20s' % (model, ))

    if zoom:
        cmd.zoom(selection)
Esempio n. 2
0
def iterate_plot(selection, expr_y, expr_x=None, scatter=0, filename=None,
        space=None, quiet=1):
    '''
DESCRIPTION

    Plot atomic properties.

ARGUMENTS

    selection = string: atom selection

    expr_y = string: python expression for y values
    
    expr_x = string: python expression for x values {default: None}

    scatter = 0/1: make line plot or scatter plot {default: 0, line plot}

EXAMPLE

    # C-alpha b-factors
    iterate_plot name CA, b, resv
    '''
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    scatter, quiet = int(scatter), int(quiet)
    if space is None:
        space = {'cmd': cmd, 'stored': cmd.pymol.stored}

    if cmd.is_string(selection):
        if selection.startswith('['):
            sele_list = selection[1:-1].split(',')
        else:
            sele_list = ['(%s) and (%s)' % (model, selection) for model in
                    cmd.get_object_list('(' + selection + ')')]
    else:
        sele_list = selection

    fig = figure()
    plt = fig.add_subplot(111)

    for selection in sele_list:
        space['_values'] = y_values = []
        cmd.iterate(selection, '_values.append(' + expr_y + ')', space=space)

        if expr_x is None:
            x_values = range(len(y_values))
        else:
            space['_values'] = x_values = []
            cmd.iterate(selection, '_values.append(' + expr_x + ')', space=space)

        color = get_model_color(selection)

        if scatter:
            plt.scatter(x_values, y_values, c=color)
        else:
            plt.plot(x_values, y_values, c=color)

    _showfigure(fig, filename, quiet)
Esempio n. 3
0
def iterate_plot(selection, expr_y, expr_x=None, scatter=0, filename=None,
        space=None, quiet=1):
    '''
DESCRIPTION

    Plot atomic properties.

ARGUMENTS

    selection = string: atom selection

    expr_y = string: python expression for y values
    
    expr_x = string: python expression for x values {default: None}

    scatter = 0/1: make line plot or scatter plot {default: 0, line plot}

EXAMPLE

    # C-alpha b-factors
    iterate_plot name CA, b, resv
    '''
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    scatter, quiet = int(scatter), int(quiet)
    if space is None:
        space = {'cmd': cmd, 'stored': cmd.pymol.stored}

    if cmd.is_string(selection):
        if selection.startswith('['):
            sele_list = selection[1:-1].split(',')
        else:
            sele_list = ['(%s) and (%s)' % (model, selection) for model in
                    cmd.get_object_list('(' + selection + ')')]
    else:
        sele_list = selection

    fig = figure()
    plt = fig.add_subplot(111)

    for selection in sele_list:
        space['_values'] = y_values = []
        cmd.iterate(selection, '_values.append(' + expr_y + ')', space=space)

        if expr_x is None:
            x_values = list(range(len(y_values)))
        else:
            space['_values'] = x_values = []
            cmd.iterate(selection, '_values.append(' + expr_x + ')', space=space)

        color = get_model_color(selection)

        if scatter:
            plt.scatter(x_values, y_values, c=color)
        else:
            plt.plot(x_values, y_values, c=color)

    _showfigure(fig, filename, quiet)
Esempio n. 4
0
def extra_fit(selection='(all)', reference=None, method='align', zoom=1,
        quiet=0, _self=cmd, **kwargs):
    '''
DESCRIPTION

    Like "intra_fit", but for multiple objects instead of
    multiple states.

ARGUMENTS

    selection = string: atom selection of multiple objects {default: all}

    reference = string: reference object name {default: first object in selection}

    method = string: alignment method (command that takes "mobile" and "target"
    arguments, like "align", "super", "cealign" {default: align}

    ... extra arguments are passed to "method"

SEE ALSO

    alignto, cmd.util.mass_align, align_all.py from Robert Campbell
    '''
    zoom, quiet = int(zoom), int(quiet)
    sele_name = cmd.get_unused_name('_')
    cmd.select(sele_name, selection) # for speed
    models = cmd.get_object_list(sele_name)
    if reference is None:
        reference = models[0]
        models = models[1:]
    elif reference in models:
        models.remove(reference)
    else:
        cmd.select(sele_name, reference, merge=1)
    if cmd.is_string(method):
        if method in cmd.keyword:
            method = cmd.keyword[method][0]
        else:
            print('Unknown method:', method)
            raise CmdException
    for model in models:
        x = method(mobile='%s and model %s' % (sele_name, model),
                target='%s and model %s' % (sele_name, reference), **kwargs)
        if not quiet:
            if cmd.is_sequence(x):
                print('%-20s RMS = %8.3f (%d atoms)' % (model, x[0], x[1]))
            elif isinstance(x, float):
                print('%-20s RMS = %8.3f' % (model, x))
            elif isinstance(x, dict) and 'RMSD' in x:
                natoms = x.get('alignment_length', 0)
                suffix = (' (%s atoms)' % natoms) if natoms else ''
                print('%-20s RMS = %8.3f' % (model, x['RMSD']) + suffix)
            else:
                print('%-20s' % (model,))

    if zoom:
        cmd.zoom(sele_name)
    cmd.delete(sele_name)
Esempio n. 5
0
def write_html_ref(filename, prefix='psico', format='html'):
    '''
DESCRIPTION

    Write psico command reference to file.

SEE ALSO

    cmd.write_html_ref
    '''
    if prefix == 'psico' and not __name__.startswith(prefix):
        prefix = __name__.rsplit('.', 1)[0]
    ref = []
    for a in sorted(cmd.keyword):
        if a.startswith('_'):
            continue
        func = cmd.keyword[a][0]
        if (func.__module__, func.__name__) == ('pymol.helping',
                                                'python_help'):
            continue
        if func.__module__.startswith(prefix) and hasattr(func, '__doc__'):
            if cmd.is_string(func.__doc__):
                ref.append([a, func])
    f = open(filename, 'w')

    if format == 'txt_short':
        import re
        pattern_header = re.compile(r'^[A-Z]+', flags=re.MULTILINE)
        pattern_emptyline = re.compile(r'\s+$', flags=re.MULTILINE)
        for (a, func) in ref:
            doc = func.__doc__.partition('DESCRIPTION')[-1]
            doc = pattern_header.split(doc, 1)[0]
            doc = pattern_emptyline.sub('', doc)
            f.write('%s\t%s\n\n' % (a, doc))
        f.close
        return

    f.write("<html><head><style type='text/css'>")
    f.write("body {font-family:sans-serif}")
    f.write("p.api {font:small monospace;color:#999}")
    f.write("</style></head><body><h1>pymol psico reference</h1><ul>")
    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()
Esempio n. 6
0
def write_html_ref(filename, prefix="psico", format="html"):
    """
DESCRIPTION

    Write psico command reference to file.

SEE ALSO

    cmd.write_html_ref
    """
    if prefix == "psico" and not __name__.startswith(prefix):
        prefix = __name__.rsplit(".", 1)[0]
    ref = []
    for a in sorted(cmd.keyword):
        if a.startswith("_"):
            continue
        func = cmd.keyword[a][0]
        if (func.__module__, func.__name__) == ("pymol.helping", "python_help"):
            continue
        if func.__module__.startswith(prefix) and hasattr(func, "__doc__"):
            if cmd.is_string(func.__doc__):
                ref.append([a, func])
    f = open(filename, "w")

    if format == "txt_short":
        import re

        pattern_header = re.compile(r"^[A-Z]+", flags=re.MULTILINE)
        pattern_emptyline = re.compile(r"\s+$", flags=re.MULTILINE)
        for (a, func) in ref:
            doc = func.__doc__.partition("DESCRIPTION")[-1]
            doc = pattern_header.split(doc, 1)[0]
            doc = pattern_emptyline.sub("", doc)
            f.write("%s\t%s\n\n" % (a, doc))
        f.close
        return

    f.write("<html><head><style type='text/css'>")
    f.write("body {font-family:sans-serif}")
    f.write("p.api {font:small monospace;color:#999}")
    f.write("</style></head><body><h1>pymol psico reference</h1><ul>")
    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()
Esempio n. 7
0
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 not cmd.is_string(needle):
        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 not cmd.is_string(haystack):
        print("Error: Please provide valid PyMOL object or selection name")
        print("Error: in which to search.")
        print("Error: For help type 'help motifFinder'.")
        return False

    # check het
    try:
        het = bool(int(het))
    except ValueError:
        print("Error: The 'het' parameter was not 0 or 1.")
        return False

    # check first Only
    try:
        firstOnly = bool(int(het))
    except ValueError:
        print("Error: The 'firstOnly' parameter was not 0 or 1.")
        return False

    # check selName
    if not cmd.is_string(selName):
        print("Error: selName was not a string.")
        return False
    return True
Esempio n. 8
0
def get_data(handle):
    if not cmd.is_string(handle):
        return handle

    try:
        import h5py
    except ImportError:
        raise CmdException("h5py module not available, cannot load vis files")

    try:
        handle = h5py.File(handle, "r")
    except IOError:
        raise CmdException("Failed to open file " + str(handle))

    return next(iter(next(iter(handle.values())).values()))
Esempio n. 9
0
    def get_docstring(self):
        '''
        Get docstring either from loaded module, or try to parse first python
        statement from file, without executing any code.
        '''
        if self.loaded:
            return self.module.__doc__

        try:
            c = compile(''.join(open(self.filename)), 'x', 'single')
            s = c.co_consts[0]
            if cmd.is_string(s):
                return s
        except:
            pass
Esempio n. 10
0
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 not cmd.is_string(needle):
        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 not cmd.is_string(haystack):
        print("Error: Please provide valid PyMOL object or selection name")
        print("Error: in which to search.")
        print("Error: For help type 'help motifFinder'.")
        return False

    # check het
    try:
        het = bool(int(het))
    except ValueError:
        print("Error: The 'het' parameter was not 0 or 1.")
        return False

    # check first Only
    try:
        firstOnly = bool(int(het))
    except ValueError:
        print("Error: The 'firstOnly' parameter was not 0 or 1.")
        return False

    # check selName
    if not cmd.is_string(selName):
        print("Error: selName was not a string.")
        return False
    return True
Esempio n. 11
0
def write_html_ref(filename, prefix='psico', format='html'):
    '''
DESCRIPTION

    Write psico command reference to file.

SEE ALSO

    cmd.write_html_ref
    '''
    if prefix == 'psico' and not __name__.startswith(prefix):
        prefix = __name__.rsplit('.', 1)[0]
    ref = []
    for a in sorted(cmd.keyword):
        if a.startswith('_'):
            continue
        func = cmd.keyword[a][0]
        if func.__module__.startswith(prefix) and hasattr(func, '__doc__'):
            if cmd.is_string(func.__doc__):
                ref.append([a, func])
    f = open(filename, 'w')

    if format == 'txt_short':
        import re
        pattern_header = re.compile(r'^[A-Z]+', flags=re.MULTILINE)
        pattern_emptyline = re.compile(r'\s+$', flags=re.MULTILINE)
        for (a, func) in ref:
            doc = func.__doc__.partition('DESCRIPTION')[-1]
            doc = pattern_header.split(doc, 1)[0]
            doc = pattern_emptyline.sub('', doc)
            f.write('%s\t%s\n\n' % (a, doc))
        f.close
        return

    f.write("<html><head><style type='text/css'>")
    f.write("p.api {font:small monospace;color:#999}")
    f.write("</style></head><body><h1>pymol psico reference</h1><ul>")
    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()
Esempio n. 12
0
    def get_docstring(self):
        '''
        Get docstring either from loaded module, or try to parse first python
        statement from file, without executing any code.
        '''
        if self.loaded:
            return self.module.__doc__

        try:
            c = compile(b''.join(open(self.filename, 'rb')), 'x', 'exec', dont_inherit=True)
            s = c.co_consts[0]
            if cmd.is_string(s):
                return s
        except SyntaxError as e:
            return 'WARNING: Plugin not Python 3.x compatible: ' + str(e)
        except:
            pass
Esempio n. 13
0
    def get_docstring(self):
        '''
        Get docstring either from loaded module, or try to parse first python
        statement from file, without executing any code.
        '''
        if self.loaded:
            return self.module.__doc__

        try:
            c = compile(''.join(open(self.filename)), 'x', 'exec', dont_inherit=True)
            s = c.co_consts[0]
            if cmd.is_string(s):
                return s
        except SyntaxError as e:
            if sys.version_info[0] > 2:
                return 'WARNING: Plugin not Python 3.x compatible: ' + str(e)
        except:
            pass
Esempio n. 14
0
def pdbremarks(filename):
    '''
DESCRIPTION

    API only. Read REMARK lines from PDB file. Return dictionary with
    remarkNum as key and list of lines as value.
    '''
    remarks = dict()
    if not cmd.is_string(filename):
        f = filename
    elif filename[-3:] == '.gz':
        import gzip
        f = gzip.open(filename)
    else:
        f = open(filename)
    for line in f:
        recname = line[0:6]
        if recname == 'REMARK':
            num = int(line[7:10])
            lstring = line[11:]
            remarks.setdefault(num, []).append(lstring)
    return remarks
Esempio n. 15
0
def pdbremarks(filename):
    '''
DESCRIPTION

    API only. Read REMARK lines from PDB file. Return dictionary with
    remarkNum as key and list of lines as value.
    '''
    remarks = dict()
    if not cmd.is_string(filename):
        f = filename
    elif filename[-3:] == '.gz':
        import gzip
        f = gzip.open(filename)
    else:
        f = open(filename)
    for line in f:
        recname = line[0:6]
        if recname == 'REMARK':
            num = int(line[7:10])
            lstring = line[11:]
            remarks.setdefault(num, []).append(lstring)
    return remarks
Esempio n. 16
0
def ramp_levels(name, levels, quiet=1):
    '''
DESCRIPTION

    Changes the slot levels of a ramp.

SEE ALSO

    ramp_new, isolevel
    '''
    quiet = int(quiet)
    if cmd.is_string(levels):
        levels = cmd.safe_list_eval(levels)

    try:
        position = cmd.get_names('all').index(name)

        odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0]
        if odata[4] != 8:
            raise TypeError('not a ramp')
        data = odata[5]
    except:
        print(' Error: Get session data for ramp "%s" failed' % (name))
        raise CmdException

    if len(levels) != len(data[3]):
        print(' Error: number of levels must agree with existing object')
        raise CmdException

    map_name = data[6]
    colors = [data[4][i:i + 3] for i in range(0, len(data[4]), 3)]
    cmd.ramp_new(name, map_name, levels, colors, quiet=quiet)

    # restore original position
    if position == 0:
        cmd.order(name, location='top')
    else:
        cmd.order(cmd.get_names('all')[position - 1] + ' ' + name)
Esempio n. 17
0
def ramp_levels(name, levels, quiet=1):
    '''
DESCRIPTION

    Changes the slot levels of a ramp.

SEE ALSO

    ramp_new, isolevel
    '''
    quiet = int(quiet)
    if cmd.is_string(levels):
        levels = cmd.safe_list_eval(levels)

    try:
        position = cmd.get_names('all').index(name)

        odata = cmd.get_session(name, 1, 1, 0, 0)['names'][0]
        if odata[4] != 8:
            raise TypeError('not a ramp')
        data = odata[5]
    except:
        print(' Error: Get session data for ramp "%s" failed' % (name))
        raise CmdException

    if len(levels) != len(data[3]):
        print(' Error: number of levels must agree with existing object')
        raise CmdException

    map_name = data[6]
    colors = [data[4][i:i+3] for i in range(0, len(data[4]), 3)]
    cmd.ramp_new(name, map_name, levels, colors, quiet=quiet)

    # restore original position
    if position == 0:
        cmd.order(name, location='top')
    else:
        cmd.order(cmd.get_names('all')[position-1] + ' ' + name)
Esempio n. 18
0
def angle_between_domains(selection1, selection2, method='align',
        state1=STATE, state2=STATE, visualize=1, quiet=1):
    '''
DESCRIPTION

    Angle by which a molecular selection would be rotated when superposing
    on a selection2.

    Do not use for measuring angle between helices, since the alignment of
    the helices might involve a rotation around the helix axis, which will
    result in a larger angle compared to the angle between helix axes.

USAGE

    angle_between_domains selection1, selection2 [, method ]

ARGUMENTS

    selection1 = string: atom selection of first helix

    selection2 = string: atom selection of second helix

    method = string: alignment command like "align" or "super" {default: align}

EXAMPLE

    fetch 3iplA 3iplB, async=0
    select domain1, resi 1-391
    select domain2, resi 392-475
    align 3iplA and domain1, 3iplB and domain1
    angle_between_domains 3iplA and domain2, 3iplB and domain2

SEE ALSO

    align, super, angle_between_helices
    '''
    import math

    try:
        import numpy
    except ImportError:
        print ' Error: numpy not available'
        raise CmdException

    state1, state2 = int(state1), int(state2)
    visualize, quiet = int(visualize), int(quiet)

    if cmd.is_string(method):
        try:
            method = cmd.keyword[method][0]
        except KeyError:
            print 'no such method:', method
            raise CmdException

    mobile_tmp = get_unused_name('_')
    cmd.create(mobile_tmp, selection1, state1, 1,  zoom=0)
    try:
        method(mobile=mobile_tmp, target=selection2, mobile_state=1,
                target_state=state2, quiet=quiet)
        mat = cmd.get_object_matrix(mobile_tmp)
    except:
        print ' Error: superposition with method "%s" failed' % (method.__name__)
        raise CmdException
    finally:
        cmd.delete(mobile_tmp)

    try:
        # Based on transformations.rotation_from_matrix
        # Copyright (c) 2006-2012, Christoph Gohlke

        R33 = [mat[i:i+3] for i in [0,4,8]]
        R33 = numpy.array(R33, float)

        # direction: unit eigenvector of R33 corresponding to eigenvalue of 1
        w, W = numpy.linalg.eig(R33.T)
        i = w.real.argmax()
        direction = W[:, i].real

        # rotation angle depending on direction
        m = direction.argmax()
        i,j,k,l = [
            [2,1,1,2],
            [0,2,0,2],
            [1,0,0,1]][m]
        cosa = (R33.trace() - 1.0) / 2.0
        sina = (R33[i, j] + (cosa - 1.0) * direction[k] * direction[l]) / direction[m]

        angle = math.atan2(sina, cosa)
        angle = abs(math.degrees(angle))
    except:
        print ' Error: rotation from matrix failed'
        raise CmdException

    if not quiet:
        try:
            # make this import optional to support running this script standalone
            from .querying import centerofmass, gyradius
        except (ValueError, ImportError):
            gyradius = None
            try:
                # PyMOL 1.7.1.6+
                centerofmass = cmd.centerofmass
            except AttributeError:
                centerofmass = lambda s: cpv.scale(cpv.add(*cmd.get_extent(s)), 0.5)

        center1 = centerofmass(selection1)
        center2 = centerofmass(selection2)
        print ' Angle: %.2f deg, Displacement: %.2f angstrom' % (angle, cpv.distance(center1, center2))

        if visualize:
            center1 = numpy.array(center1, float)
            center2 = numpy.array(center2, float)
            center = (center1 + center2) / 2.0

            if gyradius is not None:
                rg = numpy.array(gyradius(selection1), float)
            else:
                rg = 10.0

            h1 = numpy.cross(center2 - center1, direction)
            h2 = numpy.dot(R33, h1)
            h1 *= rg / cpv.length(h1)
            h2 *= rg / cpv.length(h2)

            for pos in [center1, center2, center1 + h1, center1 + h2]:
                cmd.pseudoatom(mobile_tmp, pos=list(pos), state=1)

            # measurement object for angle and displacement
            name = get_unused_name('measurement')
            cmd.distance(name, *['%s`%d' % (mobile_tmp, i) for i in [1,2]])
            cmd.angle(name, *['%s`%d' % (mobile_tmp, i) for i in [3,1,4]])

            # CGO arrow for axis of rotation
            visualize_orientation(direction, center1, rg, color='blue')

            cmd.delete(mobile_tmp)

    return angle
Esempio n. 19
0
def pmf(key,
        cutoff=7.0,
        selection1='(name CB)',
        selection2='',
        state=1,
        quiet=1):
    '''
DESCRIPTION
 
    Potential of Mean Force
 
ARGUMENTS
 
    key = string: aaindex key
 
    cutoff = float: distance cutoff {default: 7.0}
    cutoff = (float, float): distance shell
 
    selection1 = string: atom selection {default: (name CB)}
 
    selection2 = string: atom selection {default: selection1}
 
NOTES
 
    Does also support a list of keys and a list of cutoffs to deal with
    multiple distance shells.
 
EXAMPLES
 
    # distance dependent c-beta contact potentials
    pmf SIMK990101, 5,         /2x19//A//CB
    pmf SIMK990102, [5, 7.5],  /2x19//A//CB
    pmf [SIMK990101, SIMK990102, SIMK990103], [0, 5, 7.5, 10], /2x19//A//CB
 
    # interface potential
    sidechaincenters 2x19_scc, 2x19
    pmf KESO980102, 7.0, /2x19_scc//A, /2x19_scc//B
    distance /2x19_scc//A, /2x19_scc//B, cutoff=7.0
    '''
    from pymol import cmd, stored
    from chempy import cpv
    if cmd.is_string(key):
        if key.lstrip().startswith('['):
            key = cmd.safe_alpha_list_eval(key)
        else:
            key = [key]
    if cmd.is_string(cutoff):
        cutoff = eval(cutoff)
    if not cmd.is_sequence(cutoff):
        cutoff = [cutoff]
    if len(cutoff) == len(key):
        cutoff = [0.0] + list(cutoff)
    if len(cutoff) != len(key) + 1:
        print 'Error: Number of keys and number of cutoffs inconsistent'
        return
    state = int(state)
    quiet = int(quiet)
    if len(selection2) == 0:
        selection2 = selection1
    if not quiet and len(key) > 1:
        print 'Distance shells:'
        for i in range(len(key)):
            print '%s %.1f-%.1f' % (key[i], cutoff[i], cutoff[i + 1])

    idmap = dict()
    cmd.iterate_state(state,
                      '(%s) or (%s)' % (selection1, selection2),
                      'idmap[model,index] = [(resn,name),(x,y,z)]',
                      space={'idmap': idmap})
    twoN = cmd.count_atoms(selection1) + cmd.count_atoms(selection2)
    pairs = cmd.find_pairs(selection1,
                           selection2,
                           cutoff=max(cutoff),
                           state1=state,
                           state2=state)
    if len(pairs) == 0:
        print 'Empty pair list'
        return 0.0

    matrix = map(get, key)
    for i in matrix:
        assert isinstance(i, MatrixRecord)

    i_list = range(len(key))
    u_sum = 0
    count = 0
    for id1, id2 in pairs:
        a1 = idmap[id1]
        a2 = idmap[id2]
        r = cpv.distance(a1[1], a2[1])
        for i in i_list:
            if cutoff[i] <= r and r < cutoff[i + 1]:
                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
Esempio n. 20
0
def load_consurf(filename, selection, palette='red_white_blue', quiet=1):
    '''
DESCRIPTION

    Color by evolutionary conservation. Writes scores to b-factor.

    You need a "r4s.res" or "consurf.grades" input file.

USAGE

    load_consurf filename, selection [, palette ]

SEE ALSO

    consurfdb
    '''
    import re
    from .seqalign import needle_alignment, alignment_mapping
    from . import one_letter

    # reduced pattern that matches both r4s.res and consurf.grades
    pattern = re.compile(r'\s*(\d+)\s+([A-Y])\s+([-.0-9]+)\s')

    scores = []
    seqlist = []

    if cmd.is_string(filename):
        handle = open(filename)
    else:
        handle = filename

    if len(cmd.get_chains(selection)) > 1:
        print(' Warning: selection spans multiple chains')

    for line in handle:
        if line.startswith('#') or line.strip() == '':
            continue
        m = pattern.match(line)
        if m is None:
            continue
        scores.append(float(m.group(3)))
        seqlist.append(m.group(2))

    selection = '(%s) and polymer' % selection
    model_ca = cmd.get_model(selection + ' and guide')
    model_seq = ''.join(one_letter.get(a.resn, 'X') for a in model_ca.atom)
    sequence = ''.join(seqlist)

    aln = needle_alignment(model_seq, sequence)
    scores_resi = dict((model_ca.atom[i].resi, scores[j])
            for (i, j) in alignment_mapping(*aln))

    cmd.alter(selection, 'b=scores.get(resi, -10)',
            space={'scores': scores_resi}, quiet=quiet)

    if palette:
        cmd.color('yellow', selection + ' and b<-9')
        if ' ' in palette:
            from .viewing import spectrumany as spectrum
        else:
            spectrum = cmd.spectrum
        spectrum('b', palette, selection + ' and b>-9.5')
Esempio n. 21
0
def save_movie_mpeg1(filename,
                     mode='',
                     first=0,
                     last=0,
                     preserve=0,
                     fps=25,
                     twopass=1,
                     vbitrate=16000,
                     quiet=1,
                     exe='mencoder'):
    '''
DESCRIPTION

    Save movie as MPEG1

    This will not be the best quality possible for the file size, but
    we were successfull to play those movies in PowerPoint.

    Requires mencoder executable from http://mplayerhq.hu

ARGUMENTS

    filename = string: Filename, should end on '.mpeg'

    mode = normal | draw | ray

    first, last = integer: first and last frame number

    preserve = 0 or 1: delete temporary images if 0 {default: 0}

    fps = integer: frames per second {default: 25}

    twopass = 0 or 1: two pass mode encoding (improves quality) {default: 1}

    vbitrate = integer: average video bitrate {default: 16000}
    WARNING: 4-16000 (in kbit), 16001-24000000 (in bit)

SEE ALSO

    cmd.movie.produce, http://www.freemol.org
    '''
    import os, subprocess, tempfile

    first, last, quiet = int(first), int(last), int(quiet)
    fps, twopass, vbitrate = int(fps), int(twopass), int(vbitrate)

    if cmd.is_string(mode):
        if mode == '':
            if cmd.pymol.invocation.options.no_gui \
                    or cmd.get_setting_boolean('ray_trace_frames'):
                mode = 'ray'
            else:
                mode = 'draw'
        mode = produce_mode_sc.auto_err(mode, 'mode')
        mode = produce_mode_dict[mode]
    mode = int(mode)

    try:
        subprocess.call([exe])
    except OSError:
        print(' Error: Cannot execute "%s"' % (exe))
        raise CmdException

    if not quiet:
        print(' save_movie: Rendering frames...')

    tmp_path = tempfile.mkdtemp()
    prefix = os.path.join(tmp_path, 'frame')
    cmd.mpng(prefix, first, last, preserve, mode=mode)

    mpeg1line = '-mf type=png:fps=%d -ovc lavc -forceidx -noskip -of rawvideo' \
            + ' -mpegopts format=mpeg1 -lavcopts vcodec=mpeg1video:vbitrate=%d' \
            + ':vhq:trell:keyint=25'
    mpeg1line = mpeg1line % (fps, vbitrate)
    cmdline = exe + ' -quiet mf://' + prefix + '* ' + mpeg1line

    if not quiet:
        print(' save_movie: Running mencoder...')

    if twopass:
        if not quiet:
            print(' save_movie: First pass...')
            cmdline1 = cmdline + ':vpass=1'
        subprocess.call(cmdline1.split() + ['-o', os.devnull])
        if not quiet:
            print(' save_movie: Second pass...')
        cmdline = cmdline + ':vpass=2'

    subprocess.call(cmdline.split() + ['-o', filename])

    if not preserve:
        import shutil
        shutil.rmtree(tmp_path)
    elif not quiet:
        print(' save_movie: Not deleting temporary directory: ' + tmp_path)

    if not quiet:
        print(' save_movie: Done')
Esempio n. 22
0
def angle_between_domains(selection1,
                          selection2,
                          method='align',
                          state1=STATE,
                          state2=STATE,
                          visualize=1,
                          quiet=1):
    '''
DESCRIPTION

    Angle by which a molecular selection would be rotated when superposing
    on a selection2.

    Do not use for measuring angle between helices, since the alignment of
    the helices might involve a rotation around the helix axis, which will
    result in a larger angle compared to the angle between helix axes.

USAGE

    angle_between_domains selection1, selection2 [, method ]

ARGUMENTS

    selection1 = string: atom selection of first helix

    selection2 = string: atom selection of second helix

    method = string: alignment command like "align" or "super" {default: align}

EXAMPLE

    fetch 3iplA 3iplB, bsync=0
    select domain1, resi 1-391
    select domain2, resi 392-475
    align 3iplA and domain1, 3iplB and domain1
    angle_between_domains 3iplA and domain2, 3iplB and domain2

SEE ALSO

    align, super, angle_between_helices
    '''
    import math

    try:
        import numpy
    except ImportError:
        print(' Error: numpy not available')
        raise CmdException

    state1, state2 = int(state1), int(state2)
    visualize, quiet = int(visualize), int(quiet)

    if cmd.is_string(method):
        try:
            method = cmd.keyword[method][0]
        except KeyError:
            print('no such method:', method)
            raise CmdException

    mobile_tmp = get_unused_name('_')
    cmd.create(mobile_tmp, selection1, state1, 1, zoom=0)
    try:
        method(mobile=mobile_tmp,
               target=selection2,
               mobile_state=1,
               target_state=state2,
               quiet=quiet)
        mat = cmd.get_object_matrix(mobile_tmp)
    except:
        print(' Error: superposition with method "%s" failed' %
              (method.__name__))
        raise CmdException
    finally:
        cmd.delete(mobile_tmp)

    try:
        # Based on transformations.rotation_from_matrix
        # Copyright (c) 2006-2012, Christoph Gohlke

        R33 = [mat[i:i + 3] for i in [0, 4, 8]]
        R33 = numpy.array(R33, float)

        # direction: unit eigenvector of R33 corresponding to eigenvalue of 1
        w, W = numpy.linalg.eig(R33.T)
        i = w.real.argmax()
        direction = W[:, i].real

        # rotation angle depending on direction
        m = direction.argmax()
        i, j, k, l = [[2, 1, 1, 2], [0, 2, 0, 2], [1, 0, 0, 1]][m]
        cosa = (R33.trace() - 1.0) / 2.0
        sina = (R33[i, j] +
                (cosa - 1.0) * direction[k] * direction[l]) / direction[m]

        angle = math.atan2(sina, cosa)
        angle = abs(math.degrees(angle))
    except:
        print(' Error: rotation from matrix failed')
        raise CmdException

    if not quiet:
        try:
            # make this import optional to support running this script standalone
            from .querying import centerofmass, gyradius
        except (ValueError, ImportError):
            gyradius = None
            try:
                # PyMOL 1.7.1.6+
                centerofmass = cmd.centerofmass
            except AttributeError:
                centerofmass = lambda s: cpv.scale(cpv.add(*cmd.get_extent(s)),
                                                   0.5)

        center1 = centerofmass(selection1)
        center2 = centerofmass(selection2)
        print(' Angle: %.2f deg, Displacement: %.2f angstrom' %
              (angle, cpv.distance(center1, center2)))

        if visualize:
            center1 = numpy.array(center1, float)
            center2 = numpy.array(center2, float)
            center = (center1 + center2) / 2.0

            if gyradius is not None:
                rg = numpy.array(gyradius(selection1), float)
            else:
                rg = 10.0

            h1 = numpy.cross(center2 - center1, direction)
            h2 = numpy.dot(R33, h1)
            h1 *= rg / cpv.length(h1)
            h2 *= rg / cpv.length(h2)

            for pos in [center1, center2, center1 + h1, center1 + h2]:
                cmd.pseudoatom(mobile_tmp, pos=list(pos), state=1)

            # measurement object for angle and displacement
            name = get_unused_name('measurement')
            cmd.distance(name, *['%s`%d' % (mobile_tmp, i) for i in [1, 2]])
            cmd.angle(name, *['%s`%d' % (mobile_tmp, i) for i in [3, 1, 4]])

            # CGO arrow for axis of rotation
            visualize_orientation(direction, center1, rg, color='blue')

            cmd.delete(mobile_tmp)

    return angle
Esempio n. 23
0
def pca_plot(aln_object, ref='all', state=0, maxlabels=20, size=20, invert='',
        which=(0,1), alpha=0.75, filename=None, quiet=1, load_b=0):
    '''
DESCRIPTION

    Principal Component Analysis on a set of superposed conformations, given
    by an alignment object. By default all states in all objects are
    considered. Generates a 2d-plot of the first two principal components.

USAGE

    pca_plot aln_object [, ref [, state [, maxlabels ]]]

ARGUMENTS

    aln_object = string: name of alignment object, defines the selection
    and the atom mapping between objects

    ref = string: object names for which to calculate PCA for {default: all}

    state = integer: if state=0 use all states {default: 0}

    maxlabels = integer: label dots in plot if maxlabels<0 or number of models
    not more than maxlabels {default: 20}

    size = float: size of plot points in px^2 {default: 20}

    invert = string: invert plotting axes x, y or xy {default: ''}

    which = (int,int): indices of principal components to plot {default: (0,1)}

    alpha = float: opacity of plotting points

    filename = string: if given, plot to file {default: None}

EXAMPLE

    fetch 1ake 4ake 1dvr 1ak2, async=0
    split_chains
    extra_fit (*_*) and name CA, reference=1ake_A, cycles=0, object=aln
    pca_plot aln, 1ake_* 4ake_*

    fetch 1ubq 2k39, async=0
    align 2k39, 1ubq and guide, cycles=0, object=aln2
    color blue, 1ubq
    color orange, 2k39
    pca_plot aln2, filename=pca-ubq.pdf
    '''
    from numpy import array, dot
    from numpy.linalg import svd, LinAlgError
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    state, quiet = int(state), int(quiet)
    maxlabels = int(maxlabels)
    if cmd.is_string(which):
        which = cmd.safe_list_eval(which)

    if aln_object not in cmd.get_names_of_type('object:alignment'):
        print(' Warning: first argument should be an alignment object')

        from .fitting import extra_fit

        selection = aln_object
        aln_object = cmd.get_unused_name('aln')
        extra_fit(selection, cycles=0, transform=0, object=aln_object)

    if state == 0:
        states = list(range(1, cmd.count_states()+1))
    elif state < 0:
        states = [cmd.get_state()]
    else:
        states = [state]

    models = cmd.get_object_list(aln_object)
    references = set(cmd.get_object_list('(' + ref + ')')).intersection(models)
    others = set(models).difference(references)
    aln = cmd.get_raw_alignment(aln_object)

    if not quiet:
        print(' PCA References:', ', '.join(references))
        print(' PCA Others:', ', '.join(others))

    if len(references) == 0:
        print(' PCA Error: No reference objects')
        raise CmdException

    model_count = len(models)
    coords = dict((model, []) for model in models)
    aln = [pos for pos in aln if len(pos) == model_count]

    for state in states:
        idx2xyz = dict()
        cmd.iterate_state(state, aln_object, 'idx2xyz[model,index] = (x,y,z)',
                space={'idx2xyz': idx2xyz})

        for pos in aln:
            for idx in pos:
                if idx not in idx2xyz:
                    continue

                c = coords[idx[0]]
                if len(c) < state:
                    c.append([])
                c[-1].extend(idx2xyz[idx])

    c_iter = lambda models: ((c,model,i+1) for model in models
            for (i,c) in enumerate(coords[model]))
    X = array([i[0] for i in c_iter(references)])
    Y = array([i[0] for i in c_iter(others)])
    center = X.mean(0)
    X = X - center

    try:
        U, L, V = svd(X)
    except LinAlgError as e:
        print(' PCA Error: ', e)
        raise CmdException

    if int(load_b):
        cmd.alter('byobj ' + aln_object, 'b=-0.01')
        b_dict = {}
        i = which[0]
        b_array = (V[i].reshape((-1, 3))**2).sum(1)**0.5
        for pos, b in zip(aln, b_array):
            for idx in pos:
                b_dict[idx] = b
        cmd.alter(aln_object, 'b=b_dict.get((model,index), -0.01)', space=locals())
        cmd.color('yellow', 'byobj ' + aln_object)
        cmd.spectrum('b', 'blue_red', aln_object + ' and b > -0.01')

    X_labels = [i[1:3] for i in c_iter(references)]
    Y_labels = [i[1:3] for i in c_iter(others)]

    x_list = []
    y_list = []
    colors = []
    text_list = []

    def plot_pc_2d(X, labels):
        pca_12 = dot(X, V.T)[:,which]
        for (x,y), (model,state) in zip(pca_12, labels):
            x_list.append(x)
            y_list.append(y)
            colors.append(get_model_color(model))
            if maxlabels < 0 or len(pca_12) <= maxlabels:
                text_list.append('%s(%d)' % (model, state))
            else:
                text_list.append(None)

    plot_pc_2d(X, X_labels)
    if len(Y) > 0:
        Y = Y - center
        plot_pc_2d(Y, Y_labels)

    if 'x' in invert:
        x_list = [-x for x in x_list]
    if 'y' in invert:
        y_list = [-y for y in y_list]

    fig = figure()
    plt = fig.add_subplot(111, xlabel='PC %d' % (which[0]+1), ylabel='PC %d' % (which[1]+1))
    plt.scatter(x_list, y_list, float(size), colors, linewidths=0, alpha=float(alpha))

    for (x, y, text) in zip(x_list, y_list, text_list):
        if text is not None:
            plt.text(x, y, text, horizontalalignment='left')

    _showfigure(fig, filename, quiet)
Esempio n. 24
0
def pca_plot(
    aln_object,
    ref="all",
    state=0,
    maxlabels=20,
    size=20,
    invert="",
    which=(0, 1),
    alpha=0.75,
    filename=None,
    quiet=1,
    load_b=0,
):
    """
DESCRIPTION

    Principal Component Analysis on a set of superposed conformations, given
    by an alignment object. By default all states in all objects are
    considered. Generates a 2d-plot of the first two principal components.

USAGE

    pca_plot aln_object [, ref [, state [, maxlabels ]]]

ARGUMENTS

    aln_object = string: name of alignment object, defines the selection
    and the atom mapping between objects

    ref = string: object names for which to calculate PCA for {default: all}

    state = integer: if state=0 use all states {default: 0}

    maxlabels = integer: label dots in plot if maxlabels<0 or number of models
    not more than maxlabels {default: 20}

    size = float: size of plot points in px^2 {default: 20}

    invert = string: invert plotting axes x, y or xy {default: ''}

    which = (int,int): indices of principal components to plot {default: (0,1)}

    alpha = float: opacity of plotting points

    filename = string: if given, plot to file {default: None}

EXAMPLE

    fetch 1ake 4ake 1dvr 1ak2, async=0
    split_chains
    extra_fit (*_*) and name CA, reference=1ake_A, cycles=0, object=aln
    pca_plot aln, 1ake_* 4ake_*

    fetch 1ubq 2k39, async=0
    align 2k39, 1ubq and guide, cycles=0, object=aln2
    color blue, 1ubq
    color orange, 2k39
    pca_plot aln2, filename=pca-ubq.pdf
    """
    from numpy import array, dot
    from numpy.linalg import svd, LinAlgError
    from . import matplotlib_fix
    from matplotlib.pyplot import figure

    state, quiet = int(state), int(quiet)
    maxlabels = int(maxlabels)
    if cmd.is_string(which):
        which = cmd.safe_list_eval(which)

    if aln_object not in cmd.get_names_of_type("object:"):
        print(" Warning: first argument should be an alignment object")

        from .fitting import extra_fit

        selection = aln_object
        aln_object = cmd.get_unused_name("aln")
        extra_fit(selection, cycles=0, transform=0, object=aln_object)

    if state == 0:
        states = list(range(1, cmd.count_states() + 1))
    elif state < 0:
        states = [cmd.get_state()]
    else:
        states = [state]

    models = cmd.get_object_list(aln_object)
    references = set(cmd.get_object_list("(" + ref + ")")).intersection(models)
    others = set(models).difference(references)
    aln = cmd.get_raw_alignment(aln_object)

    if not quiet:
        print(" PCA References:", ", ".join(references))
        print(" PCA Others:", ", ".join(others))

    if len(references) == 0:
        print(" PCA Error: No reference objects")
        raise CmdException

    model_count = len(models)
    coords = dict((model, []) for model in models)
    aln = [pos for pos in aln if len(pos) == model_count]

    for state in states:
        idx2xyz = dict()
        cmd.iterate_state(state, aln_object, "idx2xyz[model,index] = (x,y,z)", space={"idx2xyz": idx2xyz})

        for pos in aln:
            for idx in pos:
                if idx not in idx2xyz:
                    continue

                c = coords[idx[0]]
                if len(c) < state:
                    c.append([])
                c[-1].extend(idx2xyz[idx])

    c_iter = lambda models: ((c, model, i + 1) for model in models for (i, c) in enumerate(coords[model]))
    X = array([i[0] for i in c_iter(references)])
    Y = array([i[0] for i in c_iter(others)])
    center = X.mean(0)
    X = X - center

    try:
        U, L, V = svd(X)
    except LinAlgError as e:
        print(" PCA Error: ", e)
        raise CmdException

    if int(load_b):
        cmd.alter("byobj " + aln_object, "b=-0.01")
        b_dict = {}
        i = which[0]
        b_array = (V[i].reshape((-1, 3)) ** 2).sum(1) ** 0.5
        for pos, b in zip(aln, b_array):
            for idx in pos:
                b_dict[idx] = b
        cmd.alter(aln_object, "b=b_dict.get((model,index), -0.01)", space=locals())
        cmd.color("yellow", "byobj " + aln_object)
        cmd.spectrum("b", "blue_red", aln_object + " and b > -0.01")

    X_labels = [i[1:3] for i in c_iter(references)]
    Y_labels = [i[1:3] for i in c_iter(others)]

    x_list = []
    y_list = []
    colors = []
    text_list = []

    def plot_pc_2d(X, labels):
        pca_12 = dot(X, V.T)[:, which]
        for (x, y), (model, state) in zip(pca_12, labels):
            x_list.append(x)
            y_list.append(y)
            colors.append(get_model_color(model))
            if maxlabels < 0 or len(pca_12) <= maxlabels:
                text_list.append("%s(%d)" % (model, state))
            else:
                text_list.append(None)

    plot_pc_2d(X, X_labels)
    if len(Y) > 0:
        Y = Y - center
        plot_pc_2d(Y, Y_labels)

    if "x" in invert:
        x_list = [-x for x in x_list]
    if "y" in invert:
        y_list = [-y for y in y_list]

    fig = figure()
    plt = fig.add_subplot(111, xlabel="PC %d" % (which[0] + 1), ylabel="PC %d" % (which[1] + 1))
    plt.scatter(x_list, y_list, float(size), colors, linewidths=0, alpha=float(alpha))

    for (x, y, text) in zip(x_list, y_list, text_list):
        if text is not None:
            plt.text(x, y, text, horizontalalignment="left")

    _showfigure(fig, filename, quiet)
Esempio n. 25
0
def pdb2pqr_cli(name,
                selection,
                options,
                state=-1,
                preserve=0,
                exe='pdb2pqr',
                quiet=1,
                fixrna=0,
                _proclist=None):
    import os, tempfile, subprocess, shutil

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

    if cmd.is_string(options):
        import shlex
        options = shlex.split(options)

    args = [cmd.exp_path(exe)] + list(options)

    tmpdir = tempfile.mkdtemp()
    infile = os.path.join(tmpdir, 'in.pdb')
    outfile = os.path.join(tmpdir, 'out.pqr')
    args.extend([infile, outfile])

    # For some reason, catching stdout/stderr with PIPE and communicate()
    # blocks terminate() calls from terminating early. Using a file
    # redirect doesn't show this problem.
    f_stdout = open(os.path.join(tmpdir, 'stdout.txt'), 'w+')

    # RNA resdiue names must be RA, RC, RG, and RU
    tmpmodel = ''
    if int(fixrna) and cmd.count_atoms('(%s) & resn A+C+G+U' % (selection)):
        tmpmodel = cmd.get_unused_name('_tmp')
        cmd.create(tmpmodel, selection, zoom=0)
        cmd.alter(tmpmodel + ' & polymer.nucleic & resn A+C+G+U',
                  'resn = "R" + resn')
        selection = tmpmodel

    try:
        cmd.save(infile, selection, state)

        p = subprocess.Popen(
            args,
            cwd=tmpdir,
            stdin=subprocess.PIPE,  # Windows pythonw fix
            stdout=f_stdout,
            stderr=f_stdout)
        p.stdin.close()  # Windows pythonw fix

        if _proclist is not None:
            _proclist.append(p)

        p.wait()

        # This allows PyMOL to capture it and display the output in the GUI.
        f_stdout.seek(0)
        print(f_stdout.read().rstrip())

        if p.returncode == -15:  # SIGTERM
            raise CmdException('pdb2pqr terminated')

        if p.returncode != 0:
            raise CmdException('%s failed with exit status %d' %
                               (args[0], p.returncode))

        warnings = [
            L[10:] for L in open(outfile) if L.startswith('REMARK   5')
        ]
        warnings = ''.join(warnings).strip()

        cmd.load(outfile, name)

        return warnings

    except OSError as e:
        print(e)
        raise CmdException('Cannot execute "%s"' % (exe))
    finally:
        if tmpmodel:
            cmd.delete(tmpmodel)

        f_stdout.close()

        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(' Notice: not deleting', tmpdir)
Esempio n. 26
0
def prepwizard(name,
               selection='all',
               options='',
               state=-1,
               preserve=0,
               exe='$SCHRODINGER/utilities/prepwizard',
               quiet=1,
               _proclist=None):
    '''
DESCRIPTION

    Run the SCHRODINGER Protein Preparation Wizard. Builds missing side
    chains and converts MSE to MET. Other non-default options need to be
    passed with the "options=" argument.

USAGE

    prepwizard name [, selection [, options [, state ]]]

ARGUMENTS

    name = str: name of object to create

    selection = str: atoms to send to the wizard {default: all}

    options = str: additional command line options for prepwizard

    state = int: object state {default: -1 (current)}
    '''
    import os, tempfile, subprocess, shutil, shlex

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

    exe = cmd.exp_path(exe)
    if not _is_exe(exe):
        if 'SCHRODINGER' not in os.environ:
            print(' Warning: SCHRODINGER environment variable not set')
        raise CmdException('no such script: ' + exe)

    args = [exe, '-mse', '-fillsidechains', '-WAIT']

    if options:
        if cmd.is_string(options):
            options = shlex.split(options)
        args.extend(options)

    tmpdir = tempfile.mkdtemp()
    infile = 'in.pdb'
    outfile = 'out.mae'
    args.extend([infile, outfile])

    try:
        cmd.save(os.path.join(tmpdir, infile), selection, state)

        env = dict(os.environ)
        env.pop('PYTHONEXECUTABLE', '')  # messes up Python on Mac

        p = subprocess.Popen(
            args,
            cwd=tmpdir,
            env=env,
            stdin=subprocess.PIPE,  # Windows pythonw fix
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)

        if _proclist is not None:
            _proclist.append(p)

        print(p.communicate()[0].rstrip())

        if p.wait() == -15:  # SIGTERM
            raise CmdException('prepwizard terminated')

        if p.returncode != 0:
            logfile = os.path.join(tmpdir, 'in.log')
            if os.path.exists(logfile):
                with open(logfile) as handle:
                    print(handle.read())

            raise CmdException('%s failed with exit status %d' %
                               (args[0], p.returncode))

        cmd.load(os.path.join(tmpdir, outfile), name)
    except OSError as e:
        print(e)
        raise CmdException('Cannot execute "%s"' % (exe))
    finally:
        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(' Notice: not deleting', tmpdir)

    if not quiet:
        print(' prepwizard: done')
Esempio n. 27
0
def pmf(key, cutoff=7.0, selection1='(name CB)', selection2='', state=1, quiet=1):
    '''
DESCRIPTION

    Potential of Mean Force

ARGUMENTS

    key = string: aaindex key

    cutoff = float: distance cutoff {default: 7.0}
    cutoff = (float, float): distance shell

    selection1 = string: atom selection {default: (name CB)}

    selection2 = string: atom selection {default: selection1}

NOTES

    Does also support a list of keys and a list of cutoffs to deal with
    multiple distance shells.

EXAMPLES

    # distance dependent c-beta contact potentials
    pmf SIMK990101, 5,         /2x19//A//CB
    pmf SIMK990102, [5, 7.5],  /2x19//A//CB
    pmf [SIMK990101, SIMK990102, SIMK990103], [0, 5, 7.5, 10], /2x19//A//CB

    # interface potential
    sidechaincenters 2x19_scc, 2x19
    pmf KESO980102, 7.0, /2x19_scc//A, /2x19_scc//B
    distance /2x19_scc//A, /2x19_scc//B, cutoff=7.0
    '''
    from pymol import cmd, stored
    from chempy import cpv
    if cmd.is_string(key):
        if key.lstrip().startswith('['):
            key = cmd.safe_alpha_list_eval(key)
        else:
            key = [key]
    if cmd.is_string(cutoff):
        cutoff = eval(cutoff)
    if not cmd.is_sequence(cutoff):
        cutoff = [cutoff]
    if len(cutoff) == len(key):
        cutoff = [0.0] + list(cutoff)
    if len(cutoff) != len(key) + 1:
        print('Error: Number of keys and number of cutoffs inconsistent')
        return
    state = int(state)
    quiet = int(quiet)
    if len(selection2) == 0:
        selection2 = selection1
    if not quiet and len(key) > 1:
        print('Distance shells:')
        for i in range(len(key)):
            print('%s %.1f-%.1f' % (key[i], cutoff[i], cutoff[i + 1]))

    idmap = dict()
    cmd.iterate_state(state, '(%s) or (%s)' % (selection1, selection2),
                      'idmap[model,index] = [(resn,name),(x,y,z)]', space={'idmap': idmap})
    twoN = cmd.count_atoms(selection1) + cmd.count_atoms(selection2)
    pairs = cmd.find_pairs(selection1, selection2, cutoff=max(cutoff),
                           state1=state, state2=state)
    if len(pairs) == 0:
        print('Empty pair list')
        return 0.0

    matrix = list(map(get, key))
    for i in matrix:
        assert isinstance(i, MatrixRecord)

    i_list = list(range(len(key)))
    u_sum = 0
    count = 0
    for id1, id2 in pairs:
        a1 = idmap[id1]
        a2 = idmap[id2]
        r = cpv.distance(a1[1], a2[1])
        for i in i_list:
            if cutoff[i] <= r and r < cutoff[i + 1]:
                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
Esempio n. 28
0
def load_consurf(filename, selection, palette='red_white_blue', quiet=1):
    '''
DESCRIPTION

    Color by evolutionary conservation. Writes scores to b-factor.

    You need a "r4s.res" or "consurf.grades" input file.

USAGE

    load_consurf filename, selection [, palette ]

SEE ALSO

    consurfdb
    '''
    import re
    from .seqalign import needle_alignment, alignment_mapping
    from . import one_letter

    # reduced pattern that matches both r4s.res and consurf.grades
    pattern = re.compile(r'\s*(\d+)\s+([A-Y])\s+([-.0-9]+)\s')

    scores = []
    seqlist = []

    if cmd.is_string(filename):
        handle = open(filename)
    else:
        handle = filename

    if len(cmd.get_chains(selection)) > 1:
        print(' Warning: selection spans multiple chains')

    for line in handle:
        if line.startswith('#') or line.strip() == '':
            continue
        m = pattern.match(line)
        if m is None:
            continue
        scores.append(float(m.group(3)))
        seqlist.append(m.group(2))

    selection = '(%s) and polymer' % selection
    model_ca = cmd.get_model(selection + ' and guide')
    model_seq = ''.join(one_letter.get(a.resn, 'X') for a in model_ca.atom)
    sequence = ''.join(seqlist)

    aln = needle_alignment(model_seq, sequence)
    scores_resi = dict((model_ca.atom[i].resi, scores[j])
                       for (i, j) in alignment_mapping(*aln))

    cmd.alter(selection,
              'b=scores.get(resi, -10)',
              space={'scores': scores_resi},
              quiet=quiet)

    if palette:
        cmd.color('yellow', selection + ' and b<-9')
        if ' ' in palette:
            from .viewing import spectrumany as spectrum
        else:
            spectrum = cmd.spectrum
        spectrum('b', palette, selection + ' and b>-9.5')
Esempio n. 29
0
def save_movie_mpeg1(filename, mode='', first=0, last=0, preserve=0,
        fps=25, twopass=1, vbitrate=16000, quiet=1, exe='mencoder'):
    '''
DESCRIPTION

    Save movie as MPEG1

    This will not be the best quality possible for the file size, but
    we were successfull to play those movies in PowerPoint.

    Requires mencoder executable from http://mplayerhq.hu

ARGUMENTS

    filename = string: Filename, should end on '.mpeg'

    mode = normal | draw | ray

    first, last = integer: first and last frame number

    preserve = 0 or 1: delete temporary images if 0 {default: 0}

    fps = integer: frames per second {default: 25}

    twopass = 0 or 1: two pass mode encoding (improves quality) {default: 1}

    vbitrate = integer: average video bitrate {default: 16000}
    WARNING: 4-16000 (in kbit), 16001-24000000 (in bit)

SEE ALSO

    cmd.movie.produce, http://www.freemol.org
    '''
    import os, subprocess, tempfile

    first, last, quiet = int(first), int(last), int(quiet)
    fps, twopass, vbitrate = int(fps), int(twopass), int(vbitrate)

    if cmd.is_string(mode):
        if mode == '':
            if cmd.pymol.invocation.options.no_gui \
                    or cmd.get_setting_boolean('ray_trace_frames'):
                mode = 'ray'
            else:
                mode = 'draw'
        mode = produce_mode_sc.auto_err(mode, 'mode')
        mode = produce_mode_dict[mode]
    mode = int(mode)

    try:
        subprocess.call([exe])
    except OSError:
        print ' Error: Cannot execute "%s"' % (exe)
        raise CmdException

    if not quiet:
        print ' save_movie: Rendering frames...'

    tmp_path = tempfile.mkdtemp()
    prefix = os.path.join(tmp_path, 'frame')
    cmd.mpng(prefix, first, last, preserve, mode=mode)

    mpeg1line = '-mf type=png:fps=%d -ovc lavc -forceidx -noskip -of rawvideo' \
            + ' -mpegopts format=mpeg1 -lavcopts vcodec=mpeg1video:vbitrate=%d' \
            + ':vhq:trell:keyint=25'
    mpeg1line = mpeg1line % (fps, vbitrate)
    cmdline = exe + ' -quiet mf://' + prefix + '* ' + mpeg1line

    if not quiet:
        print ' save_movie: Running mencoder...'

    if twopass:
        if not quiet:
            print ' save_movie: First pass...'
            cmdline1 = cmdline + ':vpass=1'
        subprocess.call(cmdline1.split() + ['-o', os.devnull])
        if not quiet:
            print ' save_movie: Second pass...'
        cmdline = cmdline + ':vpass=2'

    subprocess.call(cmdline.split() + ['-o', filename])

    if not preserve:
        import shutil
        shutil.rmtree(tmp_path)
    elif not quiet:
        print ' save_movie: Not deleting temporary directory:', tmp_path

    if not quiet:
        print ' save_movie: Done'
Esempio n. 30
0
def prepwizard(
    name, selection="all", options="", state=-1, preserve=0, exe="$SCHRODINGER/utilities/prepwizard", quiet=1
):
    """
DESCRIPTION

    Run the SCHRODINGER Protein Preparation Wizard. Builds missing side
    chains and converts MSE to MET. Other non-default options need to be
    passed with the "options=" argument.

USAGE

    prepwizard name [, selection [, options [, state ]]]

ARGUMENTS

    name = str: name of object to create

    selection = str: atoms to send to the wizard {default: all}

    options = str: additional command line options for prepwizard

    state = int: object state {default: -1 (current)}
    """
    import os, tempfile, subprocess, shutil, shlex

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

    exe = cmd.exp_path(exe)
    if not os.path.exists(exe):
        if "SCHRODINGER" not in os.environ:
            print(" Warning: SCHRODINGER environment variable not set")
        raise CmdException("no such script: " + exe)

    args = [exe, "-mse", "-fillsidechains", "-WAIT"]

    if options:
        if cmd.is_string(options):
            options = shlex.split(options)
        args.extend(options)

    tmpdir = tempfile.mkdtemp()
    infile = "in.pdb"
    outfile = "out.mae"
    args.extend([infile, outfile])

    try:
        cmd.save(os.path.join(tmpdir, infile), selection, state)

        p = subprocess.Popen(args, cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        print(p.communicate()[0].rstrip())

        if p.returncode != 0:
            logfile = os.path.join(tmpdir, "in.log")
            if os.path.exists(logfile):
                with open(logfile) as handle:
                    print(handle.read())

            raise CmdException("%s failed with exit status %d" % (args[0], p.returncode))

        cmd.load(os.path.join(tmpdir, outfile), name)
    except OSError:
        raise CmdException('Cannot execute "%s"' % (exe))
    finally:
        if not preserve:
            shutil.rmtree(tmpdir)
        elif not quiet:
            print(" Notice: not deleting", tmpdir)

    if not quiet:
        print(" prepwizard: done")