Exemplo n.º 1
0
    def finaliseImport(self):

        if not self.depositionImportNums[6]:
            showWarning('Failure',
                        'Need connected molecule and shift information first')
            return

        if showYesNo(
                "Save project and continue annotation",
                "Are you sure you want to save this project and continue?",
                parent=self):

            if self.depositionImportNums[5] or showYesNo(
                    "No coordinates",
                    "No coordinates are available - are you sure you want to continue?",
                    parent=self):

                showInfo("Project name",
                         "Your project will be saved in the %s directory." %
                         self.project.name,
                         parent=self)

                self.project.saveModified()

                #userData = self.project.findFirstRepository(name='userData')
                #currentPath = userData.url.path
                #currentProjectName = self.project.name

                #projectDir = os.path.join(currentPath,currentProjectName)

                eci = EntryCompletionGui(self.basePopup.root)
                eci.initProject(self.project)
Exemplo n.º 2
0
    def deleteContourFile(self, *extra):

        storedContours = self.getStoredContours()
        if not storedContours:
            return

        if len(storedContours) == 1:
            s = t = ''
        else:
            s = ' %d ' % len(storedContours)
            t = 's'
        if (showYesNo(
                'Delete stored contour%s from project' % t,
                'Are you sure you want to delete selected %sstored contour%s from the project?'
                % (s, t),
                parent=self)):
            if (showYesNo(
                    'Delete underlying contour file%s on disk' % t,
                    'Do you also want to delete underlying contour file%s on disk (normally yes)?'
                    % t,
                    parent=self)):
                for storedContour in storedContours:
                    path = storedContour.fullPath
                    try:
                        os.remove(path)
                    except:
                        print 'Warning: could not remove %s' % path
            for storedContour in storedContours:
                storedContour.delete()
Exemplo n.º 3
0
  def continueIfFileNameUsed(self, fileName):

    result = True

    storedContoursToDelete = []
    for analysisSpectrum in self.analysisProject.analysisSpectra:
      for storedContour in analysisSpectrum.storedContours:
        if storedContour.fullPath == fileName:
          storedContoursToDelete.append(storedContour)

    if storedContoursToDelete:
      if len(storedContoursToDelete) == 1:
        s = ''
        t = 's'
      else:
        s = 's'
        t = ''
      result = showYesNo('File used', 'Stored contour%s already use%s this fileName, and will be deleted: continue?' % (s, t), parent=self)
      if result:
        for storedContour in storedContoursToDelete:
          try:
            storedContour.delete()
          except:
            pass

    return result
Exemplo n.º 4
0
  def downloadResults(self):

    if not self.run:
      msg = 'No current iCing run'
      showWarning('Failure', msg, parent=self)
      return

    credentials = self.serverCredentials
    if not credentials:
      msg = 'No current iCing server job'
      showWarning('Failure', msg, parent=self)
      return

    fileName = self.resultFileEntry.get()
    if not fileName:
      msg = 'No save file specified'
      showWarning('Failure', msg, parent=self)
      return

    if os.path.exists(fileName):
      msg = 'File %s already exists. Overwite?' % fileName
      if not showOkCancel('Query', msg, parent=self):
        return

    url = self.iCingBaseUrl
    iCingUrl = self.getServerUrl(url)
    logText = iCingRobot.iCingFetch(credentials, url, iCingUrl, fileName)
    print logText

    msg = 'Results saved to file %s\n' % fileName
    msg += 'Purge results from iCing server?'
    if showYesNo('Query',msg, parent=self):
      self.purgeCingServer()
Exemplo n.º 5
0
    def saveDataToPyc(self, fileName):
        '''Pickle the data model and save it to file to
           be use later. Since this storage method relies
           on pickle, it is not guaranteed that the data
           can be loaded in future versions of this macro.
        '''

        if self.results:

            if not fileName[-4:] == '.pyc':

                fileName = fileName + '.pyc'

            if os.path.exists(fileName):
                if not showYesNo('File exists',
                                 'File "%s" exists, overwrite?' % fileName,
                                 parent=self.GUI):

                    return

            self.updateInfoText('Saving results...')
            writeFile = open(fileName, 'wb')
            cPickle.dump(self.results, writeFile, protocol=2)
            writeFile.close()
            self.updateInfoText('Results succesfully saved.')

        else:

            string = 'There are no results to save at the moment.'
            showWarning('No results to save', string, parent=self.GUI)
Exemplo n.º 6
0
 def pressButton(self):
 
   self.textWindow.setText('Button Pressed\n')
   if showYesNo('Title','Prompt: Clear text window?'):
      self.textWindow.clear()
      
   return
Exemplo n.º 7
0
    def resetShiftImport(self):

        doReset = True

        if not self.linkResDone and self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Shifts not connected to sequence',
                    'You have not checked whether the imported chemical shift information matches the imported sequence. Do you want to this first? If not, the last imported data will be invalid.',
                    parent=self):
                self.connectShiftsSequence()
                doReset = False

        if doReset:

            self.mainButtons.buttons[1].config(
                foreground=self.fontDefaultColor)

            self.shiftsLoaded = self.linkResDone = False

            self.currentShiftList = None

            self.shiftImport.setText(self.defaultSelectText)
            self.shiftImport.configure(foreground=self.fontDefaultColor)

            self.linkResCheckInfo.set("")
