def _displayMask(self, e=None):
     if self.protocol.generateMaskedVolume.get():
         maskedMapFileName = os.path.abspath(
             self.protocol._getExtraPath(
                 self.protocol._getMapMaskedByPdbBasedMaskFileName()))
         ccp4header = Ccp4Header(maskedMapFileName, readHeader=True)
         dim, _, _ = ccp4header.getDims()
         x, y, z = ccp4header.getOrigin()
         sampling, _, _ = ccp4header.getSampling()
         counter = 1
         fnCmd = self.protocol._getExtraPath("chimera_mask.cxc")
         f = open(fnCmd, 'w')
         maskFileName = os.path.abspath(maskedMapFileName)
         f.write("open %s\n" % maskFileName)
         f.write("volume #%d style surface voxelSize %f\n" %
                 (counter, sampling))
         # No origin information in header :-(
         #f.write("volume #%d origin  %0.2f,%0.2f,%0.2f\n" %
         #        (counter, x, y, z))
         f.close()
         # run in the background
         Chimera.runProgram(Chimera.getProgram(), fnCmd + "&")
         return []
     else:
         errorWindow(
             self.getTkRoot(), "This protocol has been executed "
             "without the mask option")
     return []
    def runChimeraStep(self):
        # create CMD file
        parentSessionFileName = self.parentProt._getExtraPath(sessionFile)

        # if len(self.extraCommands.get()) > 2:
        #     f.write(self.extraCommands.get())
        #     args = " --nogui --cmd " + self._getTmpPath(
        #         chimeraScriptFileName)

        program = Chimera.getProgram()

        config = configparser.ConfigParser()
        _chimeraPdbTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraPdbTemplateFileName))
        _chimeraMapTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraMapTemplateFileName))
        _sessionFile = os.path.abspath(self._getExtraPath(sessionFile))
        protId = self.getObjId()
        config['chimerax'] = {
            'chimerapdbtemplatefilename': _chimeraPdbTemplateFileName % protId,
            'chimeramaptemplatefilename': _chimeraMapTemplateFileName % protId,
            'sessionfile': _sessionFile,
            'enablebundle': True,
            'protid': self.getObjId()
        }
        with open(self._getExtraPath(CHIMERA_CONFIG_FILE), 'w') as configfile:
            config.write(configfile)

        # run in the background
        cwd = os.path.abspath(self._getExtraPath())
        Chimera.runProgram(program,
                           os.path.abspath(parentSessionFileName),
                           cwd=cwd)
Example #3
0
    def _visualize(self, obj, **args):
        """ Visualize any saved pdb and map if none were saved
        show the input files.
        """
        _inputVolFlag = False
        _inputPDBFlag = False
        directory = self.protocol._getExtraPath()

        fnCmd = os.path.abspath(self.protocol._getTmpPath("chimera_output.cxc"))
        f = open(fnCmd, 'w')
        f.write('cd %s\n' % os.getcwd())

        counter = 0
        # Find all saved maps and pdbs from protocl. If none
        # are found show the input files to the protocol
        for filename in sorted(os.listdir(directory)):
            if filename.endswith(".mrc"):
                _inputVolFlag = True
                counter += 1
                volFileName = os.path.join(directory, filename)
                vol = Volume()
                vol.setFileName(volFileName)

                # fix mrc header
                ccp4header = Ccp4Header(volFileName, readHeader=True)
                sampling = ccp4header.computeSampling()
                origin = Transform()
                shifts = ccp4header.getOrigin()
                origin.setShiftsTuple(shifts)
                f.write("open %s\n" % volFileName)
                f.write("volume #%d style surface voxelSize %f\n"
                        "volume #%d origin %0.2f,%0.2f,%0.2f\n"
                        % (counter, sampling, counter, shifts[0], shifts[1], shifts[2]))
                # Set volume to translucent
                f.write("volume #%d transparency 0.5\n" % counter)

        for filename in os.listdir(directory):
            if filename.endswith(".pdb") or filename.endswith(".cif"):
                _inputPDBFlag = True
                path = os.path.join(directory, filename)
                f.write("open %s\n" % path)


        # If no pdbs or maps found use inputs to protocol
        if not _inputVolFlag:
            counter += 1
            f.write("open %s \n" % os.path.abspath(self.protocol.inputVolume.get().getFileName()))
            # Set volume to translucent
            f.write("volume #%d transparency 0.5\n" % counter)

        if not _inputPDBFlag:
            f.write("open %s \n" % os.path.abspath(self.protocol.pdbFileToBeRefined.get().getFileName()))


        f.close()

        # run in the background
        Chimera.runProgram(chimera.getProgram(), fnCmd + "&")
        return []
    def _visualizeMapModel(self, e=None):
        bildFileName = os.path.abspath(
            self.protocol._getExtraPath("axis_output.bild"))
        if self.protocol.inputVolume.get() is None:
            _inputVol = self.protocol.inputStructure.get().getVolume()
            dim = _inputVol.getDim()[0]
            sampling = _inputVol.getSamplingRate()
        else:
            dim = self.protocol.inputVolume.get().getDim()[0]
            sampling = self.protocol.inputVolume.get().getSamplingRate()
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=bildFileName,
                                         sampling=sampling)
        counter = 1
        fnCmd = self.protocol._getExtraPath("chimera_output.cxc")
        f = open(fnCmd, 'w')
        # reference axis model = 0
        f.write("open %s\n" % bildFileName)
        f.write("cofr 0,0,0\n")

        # input 3D map
        counter += 1  # 2
        fnVol = self.protocol._getInputVolume()
        fnVolName = os.path.abspath(fnVol.getFileName())
        if fnVolName.endswith(":mrc"):
            fnVolName = fnVolName.split(":")[0]
        f.write("open %s\n" % fnVolName)
        x, y, z = fnVol.getOrigin(force=True).getShifts()
        sampling = fnVol.getSamplingRate()
        f.write("volume #%d style surface voxelSize %f\nvolume #%d origin "
                "%0.2f,%0.2f,%0.2f\n" % (counter, sampling, counter, x, y, z))

        # input PDB (usually from coot)
        counter += 1  # 3
        pdbFileName = os.path.abspath(
            self.protocol.inputStructure.get().getFileName())
        f.write("open %s\n" % pdbFileName)

        # second refmac step output -> refined PDB
        counter += 1  # 4
        pdbFileName = os.path.abspath(self.protocol.outputPdb.getFileName())
        f.write("open %s\n" % pdbFileName)

        f.close()
        # run in the background
        Chimera.runProgram(Chimera.getProgram(), fnCmd + "&")
        return []
