Exemple #1
0
def doYasaraRewritePdb(entryCode):
    """Called from ipython"""

    os.chdir(cingDirTmp)

    inputDir = os.path.join(cingDirTestsData, "cyana")

    pdbFileName = os.path.join(inputDir, entryCode, entryCode + '_org.pdb')
    localPdbFileName = entryCode + "_org.pdb"
    copy(pdbFileName, localPdbFileName)

    yasara.info.mode = 'txt'
    yasara.Console('off')
    nTmessage('Using Yasara on %s' % entryCode)

    # Read all models.
    #    obj = yasara.LoadPDB(localPdbFileName, center = 'No', correct = 'No', model=1)
    obj = yasara.LoadPDB(localPdbFileName, center='No', correct='No')
    #    yasara.CleanAll() # needed for OptHydObj
    #    yasara.OptHydObj(obj,method='Yasara')
    #    yasara.AddHydObj(obj)
    os.unlink(localPdbFileName)

    newPdbFileName = entryCode + ".pdb"
    #    newPdbFileName = localPdbFileName

    yasara.SavePDB(obj, newPdbFileName, format='IUPAC', transform='No')
    yasara.Clear()
Exemple #2
0
def copyFromCasp2CcpnArchive():
    inputDir = '/Users/jd/CASP-NMR-CING/caspNmrDbDivided'
    os.chdir(inputDir)
    for entryCode in entryList:
        #    for entryCode in entryList[0:1]:
        ch23 = entryCode[1:3]
        for city in predList:
            #        for city in cityList[0:1]:
            entryCodeNew = entryCode + city
            nTmessage("Working on: %s" % entryCodeNew)

            inputEntryDir = os.path.join(inputDir, ch23, entryCodeNew)
            outputEntryDir = os.path.join(dataDir, ch23, entryCodeNew)
            inputAuthorDir = os.path.join(outputEntryDir, 'Author')
            outputNijmegenDir = os.path.join(outputEntryDir, 'Nijmegen')

            if not os.path.exists(inputAuthorDir):
                mkdirs(inputAuthorDir)
            if not os.path.exists(outputNijmegenDir):
                mkdirs(outputNijmegenDir)
            # prevent junk
            patternList = "*.pdb *.upl *.aco *.tbl".split()
            fnList = globMultiplePatterns(inputEntryDir, patternList)
            for fn in fnList:
                orgFn = os.path.join(inputEntryDir, fn)
                #                nTmessage("Copying from %s" % fn)
                #                fnBaseName = os.path.basename(fn)
                dstFn = os.path.join(inputAuthorDir, fn)
                nTmessage("Copying from %s to %s" % (orgFn, dstFn))
                copy(orgFn, dstFn)
Exemple #3
0
def retrieveTgzFromUrl(entryId,
                       url,
                       archiveType=ARCHIVE_TYPE_FLAT,
                       formatFileName='%s.tgz'):  # pylint: disable=W0613
    """Retrieves tgz file from url to current working dir assuming the
    source is named:      $url/$x/$x.tgz
    Will skip the download if it's already present.

    Returns True on failure or None on success.
    """
    #    fileNameTgz = entryId + extension
    fileNameTgz = formatFileName % entryId
    if os.path.exists(fileNameTgz):
        nTmessage("Tgz already present, skipping download")
        return


#    nTdebug("fileNameTgz: %s" % fileNameTgz)

    pathInsert = ''
    # TODO: check
    # Commented out the next lines for NRG-CING but not certain this will work for all uses of this script.
    #    if archiveType == ARCHIVE_TYPE_BY_ENTRY:
    #        pathInsert = '/%s' % entryId
    #    if archiveType == ARCHIVE_TYPE_BY_CH23_BY_ENTRY:
    ##        entryCodeChar2and3 = entryId[1:3]
    #        pathInsert = '/%s/%s' % (entryCodeChar2and3, entryId)

    if url.startswith('file://'):
        pathSource = url.replace('file://', '')
        fullPathSource = "%s%s/%s" % (pathSource, pathInsert, fileNameTgz)
        nTmessage("copying file: %s to: %s" % (fullPathSource, fileNameTgz))
        if not os.path.exists(fullPathSource):
            nTerror("%s does not exist." % (fullPathSource))
            return True
        if not os.path.isfile(fullPathSource):
            nTerror("%s is not a file" % (fullPathSource))
            return True
        if os.path.exists(fileNameTgz):
            nTmessage('Removing old copy: %s' % fileNameTgz)
            os.unlink(fileNameTgz)
        copy(fullPathSource, fileNameTgz)
    elif url.startswith('http://'):
        urlNameTgz = "%s%s/%s" % (url, pathInsert, fileNameTgz)
        nTmessage("downloading url: %s to: %s" % (urlNameTgz, fileNameTgz))
        urllib.urlretrieve(urlNameTgz, fileNameTgz)
    elif url.startswith('ssh://'):
        urlNameTgz = "%s%s/%s" % (url, pathInsert, fileNameTgz)
        nTmessage("Retrieving by ssh: %s to: %s" % (urlNameTgz, fileNameTgz))
        if getFileBySsh(urlNameTgz, fileNameTgz, ntriesMax=2):
            nTerror("Giving up ")
    else:
        nTerror("url has to start with http:/ or file:/ but was: %s" % (url))
        return True

    if os.path.exists(fileNameTgz):
        return

    nTerror("Failed to download: " + urlNameTgz)
    return True
