コード例 #1
0
def validate_apbs_exe(exe):
    '''Get and validate apbs executable.
    Raise CmdException if not found or broken.'''
    import os, subprocess

    if exe:
        exe = cmd.exp_path(exe)
    else:
        try:
            import freemol.apbs
            exe = freemol.apbs.get_exe_path()
        except:
            pass
        if not exe:
            exe = cmd.exp_path('$SCHRODINGER/utilities/apbs')
            if not os.path.exists(exe):
                exe = "apbs"

    try:
        r = subprocess.call([exe, "--version"],
                            stdout=open(os.devnull, "w"),
                            stderr=subprocess.STDOUT)
        if r < 0:
            raise CmdException("Broken executable: " + exe)
    except OSError:
        raise CmdException("Cannot execute: " + exe)

    return exe
コード例 #2
0
ファイル: creating.py プロジェクト: menchant/pymol-psico
def corina(name, selection, exe='corina', state=-1, preserve=0, quiet=1):
    '''
DESCRIPTION

    Run corina on selection and load as new object
    '''
    import os, tempfile, subprocess, shutil
    _assert_package_import()
    from . import querying

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

    if state < 1:
        state = querying.get_selection_state(selection)

    tmpdir = tempfile.mkdtemp()
    infile = os.path.join(tmpdir, 'in.sdf')
    outfile = os.path.join(tmpdir, 'out.sdf')
    trcfile = os.path.join(tmpdir, 'corina.trc')

    args = [exe, infile, outfile]
    stderr = ''

    try:
        cmd.save(infile, selection, state)
        stdout, stderr = subprocess.Popen(
            args,
            cwd=tmpdir,
            universal_newlines=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE).communicate()

        if not quiet and stdout.strip():
            print(stdout)

        trclines = open(trcfile).readlines()
        trcerror = [line for line in trclines if 'ERROR' in line]
        if trcerror:
            raise CmdException("corina failed: " + trcerror[0].strip())

        if not os.path.exists(outfile):
            raise CmdException("corina failed: " + stderr.strip())

        cmd.load(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(' corina: done')
コード例 #3
0
def get_object_name(selection, strict=0, *, _self=cmd):
    '''
DESCRIPTION

    Returns the object name for given selection.
    '''
    names = _self.get_object_list('(' + selection + ')')
    if len(names) == 0:
        raise CmdException('No objects in selection')
    if strict and len(names) > 1:
        raise CmdException('Selection spans more than one object')
    return names[0]
コード例 #4
0
def _run_theseus(args, tempdir, preserve, quiet):
    '''
DESCRIPTION

    Helper function for theseus and intra_theseus
    '''
    import subprocess, os

    translations = []
    rotations = []
    t_type = float

    try:
        if quiet:
            subprocess.call(args, cwd=tempdir)
        else:
            import re
            unesc = re.compile('\x1b' + r'\[[\d;]+m').sub

            process = subprocess.Popen(args, cwd=tempdir, stdout=subprocess.PIPE,
                    universal_newlines=True)
            for line in process.stdout:
                print(unesc('', line.rstrip()))

        filename = os.path.join(tempdir, 'theseus_transf2.txt')

        if not os.path.exists(filename):
            # THESEUS 3.x
            filename = os.path.join(tempdir, 'theseus_transf.txt')
            if not os.path.exists(filename):
                raise CmdException('no theseus_transf2.txt or '
                        'theseus_transf.txt output file')
            t_type = lambda t: float(t) * -1.

        handle = open(filename)
        for line in handle:
            if line[10:13] == ' t:':
                translations.append(list(map(t_type, line[13:].split())))
            elif line[10:13] == ' R:':
                rotations.append(list(map(float, line[13:].split())))
        handle.close()

    except OSError:
        raise CmdException('Cannot execute "%s"' % (args[0]))
    finally:
        if not preserve:
            import shutil
            shutil.rmtree(tempdir)
        elif not quiet:
            print(' Not deleting temporary directory:', tempdir)

    return translations, rotations
コード例 #5
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()))
コード例 #6
0
    def crd_coord_iter():
        '''
        Iterator that yields True at the beginning of a coord set, followed
        by the sequence of coordinates (floats).

        6F12.7 (rst7)
        10F8.3 (crd)
        '''
        count = 0
        ncoord = natom * 3
        width = 0
        for line in line_it:
            if width == 0:
                # in second line look for floating number width
                second_dot = line.find('.', 8)
                if second_dot == -1:
                    if not quiet:
                        print('Number of atoms in second line')
                    # assume number of atoms in second line
                    _natom = int(line)
                    assert _natom == natom, 'Numbers differ: %d, %d' % (natom,
                                                                        _natom)
                    line = next(line_it)
                    second_dot = line.find('.', 8)
                if second_dot == 12:
                    width = 8
                elif second_dot == 16:
                    width = 12
                else:
                    raise CmdException(
                        'could neither detect 6F12.7 nor 10F8.3 format')
            if count > ncoord:
                raise CmdException('count={} > ncoord={}'.format(
                    count, ncoord))
            if count == ncoord:
                count = 0
                if box:
                    if not quiet:
                        print('skipping box')
                    # skip box line
                    continue
            for i in range(0, len(line.rstrip()), width):
                x = float(line[i:i + width])
                if count == 0:
                    yield True
                count += 1
                yield x
        yield False