Example #5
0
    def createChimeraScript(self, volume, pdb):
        """ Create a chimera script to visualize a pseudoatoms pdb
        obteined from a given EM 3d volume.
        A property will be set in the pdb object to
        store the location of the script.
        """
        pseudoatoms = pdb.getFileName()
        scriptFile = pseudoatoms + '_chimera.cmd'
        pdb._chimeraScript = String(scriptFile)
        sampling = volume.getSamplingRate()
        radius = sampling * self.pseudoAtomRadius.get()
        fnIn = getImageLocation(volume)
        if fnIn.endswith(":mrc"):
            fnIn = fnIn[:-4]

        x, y, z = volume.getOrigin(force=True).getShifts()
        xx, yy, zz = volume.getDim()

        dim = volume.getDim()[0]
        bildFileName = os.path.abspath(self._getExtraPath("axis.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=bildFileName,
                                         sampling=sampling)
        fhCmd = open(scriptFile, 'w')
        fhCmd.write("open %s\n" % basename(pseudoatoms))
        fhCmd.write("rangecol bfactor,a 0 white 1 red\n")
        fhCmd.write("setattr a radius %f\n" % radius)
        fhCmd.write("represent sphere\n")

        fhCmd.write("open %s\n" % abspath(fnIn))
        threshold = 0.01
        if self.maskMode == NMA_MASK_THRE:
            self.maskThreshold.get()
        # set sampling
        fhCmd.write("volume #1 level %f transparency 0.5 voxelSize %f origin "
                    "%0.2f,%0.2f,%0.2f\n" % (threshold, sampling, x, y, z))
        fhCmd.write("open %s\n" % bildFileName)
        #fhCmd.write("move %0.2f,%0.2f,%0.2f model #0 coord #2\n"
        #            % ((xx / 2. * sampling) - xv,
        #               (yy / 2. * sampling) - yv,
        #               (zz / 2. * sampling) - zv))
        fhCmd.write("move %0.2f,%0.2f,%0.2f model #0 coord #2\n" %
                    (x + (xx / 2. * sampling), y + (yy / 2. * sampling), z +
                     (zz / 2. * sampling)))
        fhCmd.close()
Example #6
0
    def _visualize(self, obj, **args):
        fnCmd = self.protocol._getTmpPath("chimera_restore_session.cxc")
        f = open(fnCmd, 'w')
        # change to workingDir
        # If we do not use cd and the project name has an space
        # the protocol fails even if we pass absolute paths
        f.write('cd %s\n' % os.getcwd())
        path1 = os.path.join(self.protocol._getExtraPath(), sessionFile)
        if os.path.exists(path1):
            # restored SESSION
            path = path1
        else:
            # SESSION from inputProtocol
            path2 = os.path.join(
                self.protocol.inputProtocol.get()._getExtraPath(), sessionFile)
            path = path2
        f.write("open %s\n" % path)

        Chimera.runProgram(Chimera.getProgram(), fnCmd + "&")
        return []
Example #7
0
    def _visualize(self, obj, **args):
        # Create minimalistic coordinate axis
        dim = 150.
        sampling = 1.
        bildFileName = self.protocol._getExtraPath("axis_output.bild")
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=bildFileName,
                                         sampling=sampling)
        fnCmd = self.protocol._getExtraPath("chimera_output.cxc")
        f = open(fnCmd, 'w')
        # change to workingDir
        # If we do not use cd and the project name has an space
        # the protocol fails even if we pass absolute paths
        f.write('cd %s\n' % os.getcwd())
        f.write("open %s\n" % bildFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates

        # show vol
        _showVol = self.protocol.outputVolume #.get()
        showVolFileName = ImageHandler.removeFileType(_showVol.getFileName())
        f.write("open %s\n" % showVolFileName)
        if _showVol.hasOrigin():
            x, y, z = _showVol.getOrigin().getShifts()
        else:
            x, y, z = _showVol.getOrigin(force=True).getShifts()

        f.write("volume #2 style surface voxelSize %f\n"
                "volume #2 origin %0.2f,%0.2f,%0.2f\n"
                % (_showVol.getSamplingRate(), x, y, z))
        # show atom struct)
        atomstruct = self.protocol.atomStruct.get()
        if atomstruct is not None:
            f.write("open %s\n" % atomstruct.getFileName())
        # run in the background
        Chimera.runProgram(Chimera.getProgram(), fnCmd + "&")
        return []
    def runChimeraStep(self):
        """ Run Chimera script to start simulation and enable scipionwrite
        """
        self.writeChimeraScript()
        fnCmd = os.path.abspath(self._getExtraPath('chimera_script.cxc'))

        # Go to extra dir and save there the output of
        # scipionwrite
        # f.write('cd %s' % os.path.abspath(
        #    self._getExtraPath()))
        # save config file with information
        # this is information is pased from scipion to chimerax
        config = configparser.ConfigParser()
        _chimeraPdbTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraPdbTemplateFileName))
        _chimeraMapTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraMapTemplateFileName))
        _sessionFile = os.path.abspath(self._getExtraPath(sessionFile))
        protId = self.getObjId()
        config['chimerax'] = {
            'chimerapdbtemplatefilename': _chimeraPdbTemplateFileName % protId,
            'chimeramaptemplatefilename': _chimeraMapTemplateFileName % protId,
            'sessionfile': _sessionFile,
            'enablebundle': True,
            'protid': self.getObjId()
        }
        # set to True when
        # protocol finished
        # viewers will check this configuration file
        with open(self._getExtraPath(CHIMERA_CONFIG_FILE), 'w') as configfile:
            config.write(configfile)

        cwd = os.path.abspath(self._getExtraPath())
        Chimera.runProgram(chimera.getProgram(), fnCmd + "&", cwd=cwd)
Example #9
0
    def _showChimera(self, paramName=None):
      if chimeraInstalled():
          prot = self.protocol
          chimScript = prot._getExtraPath('chimera_script.py')
          f = open(chimScript, "w")
          f.write("from chimerax.core.commands import run\n")

          f.write("run(session, 'cd %s')\n" % os.getcwd())
          f.write("run(session, 'cofr 0,0,0')\n")  # set center of coordinates

          _inputStruct = self.getAtomStructObject()
          _inputVol = _inputStruct.getVolume()
          if _inputVol is not None:
            strId = 3
            dim, sampling = _inputVol.getDim()[0], _inputVol.getSamplingRate()

            f.write("run(session, 'open %s')\n" % _inputVol.getFileName())
            x, y, z = _inputVol.getOrigin(force=True).getShifts()
            f.write("run(session, 'volume #%d style surface voxelSize %f')\n" % (1, sampling))
            f.write("run(session, 'volume #%d origin %0.2f,%0.2f,%0.2f')\n" % (1, x, y, z))
            f.write("run(session, 'hide #!%d models')\n" % 1)

          else:
            dim, sampling = 150., 1.
            strId = 2

          tmpFileName = os.path.abspath(prot._getExtraPath("axis_input.bild"))
          Chimera.createCoordinateAxisFile(dim,
                                           bildFileName=tmpFileName,
                                           sampling=sampling)
          f.write("run(session, 'open %s')\n" % tmpFileName)

          # Open atomstruct and color it by the bfactor (which is actually the DAQ score)
          cifDic = AtomicStructHandler().readLowLevel(_inputStruct.getFileName())
          if self._getStructureRecipient() in ['atoms']:
              f.write("run(session, 'open %s')\n" % self.replaceOcuppancyWithAttribute(cifDic))
              attrColorName = 'occupancy'
              
          elif self._getStructureRecipient() in ['residues'] and \
                  getCifKeyName(cifDic, 'asym') and getCifKeyName(cifDic, 'seq'):
              f.write("run(session, 'open %s')\n" % self.replaceOcuppancyWithAttribute(cifDic))
              attrColorName = 'occupancy'
          else:
              f.write("run(session, 'open %s')\n" % _inputStruct.getFileName())
              defAttrFile = self.createAttributesFile(_inputStruct, strId)
              f.write("run(session, 'open %s')\n" % defAttrFile)
              attrColorName = self.getEnumText('attrName')

          stepColors, colorList = self.getColors()
          scolorStr = ''
          for step, color in zip(stepColors, colorList):
            scolorStr += '%s,%s:' % (step, color)
          scolorStr = scolorStr[:-1]

          average = ''
          if self._getStructureRecipient() == 'atoms' and self.residuesAverages:
              average = 'average residues'

          f.write("run(session, 'color byattribute {} palette {} {}')\n".
                  format(attrColorName, scolorStr, average))
          f.write(generateColorLegend(stepColors, colorList))
          f.write("run(session, 'view')\n")

          f.close()
          view = ChimeraView(chimScript)
          return [view]

      else:
          return [self.warnMessage(CHIMERA_ERROR, 'Chimera not found')]