def copyFromCasp2CcpnArchive():
    inputDir = '/Users/jd/CASP-NMR-CING/caspNmrDbDivided'
    os.chdir(inputDir)
    for entryCode in entryList:
#    for entryCode in entryList[0:1]:
        ch23 = entryCode[1:3]
        for city in predList:
#        for city in cityList[0:1]:
            entryCodeNew = entryCode + city
            nTmessage("Working on: %s" % entryCodeNew)

            inputEntryDir = os.path.join(inputDir, ch23, entryCodeNew)
            outputEntryDir = os.path.join(dataDir, ch23, entryCodeNew)
            inputAuthorDir = os.path.join(outputEntryDir, 'Author')
            outputNijmegenDir = os.path.join(outputEntryDir, 'Nijmegen')

            if not os.path.exists(inputAuthorDir):
                mkdirs(inputAuthorDir)
            if not os.path.exists(outputNijmegenDir):
                mkdirs(outputNijmegenDir)
            # prevent junk
            patternList = "*.pdb *.upl *.aco *.tbl".split()
            fnList = globMultiplePatterns(inputEntryDir, patternList)
            for fn in fnList:
                orgFn = os.path.join(inputEntryDir, fn)
#                nTmessage("Copying from %s" % fn)
#                fnBaseName = os.path.basename(fn)
                dstFn = os.path.join(inputAuthorDir, fn)
                nTmessage("Copying from %s to %s" % (orgFn, dstFn))
                copy(orgFn, dstFn)
Exemple #5
0
def export2gif(molecule, pathMolGif, project = None):
    """Return True on error but will still put a default image in."""
    check_type(molecule, 'Molecule')
    check_string(pathMolGif)
    if project:
        check_type(project, 'Project')
#    nTdebug("Now in cing.Plugincode.molgrap#export2gif")
    m = Molgrap(project = project)
    m.run(molecule, pathMolGif)
    failed = False
    if not os.path.exists(pathMolGif):
        failed = True
        src =  os.path.join( cingPythonCingDir, 'PluginCode', DATA_STR, 'UnknownImage.gif' )
#        if os.path.exists(pathMolGif): # disable when done testing.
#            os.unlink(pathMolGif)
        nTmessage("copying default image from %s to %s" % (src, pathMolGif))
#        os.link(src, pathMolGif) # us a real copy JFD: fails between 2 filesystems
        disk.copy(src, pathMolGif) # us a real copy
#        os.symlink(src, pathMolGif) # funny, the extension on mac fails to show up for this file only; other extensions are shown ok...
    # end if
    pathMolGifPinup = pathMolGif[:-4] + '_pin.gif'
    if convertImageMagick(pathMolGif, pathMolGifPinup, options='-geometry 114x80'):
        nTerror("convertImageMagick failed for: " + pathMolGifPinup)
    # end if
    
    if failed:
        return True
    return None
Exemple #6
0
def doYasaraRewritePdb( entryCode ):
    """Called from ipython"""

    os.chdir(cingDirTmp)

    inputDir              = os.path.join(cingDirTestsData, "cyana" )

    pdbFileName = os.path.join(inputDir, entryCode, entryCode+'_org.pdb')
    localPdbFileName = entryCode+"_org.pdb"
    copy(pdbFileName, localPdbFileName)

    yasara.info.mode = 'txt'
    yasara.Console('off')
    nTmessage('Using Yasara on %s' % entryCode)

    # Read all models.
#    obj = yasara.LoadPDB(localPdbFileName, center = 'No', correct = 'No', model=1)
    obj = yasara.LoadPDB(localPdbFileName, center = 'No', correct = 'No')
#    yasara.CleanAll() # needed for OptHydObj
#    yasara.OptHydObj(obj,method='Yasara')
#    yasara.AddHydObj(obj)
    os.unlink(localPdbFileName)

    newPdbFileName = entryCode+".pdb"
#    newPdbFileName = localPdbFileName

    yasara.SavePDB(obj,newPdbFileName,format='IUPAC', transform='No')
    yasara.Clear()
Exemple #7
0
def retrieveTgzFromUrl(entryId, url, archiveType=ARCHIVE_TYPE_FLAT, formatFileName='%s.tgz'): # pylint: disable=W0613
    """Retrieves tgz file from url to current working dir assuming the
    source is named:      $url/$x/$x.tgz
    Will skip the download if it's already present.

    Returns True on failure or None on success.
    """