Exemplo n.º 8
0
    def deleteAxisUnit(self, *event):

        axisUnit = self.getAxisUnit()
        if (axisUnit):
            if (showYesNo(
                    'Delete axis unit',
                    'Are you sure you want to delete axis unit "%s"?' %
                    axisUnit.unit, self)):
                axisUnit.delete()
Exemplo n.º 9
0
    def deleteAxisType(self, *event):

        axisType = self.getAxisType()
        if axisType:
            if (showYesNo(
                    'Delete axis type',
                    'Are you sure you want to delete axis type "%s"?' %
                    axisType.name, self)):
                axisType.delete()
Exemplo n.º 10
0
    def commitAssignments(self):

        merge = showYesNo('Query', 'Merge with any existing spin systems?',
                          self)

        for spinSystem in self.spinSystemMatrix.currentObjects:
            if not spinSystem.residue:
                residue, p = self.getProbableResidue(spinSystem)
                assignSpinSystemResidue(spinSystem, residue, warnMerge=merge)
Exemplo n.º 11
0
    def deletePanelType(self, *event):

        panelType = self.getPanelType()
        if (panelType):
            if (showYesNo(
                    'Delete panel type',
                    'Are you sure you want to delete panel type "%s"?' %
                    panelType.name, self)):
                panelType.delete()
Exemplo n.º 12
0
    def removePoint(self):

        if self.object and (len(self.dataFitting.objects) > 2):
            self.dataFitting.objects.remove(self.object)
            if showYesNo('Query',
                         'Delete the corresponding %s?' %
                         (self.object.className),
                         parent=self):
                self.object.delete()
            self.updateAfter()
Exemplo n.º 13
0
  def checkSaving(self):

    if not self.project:
      return True

    if isProjectModified(self.project):
      if showYesNo('Save project', 'Save changes to project?', parent=self):
        if not self.quitSaveProject():
          return False

    return True
Exemplo n.º 14
0
    def updateAll(self):

        self.selectTab(self.tabbedFrame.selected)

        if self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Connect shifts to sequence',
                    'You have to check whether the chemical shift information matches the sequence. Do you want to this now?',
                    parent=self):
                self.connectShiftsSequence()

        self.waiting = False
Exemplo n.º 15
0
  def closeProject(self, queryClose=True, querySave=True):

    if queryClose:
      if (not showYesNo('Close project', 'Close current project?')):
        return False

    if querySave:
      if (not self.checkSaving()):
        return False

    self.destroyPopups()
    self.initProject()
 
    return True
Exemplo n.º 16
0
    def save(self):

        filePrefix = self.fileEntry.get()
        directory = self.dirSelect.getDirectory()
        filePrefix = joinPath(directory, filePrefix)
        fileName = filePrefix + '.tgz'

        if os.path.exists(fileName):
            if not showYesNo('File exists',
                             'File "%s" exists, overwrite?' % fileName,
                             parent=self):
                return

        includeBackups = self.backupCheck.isSelected()
        includeData = self.dataCheck.isSelected()
        packageProject(self.project, filePrefix, includeBackups, includeData)
Exemplo n.º 17
0
  def showAll(self):

    loadAll = False
    if self.chemCompDownload:
      if (showYesNo('Show all variants','Are you sure you want to display all variants? This will also download the XML files for all chemComps that are not stored locally!')):
        loadAll = True
    else:
      loadAll = True

    if loadAll:
      for key in self.chemCompInfoList:
        self.chem_comps_shown[key] = 1

      self.updateTables()

      self.chemCompDownload = False
Exemplo n.º 18
0
  def quit(self):

    if not showYesNo('Quit ' + self.programName, 'Quit ' + self.programName + '?'):
      return

    if self.project:
      if not self.checkSaving():
        return

    self.destroy()

    # Need the below code to fix the problem with Bash
    # where the commend line was getting screwed up on exit.
    if os.name == 'posix':
      os.system('stty sane')
      
    sys.exit(0)
Exemplo n.º 19
0
def _packageProject(memopsRoot):
    """Create a tar gzipped CCPN project from a MemopsRoot object"""    
    
    from memops.general.Io import saveProject, packageProject
    
    repository = memopsRoot.findFirstRepository(name='userData')
    if not repository:
        return
    
        
    projectPath = repository.url.path
    parentDir, projectDir = os.path.split(projectPath)

    
    writeable = os.access(parentDir, os.W_OK)
    if not writeable:
        msg = 'Directory %s does not have write access required to write temporary file.'
        showWarning('Warning', msg % parentDir)
        return
    
    currentProjName = memopsRoot.name
    newProjName = '__%s' % currentProjName
    newProjDir = os.path.join(parentDir, newProjName)
    
    while os.path.exists(newProjDir):
        msg = 'Filename %s exists. Overwrite?' % newProjDir
        if showYesNo('Query', msg): 
            break
        
        newProjName = '_' + newProjName
        newProjDir = os.path.join(parentDir, newProjName)
    
    try:
      saveProject(memopsRoot, newPath=newProjDir, removeExisting=True, revertToOriginal=True)
    
      packageProject(memopsRoot, filePrefix=newProjDir, userPath=newProjDir)
    finally:
      # reset project name
      # need to use override since name is frozen
      # wb104: 6 Feb 2014: should not need to do below any more because added revertToOriginal and userPath above
      #memopsRoot.override = True
      #memopsRoot.name = currentProjName
      #memopsRoot.override = False
      pass

    return newProjDir + '.tgz'