コード例 #7
0
def mutate_all(selection, new_resn, inplace=1, sculpt=0, *args, _self=cmd, **kwargs):
    '''
DESCRIPTION

    Mutate all residues in selection. By default do mutation in-place (unlike
    the 'mutate' command which by default works on a copy).

    FOR SCULPTING ONLY SUPPORTS SELECTIONS WITHIN THE SAME MODEL!

SEE ALSO

    mutate
    '''
    inplace, sculpt = int(inplace), int(sculpt)

    if sculpt and len(_self.get_object_list('(' + selection + ')')) > 1:
        raise CmdException('Sculpting in multiple models not supported')

    kwargs.pop('_self', None)
    sele_list = set()
    _self.iterate(selection,
            'sele_list.add("/%s/%s/%s/%s" % (model, segi, chain, resi))',
            space={'sele_list': sele_list})
    for sele in sele_list:
        mutate(sele, new_resn, inplace, sculpt and not inplace, *args, **kwargs)
    if sculpt and inplace:
        sculpt_relax('(' + ' '.join(sele_list) + ')', 0, sculpt == 2)
コード例 #8
0
ファイル: pyDYNAMON.py プロジェクト: boneta/jacques
    def write_selection(self, filename, resolution='atom'):
        """
            Write selection blocks to .dynn file

            Parameters
            ----------
            filename : str
                file to create/append and write selection
            resolution : {'atom', 'residue', 'subsystem'}, optional
                minimum entity size to treat not whole at writting (def: 'atom')
        """

        if not self.selection:
            raise CmdException("No selection to write", "pyDYNAMON")

        # build strings for each selection
        sele_str = []
        for sele_name, sele in self.selection.items():
            s = f"\nSELECTION {sele_name}\n"
            for segi, resis in sele.items():
                s += " " * 4 + f"S {segi}\n"
                if resolution == 'subsystem': continue
                for resi, atoms in resis.items():
                    s += " " * 8 + f"R {resi}\n"
                    if resolution == 'residue': continue
                    for name in atoms:
                        s += " " * 12 + f"A {name}\n"
            s += "SELECTION\n"
            sele_str.append(s)

        # write selections to file
        with open(filename, 'w') as f:
            f.write("\n" + "\n".join(self.opt_raw) + "\n")
            f.write("".join(sele_str))