#    fileNameTgz = entryId + extension
    fileNameTgz = formatFileName % entryId
    if os.path.exists(fileNameTgz):
        nTmessage("Tgz already present, skipping download")
        return
#    nTdebug("fileNameTgz: %s" % fileNameTgz)

    pathInsert = ''
    # TODO: check
    # Commented out the next lines for NRG-CING but not certain this will work for all uses of this script.
#    if archiveType == ARCHIVE_TYPE_BY_ENTRY:
#        pathInsert = '/%s' % entryId
#    if archiveType == ARCHIVE_TYPE_BY_CH23_BY_ENTRY:
##        entryCodeChar2and3 = entryId[1:3]
#        pathInsert = '/%s/%s' % (entryCodeChar2and3, entryId)

    if url.startswith('file://'):
        pathSource = url.replace('file://', '')
        fullPathSource = "%s%s/%s" % (pathSource, pathInsert, fileNameTgz)
        nTmessage("copying file: %s to: %s" % (fullPathSource, fileNameTgz))
        if not os.path.exists(fullPathSource):
            nTerror("%s does not exist." % (fullPathSource))
            return True
        if not os.path.isfile(fullPathSource):
            nTerror("%s is not a file" % (fullPathSource))
            return True
        if os.path.exists(fileNameTgz):
            nTmessage('Removing old copy: %s' % fileNameTgz)
            os.unlink(fileNameTgz)
        copy(fullPathSource, fileNameTgz)
    elif url.startswith('http://'):
        urlNameTgz = "%s%s/%s" % (url, pathInsert, fileNameTgz)
        nTmessage("downloading url: %s to: %s" % (urlNameTgz, fileNameTgz))
        urllib.urlretrieve(urlNameTgz, fileNameTgz)
    elif url.startswith('ssh://'):
        urlNameTgz = "%s%s/%s" % (url, pathInsert, fileNameTgz)
        nTmessage("Retrieving by ssh: %s to: %s" % (urlNameTgz, fileNameTgz))
        if getFileBySsh(urlNameTgz, fileNameTgz, ntriesMax = 2):
            nTerror( "Giving up ")
    else:
        nTerror("url has to start with http:/ or file:/ but was: %s" % (url))
        return True

    if os.path.exists(fileNameTgz):
        return

    nTerror("Failed to download: " + urlNameTgz)
    return True
def copyFromCasdNmr2CcpnArchive():
    #inputDir = '/Users/jd/CASD-NMR-CING/casdNmrDbDivided'
    programHoH = convertToProgram(participationTable)
    os.chdir(inputDir)
    for entryCode in entryList:
        #    for entryCode in entryList[0:1]:
        ch23 = entryCode[1:3]
        for city in cityList:
            #        for city in cityList[0:1]:
            entryCodeNew = entryCode + city
            programId = getDeepByKeys(programHoH, entryCode, city)
            if not (city == 'Test' or programId):
                #                nTdebug("Skipping %s" % entryCodeNew)
                continue


#            else:
#                nTdebug("Looking at %s" % entryCodeNew)
#                continue # TODO disable premature stop.

            nTmessage("Working on: %s" % entryCodeNew)

            inputEntryDir = os.path.join(inputDir, ch23, entryCodeNew)
            outputEntryDir = os.path.join(dataDir, ch23, entryCodeNew)
            inputAuthorDir = os.path.join(outputEntryDir, 'Author')
            outputNijmegenDir = os.path.join(outputEntryDir, 'Nijmegen')

            if not os.path.exists(inputAuthorDir):
                mkdirs(inputAuthorDir)
            if not os.path.exists(outputNijmegenDir):
                mkdirs(outputNijmegenDir)
            # prevent junk
            patternList = "*.pdb *.upl *.aco *.tbl".split()
            fnList = globMultiplePatterns(inputEntryDir, patternList)
            for fn in fnList:
                orgFn = os.path.join(inputEntryDir, fn)
                #                nTmessage("Copying from %s" % fn)
                #                fnBaseName = os.path.basename(fn)
                dstFn = os.path.join(inputAuthorDir, fn)
                nTmessage("Copying from %s to %s" % (orgFn, dstFn))
                copy(orgFn, dstFn)
def copyFromCasdNmr2CcpnArchive():
    #inputDir = '/Users/jd/CASD-NMR-CING/casdNmrDbDivided'
    programHoH = convertToProgram(participationTable)
    os.chdir(inputDir)
    for entryCode in entryList:
#    for entryCode in entryList[0:1]:
        ch23 = entryCode[1:3]
        for city in cityList:
#        for city in cityList[0:1]:
            entryCodeNew = entryCode + city
            programId = getDeepByKeys(programHoH, entryCode, city)
            if not (city == 'Test' or programId):