Example #10
0
import pyworkflow.protocol.params as params
import pyworkflow.gui.plotter as plotter
import pyworkflow.gui.dialog as dialog

import pwem.constants as emcts
import pwem.protocols as emprot
from pwem import emlib, splitRange
from pwem.objects import AtomStruct, SetOfAtomStructs
from pwem.viewers.viewer_chimera import mapVolsWithColorkey, Chimera, ChimeraView, generateColorLegend
from pwem.convert.atom_struct import *

from .plotter import EmPlotter, plt

CHIMERA_ERROR = 'Chimera program is not found were it was expected: \n\n{}\n\n' \
                'Either install ChimeraX in this path or install our ' \
                'scipion-em-chimera plugin'.format(Chimera.getProgram())


class LocalResolutionViewer(pwviewer.ProtocolViewer):
    """
    Visualization tools for local resolution results.

    """
    binaryCondition = ('(colorMap == %d) ' % emcts.COLOR_OTHER)

    def __init__(self, *args, **kwargs):
        pwviewer.ProtocolViewer.__init__(self, **kwargs)

    def getImgData(self, imgFile, minMaskValue=0.1, maxMaskValue=None):
        import numpy as np
        # if image ends in .mrc or .map :mrc
Example #11
0
    def _visualize(self, obj, **args):
        # THe input map or pdb may be a parameter from the protocol
        # or from the parent protocol.
        dim = 150.
        sampling = 1.
        _inputVol = None
        directory = self.protocol._getExtraPath()
        try:
            try:
                if self.protocol.inputVolume.get() is not None:
                    _inputVol = self.protocol.inputVolume.get()
                elif self.protocol.pdbFileToBeRefined.get().getVolume(
                ) is not None:
                    _inputVol = self.protocol.pdbFileToBeRefined.get(
                    ).getVolume()
                elif self.protocol.inputVolumes[0] is not None:
                    _inputVol = self.protocol.inputVolumes[0].get()
            except:
                output3DMapList = []
                for filename in sorted(os.listdir(directory)):
                    if filename.endswith(".mrc"):
                        output3DMapList.append(filename.split('.')[0])
                        output3DMap = str(output3DMapList[0])
                        if len(output3DMap) > 0:
                            _inputVol = self.protocol.output3DMap
        except:
            # TODO: I do not know if we still need this part
            # Remark that inputProtocol does not longer exist, it has been replaced by inputProtocolDict
            # Compare with the previous code, specially the alternative directory
            for item in list(self.protocol.inputProtocolDict().values()):
                if item.hasAttribute(
                        'inputVolume') and item.inputVolume.get() is not None:
                    _inputVol = item.inputVolume.get()
                    break
                elif item.hasAttribute('pdbFileToBeRefined') and \
                    item.pdbFileToBeRefined.get().getVolume() is not None:
                    _inputVol = item.pdbFileToBeRefined.get().getVolume()
                    break
                # directory = item._getExtraPath()

        if _inputVol is not None:
            dim = _inputVol.getDim()[0]
            sampling = _inputVol.getSamplingRate()

        bildFileName = self.protocol._getTmpPath("axis_output.bild")
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=bildFileName,
                                         sampling=sampling)
        fnCmd = self.protocol._getTmpPath("chimera_output.cxc")
        f = open(fnCmd, 'w')
        # change to workingDir
        # If we do not use cd and the project name has an space
        # the protocol fails even if we pass absolute paths
        f.write('cd %s\n' % os.getcwd())
        f.write("open %s\n" % bildFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates
        inputVolFileName = ''
        counter = 2
        if _inputVol is not None:
            # In case we have PDBs only, _inputVol is None:
            self.visInputVolume(f, _inputVol, counter)
        else:
            counter = 1

        if (self.protocol.hasAttribute("inputVolume2") and\
                self.protocol.inputVolume2.get() is not None):
            counter += 1
            _inputVol2 = self.protocol.inputVolume2.get()
            self.visInputVolume(f, _inputVol2, counter)

        for filename in sorted(os.listdir(directory)):
            if filename.endswith(".mrc") and filename != inputVolFileName:
                counter += 1
                volFileName = os.path.join(directory, filename)
                vol = Volume()
                vol.setFileName(volFileName)

                # fix mrc header
                ccp4header = Ccp4Header(volFileName, readHeader=True)
                sampling = ccp4header.computeSampling()
                origin = Transform()
                shifts = ccp4header.getOrigin()
                origin.setShiftsTuple(shifts)
                f.write("open %s\n" % volFileName)
                f.write("volume #%d style surface voxelSize %f\n"
                        "volume #%d origin %0.2f,%0.2f,%0.2f\n" %
                        (counter, sampling, counter, shifts[0], shifts[1],
                         shifts[2]))
                f.write("volume #%d level %0.3f\n" % (counter, 0.001))

        for filename in os.listdir(directory):
            if filename.endswith(".pdb") or filename.endswith(".cif"):
                path = os.path.join(directory, filename)
                # f.write("open %s\n" % os.path.abspath(path))
                f.write("open %s\n" % path)

        f.close()

        # run in the background
        Chimera.runProgram(Chimera.getProgram(), fnCmd + "&")
        return []
Example #12
0
    def runChimeraStep(self):
        # building script file including the coordinate axes and the input
        # volume with samplingRate and Origin information
        f = open(self._getTmpPath(chimeraScriptFileName), "w")

        if self.inputVolume.get() is None:
            _inputVol = self.pdbFileToBeRefined.get().getVolume()
        else:
            _inputVol = self.inputVolume.get()

        # building coordinate axes
        if _inputVol is not None:
            dim = _inputVol.getDim()[0]
            sampling = _inputVol.getSamplingRate()
        else:
            dim = 150  # eventually we will create a PDB library that
            # computes PDB dim
            sampling = 1.

        tmpFileName = os.path.abspath(self._getTmpPath("axis_input.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=tmpFileName,
                                         sampling=sampling)
        f.write("open %s\n" % tmpFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates

        # input vol with its origin coordinates
        pdbModelCounter = 1
        if _inputVol is not None:
            pdbModelCounter += 1
            x_input, y_input, z_input = _inputVol.getShiftsFromOrigin()
            inputVolFileName = os.path.abspath(
                ImageHandler.removeFileType(_inputVol.getFileName()))
            f.write("open %s\n" % inputVolFileName)
            f.write("volume #%d style surface voxelSize %f\n" %
                    (pdbModelCounter, _inputVol.getSamplingRate()))
            f.write("volume #%d origin %0.2f,%0.2f,%0.2f\n" %
                    (pdbModelCounter, x_input, y_input, z_input))

        if self.inputVolumes is not None:
            for vol in self.inputVolumes:
                pdbModelCounter += 1
                f.write("open %s\n" % os.path.abspath(vol.get().getFileName()))
                x, y, z = vol.get().getShiftsFromOrigin()
                f.write("volume #%d style surface voxelSize %f\n" %
                        (pdbModelCounter, vol.get().getSamplingRate()))
                f.write("volume #%d origin %0.2f,%0.2f,%0.2f\n" %
                        (pdbModelCounter, x, y, z))

        if self.pdbFileToBeRefined.get() is not None:
            pdbModelCounter += 1
            pdbFileToBeRefined = self.pdbFileToBeRefined.get()
            f.write("open %s\n" %
                    os.path.abspath(pdbFileToBeRefined.getFileName()))
            if pdbFileToBeRefined.hasOrigin():
                x, y, z = (pdbFileToBeRefined.getOrigin().getShifts())
                f.write("move %0.2f,%0.2f,%0.2f model #%d "
                        "coord #0\n" % (x, y, z, pdbModelCounter))

        # Alignment of sequence and structure
        if (hasattr(self, 'inputSequence1')
                and hasattr(self, 'inputStructureChain')):
            if (self.inputSequence1.get() is not None
                    and self.inputStructureChain.get() is not None):
                pdbModelCounter = 2
                if str(self.selectedModel) != '0':
                    f.write("select #%s.%s/%s\n" %
                            (pdbModelCounter, str(self.selectedModel + 1),
                             str(self.selectedChain1)))
                else:
                    f.write("select #%s/%s\n" %
                            (pdbModelCounter, str(self.selectedChain1)))

                if self._getOutFastaSequencesFile is not None:
                    alignmentFile1 = self._getOutFastaSequencesFile(
                        self.OUTFILE1)
                    f.write("open %s\n" % alignmentFile1)
                    f.write("sequence disassociate #%s %s\n" %
                            (pdbModelCounter, alignmentFile1.split("/")[-1]))
                    if str(self.selectedModel) != '0':
                        f.write("sequence associate #%s.%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedModel + 1),
                                 str(self.selectedChain1),
                                 alignmentFile1.split("/")[-1]))
                    else:
                        f.write("sequence associate #%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedChain1),
                                 alignmentFile1.split("/")[-1]))

            if (self.additionalTargetSequence.get() is True
                    and self.inputSequence2.get() is not None
                    and self.inputStructureChain.get() is not None):
                f.write("select clear\n")
                f.write("select #%s/%s,%s\n" %
                        (pdbModelCounter, str(
                            self.selectedChain1), str(self.selectedChain2)))

                if self._getOutFastaSequencesFile is not None:
                    alignmentFile2 = self._getOutFastaSequencesFile(
                        self.OUTFILE2)
                    f.write("open %s\n" % alignmentFile2)
                    f.write("sequence disassociate #%s %s\n" %
                            (pdbModelCounter, alignmentFile2.split("/")[-1]))
                    if str(self.selectedModel) != '0':
                        f.write("sequence associate #%s.%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedModel + 1),
                                 str(self.selectedChain2),
                                 alignmentFile2.split("/")[-1]))
                    else:
                        f.write("sequence associate #%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedChain2),
                                 alignmentFile2.split("/")[-1]))

        # other pdb files
        for pdb in self.inputPdbFiles:
            pdbModelCounter += 1
            f.write("open %s\n" % os.path.abspath(pdb.get().getFileName()))
            if pdb.get().hasOrigin():
                x, y, z = pdb.get().getOrigin().getShifts()
                f.write("move %0.2f,%0.2f,%0.2f model #%d "
                        "coord #0\n" % (x, y, z, pdbModelCounter))
            # TODO: Check this this this this this this

        # Go to extra dir and save there the output of
        # scipionwrite
        #f.write('cd %s' % os.path.abspath(
        #    self._getExtraPath()))
        # save config file with information
        # this is information is pased from scipion to chimerax
        config = configparser.ConfigParser()
        _chimeraPdbTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraPdbTemplateFileName))
        _chimeraMapTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraMapTemplateFileName))
        _sessionFile = os.path.abspath(self._getExtraPath(sessionFile))
        protId = self.getObjId()
        config['chimerax'] = {
            'chimerapdbtemplatefilename': _chimeraPdbTemplateFileName % protId,
            'chimeramaptemplatefilename': _chimeraMapTemplateFileName % protId,
            'sessionfile': _sessionFile,
            'enablebundle': True,
            'protid': self.getObjId()
        }
        # set to True when
        # protocol finished
        # viewers will check this configuration file
        with open(self._getExtraPath(CHIMERA_CONFIG_FILE), 'w') as configfile:
            config.write(configfile)

        # run the text:
        _chimeraScriptFileName = os.path.abspath(
            self._getTmpPath(chimeraScriptFileName))
        if len(self.extraCommands.get()) > 2:
            f.write(self.extraCommands.get())
            args = " --nogui " + _chimeraScriptFileName
        else:
            args = " " + _chimeraScriptFileName

        f.close()

        self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)

        # run in the background
        cwd = os.path.abspath(self._getExtraPath())
        Chimera.runProgram(Plugin.getProgram(), args, cwd=cwd)