Exemplo n.º 20
0
    def setDir(self):

        directory = self.dir_entry.get()
        if not directory:
            showWarning('No directory',
                        'No directory specified, not setting backup directory',
                        parent=self)
            return

        if not os.path.abspath(directory):
            directory = joinPath(os.getcwd(), directory)

        if os.path.exists(directory):
            if not os.path.isdir(directory):
                showWarning('Path not directory',
                            'Path "%s" exists but is not a directory' %
                            directory,
                            parent=self)
                return
        else:
            if showYesNo(
                    'Directory does not exist',
                    'Directory "%s" does not exist, should it be created?' %
                    directory,
                    parent=self):
                os.mkdir(directory)
            else:
                showWarning(
                    'Directory not created',
                    'Directory "%s" not created so not setting backup directory'
                    % directory,
                    parent=self)
                return

        repository = self.project.findFirstRepository(name='backup')
        if not repository:
            showWarning(
                'No backup repository',
                'No backup repository found (something wrong somewhere)',
                parent=self)
            return

        url = repository.url
        if url.path != directory:
            repository.url = Url(path=normalisePath(directory))
Exemplo n.º 21
0
  def apply(self):
    
    returnValue = True
    
    if self.importExportFlag == 'import':
      
      returnValue = self.importExportFile(self.component) # If none, will do all components

      if returnValue and self.project.molSystems:
        
        if self.project.currentNmrProject.resonances or self.project.currentNmrProject.nmrConstraintStores:
          
          runLinkResonances = showYesNo('Run linkResonances','You have a defined molecular system and NMR atom assignment information in your project. To connect this information to each other you have to run linkResonances. Do you want to run this program now?')
          
          if runLinkResonances:
            self.parent.linkResonances()

    return returnValue
Exemplo n.º 22
0
    def quit(self):

        msg = 'Quit ' + PROGRAM_NAME

        if not showYesNo('Confirm', msg + '?', parent=self):
            return

        if self.project:
            if not self.checkSaving():
                return

        self.destroy()

        # Need the below code to fix the problem with Bash
        # where the commend line was getting screwed up on exit.
        if os.name == 'posix':
            os.system('stty sane')

        sys.exit(0)
Exemplo n.º 23
0
  def quit(self):

    if not hasattr(self.parent, 'project'): 
      if not showYesNo('Quit ' + self.programName, 'Quit ' + self.programName + '?'):
        return

    #if self.project:
    #  if not self.checkSaving():
    #    return

    self.destroy()

    # Only exit system of not inside another app 
    if not hasattr(self.parent, 'project'): 
      # Need the below code to fix the problem with Bash
      # where the command line was getting screwed up on exit.
      if os.name == 'posix':
        os.system('stty sane')
 
      sys.exit(0)
Exemplo n.º 24
0
  def go(self):
  
    if showYesNo('Re-reference', "Are you sure?"):
            
      for i in range(self.numDims):
        
        self.adjusts[i] = self.adjustEntry[i].get()
	      
      for peak in self.peakList.peaks:
        
	dims = peak.peakDims
        
        for i, peakDim in enumerate(peak.sortedPeakDims()):
          
	  peakDim.position = peakDim.position + self.adjusts[i]
        
    self.parent.parent.owner.peaksUpdate()
    self.close() 
    
      
Exemplo n.º 25
0
    def quit(self):

        msg = 'Quit ' + self.programName

        if not showYesNo('Confirm', msg + '?', parent=self):
            return

        # turn off the daemon!
        self.taskDaemon.alive = False

        if self.project:
            if not self.checkSaving():
                return

        self.destroy()

        # Need the below code to fix the problem with Bash
        # where the commend line was getting screwed up on exit.
        if os.name == 'posix':
            os.system('stty sane')

        sys.exit(0)
Exemplo n.º 26
0
    def saveText(self):

        fileSelectPopup = FileSelectPopup(
            self,
            file_types=[
                FileType('Text', ['*.txt', '*.out', '*.text']),
                FileType('All', ['*'])
            ],
            title='Select text output save file')

        fileName = fileSelectPopup.getFile()

        if fileName:
            writeFile = 1
            if os.path.exists(fileName):
                if not showYesNo('Overwrite file',
                                 'Overwrite existing file %s?' % fileName):
                    writeFile = 0

            if writeFile:
                fout = open(fileName, 'w')
                fout.write(self.text.text_area.getText())
                fout.close()
Exemplo n.º 27
0
    def resetSequenceImport(self):

        doReset = True

        if not self.linkResDone and self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Shifts not connected to sequence',
                    'You have not checked whether the imported chemical shift information matches the imported sequence. Do you want to this first? If not, the last imported data will be invalid.',
                    parent=self):
                self.connectShiftsSequence()
                doReset = False

        if doReset:

            self.mainButtons.buttons[0].config(
                foreground=self.fontDefaultColor)

            self.sequenceCoordinatesLoaded = self.shiftsLoaded = self.linkResDone = False

            self.sequenceCoordinatesImport.setText(self.defaultSelectText)
            self.sequenceCoordinatesImport.configure(
                foreground=self.fontDefaultColor)

            self.moleculeSelect.destroy()
            self.moleculeSelect = Label(
                self.frameA,
                text="None available yet - import valid file first",
                foreground=self.fontBadColor)
            self.moleculeSelect.grid(row=self.moleculeSelectRow,
                                     column=0,
                                     sticky='ew')

            self.shiftImport.setText(self.defaultSelectText)
            self.shiftImport.configure(foreground=self.fontDefaultColor)

            self.linkResCheckInfo.set("")