#                nTdebug("Skipping %s" % entryCodeNew)
                continue
#            else:
#                nTdebug("Looking at %s" % entryCodeNew)
#                continue # TODO disable premature stop.

            nTmessage("Working on: %s" % entryCodeNew)

            inputEntryDir = os.path.join(inputDir, ch23, entryCodeNew)
            outputEntryDir = os.path.join(dataDir, ch23, entryCodeNew)
            inputAuthorDir = os.path.join(outputEntryDir, 'Author')
            outputNijmegenDir = os.path.join(outputEntryDir, 'Nijmegen')

            if not os.path.exists(inputAuthorDir):
                mkdirs(inputAuthorDir)
            if not os.path.exists(outputNijmegenDir):
                mkdirs(outputNijmegenDir)
            # prevent junk
            patternList = "*.pdb *.upl *.aco *.tbl".split()
            fnList = globMultiplePatterns(inputEntryDir, patternList)
            for fn in fnList:
                orgFn = os.path.join(inputEntryDir, fn)
#                nTmessage("Copying from %s" % fn)
#                fnBaseName = os.path.basename(fn)
                dstFn = os.path.join(inputAuthorDir, fn)
                nTmessage("Copying from %s to %s" % (orgFn, dstFn))
                copy(orgFn, dstFn)
Exemple #10
0
    def run(self, ranges=None, export = True, createPlots=True, runAqua=True):
        """
        Run procheck analysis.

        Ranges: GWV 25 Sep 2008: does work ok, using modified script to only implement for tplot call

        Return True on error (None on success; Python default)
        """
        #

        if self.molecule.modelCount == 0:
            nTwarning('Procheck run: no models for "%s"', self.molecule)
            return

        # It's actually important not to write any to Procheck then because
        # there might be more than 200 stretches which upsets PC.
        nTmessage('==> Running procheck_nmr')

        useRanges = self.molecule.useRanges(ranges)
        if useRanges:
            self.ranges = ranges
#            nTdebug("pc.ranges: %s" % self.ranges)
            # Convert the ranges and translate into procheck format
            selectedResidues = self.molecule.setResiduesFromRanges(ranges)
            if selectedResidues == None:
                nTerror( 'In procheck.run selectedResidues None for ranges: %s' % ranges)
                return True
            rangesTxtPlugin = self.rangesForPlugin(ranges)
            if rangesTxtPlugin == None:
                nTerror('Procheck.run: Failed to get rangesTxtPlugin for ranges: [%s]' % ranges)
                return True
            writeTextToFile(os.path.join(self.rootPath, self.rangesFileName), rangesTxtPlugin)
        #end if

        #copy script
        source = os.path.join(cingPythonCingDir, 'PluginCode', DATA_STR, self.procheckScript)
        destination = os.path.join(self.rootPath, self.procheckScript)
        try:
            copy(source, destination)
        except:
            nTerror('Procheck.run: Failed to copy (by exception) "%s"', source)
            return True

        # Copy parameter file
        pcNmrParameterFileOrg = 'procheck_nmr.prm'
        if not createPlots:
            pcNmrParameterFileOrg = 'procheck_nmr_nada.prm'

        pcNmrParameterFile = os.path.join(cingPythonCingDir, 'PluginCode', DATA_STR, pcNmrParameterFileOrg)
        pcNmrParameterFileDestination = os.path.join(self.rootPath, 'procheck_nmr.prm')
        if os.path.exists(pcNmrParameterFileDestination):
#            nTdebug("Removing existing pcNmrParameterFileDestination:"+ pcNmrParameterFileDestination)
            os.unlink(pcNmrParameterFileDestination)
#        nTdebug("Copying "+pcNmrParameterFile+" to: " + pcNmrParameterFileDestination)

        try: # Don't allow this to mess up CING.1
            if copy(pcNmrParameterFile, pcNmrParameterFileDestination):
    #        if os.link(pcNmrParameterFile, pcNmrParameterFileDestination): # don't use link in python for this.
                nTerror("Procheck.run: Failed to copy from " +pcNmrParameterFile+" to: " + pcNmrParameterFileDestination)
                return True
        except:
            nTerror("Procheck.run: Failed to copy (by exception) from " +pcNmrParameterFile+" to: " + pcNmrParameterFileDestination)
            return True

        max_models = self.getMaxModelCount()

        path = os.path.join(self.rootPath, self.molecule.name + '.pdb')
        if export:
            self.molecule.toPDB(path, convention=AQUA, max_models = max_models)