コード例 #9
0
def get_mcs_indices(method, quiet, *args, **kwargs):
    '''Find the MCS between two molecules and return the substructure
    atom indices for both molecules.
    
    @param method: empty string, rdkit, or indigo
    @param quiet: 0 or 1 (verbosity flag)
    @param m_sdf: mobile molecule as MOL string
    @param t_sdf: target molecule as MOL string
    @param timeout: timeout in seconds (only used with rdkit)

    @return: two sequences of integers with atom indices
    @rtype: tuple
    '''

    methods = {
        'rdkit': get_mcs_indices_rdkit,
        'indigo': get_mcs_indices_indigo,
    }

    if not method:
        for method in methods:
            try:
                __import__(method)
                break
            except ImportError:
                continue
        else:
            raise CmdException('neither "rdkit" nor "indigo" available')

        if not int(quiet):
            print(" Note: using method '%s'" % (method, ))

    return methods[method](*args, **kwargs)
コード例 #10
0
def csp(sele1, sele2='', quiet=1, var="formal_charge", _self=cmd):
    """
DESCRIPTION

    Charge Symmetry Parameter between two selections. Can be used to compute
    FvCSP according to Sharma 2014.

    If only sele1 is given, it must contain excatly two chains.
    """
    if not sele2:
        chains = _self.get_chains(sele1)

        if len(chains) != 2:
            raise CmdException("need two chains")

        sele2 = '({}) & chain "{}"'.format(sele1, chains[1])
        sele1 = '({}) & chain "{}"'.format(sele1, chains[0])

    charges1 = iterate_to_list(sele1, var, _self=_self)
    charges2 = iterate_to_list(sele2, var, _self=_self)

    r = sum(charges1) * sum(charges2)

    if not int(quiet):
        print(" csp: {}".format(r))

    return r
コード例 #11
0
ファイル: cnstr.py プロジェクト: fabriceallain/pymtools
    def run(self):
        """
        Load structure and restraint files and save pymol session with projected
        restraints.
        """
        LOG.info("Load structure file %s" % self.settings.args.get('pdb'))
        try:
            cmd.load(self.settings.args.get('pdb'), object=self._pdbname)
        except CmdException:
            LOG.error("Can't load %s", self.settings.args.get('pdb'))

        if self.settings.args.get('ref'):
            LOG.info("Load reference structure file")
            self._refname = os.path.basename(
                os.path.splitext(self.settings.args.get('ref'))[0])
            try:
                cmd.load(self.settings.args.get('ref'), object=self._refname)
                self._reflag = True
            except CmdException:
                LOG.error("Can't load %s", self._refname)
            method = self.settings.config.get('ali_method', 'align')
            mobile = self._pdbname
            target = self._refname
            try:
                align = cmd.keyword[method][0]
                LOG.info("Align %s on %s" % (mobile, target))
                align(mobile, target, object="_aln")
                cmd.delete("_aln")
            except Exception as msg:
                LOG.error('Wrong alignment method (%s)' % method)
                raise CmdException(msg)
        LOG.info("Load constrains file %s" %
                 self.settings.args.get('constrains'))
        # read cnstr file
        self.load_cnstr()
コード例 #12
0
def intra_boxfit(selection="polymer", center=[0.5, 0.5, 0.5], _self=cmd):
    """
DESCRIPTION

    Center selection in simulation box.

ARGUMENTS

    selection = str: atom selection to center {default: polymer}

    center = list-of-3-floats: Target position in fractional space
    {default: [0.5, 0.5, 0.5]}
    """
    from numpy import dot, asfarray
    from .xtal import cellbasis

    if isinstance(center, str):
        center = _self.safe_list_eval(center)

    objects = _self.get_object_list(selection)

    for state in range(1, _self.count_states(selection) + 1):
        selecenter = _self.get_coords(selection, state).mean(0)

        for obj in objects:
            sym = _self.get_symmetry(obj, state)

            if not sym:
                raise CmdException("no symmetry")

            basis = cellbasis(sym[3:6], sym[0:3])[:3,:3]
            cset = _self.get_coordset(obj, state, copy=0)
            cset += dot(basis, center) - selecenter

    _self.rebuild(selection)