Exemplo n.º 28
0
def makeStructureEnsemble(strucDict,
                          molSystem,
                          modelNames=None,
                          doWarnings=False,
                          checkTruncation=True,
                          fixAtomNames=True):
    """Makes structure ensemble from a structure dictionary
             [model][chainCode][resNum][atomName] = (x,y,z coords)
             in a mol system. Options to supress warnings and thus
             automatically link non-identical, but similar chains
             or make a new chain if none is found,
             NB chains and resides are those present in FIRST model
                atoms are taken from all models, 
                and missing atoms are given x=y=z = 0.0; occupancy=0.0 
  .. describe:: Input
  
  Dictionary, MolSystem.MolSystem, Boolean

  .. describe:: Output

  MolStructures.StructureEnsemble
  """

    # Rasmus Fogh 20/6/2011: Changed to new MolStructure model

    # Rasmus Fogh 4/5/2013:Added automatic  name fixing: 2HB -> HB2

    #
    # Set up, and create structure ensemble
    #

    ll = sorted(strucDict.keys())
    firstModelId = ll[0]

    project = molSystem.root

    ensembles = molSystem.sortedStructureEnsembles()
    if ensembles:
        eId = ensembles[-1].ensembleId + 1
    else:
        eId = 1

    ensemble = project.newStructureEnsemble(molSystem=molSystem,
                                            ensembleId=eId)

    #models = []
    #for m in strucDict.keys():
    #  models.append((m, ensemble.newModel()))

    #
    # record data list - for creating and processing records in reading order
    #

    recordDataList = []
    recordDataDict = {}
    coordResidues = {}
    allMsResidues = {}

    usedChains = []
    failedAtoms = []
    msAtomDict = {}
    atomCheckDict = {}
    systemAtoms = set()
    chainsDict = strucDict[firstModelId]

    # match or make chains
    chCodes = list(chainsDict.keys())
    chCodes.sort()
    nOrigChCodes = len(chCodes)
    for iChCode, chCode in enumerate(chCodes):
        resDict = chainsDict[chCode]
        seqIds = resDict.keys()
        seqIds.sort()

        chemComps = []
        ccpCodes = []
        seqIdsGood = []

        # get list of good chemcomps
        molTypes = set()
        resNames = []
        for seqId in seqIds:
            ll = resDict[seqId].keys()
            resName = resDict[seqId][ll[0]]['resName']
            atomNames = [tt[0] for tt in ll]
            chemComp = DataConvertLib.getBestChemComp(project, resName,
                                                      atomNames)
            resNames.append(resName)

            if chemComp:
                chemComps.append(chemComp)
                ccpCodes.append(chemComp.ccpCode)
                seqIdsGood.append(seqId)
                molTypes.add(chemComp.molType)

        if not seqIdsGood:
            msg = 'Could not find any matching CCPN ChemComps for sequence: '
            msg += ' '.join(resNames)
            showWarning('Structure Creation Failed', msg)
            continue

        #get matching MolSystem chains
        seqIds = seqIdsGood
        msChains, mappings = findMatchingChains(molSystem,
                                                ccpCodes,
                                                excludeChains=usedChains,
                                                doWarning=doWarnings,
                                                molTypes=molTypes)

        nChains = len(msChains)
        if nChains == 1:
            msChain = msChains[0]
            mapping = mappings[0]

        elif nChains:
            from memops.gui.DataEntry import askString

            codes = [c.code for c in msChains]
            msg = 'Structure chain %s matches %d \nCCPN chains' % (chCode,
                                                                   nChains)
            msg += ' equally well: %s\n' % (' '.join(codes), )
            msg += 'Which CCPN chain should be linked to?'

            if chCode in codes:
                default = chCode
            else:
                default = codes[0]

            choice = None
            while choice not in codes:
                choice = askString('Query', msg, default) or ''
                choice = choice.strip()

            index = codes.index(choice)
            msChain = msChains[index]
            mapping = mappings[index]

        else:
            msChain = None

        if nChains:
            nRes = len(mapping)
            startPair = 0
            endPair = nRes - 1

            for i in range(nRes):
                residueA, residueB = mapping[i]
                if residueA and residueB:
                    startPair = i
                    break

            for endTrunc in range(nRes):
                j = endPair - endTrunc
                residueA, residueB = mapping[j]
                if residueA and residueB:
                    endPair = j
                    break

            mismatch = []
            for i in range(startPair, endPair + 1):
                if None in mapping[i]:
                    mismatch.append(i)
                    break

            if doWarnings:
                if checkTruncation and ((endTrunc > 10) or (startPair > 10)):
                    msg = 'Structure truncated (Start:%s, End:%s) ' % (
                        startPair, endTrunc)
                    msg += 'compared to existing chain. Really link to chain %s?' % msChain.code
                    msg += ' (Otherwise a new chain will be made)'
                    if not showYesNo('Query', msg):
                        msChain = None

                if mismatch and msChain is not None:
                    msg = 'Imperfect match: %s non-terminal mismatches, ' % len(
                        mismatch)
                    msg += 'compared to existing chain. Really link to chain %s?' % msChain.code
                    msg += ' (Otherwise a new chain will be made)'
                    if not showYesNo('Query', msg):
                        msChain = None

            else:

                if checkTruncation and (startPair or endTrunc):
                    print(
                        'WARNING, Structure truncated (Start:%s, End:%s) rel. to existing chain.'
                        % (startPair, endTrunc))

                if mismatch:
                    print 'WARNING, Imperfect match: %s non-terminal mismatches' % len(
                        mismatch)

        if not msChain:
            # no matching chain - make new one
            # use existing chain code from PDB file if possible
            sysChainCode = chCode.strip()
            if not sysChainCode or molSystem.findFirstChain(code=sysChainCode):
                sysChainCode = nextChainCode(molSystem)

            if molTypes == set(('DNA', )) and iChCode <= nOrigChCodes:
                # check for special case:
                # double stranded DNA with a single chain code
                oneLetterCodes = [cc.code1Letter for cc in chemComps]
                if None not in oneLetterCodes:
                    # All ChemComps are (variants of) Std bases.
                    # Not sure certain, but this should mostly work.
                    nCodes = len(oneLetterCodes)
                    halfway, remainder = divmod(nCodes, 2)
                    if not remainder:
                        # even number of codes
                        resMap = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
                        for ii in range(halfway):
                            if oneLetterCodes[ii] != resMap[oneLetterCodes[
                                    -1 - ii]]:
                                break
                        else:
                            # the second half is the reverse complement of the first half.
                            # treat as two separate DNA chains
                            # Move second half to a new chain, and remove from this chain.
                            newChCode = chCode
                            while newChCode in chCodes:
                                newChCode = chr(ord(newChCode) + 1)
                            newResDict = chainsDict[newChCode] = {}
                            for ii in range(halfway, nCodes):
                                iix = seqIds[ii]
                                newResDict[iix] = resDict[iix]
                                del resDict[iix]

                            # put both chains on end of list for later (re)processing
                            chCodes.append(chCode)
                            chCodes.append(newChCode)
                            continue

            codes = (molSystem.code, sysChainCode)
            msg = 'Structure residue sequence (chain %s) not in molecular system. ' % chCode
            msg += 'Make new molecular system %s chain (%s) for this sequence?' % codes
            if not doWarnings or (not molSystem.chains) or (
                    doWarnings and showOkCancel('Confirm', msg)):

                atomNames = resDict[seqIds[0]].keys()

                molType = chemComps[0].molType
                ccpCodes0 = []
                startNum = resDict[seqIds[0]][atomNames[0]]['seqCode']

                project = molSystem.root
                molecule = makeMolecule(project, molType, [])

                for i in range(len(seqIds)):
                    chemComp = chemComps[i]

                    if (chemComp.molType != molType) or (
                            i and (seqIds[i] != seqIds[i - 1] + 1)):
                        newMolResidues = addMolResidues(molecule,
                                                        molType,
                                                        ccpCodes0,
                                                        startNum=startNum)

                        # set seqCodes and seqInsertCodes
                        xSeqIds = seqIds[i - len(newMolResidues):i]
                        for j, x in enumerate(xSeqIds):
                            rr = newMolResidues[j]
                            for dummy in resDict[x]:
                                # future-safe of getting a random atomDict for seqId x
                                dd = resDict[x][dummy]
                                break

                            rr.seqCode = dd['seqCode']
                            rr.seqInsertCode = dd['insertCode']

                        ccpCodes0 = [
                            chemComp.ccpCode,
                        ]
                        molType = chemComp.molType
                        startNum = seqIds[i]

                    else:
                        ccpCodes0.append(chemComp.ccpCode)

                if ccpCodes0:
                    addMolResidues(molecule,
                                   molType,
                                   ccpCodes0,
                                   startNum=startNum)

                msChain = makeChain(molSystem, molecule, code=sysChainCode)

                resMapping = {}
                for i, residue in enumerate(msChain.sortedResidues()):
                    resMapping[i] = residue

                # TBD deal with HETATMs, proper Molecule name,
                # store CCPN xml as non-standard naming system?

            else:
                continue

        else:
            # msChain is not None
            sysChainCode = msChain.code
            resMapping = {}
            for i, residue in mapping:
                resMapping[i] = residue

        usedChains.append(msChain)

        atomNamesList = []
        msResidues = []
        for j, seqId in enumerate(seqIds):
            atomNames = [tt[0] for tt in resDict[seqId].keys()]
            if fixAtomNames:
                # change names to get right naming system.
                for ii, name in enumerate(atomNames):
                    if name[0] in '123':
                        atomNames[ii] = name[1:] + name[0]
            atomNamesList.append(atomNames)
            msResidue = resMapping.get(j)
            msResidues.append(msResidue)

        namingSystem = DataConvertLib.getBestNamingSystem(
            msResidues, atomNamesList)

        coordChain = ensemble.newChain(code=sysChainCode)
        #ensemble.override = True

        #
        # Done making chain - start adding residues to chain
        #

        for j, seqId in enumerate(seqIds):
            msResidue = msResidues[j]

            if not msResidue:  # Structure is bigger
                continue

            resName = ccpCodes[j]
            ccpCode = msResidue.ccpCode

            if doWarnings:
                if resName != ccpCode:
                    msg = 'Residue names [%s,%s] don\'t match\nin'
                    msg += ' loaded molecular system\nchain %s position %d'
                    data = (resName, ccpCode, chCode, seqId)
                    showWarning('Warning', msg % data)
                    continue

                if msResidue is None:
                    msg = 'No equivalent molecular system residue'
                    msg += '\nfor PDB chain %s residue %d'
                    showWarning('Warning', msg % (chCode, seqId))
                    continue

            coordResidue = coordChain.newResidue(
                seqCode=msResidue.seqCode,
                seqInsertCode=msResidue.seqInsertCode,
                seqId=msResidue.seqId)
            coordResidues[(chCode, seqId)] = coordResidue
            allMsResidues[(chCode, seqId)] = msResidue
            #
            # Now make atoms
            #

            for atomKey, coordDict in resDict[seqId].items():

                atomName, altLoc = atomKey

                key = '%s:%s:%s' % (atomName, msResidue, namingSystem)

                if key in msAtomDict:
                    systemAtom = msAtomDict.get(key)

                else:
                    systemAtom = DataConvertLib.findMatchingMolSystemAtom(
                        atomName,
                        msResidue,
                        namingSystem,
                        systemAtoms,
                        fixAtomNames=fixAtomNames)
                    msAtomDict[key] = systemAtom

                if (systemAtom is None) or atomCheckDict.get(
                    (systemAtom, altLoc)):
                    #print '### failing', atomName
                    failedAtoms.append(
                        '%s %d %s %4s' %
                        (chCode, seqId, msResidue.ccpCode, atomName))
                    continue

                systemAtoms.add(systemAtom)
                #print '### adding', atomName, systemAtom.name
                atomCheckDict[(systemAtom, altLoc)] = True

                tt = (coordDict.get('recordId'), (chCode, seqId, atomKey),
                      coordResidue, systemAtom.name, coordDict)
                recordDataList.append(tt)
                recordDataDict[(chCode, seqId, atomKey)] = tt

    #
    #  Finished getting data for reading order from first model
    #
    #  Now loop over other models and add new atoms to existing residues
    #  ignoring new residues and chains, to cater for varying atom presence
    #

    for modelInd, chainsDict in sorted(strucDict.items()[1:]):
        for chCode, resDict in sorted(chainsDict.items()):
            for seqId, atomDict in sorted(resDict.items()):
                coordResidue = coordResidues.get((chCode, seqId))
                msResidue = allMsResidues.get((chCode, seqId))
                if coordResidue is None or msResidue is None:
                    continue
                for atomKey, coordDict in atomDict.items():
                    tt = recordDataDict.get((chCode, seqId, atomKey))
                    if tt is None:
                        # new atom, make new record
                        atomName, altLoc = atomKey
                        key = '%s:%s:%s' % (atomName, msResidue, namingSystem)

                        if key in msAtomDict:
                            systemAtom = msAtomDict.get(key)

                        else:
                            systemAtom = DataConvertLib.findMatchingMolSystemAtom(
                                atomName,
                                msResidue,
                                namingSystem,
                                systemAtoms,
                                fixAtomNames=fixAtomNames)
                            msAtomDict[key] = systemAtom

                        if (systemAtom is None) or atomCheckDict.get(
                            (systemAtom, altLoc)):
                            failedAtoms.append(
                                '%s %d %s %4s' %
                                (chCode, seqId, msResidue.ccpCode, atomName))
                            continue
                        print '### NBNB add extra atom:', (chCode, seqId,
                                                           atomKey)

                        systemAtoms.add(systemAtom)
                        atomCheckDict[(systemAtom, altLoc)] = True

                        tt = (coordDict.get('recordId'), (chCode, seqId,
                                                          atomKey),
                              coordResidue, systemAtom.name, coordDict)
                        recordDataList.append(tt)
                        recordDataDict[(chCode, seqId, atomKey)] = tt

    #
    #  Finished getting data for reading order
    #

    # sort by recordId. If not set - or if duplicate recordId
    # will sort by full key.
    recordDataList.sort()

    #
    nAtoms = len(recordDataList)

    #
    # Create atoms
    #
    for tt in recordDataList:
        recordId, fullKey, coordResidue, atomName, coordDict = tt

        # make coordAtom
        coordResidue.newAtom(name=atomName, altLocationCode=fullKey[2][1])

    #
    # set data for all models
    #

    kk = 0
    for modelInd, chainsDict in sorted(strucDict.items()):

        #create model
        model = ensemble.newModel()
        if modelNames:
            model.name = modelNames[kk]
            kk += 1

        # set up for data reading
        coordinates = [0.0] * (3 * nAtoms
                               )  # NB deliberate this is 0.0, not None
        # There might be atoms missing in other models
        occupancies = [1.0] * nAtoms
        bFactors = [0.0] * nAtoms
        ii = 0
        jj = 0
        hasOccupancies = False
        hasBFactors = False

        for tt in recordDataList:
            recordId, fullKey, coordResidue, atomName, coordDict = tt

            resDict = chainsDict.get(fullKey[0])
            if resDict:
                atomDict = resDict.get(fullKey[1])
                if atomDict:
                    coordDict = atomDict.get(fullKey[2])
                    #try:
                    #  xxx = atomDict[fullKey[2]]
                    #  coordDict = xxx
                    #except:
                    #  print '###', atomDict.keys(), tt

                    if coordDict:
                        # get data for model
                        coordinates[jj] = coordDict['x']
                        jj += 1
                        coordinates[jj] = coordDict['y']
                        jj += 1
                        coordinates[jj] = coordDict['z']
                        jj += 1
                        occupancy = coordDict.get('occupancy', 1.0)
                        if occupancy != 1.0:
                            occupancies[ii] = occupancy
                            hasOccupancies = True
                        bFactor = coordDict.get('bFactor', 0.0)
                        if bFactor != 0.0:
                            bFactors[ii] = bFactor
                            hasBFactors = True
                        ii += 1
                    else:
                        # This atom not found in this model
                        # Just leave default values, set occupancy to 0
                        # and increment indices
                        # NBNB this leaves coordinates as 0.0 NBNBNB
                        occupancies[ii] = 0.0
                        hasOccupancies = True
                        ii += 1
                        jj += 3

        # fill data into model
        model.setSubmatrixData('coordinates', coordinates)
        if hasOccupancies:
            model.setSubmatrixData('occupancies', occupancies)
        if hasBFactors:
            model.setSubmatrixData('bFactors', bFactors)

    # final validity check
    try:
        ensemble.checkAllValid()
    except:
        ensemble.delete()
        return

    # reset switches
    #ensemble.override = False

    if failedAtoms:
        ll = sorted(set(failedAtoms))
        ll = [x for x in ll if not ('Q' in x[-5:] or '*' in x[-5:])]
        #skipAtoms = (' HT1', ' HT2', ' HT3', ' 1HT', ' 2HT', ' 3HT', ' OXT',
        #            ' OT1', ' OT2', ' 1H', ' 2H', ' 3H')
        #ll = [x for x in failedAtoms
        #      if 'Q' not in x
        #      and not [x.endswith(y) for y in skipAtoms]]
        if ll:
            print(
                '## WARNING %s failed atoms. Unique, non-pesudo atoms are:' %
                len(failedAtoms), ', '.join(ll))

    if failedAtoms and doWarnings:
        msg = 'No equivalent molecular system atoms for PDB atoms: %s'
        showWarning('Warning', msg % (' '.join(failedAtoms)))

    if not ensemble.coordChains:
        ensemble.delete()
        ensemble = None

    return ensemble