Example #13
0
    def runChimeraStep(self):
        # building script file including the coordinate axes and the input
        # volume with samplingRate and Origin information
        f = open(self._getTmpPath(chimeraScriptFileName), "w")
        _inputVol = None
        if (hasattr(self, 'inputVolume') and (self.inputVolume.get() is None)
                and (self.pdbFileToBeRefined.get() is not None)):
            _inputVol = self.pdbFileToBeRefined.get().getVolume()
        else:
            _inputVol = self.inputVolume.get()

        # building coordinate axes
        if _inputVol is not None:
            dim = _inputVol.getDim()[0]
            sampling = _inputVol.getSamplingRate()
        else:
            dim = 150  # eventually we will create a PDB library that
            # computes PDB dim
            sampling = 1.

        tmpFileName = os.path.abspath(self._getTmpPath("axis_input.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=tmpFileName,
                                         sampling=sampling)
        f.write("open %s\n" % tmpFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates

        # input vol with its origin coordinates
        pdbModelCounter = 1
        if _inputVol is not None:
            pdbModelCounter += 1
            x_input, y_input, z_input = _inputVol.getShiftsFromOrigin()
            inputVolFileName = os.path.abspath(
                ImageHandler.removeFileType(_inputVol.getFileName()))
            f.write("open %s\n" % inputVolFileName)
            f.write("volume #%d style surface voxelSize %f\n" %
                    (pdbModelCounter, _inputVol.getSamplingRate()))
            f.write("volume #%d origin %0.2f,%0.2f,%0.2f\n" %
                    (pdbModelCounter, x_input, y_input, z_input))

        if hasattr(self, 'inputVolumes') and \
                self.inputVolumes is not None:
            for vol in self.inputVolumes:
                pdbModelCounter += 1
                f.write("open %s\n" % os.path.abspath(vol.get().getFileName()))
                x, y, z = vol.get().getShiftsFromOrigin()
                f.write("volume #%d style surface voxelSize %f\n" %
                        (pdbModelCounter, vol.get().getSamplingRate()))
                f.write("volume #%d origin %0.2f,%0.2f,%0.2f\n" %
                        (pdbModelCounter, x, y, z))

        if self.pdbFileToBeRefined.get() is not None:
            pdbModelCounter += 1
            pdbFileToBeRefined = self.pdbFileToBeRefined.get()
            f.write("open %s\n" %
                    os.path.abspath(pdbFileToBeRefined.getFileName()))
            if pdbFileToBeRefined.hasOrigin():
                x, y, z = (pdbFileToBeRefined.getOrigin().getShifts())
                f.write("move %0.2f,%0.2f,%0.2f model #%d "
                        "coord #0\n" % (x, y, z, pdbModelCounter))

        # other pdb files
        if hasattr(self, 'inputPdbFiles'):
            for pdb in self.inputPdbFiles:
                pdbModelCounter += 1
                f.write("open %s\n" % os.path.abspath(pdb.get().getFileName()))
                if pdb.get().hasOrigin():
                    x, y, z = pdb.get().getOrigin().getShifts()
                    f.write("move %0.2f,%0.2f,%0.2f model #%d "
                            "coord #0\n" % (x, y, z, pdbModelCounter))

        # run the text:
        _chimeraScriptFileName = os.path.abspath(
            self._getTmpPath(chimeraScriptFileName))
        if len(self.extraCommands.get()) > 2:
            f.write(self.extraCommands.get())
            args = " --nogui " + _chimeraScriptFileName
        else:
            args = " " + _chimeraScriptFileName

        f.close()

        self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)

        # run in the background
        cwd = os.path.abspath(self._getExtraPath())
        Plugin.runChimeraProgram(Plugin.getProgram(),
                                 args,
                                 cwd=cwd,
                                 extraEnv=getEnvDictionary(self))
    def runChimeraStep(self):
        config = configparser.ConfigParser()
        _chimeraPdbTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraPdbTemplateFileName))
        _chimeraMapTemplateFileName = \
            os.path.abspath(self._getExtraPath(
                chimeraMapTemplateFileName))
        _sessionFile = os.path.abspath(self._getExtraPath(sessionFile))
        protId = self.getObjId()
        config['chimerax'] = {
            'chimerapdbtemplatefilename': _chimeraPdbTemplateFileName % protId,
            'chimeramaptemplatefilename': _chimeraMapTemplateFileName % protId,
            'sessionfile': _sessionFile,
            'enablebundle': True,
            'protid': self.getObjId()
        }
        with open(self._getExtraPath(CHIMERA_CONFIG_FILE), 'w') as configfile:
            config.write(configfile)

        # building script file including the coordinate axes and the input
        # volume with samplingRate and Origin information
        f = open(self._getTmpPath(chimeraScriptFileName), "w")
        f.write("from chimerax.core.commands import run\n")

        # building coordinate axes
        dim = self.vol.getDim()[0]
        sampling = self.vol.getSamplingRate()
        bildFileName = os.path.abspath(self._getTmpPath("axis_input.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=bildFileName,
                                         sampling=sampling)
        # origin coordinates
        modelId = 1  # axis
        f.write("run(session, 'open %s')\n" % (bildFileName))
        f.write("run(session, 'cofr 0,0,0')\n")  # set center of coordinates
        # input volume
        modelMapM = modelId + 1  # 2, Minuend, result = minuend − subtrahend
        f.write("run(session,'open %s')\n" % self.fnVolName)
        # step = 1 -> no  binning
        f.write("run(session,'volume #%d style surface voxelSize %f')\n" %
                (modelMapM, sampling))
        x, y, z = self.vol.getShiftsFromOrigin()
        f.write("run(session,'volume #%d origin %0.2f,%0.2f,%0.2f')\n" %
                (modelMapM, x, y, z))
        modelMapS = 7
        modelAtomStruct = 3
        modelAtomStructChain = 4
        modelAtomStructChainSym = 5
        modelIdZone = 6
        modelMapDiff = 8
        modelMapDiffFil = 9

        if self.mapOrModel == 0:  # subtrahend is a 3D Map
            # input map
            # with its origin coordinates
            # modelMapS = modelMapM + 1  # 3 Subtrahend
            f.write("run(session,'open %s')\n" % (self.subVolName))
            f.write("run(session, 'rename #3 id #%d')\n" % modelMapS)
            f.write(
                "run(session,'volume #%d style surface voxelSize %f step 1')\n"
                % (modelMapS, sampling))
            x, y, z = self.subVol.getShiftsFromOrigin()
            f.write("run(session,'volume #%d origin %0.2f,%0.2f,%0.2f')\n" %
                    (modelMapS, x, y, z))
            if self.subtractOrMask == 1 and self.level.get() is not None:
                f.write("run(session,'volume #%d level %f')\n" %
                        (modelMapS, self.level))
        else:  # subtrahend is an atomic structure
            f.write("run(session,'open %s')\n" % self.atomStructName)
            # input atomic structure
            if self.selectChain == True:
                # model and chain selected
                if self.selectStructureChain.get() is not None:
                    chain = self.selectStructureChain.get()
                    self.selectedModel = chain.split(',')[0].split(
                        ':')[1].strip()
                    #TODO: Study problems with multimodels
                    if int(self.selectedModel) != 0:
                        modelId = int(modelAtomStruct +
                                      int(self.selectedModel))

                        f.write("run(session, 'rename #%d id #%d')\n" %
                                (modelId, modelAtomStruct))
                    self.selectedChain = \
                        chain.split(',')[1].split(':')[1].strip().split('"')[1]
                    print("Selected chain: %s from model: %s from structure: %s" \
                        % (self.selectedChain, self.selectedModel,
                            os.path.basename(self.atomStructName)))
                    f.write("run(session,'sel #%d/%s')\n" %
                            (modelAtomStruct, self.selectedChain))
                    tmpPath = os.path.abspath(self._getTmpPath('chain.cif'))

                    f.write(
                        "run(session,"
                        "'save %s format mmcif models #%d relModel #%d selectedOnly true')\n"
                        % (tmpPath, modelAtomStruct, modelId))
                    f.write("run(session,'open %s')\n" % tmpPath)
                    f.write(
                        "run(session,'scipionwrite #%d prefix chain_%s_ ')\n" %
                        (modelAtomStructChain, self.selectedChain))
                    if self.selectAreaMap == True:  # mask the minuend using the atomic structure
                        if self.applySymmetry == True and self.symmetryGroup.get(
                        ) is not None:
                            sym = CHIMERA_SYM_NAME[self.symmetryGroup.get()]
                            modelId = modelAtomStructChain  #4
                            self.symMethod(f, modelId, sym, self.symmetryOrder)

                            f.write(
                                "run(session,'volume zone #%d nearAtoms #%d "
                                "range %d newMap true modelId #%d')\n" %
                                (modelMapM, modelAtomStructChainSym,
                                 self.radius, modelIdZone))
                            if not self.removeResidues:
                                f.write(
                                    "run(session,'scipionwrite #%d prefix sym_  ')\n"
                                    % modelAtomStructChainSym)

                            f.write("run(session,'close #%d')\n" %
                                    (modelAtomStructChainSym))
                        else:
                            f.write(
                                "run(session,'volume zone #%d nearAtoms #%d "
                                "range %d newMap true modelId #%d')\n" %
                                (modelMapM, modelAtomStructChain, self.radius,
                                 modelIdZone))

                        f.write(
                            "run(session,'scipionwrite #%d prefix zone_  ')\n"
                            % modelIdZone)

                    if self.removeResidues == True:
                        if (self.firstResidueToRemove.get() is not None and
                                self.lastResidueToRemove.get() is not None):
                            self.firstResidue = self.firstResidueToRemove.get().\
                            split(":")[1].split(",")[0].strip()
                            self.lastResidue = self.lastResidueToRemove.get(). \
                                split(":")[1].split(",")[0].strip()
                            f.write("run(session,'sel #%d/%s:%d-%d')\n" %
                                    (modelAtomStructChain, self.selectedChain,
                                     int(self.firstResidue),
                                     int(self.lastResidue)))
                            f.write("run(session,'del sel')\n")
                            f.write("run(session,'sel #%d/%s:%d-%d')\n" %
                                    (modelAtomStructChain, self.selectedChain,
                                     int(self.firstResidue) - 10,
                                     int(self.lastResidue) + 10))
                    if self.applySymmetry == True:
                        if self.symmetryGroup.get() is not None:
                            sym = CHIMERA_SYM_NAME[self.symmetryGroup.get()]
                            modelId = modelAtomStructChain
                            self.symMethod(f, modelId, sym, self.symmetryOrder,
                                           self.rangeDist)
                            f.write(
                                "run(session,'scipionwrite #%d prefix sym_  ')\n"
                                % modelAtomStructChainSym)
                            f.write(
                                "v=run(session,'molmap #%d %0.3f gridSpacing %f')\n"
                                % (modelAtomStructChainSym, self.resolution,
                                   sampling))
                            f.write(
                                "run(session,'rename #%d id #7' % v.id[0])\n"
                            )  ## #7 is modelMapS id
                            if self.subtractOrMask == 1 and self.level.get(
                            ) is not None:
                                f.write(
                                    "run(session,'volume #%d level %f')\n" %
                                    (modelMapS, self.level))
                            if self.removeResidues == True:
                                if (self.firstResidueToRemove.get() is not None
                                        and self.lastResidueToRemove.get()
                                        is not None):
                                    f.write("run(session,'sel #%d:%d-%d')\n" %
                                            (modelAtomStructChainSym,
                                             int(self.firstResidue) - 10,
                                             int(self.lastResidue) + 10))

                    else:
                        f.write(
                            "v=run(session,'molmap #%d %0.3f gridSpacing %f')\n"
                            %
                            (modelAtomStructChain, self.resolution, sampling))
                        f.write("run(session,'rename #%d id #7' % v.id[0])\n"
                                )  ## #7 is modelMapS id
                        if self.subtractOrMask == 1 and self.level.get(
                        ) is not None:
                            f.write("run(session,'volume #%d level %f')\n" %
                                    (modelMapS, self.level))

                    f.write(
                        "run(session,'scipionwrite #%d prefix molmap_chain%s_')\n"
                        % (modelMapS, self.selectedChain))

            else:  # use whole atomic model
                f.write("run(session,'scipionwrite #%d')\n" % modelAtomStruct)
                if self.selectAreaMap == True:
                    if self.applySymmetry == True and self.symmetryGroup.get(
                    ) is not None:
                        sym = CHIMERA_SYM_NAME[self.symmetryGroup.get()]
                        modelId = modelAtomStruct
                        self.symMethod(f, modelId, sym, self.symmetryOrder,
                                       self.rangeDist)
                        f.write("run(session, 'rename #4 id #%d')\n" %
                                modelAtomStructChainSym)
                        f.write("run(session,'volume zone #%d nearAtoms #%d "
                                "range %d newMap true modelId #%d')\n" %
                                (modelMapM, modelAtomStructChainSym,
                                 self.radius, modelIdZone))

                        f.write("run(session,'close #%d')\n" %
                                (modelAtomStructChainSym))

                    else:
                        f.write("run(session,'volume zone #%d nearAtoms #%d "
                                "range %d newMap true modelId #%d')\n" %
                                (modelMapM, modelAtomStruct, self.radius,
                                 modelIdZone))

                    f.write(
                        "run(session,'scipionwrite #%d prefix zone_  ')\n" %
                        modelIdZone)

                if self.removeResidues == True:
                    if (self.inputStructureChain.get() is not None
                            and self.firstResidueToRemove.get() is not None
                            and self.lastResidueToRemove.get() is not None):
                        chain = self.inputStructureChain.get()
                        self.selectedModel = chain.split(',')[0].split(
                            ':')[1].strip()
                        # TODO: Study problems with multimodels
                        if int(self.selectedModel) != 0:
                            modelId = int(modelAtomStruct +
                                          int(self.selectedModel))

                            f.write("run(session, 'rename #%d id #%d')\n" %
                                    (modelId, modelAtomStruct))
                        self.selectedChain = \
                            chain.split(',')[1].split(':')[1].strip().split('"')[1]
                        print("Selected chain: %s from model: %s from structure: %s"\
                              % (self.selectedChain, self.selectedModel,
                                 os.path.basename(self.atomStructName)))
                        f.write("run(session,'sel #%d/%s')\n" %
                                (modelAtomStruct, self.selectedChain))
                        self.firstResidue = self.firstResidueToRemove.get(). \
                            split(":")[1].split(",")[0].strip()
                        self.lastResidue = self.lastResidueToRemove.get(). \
                            split(":")[1].split(",")[0].strip()
                        f.write(
                            "run(session,'sel #%d/%s:%d-%d')\n" %
                            (modelAtomStruct, self.selectedChain,
                             int(self.firstResidue), int(self.lastResidue)))
                        f.write("run(session,'del sel')\n")
                        f.write(
                            "run(session,'scipionwrite #%d prefix mutated_ ')\n"
                            % modelAtomStruct)

                        f.write("run(session,'sel #%d/%s:%d-%d')\n" %
                                (modelAtomStruct, self.selectedChain,
                                 int(self.firstResidue) - 10,
                                 int(self.lastResidue) + 10))

                if self.applySymmetry == True:
                    if self.symmetryGroup.get() is not None:
                        sym = CHIMERA_SYM_NAME[self.symmetryGroup.get()]
                        modelId = modelAtomStruct
                        self.symMethod(f, modelId, sym, self.symmetryOrder,
                                       self.rangeDist)
                        f.write("run(session, 'rename #4 id #%d')\n" %
                                modelAtomStructChainSym)
                        f.write(
                            "run(session,'scipionwrite #%d prefix sym_ ')\n" %
                            modelAtomStructChainSym)
                        if (self.inputStructureChain.get() is not None
                                and self.firstResidueToRemove.get() is not None
                                and self.lastResidueToRemove.get()
                                is not None):
                            f.write(
                                "run(session, 'sel #%d/%s:%d-%d')\n" %
                                (modelAtomStructChainSym, self.selectedChain,
                                 int(self.firstResidue) - 10,
                                 int(self.lastResidue) + 10))
                        f.write(
                            "v=run(session,'molmap #%d %0.3f gridSpacing %f')\n"
                            % (modelAtomStructChainSym, self.resolution,
                               sampling))
                        f.write("run(session,'rename #%d id #7' % v.id[0])\n"
                                )  ## #7 is modelMapS id
                        # modelMapS = modelAtomStructChainSym + 1
                        if self.subtractOrMask == 1 and self.level.get(
                        ) is not None:
                            f.write("run(session,'volume #%d level %f')\n" %
                                    (modelMapS, self.level))
                else:  # no symmetry
                    f.write(
                        "v=run(session,'molmap #%d %0.3f gridSpacing %f')\n" %
                        (modelAtomStruct, self.resolution, sampling))
                    f.write("run(session,'rename #%d id #7' % v.id[0])\n"
                            )  ## #7 is modelMapS id
                    if self.subtractOrMask == 1 and self.level.get(
                    ) is not None:
                        f.write("run(session,'volume #%d level %f')\n" %
                                (modelMapS, self.level))
                f.write("run(session,'scipionwrite #%d prefix molmap_  ')\n" %
                        modelMapS)

        # Generation of the differential map
        if self.selectAreaMap == True:
            modelId = modelIdZone
        else:
            modelId = modelMapM
        if self.subtractOrMask == 0:
            f.write("run(session, 'volume subtract #%d #%d modelId #%d "
                    "minRms true onGrid #%d')\n" %
                    (modelId, modelMapS, modelMapDiff, modelId))
        else:
            f.write("run(session, 'volume mask #%d surfaces #%d invertMask "
                    "true modelId #%d')\n" %
                    (modelId, modelMapS, modelMapDiff))
        f.write("run(session,'scipionwrite #%d prefix difference_')\n" %
                modelMapDiff)

        # Generation of the filtered map
        if self.filterToApplyToDiffMap.get() == 0:
            f.write(
                "run(session,'volume gaussian #%d sd %0.3f modelId %#d')\n" %
                (modelMapDiff, self.widthFilter.get(), modelMapDiffFil))
        else:
            f.write("run(session,'volume laplacian #%d')\n" % modelMapDiff)

        f.write("run(session,'scipionwrite #%d prefix filtered_')\n" %
                modelMapDiffFil)
        if self.inputPdbFiles is not None:  # Other atomic models different
            # from the subtrahend
            for atomStruct in self.inputPdbFiles:
                f.write("run(session,'open %s')\n" %
                        os.path.abspath(atomStruct.get().getFileName()))
        # Finally save session
        f.write("run(session,'scipionss')\n")

        # run the script:
        if len(self.extraCommands.get()) > 2:
            f.write(self.extraCommands.get())
            args = " --nogui --script " + \
                   os.path.abspath(self._getTmpPath(chimeraScriptFileName))
        else:
            args = " --script " + \
                   os.path.abspath(self._getTmpPath(chimeraScriptFileName))
        f.close()

        self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)

        # run in the background
        cwd = os.path.abspath(self._getExtraPath())
        Chimera.runProgram(Plugin.getProgram(), args, cwd=cwd)