コード例 #13
0
def load_mtz(filename,
             prefix='',
             maptypes='FoFc 2FoFc',
             multistate=0,
             quiet=1,
             *,
             _self=cmd):
    '''
DESCRIPTION

    Load a MTZ file as two map objects (FoFc, 2FoFc)

    This only works with the incentive PyMOL product!

USAGE

    load_mtz filename [, prefix [, maptypes ]]
    '''
    from pymol import headering

    multistate, quiet = int(multistate), int(quiet)

    header = headering.MTZHeader(filename)

    for coltype in ('F', 'P'):
        if not header.getColumnsOfType(coltype):
            raise CmdException('could not find %s type column' % coltype)

    if not prefix:
        prefix = os.path.basename(filename).rsplit('.', 1)[0]

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

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

        _self.map_generate(name, filename, F, P, 'None', 0, 0, quiet)
        if name not in _self.get_names('objects'):
            print(' Error: Loading %s map failed.' % (maptype))
            raise CmdException(
                'This PyMOL version might not be capable of loading MTZ files')
コード例 #14
0
ファイル: pyDYNAMON.py プロジェクト: boneta/jacques
def load_dynn(filename):
    """
        Load a DYNAMON selection file and read QM/NOFIX to sele objects

        Parameters
        ----------
        filename : str
            file to read selection
    """

    # check file exists
    if not os.path.isfile(filename):
        raise CmdException(f"File '{filename}' not found.", "pyDYNAMON")

    print(f" pyDYNAMON: reading \"{filename}\"")
    dynn = DynnConfigSele()
    dynn.read_selection(filename)

    if not dynn.selection:
        raise CmdException("No selections to read in file. Aborting.",
                           "pyDYNAMON")

    # build selection algebra
    for sele_name, sele in dynn.selection.items():
        sele1_list = []
        for segi, resdict in sele.items():
            sele1 = f"segi {segi}"
            if resdict:
                sele1 += " & ("
                sele2_list = []
                for resi, namelist in resdict.items():
                    sele2 = f"resi {resi}"
                    if namelist:
                        sele2 += " & name " + "+".join(namelist)
                    sele2_list.append(sele2)
                sele1 += " | ".join(sele2_list) + " )"
            sele1_list.append(sele1)
        sele_final = " | ".join(sele1_list)

        # selection command
        cmd.select(sele_name, sele_final, enable=0, quiet=1)
        natoms = cmd.count_atoms(sele_name)
        print(
            f" pyDYNAMON: selection \"{sele_name}\" defined with {natoms} atoms."
        )
コード例 #15
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 = _self.get_unused_name('_')
    _self.select(sele_name, selection) # for speed
    models = _self.get_object_list(sele_name)
    if reference is None:
        reference = models[0]
        models = models[1:]
    elif reference in models:
        models.remove(reference)
    else:
        _self.select(sele_name, reference, merge=1)
    if isinstance(method, str):
        if method in cmd.keyword:
            method = cmd.keyword[method][0]
        else:
            raise CmdException('Unknown method: ' + str(method))
    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 isinstance(x, (list, tuple)):
                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:
        _self.zoom(sele_name)
    _self.delete(sele_name)