Exemplo n.º 29
0
    def getOutputHandler(self, width, height, fonts=None):

        if not fonts:
            fonts = []
        else:
            fonts = list(fonts)

        for n in range(len(fonts)):
            if fonts[n] == 'Times':
                fonts[n] = 'Times-Roman'

        self.setOptionValues()

        if not self.file_name:
            showError('No file', 'No file specified', parent=self)
            return None

        if os.path.exists(self.file_name):
            if not showYesNo('File exists',
                             'File "%s" exists, overwrite?' % self.file_name,
                             parent=self):
                return None

        if (self.paper_type == Output.other_paper_type):
            paper_size = self.other_size + [self.other_unit]
        else:
            paper_size = paper_sizes[self.paper_type]
        output_scaling = self.scaling / 100.0

        font = 'Times-Roman'
        border_text = {}
        for decoration in self.border_decoration:
            if (decoration == 'Time & date'):
                location = 'se'
                text = time.ctime(time.time())
            elif (decoration == 'File name'):
                location = 'sw'
                text = self.file_name
            else:
                continue  # should not be here
            border_text[location] = (text, font, 12)
        if (self.title):
            location = 'n'
            border_text[location] = (self.title, font, 18)

        if font not in fonts:
            fonts.append(font)

        outputHandler = PrintHandler.getOutputHandler(
            self.file_name,
            width,
            height,
            output_scaling=output_scaling,
            paper_size=paper_size,
            paper_orientation=self.paper_orientation,
            output_style=self.output_style,
            output_format=self.output_format,
            border_text=border_text,
            fonts=fonts,
            do_outline_box=self.doOutlineBox)

        return outputHandler