Example #15
0
    def runChimeraStep(self):
        # building script file including the coordinate axes and the input
        # volume with samplingRate and Origin information
        f = open(self._getTmpPath(chimeraScriptFileName), "w")
        # building coordinate axes

        dim = 150  # eventually we will create a PDB library that
        # computes PDB dim
        sampling = 1.

        tmpFileName = os.path.abspath(self._getTmpPath("axis_input.bild"))
        Chimera.createCoordinateAxisFile(dim,
                                         bildFileName=tmpFileName,
                                         sampling=sampling)
        f.write("open %s\n" % tmpFileName)
        f.write("cofr 0,0,0\n")  # set center of coordinates

        # input vol with its origin coordinates
        pdbModelCounter = 1
        if (not self.addTemplate and self.inputSequence1.get() is not None
                and self._getOutFastaSequencesFile is not None):
            alignmentFile1 = self._getOutFastaSequencesFile(self.OUTFILE1)
            f.write("open %s\n" % alignmentFile1)
            f.write("blastprotein %s:%s database %s matrix %s "
                    "cutoff %.3f maxSeqs %d log true\n" %
                    (alignmentFile1.split("/")[-1], self.targetSeqID1,
                     self.OptionForDataBase[int(self.dataBase)],
                     self.OptionForMatrix[int(self.similarityMatrix)],
                     self.cutoffValue, self.maxSeqs))

        if (hasattr(self, 'pdbFileToBeRefined')
                and self.pdbFileToBeRefined.get() is not None):
            pdbModelCounter += 1
            pdbFileToBeRefined = self.pdbFileToBeRefined.get()
            f.write("open %s\n" %
                    os.path.abspath(pdbFileToBeRefined.getFileName()))
            if pdbFileToBeRefined.hasOrigin():
                x, y, z = (pdbFileToBeRefined.getOrigin().getShifts())
                f.write("move %0.2f,%0.2f,%0.2f model #%d "
                        "coord #0\n" % (x, y, z, pdbModelCounter))

        # Alignment of sequence and structure
        if (hasattr(self, 'inputSequence1')
                and hasattr(self, 'inputStructureChain')):
            if (self.inputSequence1.get() is not None
                    and self.inputStructureChain.get() is not None):
                pdbModelCounter = 2
                if str(self.selectedModel) != '0':
                    f.write("select #%s.%s/%s\n" %
                            (pdbModelCounter, str(self.selectedModel + 1),
                             str(self.selectedChain1)))
                else:
                    f.write("select #%s/%s\n" %
                            (pdbModelCounter, str(self.selectedChain1)))

                if self._getOutFastaSequencesFile is not None:
                    alignmentFile1 = self._getOutFastaSequencesFile(
                        self.OUTFILE1)
                    f.write("open %s\n" % alignmentFile1)
                    f.write("sequence disassociate #%s %s\n" %
                            (pdbModelCounter, alignmentFile1.split("/")[-1]))
                    if str(self.selectedModel) != '0':
                        f.write("sequence associate #%s.%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedModel + 1),
                                 str(self.selectedChain1),
                                 alignmentFile1.split("/")[-1]))
                    else:
                        f.write("sequence associate #%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedChain1),
                                 alignmentFile1.split("/")[-1]))

            if (self.additionalTargetSequence.get() is True
                    and self.inputSequence2.get() is not None
                    and self.inputStructureChain.get() is not None):
                f.write("select clear\n")
                f.write("select #%s/%s,%s\n" %
                        (pdbModelCounter, str(
                            self.selectedChain1), str(self.selectedChain2)))

                if self._getOutFastaSequencesFile is not None:
                    alignmentFile2 = self._getOutFastaSequencesFile(
                        self.OUTFILE2)
                    f.write("open %s\n" % alignmentFile2)
                    f.write("sequence disassociate #%s %s\n" %
                            (pdbModelCounter, alignmentFile2.split("/")[-1]))
                    if str(self.selectedModel) != '0':
                        f.write("sequence associate #%s.%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedModel + 1),
                                 str(self.selectedChain2),
                                 alignmentFile2.split("/")[-1]))
                    else:
                        f.write("sequence associate #%s/%s %s:1\n" %
                                (pdbModelCounter, str(self.selectedChain2),
                                 alignmentFile2.split("/")[-1]))

        # run the text:
        _chimeraScriptFileName = os.path.abspath(
            self._getTmpPath(chimeraScriptFileName))
        if len(self.extraCommands.get()) > 2:
            f.write(self.extraCommands.get())
            args = " --nogui " + _chimeraScriptFileName
        else:
            args = " " + _chimeraScriptFileName

        f.close()

        self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)

        # run in the background
        cwd = os.path.abspath(self._getExtraPath())
        Plugin.runChimeraProgram(Plugin.getProgram(),
                                 args,
                                 cwd=cwd,
                                 extraEnv=getEnvDictionary(self))