コード例 #16
0
def prosmart(mobile, target, mobile_state=1, target_state=1,
        exe='prosmart', transform=1, object=None, quiet=0, *, _self=cmd):
    '''
DESCRIPTION

    ProSMART wrapper.

    http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/
    '''
    import subprocess, tempfile, os, shutil, glob

    quiet = int(quiet)

    tempdir = tempfile.mkdtemp()
    mobile_filename = os.path.join(tempdir, 'mobile.pdb')
    target_filename = os.path.join(tempdir, 'target.pdb')

    _self.save(mobile_filename, mobile, state=mobile_state)
    _self.save(target_filename, target, state=target_state)

    exe = cmd.exp_path(exe)
    args = [exe, '-p1', mobile_filename, '-p2', target_filename, '-a']

    xglob = lambda x: glob.glob(os.path.join(tempdir, 'ProSMART_Output/Output_Files', x))

    try:
        subprocess.check_call(args, cwd=tempdir)

        transfiles = xglob('Superposition/Transformations/*/*.txt')
        with open(transfiles[0]) as f:
            f = iter(f)
            for line in f:
                if line.startswith('ROTATION'):
                    matrix = [list(map(float, next(f).split())) + [0] for _ in range(3)]
                elif line.startswith('TRANSLATION'):
                    matrix.append([-float(v) for v in next(f).split()] + [1])
                    break

        if int(transform):
            matrix = [v for m in matrix for v in m]
            assert len(matrix) == 4*4
            for model in _self.get_object_list(mobile):
                _self.transform_object(model, matrix, state=0)

        if object:
            from .importing import load_aln
            alnfiles = xglob('Residue_Alignment_Scores/*/*.txt')
            alnfiles = [x for x in alnfiles if not x.endswith('_clusters.txt')]
            load_aln(alnfiles[0], object, mobile, target, _self=_self)

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

    if not quiet:
        print(' prosmart: done')
コード例 #17
0
def intra_promix(selection, K=0, prefix=None, conformers=0, guide=1,
        quiet=1, async_=-1, _self=cmd, **kwargs):
    '''
DESCRIPTION

    Finds rigid segments in a multi-state object.

    Requires CSB, https://github.com/csb-toolbox/CSB

ARGUMENTS

    selection = string: atom selection

    K = integer: Number of segments {default: guess}

    prefix = string: Prefix of named segment selections to make

SEE ALSO

    promix

REFERENCE

    Mixture models for protein structure ensembles
    Hirsch M, Habeck M. - Bioinformatics. 2008 Oct 1;24(19):2184-92
    '''
    from numpy import asarray
    from csb.statistics import mixtures
    from .querying import get_ensemble_coords, get_object_name

    K, conformers = int(K), int(conformers)
    guide, quiet, async_ = int(guide), int(quiet), int(kwargs.pop('async', async_))
    if async_ < 0:
        async_ = not quiet

    Mixture = mixtures.ConformerMixture if conformers else mixtures.SegmentMixture

    obj = get_object_name(selection, _self=_self)
    n_models = _self.count_states(obj)

    if guide:
        selection = '(%s) and guide' % (selection)

    if n_models < 2:
        raise CmdException('object needs multiple states')

    X = asarray(get_ensemble_coords(selection, _self=_self))
    assert X.shape == (n_models, _self.count_atoms(selection), 3)

    if not async_:
        _promix(**locals())
    else:
        import threading
        t = threading.Thread(target=_promix, kwargs=locals())
        t.setDaemon(1)
        t.start()
コード例 #18
0
def loop_orientation(selection,
                     state=STATE,
                     visualize=1,
                     quiet=1,
                     *,
                     _self=cmd):
    '''
DESCRIPTION

    Get the center and approximate direction of a peptide. Works for any
    secondary structure.
    Averages direction of N(i)->C(i) pseudo bonds.

USAGE

    loop_orientation selection [, visualize ]

SEE ALSO

    helix_orientation
    '''
    state, visualize, quiet = int(state), int(visualize), int(quiet)

    coords = dict()
    _self.iterate_state(state,
                        '(%s) and name N+C' % (selection),
                        'coords.setdefault(chain + resi, {})[name] = x,y,z',
                        space=locals())

    vec = cpv.get_null()
    center = cpv.get_null()

    count = 0
    for x in coords.values():
        if 'C' in x and 'N' in x:
            vec = cpv.add(vec, cpv.sub(x['C'], x['N']))
        for coord in x.values():
            center = cpv.add(center, coord)
            count += 1

    if count == 0:
        raise CmdException('count == 0')

    vec = cpv.normalize(vec)
    center = cpv.scale(center, 1. / count)

    _common_orientation(selection,
                        center,
                        vec,
                        visualize,
                        2.0 * len(coords),
                        quiet,
                        _self=_self)
    return center, vec