#            self.molecule.toPDBfile(path, convention=AQUA) #GV removed because not implemented in toPDBfile; 12 Jan 09 Try-again
            # Can't use IUPAC here because aqua doesn't understand difference between
            # G and DG.(oxy/deoxy).

        canAqpc = True

        if cingPaths.aqpc == None or cingPaths.aqpc == PLEASE_ADD_EXECUTABLE_HERE:
            nTmessage("No aqpc installed so skipping this step")
            canAqpc = False

        if canAqpc:
            # Save restraints for Aqua
            if self.project.export2aqua():
                canAqpc = False
                nTwarning("Failed to export restraints to Aqua; will run pc without restraints")
            else:
                hasRestraints = False
                for extensionRestraintFile in [ "noe", "tor" ]:
                    srcDir = os.path.join(self.project.rootPath(self.project.name)[0], self.project.directories.aqua )
                    if not os.path.exists(srcDir):
                        nTcodeerror("Aqua export dir is absent")
                        return True
                    fileName = self.project.name +'.' + extensionRestraintFile
                    path = os.path.join(srcDir, fileName )
                    if not os.path.exists(path):
#                        nTdebug("No "+ path+" file found (in Aqua export dir)")
                        pass
                    else:
                        # Map from Aqua per project file to Cing per molecule file.
                        dstFileName = self.molecule.name + '.' + extensionRestraintFile
                        dstPath = os.path.join( self.rootPath, dstFileName )
                        if os.path.exists(dstPath):
#                            nTdebug("Removing existing copy: " + dstPath)
                            os.unlink(dstPath)
#                        nTdebug("Trying to copy from: " + path+" to: "+dstPath)
#                        if os.link(path, dstPath):# don't use link in python for this.
                        if disk.copy(path, dstPath):# don't use link in python for this.
                            nTcodeerror("Failed to copy from: " + path+" to: "+self.rootPath)
                            return True
                        hasRestraints = True
                # run aqpc
                if not canAqpc:
                    nTwarning("Skipping aqpc because failed to convert restraints to Aqua")
                elif not hasRestraints:
                    pass
#                    nTdebug("Skipping aqpc because no Aqua restraints were copied for Aqua")
                else:
#                    nTdebug("Trying aqpc")
                    if self.aqpc( '-r6sum 1 ' + self.molecule.name + '.pdb'):
                        nTcodeerror("Failed to run aqpc; please consult the log file aqpc.log etc. in the molecules procheck directory.")
                        return True
                    else:
                        nTmessage("==> Finished aqpc successfully")

#        nTdebug("Trying procheck_nmr")
        cmd = self.molecule.name +'.pdb'
        if useRanges:
            cmd += ' ' + self.rangesFileName
        if self.procheck(cmd):
            nTerror('Failed to run procheck_nmr successfully; please consult the log file (.log, .out0 etc). in the "%s" directory.',
                    self.rootPath)
            return True
        if self.parseResult():
            nTerror('Failed to procheck_nmr parseResult.')
            return False
        # Remove temp files in case the run was successful and parsed ok.
        removeTempFiles(self.rootPath)

        # Store in project file that we ran procheck successfully
        self.project.procheckStatus.completed = True
        if useRanges:
            self.project.procheckStatus.ranges = ranges
        else:
            self.project.procheckStatus.ranges = None
        nTmessage("==> Finished procheck_nmr successfully")

        return True
Exemple #11
0
def doSetup(config, project, basePath, options):
    """Generate the directory setup and parameter.py file from project and basePath
       Export the data from project.
       Return parameters or None on error.
    """
    nTmessage("\n-- doSetup --")

    if os.path.exists(basePath):
        removedir(basePath)
    #end if

    xplor = Xplor(config, basePath=basePath, project=project
                  )  # generates the directories and initialize parameter setup

    # Set some defaults
    optionNameList = 'modelsAnneal models bestModels'.split()
    modelCount = project.molecule.modelCount
    modelsStr = '0'
    if modelCount != 1:
        modelsStr += '-%d' % (modelCount - 1)
    for optionName in optionNameList:  # DEFAULT: number of molecules in current project
        xplor[optionName] = modelsStr
    setParametersFromOptions(
        project, options,
        xplor)  # Do here for the first time and every time refine is called.
    # copy xplor parameter and topology files
    for fname in os.listdir(os.path.join(xplor.refinePath, 'toppar')):
        if not fnmatch(fname, '.*'):
            #            print '>>',fname
            copy(os.path.join(xplor.refinePath, 'toppar', fname),
                 xplor.joinPath(xplor.directories.toppar, fname))
    #print ">>", xplor

    # restore the data
#    project.restore() # JFD: why ? I get doubling of restraint lists by this.
    nTmessage(project.format())
    if project.molecule == None:
        nTerror('doSetup: No molecule defined for project %s\n', project)
        return
    #end if

    project.validateRestraints(toFile=True)

    if xplor.superpose and len(xplor.superpose) > 0:
        project.molecule.superpose(ranges=xplor.superpose)

    # export the data