Example #16
0
def chimeraInstalled():
  return Chimera.getHome() and os.path.exists(Chimera.getProgram())
Example #17
0
    def _visualize(self, obj, **args):
        # TODO if input volume is not mrc this will not work.
        # Construct the coordinate file and visualization
        bildFileName = os.path.abspath(
            self.protocol._getExtraPath("axis.bild"))
        dims = []
        samplings = []
        if len(self.protocol.inputVolumes) is 0:
            if self.protocol.pdbFileToBeRefined.get().getVolume() is not None:
                dim = self.protocol.pdbFileToBeRefined.get().getVolume(
                ).getDim()[0]
                sampling = self.protocol.pdbFileToBeRefined.get().getVolume().\
                    getSamplingRate()
                dims.append(dim)
                samplings.append(sampling)
        else:
            for i in range(len(self.protocol.inputVolumes)):
                dim = self.protocol.inputVolumes[i].get().getDim()[0]
                sampling = self.protocol.inputVolumes[i].get().\
                    getSamplingRate()
                dims.append(dim)
                samplings.append(sampling)
        if len(dims) != 0 and len(samplings) != 0:
            Chimera.createCoordinateAxisFile(max(dims),
                                             bildFileName=bildFileName,
                                             sampling=max(samplings))
        else:
            dim = 150.
            sampling = 1.
            Chimera.createCoordinateAxisFile(dim,
                                             bildFileName=bildFileName,
                                             sampling=sampling)

        fnCmd = self.protocol._getExtraPath("chimera.cxc")
        f = open(fnCmd, 'w')
        f.write("open %s\n" % bildFileName)
        f.write("cofr 0,0,0\n")

        outputsVol = []
        if len(self.protocol.inputVolumes) is 0:
            if self.protocol.pdbFileToBeRefined.get().getVolume() is not None:
                outputVol = self.protocol.pdbFileToBeRefined.get().getVolume()
                outputsVol.append(outputVol)
        else:
            for i in range(len(self.protocol.inputVolumes)):
                outputVol = self.protocol.inputVolumes[i].get()
                outputsVol.append(outputVol)

        count = 2
        if len(outputsVol) != 0:
            for outputVol in outputsVol:
                outputVolFileName = os.path.abspath(
                    ImageHandler.removeFileType(outputVol.getFileName()))
                x, y, z = outputVol.getOrigin(force=True).getShifts()
                f.write("open %s\n" % outputVolFileName)
                f.write("volume #%d  style surface voxelSize %f\n"
                        "volume #%d  origin %0.2f,%0.2f,%0.2f\n" %
                        (count, outputVol.getSamplingRate(), count, x, y, z))
                count += 1

        # counter = 1
        # template = self.protocol._getExtraPath(COOTPDBTEMPLATEFILENAME)
        databasePath = self.protocol._getExtraPath(
            OUTPUTDATABASENAMESWITHLABELS)
        conn = sqlite3.connect(databasePath)
        c = conn.cursor()
        sql = 'SELECT fileName FROM %s where saved = 1 order by id' % \
              DATABASETABLENAME
        c.execute(sql)
        for row in c:
            pdbFileName = os.path.abspath(row[0])
            if not pdbFileName.endswith(".mrc"):
                f.write("open %s\n" % pdbFileName)

        f.close()
        conn.close()
        # run in the background
        chimeraPlugin = Domain.importFromPlugin('chimera',
                                                'Plugin',
                                                doRaise=True)
        chimeraPlugin.runChimeraProgram(chimeraPlugin.getProgram(),
                                        fnCmd + "&")
        return []