コード例 #19
0
def aaindex2b(key, selection='all', var='b', quiet=1, *, _self=cmd):
    '''
DESCRIPTION

    Looks up the Amino Acid Index from http://www.genome.jp/aaindex/
    for the given key and assignes b-factors to the given selection. Unknown
    residues get the average index value assigned.

USAGE

    aaindex2b key [, selection ]

ARGUMENTS

    key = string: Key of AAindex entry

    selection = string: atoms to assign b-factors {default: (all)}

EXAMPLE

    # Hydropathy index by Kyte-Doolittle
    aaindex2b KYTJ820101
    spectrumany b, white yellow forest
    show surface

SEE ALSO

    hydropathy2b
    '''
    _assert_package_import()
    from . import one_letter

    quiet = int(quiet)

    aaindex = _get_aaindex1(_self=_self)

    try:
        entry = aaindex[key]
    except KeyError:
        raise CmdException('No such key in AAindex: {}'.format(key))

    median = entry.median()

    if not quiet:
        print(entry.desc.strip())

    def lookup(resn):
        aa = one_letter.get(resn, 'X')
        value = entry.get(aa)
        if value is None:
            return median
        return value

    _self.alter(selection, var + '=lookup(resn)', space=locals())
コード例 #20
0
ファイル: pyDYNAMON.py プロジェクト: boneta/jacques
def write_sele(filename,
               selection_name='',
               selection='sele',
               resolution='atom'):
    """
        Append selection to file and overwrite section if existing

        Parameters
        ----------
        filename : str
            file to create/append and write selection
        selection_name : str, optional
            name of selection to write (i.e. 'QM'/'NOFIX')
            default taken from selection argument
        selection : str, optional
            name of a PyMOL selection object (def: 'sele')
        resolution : {'atom', 'residue', 'subsystem'}, optional
            minimum entity size to treat not whole at writting (def: 'atom')
    """

    selection_name = selection_name.upper() or selection.upper()

    # check selection exists
    if not selection in cmd.get_names('selections'):
        raise CmdException(f"Selection '{selection}' not found", "pyDYNAMON")

    # get selection with DynnConfigSele structure
    natoms = 0
    sele = dict()
    obj_list = cmd.get_object_list(selection)
    for obj in obj_list:
        model = cmd.get_model(selection + " and " + obj)
        natoms += model.nAtom
        for a in model.atom:
            segi = str(a.segi)
            resi = int(a.resi)
            name = str(a.name)
            sele.setdefault(segi, {})
            if resolution == 'subsystem': continue
            sele[segi].setdefault(resi, [])
            if resolution == 'residue': continue
            sele[segi][resi].append(name)

    # read file to overwrite a section if already exists
    dynn = DynnConfigSele()
    dynn.read_selection(filename)

    # assign to object and write
    dynn.selection[selection_name] = sele
    dynn.write_selection(filename, resolution='atom')

    print(
        f" pyDYNAMON: {selection_name} with {natoms} written to \"{os.path.abspath(filename)}\""
    )
コード例 #21
0
def get_object_state(name, *, _self=cmd):
    '''
DESCRIPTION
    Returns the effective object state.
    '''
    states = _self.count_states(name)
    if states < 2 and _self.get_setting_boolean('static_singletons'):
        return 1
    state = _self.get_setting_int('state', name)
    if state > states:
        raise CmdException('Invalid state %d for object %s' % (state, name))
    return state