#    nTmessage('\n' + dots * 10)
    nTmessage('==> Exporting %s to %s for refinement', project, basePath)

    for drl in project.distances:
        if drl.status == 'keep':
            drl.renameToXplorCompatible()
            xplor.noeRestraints.append(refineNoeParameters(drl.name))
            fname = xplor.joinPath(xplor.directories.tables, drl.name + '.tbl')
            drl.export2xplor(fname)
        #end if
    #end for

    for drl in project.dihedrals:
        if ((drl.name == TALOSPLUS_LIST_STR) & (drl.status != 'noRefine')):
            drl.status = 'noRefine'
        #end if
        if drl.status == 'keep':
            drl.renameToXplorCompatible()
            xplor.dihedralRestraints.append(refineDihedralParameters(drl.name))
            fname = xplor.joinPath(xplor.directories.tables, drl.name + '.tbl')
            drl.export2xplor(fname)
        #end if
    #end for

    # export structures in Xplor-PDB format
    xplor.baseName = project.molecule.name + '_%03d.pdb'
    # Only used for psf generation:
    xplor.baseNameByChain = project.molecule.name + '_%s_%03d.pdb'
    pathByChain = xplor.joinPath(xplor.directories.converted,
                                 xplor.baseNameByChain)
    nTmessage('==> -A- Exporting first model of %s to XPLOR PDB-files (%s)',
              project.molecule, pathByChain)
    project.molecule.export2xplor(pathByChain,
                                  chainName=ALL_CHAINS_STR,
                                  model=0)
    path = xplor.joinPath(xplor.directories.converted, xplor.baseName)
    nTmessage('==> -B- Exporting all models  of %s to XPLOR PDB-files (%s)',
              project.molecule, path)
    project.molecule.export2xplor(path)

    # PSF file
    xplor.psfFile = project.molecule.name + '.psf'
    # Set the patches for the psf file
    for res in project.molecule.residuesWithProperties('HIS'):
        xplor.patchHISD.append((res.chain.name, res.resNum))
    for res in project.molecule.residuesWithProperties('HISE'):
        xplor.patchHISE.append((res.chain.name, res.resNum))
    for res in project.molecule.residuesWithProperties('cPRO'):
        xplor.patchCISP.append((res.chain.name, res.resNum))
    disulfide_bridges = project.molecule.idDisulfides(toFile=False,
                                                      applyBonds=False)

    if disulfide_bridges == True:
        nTerror("Failed to analyze disulfide bridges.")
    elif disulfide_bridges:
        nTmessage("==> Located disulfide bridges %s" % str(disulfide_bridges))
    for (res1, res2) in disulfide_bridges:
        xplor.patchDISU.append(
            ((res1.chain.name, res1.resNum), (res2.chain.name, res2.resNum)))

    parfile = xplor.joinPath(PARAMETERS_FILE_NAME)
    xplor.toFile(parfile)
    nTmessage("==> Saved the parameter file %s" % parfile)
    #    nTmessage('\n==> Generated setup under "%s"\nEdit "%s" before continuing\n', basePath, parfile ) # Not in all setups relevant.
    return xplor
Exemple #12
0
    def run(self, ranges=None, export=True, createPlots=True, runAqua=True):
        """
        Run procheck analysis.

        Ranges: GWV 25 Sep 2008: does work ok, using modified script to only implement for tplot call

        Return True on error (None on success; Python default)
        """
        #

        if self.molecule.modelCount == 0:
            nTwarning('Procheck run: no models for "%s"', self.molecule)
            return

        # It's actually important not to write any to Procheck then because
        # there might be more than 200 stretches which upsets PC.
        nTmessage('==> Running procheck_nmr')

        useRanges = self.molecule.useRanges(ranges)
        if useRanges:
            self.ranges = ranges
            #            nTdebug("pc.ranges: %s" % self.ranges)
            # Convert the ranges and translate into procheck format
            selectedResidues = self.molecule.setResiduesFromRanges(ranges)
            if selectedResidues == None:
                nTerror(
                    'In procheck.run selectedResidues None for ranges: %s' %
                    ranges)
                return True
            rangesTxtPlugin = self.rangesForPlugin(ranges)
            if rangesTxtPlugin == None:
                nTerror(
                    'Procheck.run: Failed to get rangesTxtPlugin for ranges: [%s]'
                    % ranges)
                return True
            writeTextToFile(os.path.join(self.rootPath, self.rangesFileName),
                            rangesTxtPlugin)
        #end if

        #copy script
        source = os.path.join(cingPythonCingDir, 'PluginCode', DATA_STR,
                              self.procheckScript)
        destination = os.path.join(self.rootPath, self.procheckScript)
        try:
            copy(source, destination)
        except:
            nTerror('Procheck.run: Failed to copy (by exception) "%s"', source)
            return True

        # Copy parameter file
        pcNmrParameterFileOrg = 'procheck_nmr.prm'
        if not createPlots:
            pcNmrParameterFileOrg = 'procheck_nmr_nada.prm'

        pcNmrParameterFile = os.path.join(cingPythonCingDir, 'PluginCode',
                                          DATA_STR, pcNmrParameterFileOrg)
        pcNmrParameterFileDestination = os.path.join(self.rootPath,
                                                     'procheck_nmr.prm')
        if os.path.exists(pcNmrParameterFileDestination):
            #            nTdebug("Removing existing pcNmrParameterFileDestination:"+ pcNmrParameterFileDestination)
            os.unlink(pcNmrParameterFileDestination)