Example #18
0
    def chimeraClashesStep(self):
        labelDictAux = json.loads(self.chainStructure.get(),
                                  object_pairs_hook=collections.OrderedDict)
        labelDict = collections.OrderedDict(
            sorted(labelDictAux.items(), key=itemgetter(1)))
        # labelDict = collections.OrderedDict(sorted(list(labelDictAux.items()), key=itemgetter(1)))
        pdbFileName = os.path.abspath(
            self.pdbFileToBeRefined.get().getFileName())
        # first element of dictionary
        firstValue = labelDict[list(labelDict)[0]]
        outFiles = []
        f = open(self.getChimeraScriptFileName1(), "w")
        f.write("from chimerax.core.commands import run\n")
        f.write("run(session, 'open {}')\n".format(pdbFileName))
        if self.sym == "Cn" and self.symOrder != 1:
            f.write("run(session,'sym #1 C%d copies t')\n" % self.symOrder)
        elif self.sym == "Dn" and self.symOrder != 1:
            f.write("run(session,'sym #1 d%d copies t')\n" % self.symOrder)
        elif self.sym == "T222" or self.sym == "TZ3":
            f.write("run(session,'sym #1 t,%s copies t')\n" % self.sym[1:])
        elif self.sym == "O":
            f.write("run(session,'sym #1 O copies t')\n")
        elif self.sym == "I222" or self.sym == "I222r" or self.sym == "In25" or \
                self.sym == "In25r" or self.sym == "I2n3" or self.sym == "I2n3r" or \
                self.sym == "I2n5" or self.sym == "I2n5r":
            f.write("run(session,'sym #1 i,%s copies t')\n" % self.sym[1:])
        self.SYMMETRY = self.SYMMETRY.get()
        if self.SYMMETRY:
            f.write("run(session,'delete #2 & #1 #>3')\n")
            f.write("run(session,'save {symmetrizedModelName} #2')\n".format(
                symmetrizedModelName=self.getSymmetrizedModelName()))
            f.write("run(session, 'close #1')\n")
            f.write("run(session, 'rename #2 id #1')\n")
        self.endChimeraScript(firstValue, labelDict, outFiles, f)
        f.write("run(session, 'exit')\n")
        f.close()
        args = " --nogui --script " + self.getChimeraScriptFileName1()
        self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)
        Chimera.runProgram(Plugin.getProgram(), args)

        if self.SYMMETRY and not os.path.exists(
                self.getSymmetrizedModelName()):
            # When self.SYMMETRY = TRUE and no one neighbor unit cell has not been
            # generated at less than 3 Angstroms, probably because the symmetry
            # center is not equal to the origin of coordinates, at least we have the
            # contacts that are within the unit cell.
            print(
                red("Error: No neighbor unit cells are available. "
                    "Is the symmetry center equal to the origin of "
                    "coordinates?"))
            self.SYMMETRY = False
            f = open(self.getChimeraScriptFileName2(), "w")
            f.write("from chimerax.core.commands import run\n")
            f.write("session, run('open {}')\n".format(pdbFileName))
            self.endChimeraScript(firstValue, labelDict, outFiles, f)
            f.write("run(session, 'exit')\n")
            f.close()
            args = " --nogui --script " + self.getChimeraScriptFileName2()
            self._log.info('Launching: ' + Plugin.getProgram() + ' ' + args)
            Chimera.runProgram(Plugin.getProgram(), args)

        # parse all files created by chimera
        c, conn = self.prepareDataBase()
        self.parseFiles(outFiles, c)
        conn.commit()
        conn.close()