Exemplo n.º 30
0
    def runDangle(self):

        chain = self.chain
        shiftList = self.shiftList

        if (not chain) or (not shiftList):
            showError('Cannot Run DANGLE',
                      'Please specify a chain and a shift list.',
                      parent=self)
            return

        # check if there is a DangleChain available
        self.checkDangleStore()
        dangleStore = self.dangleStore

        if not dangleStore:
            return

        dangleChain = dangleStore.findFirstDangleChain(chain=chain)
        if dangleChain:
            data = (chain.code, dangleChain.shiftList.serial)
            msg = 'Predictions for Chain %s using Shift List %d already exist.\nReplace data?' % data

            if not showYesNo('Replace Data', msg, parent=self):
                return

            else:
                self.dangleChain = dangleChain
                dangleChain.shiftList = shiftList

        else:
            self.dangleChain = dangleStore.newDangleChain(chain=chain,
                                                          shiftList=shiftList)

        #dangleStore.packageLocator.repositories[0].url.dataLocation = '/home/msc51/ccpn/NexusTestGI'
        #dangleStore.packageName = 'cambridge.dangle'

        repository = dangleStore.packageLocator.repositories[0]
        array = dangleStore.packageName.split('.')
        path = os.path.join(repository.url.dataLocation, *array)
        path = os.path.join(path, dangleStore.name,
                            chain.code)  # Dangle_dir/dangleStoreName/chainCode
        if not os.path.exists(path):
            os.makedirs(path)

        self.dangleDir = path

        inputFile = os.path.join(self.dangleDir, 'dangle_cs.inp')
        if os.path.isfile(inputFile):
            os.unlink(inputFile)

        outputFile = os.path.join(self.dangleDir, 'danglePred.txt')
        if os.path.isfile(outputFile):
            os.unlink(outputFile)

        numShift = self.makeDangleInput(inputFile, chain, shiftList)

        if not os.path.isfile(inputFile):
            msg = 'No DANGLE input has been generated.\nPlease check shift lists.'
            showError('File Does Not Exist', msg, parent=self)
            return
        if numShift == 0:
            msg = 'No shift data in input file.\nPerhaps shifts are not assigned.\nContinue prediction anyway?'
            if not showYesNo('Empty DANGLE input', msg, parent=self):
                return

        rejectThresh = self.rejectPulldown.getObject()

        # Use the Reference info from the main installation
        # location must be absolute because DANGLE could be run from anywhere
        location = os.path.dirname(dangleModule.__file__)

        progressBar = ProgressBar(self)
        self.update_idletasks()

        dangle = Dangle(location,
                        inputFile=inputFile,
                        outputDir=self.dangleDir,
                        reject=rejectThresh,
                        angleOnly=False,
                        progressBar=progressBar,
                        writePgm=False)

        #self.dangleDir = '/home/msc51/nexus/gItest/DanglePred/'
        #outputFile =  '/home/msc51/nexus/gItest/DanglePred/danglePred.txt'

        predictions = dangle.predictor.predictions
        gleScores = dangle.predictor.gleScores

        self.readPredictions(predictions, gleScores)
        self.updatePredictionMatrix()