コード例 #22
0
def validate_apbs_exe(exe):
    '''Get and validate apbs executable.
    Raise CmdException if not found or broken.'''
    import subprocess

    if exe:
        exe = cmd.exp_path(exe)
    else:
        exe = find_apbs_exe() or 'apbs'

    try:
        r = subprocess.call([exe, "--version"],
                stdin=subprocess.PIPE,  # Windows pythonw fix
                stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
        if r < 0:
            raise CmdException("Broken executable: " + exe)
    except OSError as e:
        print(e)
        raise CmdException("Cannot execute: " + exe)

    return exe
コード例 #23
0
def get_selection_state(selection, *, _self=cmd):
    '''
DESCRIPTION
    Returns the effective object state for all objects in given selection.
    Raises exception if objects are in different states.
    '''
    state_set = set(
        map(get_object_state, _self.get_object_list('(' + selection + ')')))
    if len(state_set) != 1:
        if len(state_set) == 0:
            return 1
        raise CmdException('Selection spans multiple object states')
    return state_set.pop()
コード例 #24
0
    def help_setting(name, quiet=1, _self=cmd):
        '''
DESCRIPTION

    Print documentation for a setting.

USAGE

    help_setting name
        '''
        import textwrap
        from pymol.setting import setting_sc
        from pymol.setting_help import setting_help_dict

        name = setting_sc[name]
        if not name:
            raise CmdException('unknown setting')
        if name not in setting_help_dict:
            raise CmdException('no doc for setting ' + name)

        text, stype, default, level = setting_help_dict[name]

        r = 'SYNOPSIS\n\n    %s' % name
        if stype:
            r += ' = %s' % stype
        if default:
            r += ' {default: %s}' % default
        r += ' (%s)' % [
            'global', 'object', 'object-state', 'atom', 'atom-state'
        ][int(level)]
        if text:
            r += '\n\nDESCRIPTION\n\n' + textwrap.fill(
                text,
                width=80,
                break_long_words=False,
                initial_indent='    ',
                subsequent_indent='    ')
        print(r)
コード例 #25
0
def stride(selection='(all)',
           exe='stride',
           raw='',
           state=-1,
           quiet=1,
           *,
           _self=cmd):
    '''
DESCRIPTION

    Secondary structure assignment with STRIDE.
    http://webclu.bio.wzw.tum.de/stride/

SEE ALSO

    dss, dssp
    '''
    from subprocess import Popen, PIPE
    import tempfile, os

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

    ss_map = {
        'C': 'L',
        'B': 'S',
        'b': 'S',
        'E': 'S',
        'T': 'L',
        'G': 'H',
        'H': 'H',
    }
    tmpfilepdb = tempfile.mktemp('.pdb')
    ss_dict = dict()
    for model in _self.get_object_list(selection):
        _self.save(tmpfilepdb, '%s and (%s)' % (model, selection), state)
        try:
            process = Popen([exe, tmpfilepdb],
                            stdout=PIPE,
                            universal_newlines=True)
        except OSError:
            raise CmdException('Cannot execute exe=' + exe)
        for line in process.stdout:
            if not line.startswith('ASG'):
                continue
            chain = line[9].strip('-')
            resi = line[11:16].strip()
            ss = line[24]
            ss_dict[model, chain, resi] = ss
    os.remove(tmpfilepdb)
    _common_ss_alter(selection, ss_dict, ss_map, raw, _self=_self)
コード例 #26
0
    def toList(self, model):
        if len(model.atom) > 999:
            raise CmdException(
                "Cannot write file, too many atoms for MOL format: %d > 999." %
                len(model.atom))

        molList = []

        # write header records
        molList.append(model.molecule.title + "\n")
        molList.append(
            "  ChemPy            %2s                             0\n" %
            model.molecule.dim_code)
        molList.append(model.molecule.comments + "\n")
        molList.append("%3d%3d  0  0  %1d  0  0  0  0  0999 V2000\n" %
                       (model.nAtom, model.nBond, model.molecule.chiral))

        # write atom records
        for a in model.atom:
            chg = a.formal_charge
            if chg != 0: chg = 4 - chg
            molList.append("%10.4f%10.4f%10.4f %-3s 0  %1d  %1d  0  0  0  0  0  0  0  0  0\n" % \
                            (a.coord[0], a.coord[1], a.coord[2], a.symbol, chg, a.stereo))

            # write bond records
        for b in model.bond:
            molList.append("%3d%3d%3d%3d  0  0  0\n" %
                           (b.index[0] + 1, b.index[1] + 1, b.order, b.stereo))

            # if necessary, write M  CHG records for charged atoms
        charge_atoms = []
        charge_values = []
        for a in model.atom:
            if a.formal_charge != 0:
                charge_atoms.append(a)
        if len(charge_atoms):
            c = 0
            for a in model.atom:
                a.index = c
                c = c + 1
            while len(charge_atoms) != 0:
                chg_set = charge_atoms[0:8]
                charge_atoms = charge_atoms[8:]
                tline = "M  CHG%3d" % (len(chg_set))
                for i in chg_set:
                    tline = tline + "%4d%4d" % (i.index + 1, i.formal_charge)
                molList.append(tline + "\n")
        molList.append("M  END\n")
        return (molList)
コード例 #27
0
def movie_fade(setting,
               startFrame,
               startVal,
               endFrame,
               endVal=None,
               selection=""):
    """
DESCRIPTION

    Fades representations in movies with their transparency settings.

USAGE

    movie_fade setting, startFrame, startVal, endFrame, endVal [, selection ]

EXAMPLE

    fetch 1rx1, async=0
    as cartoon
    show surface
    mset 1x80
    movie.roll
    movie_fade transparency,  1, 0., 40, 1.
    movie_fade transparency, 41, 1., 80, 0.

SEE ALSO

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

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

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

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

        value = (1.0 - frac) * startVal + frac * endVal
        cmd.mappend(
            frame,
            "/cmd.set(%s, %f, %s)" % (repr(setting), value, repr(selection)))
コード例 #28
0
 def callback(*args):
     code = var_code.get()
     type = get_trunc(var_type)
     if type in ('pdb', 'cif'):
         code += var_chain.get()
     if type == 'cif':
         cmd.set('assembly', var_assembly.get())
     try:
         result = cmd.fetch(code, var_name.get(), type=type)
         if result == -1:
             raise CmdException('You entered an invalid pdb code: ' + code)
     except CmdException as e:
         tkMessageBox.showerror('Error', str(e), parent=self)
         return
     cmd.log('fetch %s, type=%s, async=0\n' % (code, type))
     if not var_keep.get():
         self.destroy()
コード例 #29
0
    def __init__(self, mobile, target, match, *, autodelete=True, _self=cmd):
        self._self = _self
        self.autodelete = autodelete
        self.temporary = []

        if match == 'none':
            self.mobile = mobile
            self.target = target
        elif match in ['in', 'like']:
            self.mobile = '(%s) %s (%s)' % (mobile, match, target)
            self.target = '(%s) %s (%s)' % (target, match, mobile)
        elif match in ['align', 'super']:
            self.align(mobile, target, match)
        elif match in _self.get_names('all') and _self.get_type(match) in ('object:', 'object:alignment'):
            self.from_alignment(mobile, target, match)
        else:
            raise CmdException('unkown match method', match)
コード例 #30
0
def consurfdb(code, chain='A', selection=None, palette='red_white_blue', quiet=1, *, _self=cmd):
    '''
DESCRIPTION

    Color by evolutionary conservation. Writes scores to b-factor.
 
    Fetches pre-calculated conservation profile from ConSurf-DB.
    http://consurfdb.tau.ac.il/

USAGE

    consurfdb code [, chain [, selection [, palette ]]]

EXAMPLE

    fetch 1ubq, async=0
    consurfdb 5nvg, A, 1ubq

SEE ALSO

    load_consurf
    '''
    import ssl
    import urllib.request as urllib2

    code = code.upper()
    url = 'https://consurfdb.tau.ac.il/DB/%s%s/consurf_summary.txt' % (code, chain)
    context = ssl._create_unverified_context()

    try:
        handle = urllib2.urlopen(url, context=context)
    except urllib2.HTTPError:
        raise CmdException('no pre-calculated profile for %s/%s' % (code, chain))

    if selection is None:
        object_list = _self.get_object_list()
        if code not in object_list:
            if code.lower() in object_list:
                code = code.lower()
            else:
                from .importing import fetch
                fetch(code, _self=_self)
        selection = '%s and chain %s' % (code, chain)

    load_consurf(handle, selection, palette, quiet, _self=_self)