#        nTdebug("Copying "+pcNmrParameterFile+" to: " + pcNmrParameterFileDestination)

        try:  # Don't allow this to mess up CING.1
            if copy(pcNmrParameterFile, pcNmrParameterFileDestination):
                #        if os.link(pcNmrParameterFile, pcNmrParameterFileDestination): # don't use link in python for this.
                nTerror("Procheck.run: Failed to copy from " +
                        pcNmrParameterFile + " to: " +
                        pcNmrParameterFileDestination)
                return True
        except:
            nTerror("Procheck.run: Failed to copy (by exception) from " +
                    pcNmrParameterFile + " to: " +
                    pcNmrParameterFileDestination)
            return True

        max_models = self.getMaxModelCount()

        path = os.path.join(self.rootPath, self.molecule.name + '.pdb')
        if export:
            self.molecule.toPDB(path, convention=AQUA, max_models=max_models)
#            self.molecule.toPDBfile(path, convention=AQUA) #GV removed because not implemented in toPDBfile; 12 Jan 09 Try-again
# Can't use IUPAC here because aqua doesn't understand difference between
# G and DG.(oxy/deoxy).

        canAqpc = True

        if cingPaths.aqpc == None or cingPaths.aqpc == PLEASE_ADD_EXECUTABLE_HERE:
            nTmessage("No aqpc installed so skipping this step")
            canAqpc = False

        if canAqpc:
            # Save restraints for Aqua
            if self.project.export2aqua():
                canAqpc = False
                nTwarning(
                    "Failed to export restraints to Aqua; will run pc without restraints"
                )
            else:
                hasRestraints = False
                for extensionRestraintFile in ["noe", "tor"]:
                    srcDir = os.path.join(
                        self.project.rootPath(self.project.name)[0],
                        self.project.directories.aqua)
                    if not os.path.exists(srcDir):
                        nTcodeerror("Aqua export dir is absent")
                        return True
                    fileName = self.project.name + '.' + extensionRestraintFile
                    path = os.path.join(srcDir, fileName)
                    if not os.path.exists(path):
                        #                        nTdebug("No "+ path+" file found (in Aqua export dir)")
                        pass
                    else:
                        # Map from Aqua per project file to Cing per molecule file.
                        dstFileName = self.molecule.name + '.' + extensionRestraintFile
                        dstPath = os.path.join(self.rootPath, dstFileName)
                        if os.path.exists(dstPath):
                            #                            nTdebug("Removing existing copy: " + dstPath)
                            os.unlink(dstPath)
#                        nTdebug("Trying to copy from: " + path+" to: "+dstPath)
#                        if os.link(path, dstPath):# don't use link in python for this.
                        if disk.copy(
                                path,
                                dstPath):  # don't use link in python for this.
                            nTcodeerror("Failed to copy from: " + path +
                                        " to: " + self.rootPath)
                            return True
                        hasRestraints = True
                # run aqpc
                if not canAqpc:
                    nTwarning(
                        "Skipping aqpc because failed to convert restraints to Aqua"
                    )
                elif not hasRestraints:
                    pass
#                    nTdebug("Skipping aqpc because no Aqua restraints were copied for Aqua")
                else:
                    #                    nTdebug("Trying aqpc")
                    if self.aqpc('-r6sum 1 ' + self.molecule.name + '.pdb'):
                        nTcodeerror(
                            "Failed to run aqpc; please consult the log file aqpc.log etc. in the molecules procheck directory."
                        )
                        return True
                    else:
                        nTmessage("==> Finished aqpc successfully")

#        nTdebug("Trying procheck_nmr")
        cmd = self.molecule.name + '.pdb'
        if useRanges:
            cmd += ' ' + self.rangesFileName
        if self.procheck(cmd):
            nTerror(
                'Failed to run procheck_nmr successfully; please consult the log file (.log, .out0 etc). in the "%s" directory.',
                self.rootPath)
            return True
        if self.parseResult():
            nTerror('Failed to procheck_nmr parseResult.')
            return False
        # Remove temp files in case the run was successful and parsed ok.
        removeTempFiles(self.rootPath)

        # Store in project file that we ran procheck successfully
        self.project.procheckStatus.completed = True
        if useRanges:
            self.project.procheckStatus.ranges = ranges
        else:
            self.project.procheckStatus.ranges = None
        nTmessage("==> Finished procheck_nmr successfully")

        return True