Exemplo n.º 31
0
def findMatchingChain(molSystem,
                      ccpCodes,
                      excludeChains=None,
                      molTypes=None,
                      doWarning=True):
    """* * * Deprecated in light of findMathcingChains() * * * 
             Find the mol system chain that best matches the input ccpCodes
             (like three letter codes). Useful for trying to match structures
             to existing molecular data. Optional argument to specify which
             chains cannot be matched.
  .. describe:: Input
  
  MolSystem.MolSystem, List of Strings (MolSystem.MolResidue.ccpCodes),
             List of MolSystem.Chains

  .. describe:: Output
  
  Tuple of (MolSystem.Chain, Int (index of first matching ccpCode),
             Int (first matching MolSystem.Residue.seqId))
  """
    print("DEPRECATED, function findMatchingChain should not be used")

    chains = []
    for chain in molSystem.sortedChains():
        if excludeChains and (chain in excludeChains):
            continue

        sequence = []
        if not chain.residues:
            continue

        chains.append(chain)

        residues = []
        for residue in chain.sortedResidues():
            molType = residue.molType
            if molTypes and (molType not in molTypes):
                break

            residues.append((residue.seqId, residue))

        else:
            residues.sort()

            for residue in residues:
                sequence.append(residue[1].ccpCode)

            len0 = len(sequence)
            len1 = len(ccpCodes)

            if len0 < len1:
                continue

            elif len0 == len1:
                if sequence == ccpCodes:
                    mapping = [(i, residues[i][1]) for i in range(len0)]
                    return chain, mapping

                else:
                    misMatch = 0
                    for i in range(len0):
                        if (ccpCodes[i]
                                is not None) and (ccpCodes[i] != sequence[i]):
                            misMatch = 1
                            break
                    if misMatch:
                        continue
                    else:
                        mapping = [(i, residues[i][1]) for i in range(len0)]
                        return chain, mapping

            else:
                d = len0 - len1
                for x in range(d + 1):
                    misMatch = 0
                    for i in range(len1):
                        if (ccpCodes[i] is not None) and (ccpCodes[i] !=
                                                          sequence[i + x]):
                            misMatch = 1
                            break
                    if misMatch:
                        continue
                    else:
                        mapping = [(i, residues[i + x][1])
                                   for i in range(len1)]
                        return chain, mapping

    scoreList = []

    bestMapping = None
    bestScore = 0
    bestChain = None

    for chain in chains:
        mapping, score = getSequenceResidueMapping(chain, ccpCodes)
        scoreList.append((score, chain, mapping))

    if scoreList:
        scoreList.sort()
        bestScore, bestChain, bestMapping = scoreList[-1]

    chain = None
    if bestScore and (bestScore / float(len(bestChain.residues)) > 2.0):
        chain = bestChain

        if chain.molecule.molType in (
                CARBOHYDRATE_MOLTYPE):  # DNA & RNA now hopefully fine to align
            chain = None

        if doWarning:
            msg = 'Residue sequence matches an existing chain, but not exactly. '
            msg += 'Really link to chain %s? (Otherwise a new chain will be made)' % chain.code
            if not showYesNo('Query', msg):
                chain = None

    return chain, bestMapping