Exemple #13
0
def doSetup(config, project, basePath, options):
    """Generate the directory setup and parameter.py file from project and basePath
       Export the data from project.
       Return parameters or None on error.
    """
    nTmessage("\n-- doSetup --")

    if os.path.exists(basePath):
        removedir(basePath)
    #end if

    xplor = Xplor(config, basePath=basePath, project=project) # generates the directories and initialize parameter setup

    # Set some defaults
    optionNameList = 'modelsAnneal models bestModels'.split()
    modelCount = project.molecule.modelCount
    modelsStr = '0'
    if modelCount != 1:
        modelsStr += '-%d' % (modelCount-1)
    for optionName in optionNameList:    # DEFAULT: number of molecules in current project
        xplor[ optionName ] = modelsStr
    setParametersFromOptions(project, options, xplor) # Do here for the first time and every time refine is called.
    # copy xplor parameter and topology files
    for fname in os.listdir(os.path.join(xplor.refinePath, 'toppar')):
        if not fnmatch(fname, '.*'):
#            print '>>',fname
            copy(os.path.join(xplor.refinePath, 'toppar', fname), xplor.joinPath(xplor.directories.toppar, fname))
    #print ">>", xplor

    # restore the data
#    project.restore() # JFD: why ? I get doubling of restraint lists by this.
    nTmessage(project.format())
    if project.molecule == None:
        nTerror('doSetup: No molecule defined for project %s\n', project)
        return
    #end if

    project.validateRestraints(toFile=True)

    if xplor.superpose and len(xplor.superpose) > 0:
        project.molecule.superpose(ranges=xplor.superpose)

    # export the data
#    nTmessage('\n' + dots * 10)
    nTmessage('==> Exporting %s to %s for refinement', project, basePath)

    for drl in project.distances:
        if drl.status == 'keep':
            drl.renameToXplorCompatible()
            xplor.noeRestraints.append(refineNoeParameters(drl.name))
            fname = xplor.joinPath(xplor.directories.tables, drl.name + '.tbl')
            drl.export2xplor(fname)
        #end if
    #end for

    for drl in project.dihedrals:
        if ((drl.name == TALOSPLUS_LIST_STR) & (drl.status != 'noRefine')) :
            drl.status = 'noRefine'
        #end if
        if drl.status == 'keep':
            drl.renameToXplorCompatible()
            xplor.dihedralRestraints.append(refineDihedralParameters(drl.name))
            fname = xplor.joinPath(xplor.directories.tables, drl.name + '.tbl')
            drl.export2xplor(fname)
        #end if
    #end for

    # export structures in Xplor-PDB format
    xplor.baseName = project.molecule.name + '_%03d.pdb'
    # Only used for psf generation:
    xplor.baseNameByChain = project.molecule.name + '_%s_%03d.pdb'
    pathByChain = xplor.joinPath(xplor.directories.converted, xplor.baseNameByChain)
    nTmessage('==> -A- Exporting first model of %s to XPLOR PDB-files (%s)', project.molecule, pathByChain)
    project.molecule.export2xplor(pathByChain, chainName = ALL_CHAINS_STR, model = 0)
    path = xplor.joinPath(xplor.directories.converted, xplor.baseName)
    nTmessage('==> -B- Exporting all models  of %s to XPLOR PDB-files (%s)', project.molecule, path)
    project.molecule.export2xplor(path)


    # PSF file
    xplor.psfFile = project.molecule.name + '.psf'
    # Set the patches for the psf file
    for res in project.molecule.residuesWithProperties('HIS'):
        xplor.patchHISD.append((res.chain.name, res.resNum))
    for res in project.molecule.residuesWithProperties('HISE'):
        xplor.patchHISE.append((res.chain.name, res.resNum))
    for res in project.molecule.residuesWithProperties('cPRO'):
        xplor.patchCISP.append((res.chain.name, res.resNum))
    disulfide_bridges = project.molecule.idDisulfides(toFile=False, applyBonds=False)

    if disulfide_bridges == True:
        nTerror("Failed to analyze disulfide bridges.")
    elif disulfide_bridges:
        nTmessage("==> Located disulfide bridges %s" % str(disulfide_bridges))
    for (res1, res2) in disulfide_bridges:
        xplor.patchDISU.append( ((res1.chain.name, res1.resNum),
                                 (res2.chain.name, res2.resNum)))

    parfile = xplor.joinPath(PARAMETERS_FILE_NAME)
    xplor.toFile(parfile)
    nTmessage("==> Saved the parameter file %s" % parfile)
#    nTmessage('\n==> Generated setup under "%s"\nEdit "%s" before continuing\n', basePath, parfile ) # Not in all setups relevant.
    return xplor