Exemple #1
0
    def setPeakFilePeakDimInfo(self):

        self.ppm.append(self.peakDim.getValue())

        #
        # Transfer assignment
        #

        peakDimContribs = self.peakDim.sortedPeakDimContribs()

        code3Letter = seqCode = atomName = ''

        if self.writeAssignments and peakDimContribs:

            if isinstance(peakDimContribs[0], Nmr.PeakDimContribN):
                print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored."
                return

            atomSetIds = []
            atomIds = []

            for peakDimContrib in peakDimContribs:

                resonance = peakDimContrib.resonance

                if resonance.resonanceSet:
                    code3Letter = resonance.resonanceSet.findFirstAtomSet(
                    ).findFirstAtom().residue.molResidue.chemComp.ccpCode
                    code3Letter = string.capitalize(code3Letter)

                else:
                    code3Letter = ""

                if self.resonanceToAtoms.has_key(resonance):

                    if self.useOriginalResNames:

                        if len(self.resonanceToAtoms[resonance]) > 1:
                            print "   Warning: Only first original resName taken for peak %d." % self.peak.serial

                        resonanceToAtom = self.resonanceToAtoms[resonance][0]

                        atomIds.append([
                            resonanceToAtom.chain.code, resonanceToAtom.seqId,
                            resonanceToAtom.atomName, None, code3Letter
                        ])

                    else:

                        for resonanceToAtom in self.resonanceToAtoms[
                                resonance]:

                            #
                            # Always keep track of single ones...
                            #

                            # Modified because cleanAtomNameLists needs atomId and atomSetId that compare
                            atomId = resonanceToAtom.getAtomId()
                            atomId[-1] = code3Letter

                            if atomId and atomIds.count(atomId) == 0:
                                atomIds.append(atomId)

                                #
                                # Check atomSet: use this if the same for all...
                                #

                                atomSetId = resonanceToAtom.getAtomSetId()

                                if atomSetId:
                                    atomSetId[-1] = code3Letter
                                else:
                                    atomSetId = None

                                atomSetIds.append(atomSetId)

            if len(atomIds) > 1 and self.compressResonances:
                # Replace atomId with single atomSetId for duplicates
                atomIds, atomSetIds = cleanAtomNameLists(atomIds, atomSetIds)

            chain = None

            if atomIds:
                chain, seqId, atomName, code3Letter = atomIds[0]

                if len(atomIds) > 1:
                    print "   Warning: Multiple assignment possibilities for peak %d - only first used." % self.peak.serial

            else:

                print "    Warning: no atom link for resonance %s" % getResNameText(
                    resonance)

            #
            # Use chain and seqcode mapping
            #

            if chain:

                #chainCode = self.chainDict[chain][0]
                seqCode = self.getExportSeqCode(
                    self.chainDict[chain][1],
                    chain.findFirstResidue(seqId=seqId))

        self.assignResNum.append(str(seqCode))
        self.assignRes.append(code3Letter)
        self.assignAtom.append(atomName)
Exemple #2
0
    def setPeakFilePeakDimInfo(self):

        point = self.peakDim.position

        self.points.append(point)

        if self.peakDim.positionError:
            self.pointsDev.append(self.peakDim.positionError)
        else:
            self.pointsDev.append(2)

        if self.useAliasing:
            ppm = self.peakDim.dataDimRef.pointToValue(point)
        else:
            ppm = self.peakDim.value

        self.ppm.append(ppm)

        self.hz.append((point * self.dataDimRef.dataDim.spectralWidth) /
                       self.dataDimRef.dataDim.numPoints)

        if self.peakDim.boxWidth:
            boxWidth = self.peakDim.boxWidth
        else:
            boxWidth = 1

        self.limits.append([int(point - boxWidth), int(point + boxWidth)])

        if self.peakDim.decayRate:
            fwhm_Hz = self.peakDim.decayRate
            fwhm = fwhm_Hz * self.dataDimRef.dataDim.numPoints / self.dataDimRef.dataDim.spectralWidth
        elif hasattr(self.peakDim, 'lineWidth') and self.peakDim.lineWidth:
            fwhm_Hz = self.peakDim.lineWidth
            fwhm = fwhm_Hz * self.dataDimRef.dataDim.numPoints / self.dataDimRef.dataDim.spectralWidth
        else:
            fwhm = 0
            fwhm_Hz = 0

        self.fwhm.append(fwhm)
        self.fwhm_Hz.append(fwhm_Hz)

        #
        # Transfer assignment - TODO: currently lose information on specific assignment (peakContrib) items here!
        #

        peakDimContribs = self.peakDim.peakDimContribs

        resNameText = ""

        if self.writeAssignments and peakDimContribs:

            resNames = []
            resonanceToAtoms = []

            for peakDimContrib in peakDimContribs:

                if isinstance(peakDimContrib, Nmr.PeakDimContribN):
                    print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored."
                    continue

                # get resonanceToAtoms
                ll = self.resonanceToAtoms.get(peakDimContrib.resonance)
                if ll is None:
                    print("  Can't handle resonance %s for peak %d" %
                          (getResNameText(
                              peakDimContrib.resonance), self.peak.serial))
                else:
                    resonanceToAtoms.extend(ll)

            #  sort, filter, and transform
            if self.presetResonanceMapping:
                nameInfo = filteredNameInfo(resonanceToAtoms, mode='preset')
            elif self.compressResonances:
                nameInfo = filteredNameInfo(resonanceToAtoms, mode='compress')
            else:
                nameInfo = filteredNameInfo(resonanceToAtoms)

            # make names

            #
            # Don't use chainCode for nmrDraw output
            # Using chain and seqCode mapping for output
            # Note that code same whether original res names
            # are being used or not...
            #

            for resonanceToAtom, atomName in nameInfo:

                chain = resonanceToAtom.chain
                seqId = resonanceToAtom.seqId

                seqCode = self.getExportSeqCode(
                    self.chainDict[chain][1],
                    chain.findFirstResidue(seqId=seqId))

                resName = str(seqCode) + tagSep + atomName

                if resName not in resNames:
                    resNames.append(resName)

            # Make resNameText
            resNameText = ','.join(resNames)

            ##
            ## Use atomSet if same for all (and more than one different contrib)
            ##

            #if (len(resNames) > 1 and len(resAtomSetNames) == 1
            #    and None not in resAtomSetNames and self.compressResonances):

            #  resNameText = string.join(resAtomSetNames,',')

            #else:

            #  resNameText = string.join(resNames,',')

        self.assignment += resNameText + ';'
Exemple #3
0
def duplicateResonances(nmrConstraintStore,format,mappingDict):
  
  #
  # Check which resonances have to be copied, and copy...
  #
  
  resonanceMappingDict = {}
  
  copyResonances = []
  resonanceDict = {}

  copyConstraints = []
  constrLinks = ['dihedralConstraints','chemShiftConstraints']

  copyConstraintItems = {}
  copyConstraintItemsList = []
  
  #
  # First determine which resonances are eligible for copying, and create a dictionary with resNames...
  #
  
  for resonance in nmrConstraintStore.sortedFixedResonances():
         
    applData = resonance.findFirstApplicationData(application = format, keyword = assign_kw)

    if applData:

      resName = applData.value
      
      resonanceDict[resName] = resonance

      (chain,seqCode,spinSystemId,seqInsertCode,atomName) = getNameInfo(resName)
              
      if mappingDict.has_key(chain):
        
        copyResonances.append(resonance)
        
  #
  # Then determine which constraint/items have to be copied (all resonances have to have the same chainCode!!)
  #
  
  for resonance in copyResonances:
    
    #
    # Constraints
    #

    for constrLink in constrLinks:
      for constr in getattr(resonance,constrLink):
        copyConstraint = 1
        for otherRes in constr.resonances:
          if otherRes not in copyResonances:
            copyConstraint = 0
            break
        
        if copyConstraint and constr not in copyConstraints:
          j = 0
          constrKey = (constr.parent.serial,constr.serial)
          for j in range(0,):
            if constrKey < (copyConstraints[j].parent.serial,copyConstraints[j].serial):
              copyConstraints.insert(j,constr)
              break
          listLen = len(copyConstraints)
          if j == (listLen - 1) or listLen == 0:
            copyConstraints.append(constr)
            

    #
    # ConstraintItems
    #

    for constrItem in resonance.sortedPairwiseConstraintItems():

      copyConstraintItem = 1
      for otherRes in constrItem.resonances:
        if otherRes not in copyResonances:
          copyConstraintItem = 0
          break

      if copyConstraintItem:
        if not copyConstraintItems.has_key(constrItem.constraint):
          copyConstraintItems[constrItem.constraint] = []
          j = 0

          constrKey = (constrItem.constraint.parent.serial,constrItem.constraint.serial)

          for j in range(0,len(copyConstraintItemsList)):
            if constrKey < (copyConstraintItemsList[j].parent.serial,copyConstraintItemsList[j].serial):
              copyConstraintItemsList.insert(j,constrItem.constraint)
              break
          listLen = len(copyConstraintItemsList)
          #print constrKey, j, listLen
          if j == (listLen - 1) or listLen == 0:
            copyConstraintItemsList.append(constrItem.constraint)

        if constrItem not in copyConstraintItems[constrItem.constraint]:
          copyConstraintItems[constrItem.constraint].append(constrItem)

  #
  # Now copy the resonances or find an existing resonance...
  #
  
  for resonance in copyResonances:
         
    applData = resonance.findFirstApplicationData(application = format, keyword = assign_kw)
    applDataClass = applData.__class__

    resName = applData.value

    (chain,seqCode,spinSystemId,seqInsertCode,atomName) = getNameInfo(resName)
      
    resonanceMappingDict[resonance] = {}
    
    resonance.removeApplicationData(applData)
    
    newValue = getResName(mappingDict[chain][0],seqCode,atomName,seqInsertCode = seqInsertCode)
    resonance.addApplicationData(applDataClass(application = format, keyword = assign_kw, value = newValue))

    for i in range(1,len(mappingDict[chain])):

      newChainCode = mappingDict[chain][i]
      newResName = getResName(newChainCode,seqCode,atomName,seqInsertCode = seqInsertCode)
      
      if resonanceDict.has_key(newResName):
        newResonance = resonanceDict[newResName]
        print "  Using existing resonance %s..." % newResName

      else:

        print "  Creating new resonance %s..." % newResName

        newResonance = nmrConstraintStore.newFixedResonance(isotopeCode = resonance.isotopeCode)
        resonanceDict[newResName] = newResonance

        copyResonanceInfo(resonance,newResonance,toResName = newResName)

        applData = newResonance.findFirstApplicationData(application = format, keyword = assign_kw)
        applDataClass = applData.__class__

        newResonance.removeApplicationData(applData)
        newResonance.addApplicationData(applDataClass(application = format, keyword = assign_kw, value = newResName))

        #
        # Constraints and constraint items have to be deleted and recreated later...
        #
        
        for constrLink in constrLinks:
          for constr in getattr(newResonance,constrLink):
            constr.delete()

        for constrItem in newResonance.pairwiseConstraintItems:
          constrItem.delete()

      resonanceMappingDict[resonance][newChainCode] = newResonance

  #
  # Loop over the 'new' chain codes...
  #
  
  print
  print "########################## "
  print "# Duplicating resonances # "
  print "########################## "
  print
  
  for i in range(1,len(mappingDict[chain])):

    newChainCode = mappingDict[chain][i]
  
    #
    # Copy the relevant dihedral constraints...
    #

    for constraint in copyConstraints:
    
      print "  Copying constraint %d.%d" % (constraint.parent.serial,constraint.serial)
      print "    Resonances %s" % ', '.join([getResNameText(res) for res in constraint.resonances])

      (newResonances, oldToNewResonanceDict) = getMappedResonances(constraint,resonanceMappingDict,newChainCode)
      
      print "            to %s" % ', '.join([getResNameText(res) for res in newResonances])

      newConstr = constraint.__class__(constraint.parent,resonances = newResonances)
      copyAttributeInfo(constraint,newConstr)

      for constrItem in constraint.sortedItems():

        newConstrItem = constrItem.__class__(newConstr, upperLimit = 1.0, lowerLimit = 0.0)
        copyAttributeInfo(constrItem,newConstrItem)
      
      print

    #
    # ..and the constraints from the relevant constraintItems...
    #

    for constraint in copyConstraintItemsList:
   
      print "  Copying constraint %d.%d" % (constraint.parent.serial,constraint.serial)

      newConstr = constraint.__class__(constraint.parent)
      copyAttributeInfo(constraint,newConstr)
      
      if hasattr(constraint,'weight'):
        newConstr.weight = constraint.weight

      for constrItem in constraint.sortedItems():
        print "    Copying item with resonances %s" %  ', '.join([getResNameText(res) for res in constrItem.resonances])
      
        if constrItem in copyConstraintItems[constraint]:

          (newResonances, oldToNewResonanceDict) = getMappedResonances(constrItem,resonanceMappingDict,newChainCode)
        
        else:
        
          newResonances = constrItem.resonances
          oldToNewResonanceDict = {}

      
        print "                              to %s" % ', '.join([getResNameText(res) for res in newResonances])

        newConstrItem = constrItem.__class__(newConstr,resonances = newResonances)

        if constrItem.className in ('DistanceConstraintItem', 'HBondConstraintItem', 'JCouplingConstraintItem', 'RdcConstraintItem'):
          firstResonance = constrItem.firstResonance
          if oldToNewResonanceDict:
            firstResonance = oldToNewResonanceDict[firstResonance] 

          newConstrItem.firstResonance = firstResonance
 
        copyAttributeInfo(constrItem,newConstrItem)
      
      print

  print "###################### "
  print "# End of duplication # "
  print "###################### "
  print
Exemple #4
0
    def setPeakFilePeakDimInfo(self):

        ppm = self.peakDim.getValue()

        if self.peakDim.boxWidth:
            boxWidth = self.peakDim.boxWidth * self.dataDimRef.valuePerPoint
        else:
            boxWidth = 0.05

        if self.peakDim.decayRate:
            decayRate = self.peakDim.decayRate * self.dataDimRef.valuePerPoint  # TODO: this is NOT correct - shouldn't be stored in points in data model
        else:
            decayRate = 0.05

        self.ppm.append(ppm)
        self.box.append(boxWidth)
        self.width.append(decayRate)
        self.shape.append(
            '?')  # TODO: if appldata for nmrView, get from there?

        #
        # Transfer assignment. Code by Gary Thompson, should handle NmrView correctly!
        #

        peakDim = self.peakDim.dim
        peakDimContribSets = []

        for peakContrib in self.peakDim.peak.sortedPeakContribs():

            if len(peakContrib.peakDimContribs) == 0:
                continue

            peakDimContribSet = []
            peakDimContribSets.append(peakDimContribSet)

            for peakDimContrib in peakContrib.peakDimContribs:
                if peakDimContrib.dim == peakDim:
                    peakDimContribSet.append(peakDimContrib)

        resNameTexts = []
        for peakDimContribs in peakDimContribSets:

            if self.writeAssignments and peakDimContribs != ():

                resNames = []
                resAtomSetNames = []

                for peakDimContrib in peakDimContribs:

                    if isinstance(peakDimContrib, Nmr.PeakDimContribN):
                        print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored for peak %d " % self.peakDim.peak.serial
                        continue

                    resNameText = ""
                    resonance = peakDimContrib.resonance
                    resName = None

                    if self.resonanceToAtoms.has_key(resonance):

                        for resonanceToAtom in self.resonanceToAtoms[
                                resonance]:

                            #theough
                            # Don't use chainCode for nmrView output
                            # Using chain and seqCode mapping for output
                            # Note that code same whether original res names
                            # are being used or not...
                            #

                            chain = resonanceToAtom.chain
                            seqId = resonanceToAtom.seqId

                            seqCode = self.getExportSeqCode(
                                self.chainDict[chain][1],
                                chain.findFirstResidue(seqId=seqId))

                            resName = str(
                                seqCode) + tagSep + resonanceToAtom.atomName

                            if resName not in resNames:
                                resNames.append(resName)

                            #
                            # Also check atomSet: use this if the same for all...
                            #

                            atomSetId = resonanceToAtom.getAtomSetId()

                            if atomSetId:

                                atomName = atomSetId[2]

                                resName = str(seqCode) + tagSep + atomName

                                if resName not in resAtomSetNames:
                                    resAtomSetNames.append(resName)

                    if not resName:
                        print "  Can't handle resonance %s for peak %d" % (
                            getResNameText(resonance), self.peak.serial)

                #
                # Use atomSet if same for all (and more than one different contrib)
                #

                #print resNames,resNameText
                resNameText = ""

                if len(resNames) > 1 and len(
                        resAtomSetNames) == 1 and self.compressResonances:
                    resNameText = self.assignTagSep.join(resAtomSetNames)
                elif len(resNames) > 0:
                    resNameText = self.assignTagSep.join(resNames)

                if len(resNames) > 1:
                    resNameText = "{%s}" % resNameText

                resNameTexts.append(resNameText)

        result = " ".join(resNameTexts)

        if len(result) == 0:
            result = "?"

        self.assign.append(result)
Exemple #5
0
    def setPeakFilePeakDimInfo(self):

        point = self.peakDim.position

        self.points.append(point)

        if self.peakDim.positionError:
            self.pointsDev.append(self.peakDim.positionError)
        else:
            self.pointsDev.append(2)

        if self.useAliasing:
            ppm = self.peakDim.dataDimRef.pointToValue(point)
        else:
            ppm = self.peakDim.value

        self.ppm.append(ppm)

        self.hz.append((point * self.dataDimRef.dataDim.spectralWidth) /
                       self.dataDimRef.dataDim.numPoints)

        if self.peakDim.boxWidth:
            boxWidth = self.peakDim.boxWidth
        else:
            boxWidth = 1

        self.limits.append([int(point - boxWidth), int(point + boxWidth)])

        if self.peakDim.decayRate:
            fwhm_Hz = self.peakDim.decayRate
            fwhm = fwhm_Hz * self.dataDimRef.dataDim.numPoints / self.dataDimRef.dataDim.spectralWidth
        else:
            fwhm = 0
            fwhm_Hz = 0

        self.fwhm.append(fwhm)
        self.fwhm_Hz.append(fwhm_Hz)

        #
        # Transfer assignment - TODO: currently lose information on specific assignment (peakContrib) items here!
        #

        peakDimContribs = self.peakDim.peakDimContribs

        resNameText = ""

        if self.writeAssignments and peakDimContribs != ():

            resNames = []
            resAtomSetNames = []

            for peakDimContrib in peakDimContribs:

                if isinstance(peakDimContrib, Nmr.PeakDimContribN):
                    print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored."
                    continue

                resonance = peakDimContrib.resonance
                resName = None

                if self.resonanceToAtoms.has_key(resonance):

                    for resonanceToAtom in self.resonanceToAtoms[resonance]:

                        #
                        # Don't use chainCode for nmrView output
                        # Using chain and seqCode mapping for output
                        # Note that code same whether original res names
                        # are being used or not...
                        #

                        chain = resonanceToAtom.chain
                        seqId = resonanceToAtom.seqId

                        seqCode = self.getExportSeqCode(
                            self.chainDict[chain][1],
                            chain.findFirstResidue(seqId=seqId))

                        resName = str(
                            seqCode) + tagSep + resonanceToAtom.atomName

                        if resName not in resNames:
                            resNames.append(resName)

                        #
                        # Also check atomSet: use this if the same for all...
                        #

                        atomSetId = resonanceToAtom.getAtomSetId()

                        if atomSetId:

                            atomName = atomSetId[2]

                            resName = str(seqCode) + tagSep + atomName

                            if resName not in resAtomSetNames:
                                resAtomSetNames.append(resName)

                if not resName:
                    print "  Can't handle resonance %s" % getResNameText(
                        resonance)

            #
            # Use atomSet if same for all (and more than one different contrib)
            #

            if len(resNames) > 1 and len(
                    resAtomSetNames) == 1 and self.compressResonances:

                resNameText = string.join(resAtomSetNames, ',')

            else:

                resNameText = string.join(resNames, ',')

        self.assignment += resNameText + ';'
Exemple #6
0
    def resetAromaticAssignments(self, nmrConstraintStore, structureEnsemble):
        """
    Input:
    
    nmrConstraintStore
    structureEnsemble
    
    Will reset badly set aromatic assigments
    
    """

        print "\n### Resetting aromatic assignments ###\n"

        if not structureEnsemble:
            print "  Error no structureEnsemble available - aborting"
            return

        models = structureEnsemble.sortedModels()

        if not models:
            print "  Error no structureEnsemble models available for structure ensemble - aborting"
            return

        refMolStructure = models[0]
        molSystem = structureEnsemble.molSystem

        for chain in molSystem.sortedChains():
            for aromResName in ['Phe', 'Tyr']:
                aromResidues = chain.findAllResidues(ccpCode=aromResName)

                for aromRes in aromResidues:
                    for aromProtonGroup in [('HD1', 'HD2'), ('HE1', 'HE2')]:
                        for i in range(0, 2):
                            aromProtonName = aromProtonGroup[i]
                            aromProton = aromRes.findFirstAtom(
                                name=aromProtonName)

                            atomSet = aromProton.findFirstFixedAtomSet(
                                nmrConstraintStore=nmrConstraintStore)

                            #
                            # Assuming that only one resonanceSet for the atomSet!
                            #

                            if atomSet and atomSet.resonanceSets:

                                otherAromProtonName = aromProtonGroup[not i]
                                otherAromProton = aromRes.findFirstAtom(
                                    name=otherAromProtonName)

                                otherAtomSet = otherAromProton.findFirstFixedAtomSet(
                                    nmrConstraintStore=nmrConstraintStore)

                                if otherAtomSet:
                                    if otherAtomSet != atomSet:

                                        if otherAtomSet.resonanceSets and otherAtomSet.resonanceSets != atomSet.resonanceSets:
                                            resonanceSet = atomSet.sortedResonanceSets(
                                            )[0]
                                            otherResonances = otherAtomSet.sortedResonanceSets(
                                            )[0].sortedResonances()
                                            otherAtomSet.sortedResonanceSets(
                                            )[0].delete()
                                            for otherResonance in otherResonances:
                                                resonanceSet.addResonance(
                                                    otherResonance)
                                                print "  Warning: moved aromatic resonance %s to joined resonanceSet..." % getResNameText(
                                                    otherResonance)

                                        atomSet.addAtom(otherAromProton)
                                        otherAtomSet.delete()
                                        print "  Warning: made joined atomSet for atoms '%s' and '%s'..." % (
                                            getAtomNameText(aromProton),
                                            getAtomNameText(otherAromProton))
                                        break

                                    else:
                                        break

                                else:
                                    atomSet.addAtom(otherAromProton)
                                    print "  Warning: added atom '%s' to joined atomSet..." % (
                                        getAtomNameText(otherAromProton))
Exemple #7
0
def createChemShifts(peakLists,
                     guiParent=None,
                     messageReporter=None,
                     multiDialog=None,
                     shiftList=None,
                     useAllContribs=1,
                     defaultShiftError=None,
                     shiftListName='None'):

    #
    # Set up GUI or non-GuI user interaction if not passed in
    #

    if not messageReporter:
        messageReporter = setupMessageReporter(guiParent)

    if not multiDialog:
        multiDialog = setupMultiDialog(guiParent)

    #
    # Initial checks
    #

    if not peakLists:
        messageReporter.showError("Error", "No peaklist(s) provided.")
        return False

    for peakList in peakLists:
        if not isinstance(peakList, Nmr.PeakList):
            messageReporter.showError("Error", "Invalid peaklist provided.")
            return False

    #
    # Initialize some stuff
    #

    if not defaultShiftError:
        defaultShiftError = {}

    for (nucl, defValue) in (('1H', 0.002), ('13C', 0.1), ('15N', 0.1)):
        if not defaultShiftError.has_key(nucl):
            defaultShiftError[nucl] = defValue

    proj = peakLists[0].root

    resonanceChemShifts = {}

    experiments = []

    #
    # Read the chemshifts and link them to the relevant resonances
    #

    for peakList in peakLists:

        if peakList.dataSource.experiment not in experiments:
            experiments.append(peakList.dataSource.experiment)

        for peak in peakList.sortedPeaks():

            for peakDim in peak.sortedPeakDims():

                chemShift = peakDim.value

                peakDimContribs = tuple(peakDim.peakDimContribs)
                if useAllContribs == 0 and len(peakDimContribs) > 1:

                    #
                    # First check if resonances for contribs connected through one resonanceSet
                    # If so, then set values anyway.
                    #

                    resonanceSet = peakDimContribs[0].resonance.resonanceSet

                    sameShiftGroup = 1

                    if resonanceSet:

                        resonanceSetResonances = resonanceSet.sortedResonances(
                        )

                        for peakDimContrib in peakDimContribs[1:]:

                            if peakDimContrib.resonance not in resonanceSetResonances:
                                sameShiftGroup = 0
                                break

                    if not sameShiftGroup:

                        #
                        # Ignore this peakDim - many contribs possible and not wanted (?)
                        #

                        print "  Warning: ignoring peakDim %d for peak %d... more than one resonance contribution" % (
                            peakDim.dim, peak.serial)
                        continue

                for peakDimContrib in peakDimContribs:

                    resonance = peakDimContrib.resonance

                    if not resonanceChemShifts.has_key(resonance):
                        resonanceChemShifts[resonance] = []

                    resonanceChemShifts[resonance].append(chemShift)

    #
    # Make a new chemical shift list if none passed in
    #

    if shiftList == None:
        shiftList = Nmr.ShiftList(proj.currentNmrProject,
                                  name=shiftListName,
                                  unit='ppm',
                                  experiments=experiments)

    #
    # Get the average (and standard dev) of the chemical shift for each resonance
    # Create the chemical shifts
    #

    for resonance in resonanceChemShifts.keys():

        chemShiftTotal = 0.0

        for chemShift in resonanceChemShifts[resonance]:

            chemShiftTotal += chemShift

        chemShiftAverage = chemShiftTotal / len(resonanceChemShifts[resonance])

        standardDev = getStandardDev(resonanceChemShifts[resonance],
                                     chemShiftTotal)

        if standardDev == None:
            if defaultShiftError.has_key(resonance.isotopeCode):
                shiftError = defaultShiftError[resonance.isotopeCode]
            else:
                shiftError = 0.1

        else:
            shiftError = standardDev * 2

        #
        # Set the chemical shift value
        #

        shift = shiftList.findFirstMeasurement(resonance=resonance)

        if not shift:
            Nmr.Shift(shiftList,
                      value=chemShiftAverage,
                      error=shiftError,
                      resonance=resonance)
        else:
            allowedErrorMargin = shiftError / 10
            if shift.value + allowedErrorMargin < chemShiftAverage or chemShiftAverage < shift.value - allowedErrorMargin:
                resName = getResNameText(resonance)
                multiDialog.MeasurementSelect(guiParent, resName, resonance,
                                              chemShiftAverage, shiftList,
                                              'Shift')

    return shiftList
Exemple #8
0
  def checkSwapsAndClean(self,method = 'SUM_AVERAGING', violationCodes = None, swapFraction = 0.75):
  
    if not self.distanceConstraintLists or not self.structureEnsemble or not self.structureEnsemble.models:
      print "Error: no constraint lists or no structures available! Aborting..."
      return
  
    print
    print "Checking swap status and cleaning prochiral groups in constraint lists..."
    print
    
    #
    # Initialize... see parameters above for swapFraction
    #
    # Set a dictionary with violationCodes (what is a large violation?)
    #
    
    if violationCodes:
      self.violationCodes = violationCodes
      
    else:
      self.violationCodes = {}
      self.violationCodes['xl'] = {'violation': 2.0, 'fraction': 0.00001}
      self.violationCodes['l'] = {'violation': 1.0, 'fraction': 0.5}
  
    #
    # Set up a dict of resonances
    # TODO: Should this be done in cleanStereoAssignments?!?
    #       Should I make this a 'violationHandler' class??!?!
    #

    (self.resAtomDict,self.resAtomSetDict) = createResonanceAtomAndAtomSetDict(self.distanceConstraintLists[0].parent.fixedResonances)    
    if self.verbose:
      print "Made resAtomDict, resAtomSetDict"
  
    (self.resAtomSwapDict,self.prochiralResonancesDict) = createResAtomSwapDict(self.resAtomSetDict)
    if self.verbose:
      print "Made resAtomSwapDict,prochiralResonancesDict"
  
    structureViolations = []
  
    """
    infoStrings = []
    for resonance in resAtomSwapDict.keys():
      atoms = resAtomDict[resonance]
      infoString = "%3d.%s" % (atoms[0].residue.seqId, atoms[0].atomSet.name)
      atoms = resAtomSwapDict[resonance]
      infoString += "-> swap is %3d.%s" % (atoms[0].residue.seqId, atoms[0].name)
      infoStrings.append(infoString)
    infoStrings.sort()
    for infoString in infoStrings:
      print infoString
    """

    #
    # Set the factor for calculating violations
    #

    if method == 'SUM_AVERAGING':
      factor = 1.0/6.0
    
    #
    # Loop over the structures
    #
    
    self.models = self.structureEnsemble.sortedModels()
    #self.models = self.models[:3]
    for model in self.models:

      self.prochiralViolationDict = self.createProchiralViolationDict()
    
      #violationList = Nmr.ViolationList(distanceConstraintLists[0].structureGeneration,molStructures = [model])
    
      totalViols = 0
    
      #
      # Set up dict for coordinates
      #
    
      self.atomCoordDict = {}
      
      # No need for sorting here...
      for cChain in self.structureEnsemble.coordChains:
        for cRes in cChain.residues:
          for cAtom in cRes.atoms:
            if cAtom.atom:
          
              #
              # TODO: cannot handle multiple coords for one atom!!
              #
            
              self.atomCoordDict[cAtom.atom] = model.findFirstCoord(atom = cAtom)
              
      if self.verbose:
        print "Made atomCoordDict for model %d" % model.serial
    
      #
      # Go over the distance constraints
      #
    
      for distanceConstraintList in self.distanceConstraintLists:
    
        for distConstr in distanceConstraintList.sortedConstraints():
        
          # TODO: extend to other methods?

          if method == 'SUM_AVERAGING':

            #
            # Calculate sum averaged distance (Nilges et al., Proteins 17, 297-309, 1993)
            #

            (avgDist,prochiralContribs) = getDistConstrSumAvg(distConstr,self.resAtomDict,self.atomCoordDict,factor,self.resAtomSwapDict,self.prochiralResonancesDict)
            totalViols += self.setViolationDict(avgDist,prochiralContribs,distConstr,'orig')

            #
            # Now do the same but for the swap...
            #

            if prochiralContribs:
              (avgDist,prochiralContribs) = getDistConstrSumAvg(distConstr,self.resAtomDict,self.atomCoordDict,factor,self.resAtomSwapDict,self.prochiralResonancesDict,swap = True)
              self.setViolationDict(avgDist,prochiralContribs,distConstr,'swap')
            
      structureViolations.append(self.prochiralViolationDict)
      
      if self.verbose:
        print "Total violations %d" % totalViols

    #
    # Check if whether original or swap state was the best...
    #

    prochiralSwaps = {}

    for i in range(0,len(structureViolations)):
      prochiralViolationDict = structureViolations[i]

      for prochiralKey in prochiralViolationDict['orig']['total']:

        #
        # Calculate total violation over all structures for swapping...
        #

        if prochiralViolationDict['orig']['total'][prochiralKey] > prochiralViolationDict['swap']['total'][prochiralKey]:
          if not prochiralSwaps.has_key(prochiralKey):
            prochiralSwaps[prochiralKey] = 0
          prochiralSwaps[prochiralKey] += 1
      
  
    #
    # Finally make the changes in the data model where appropriate
    #

    cutoff = swapFraction * len(structureViolations)
    infoText = []
    
    totalStructures = len(self.models)

    for prochiralKey in prochiralViolationDict['orig']['total']:
      
      #
      # Set the swapstatus
      #
      
      if prochiralSwaps.has_key(prochiralKey) and prochiralSwaps[prochiralKey] > cutoff:
        swapStatus = 'swap'
        percent = prochiralSwaps[prochiralKey] * 100 / len(structureViolations)
        infoText.append("Swapping stereo assignment status chain %s, residue %3d group %s: %.3f%%" % (prochiralKey[0],prochiralKey[1],prochiralKey[2].name,percent))

      else:
        swapStatus = 'orig'

      #
      # Check for constraints with large violations based on the swap state...
      #
      
      constraintItemsReset = []

      for violationCode in self.violationCodes.keys():
      
        constraintsViolated = {}
        cutoffFraction = self.violationCodes[violationCode]['fraction']
        
        #
        # Again look over all structures
        #
        
        for prochiralViolationDict in structureViolations:
          for distConstr in prochiralViolationDict[swapStatus][violationCode][prochiralKey].keys():
            if not constraintsViolated.has_key(distConstr):
              constraintsViolated[distConstr] = [0.0,[]]         
            constraintsViolated[distConstr][0] += 1.0
            
            for constrItem in prochiralViolationDict[swapStatus][violationCode][prochiralKey][distConstr][1]:
              if constrItem not in constraintsViolated[distConstr][1]:
                constraintsViolated[distConstr][1].append(constrItem)
        
        #
        # Then recalculate and add a constraint item if necessary
        #
        
        distConstraints = constraintsViolated.keys()
        distConstraints.sort()
        
        for distConstr in distConstraints:

          fractionViolated = constraintsViolated[distConstr][0] / totalStructures
          #print prochiralKey, violationCode, fractionViolated 
          if fractionViolated >= cutoffFraction:

            prochiralResonances = []
            for resonance in self.prochiralResonancesDict.keys():
              if self.prochiralResonancesDict[resonance] == prochiralKey:
                prochiralResonances.append(resonance)
            
            #
            # Have to make a new prochiral resonance if there's only one!!
            #
            
            if len(prochiralResonances) == 1:
            
              otherProchiralResonance = NmrConstraint.FixedResonance(self.nmrConstraintStore, isotopeCode = prochiralResonances[0].isotopeCode)
              otherAtoms = self.resAtomSwapDict[prochiralResonances[0]]
              if otherAtoms[0].atomSet:
                otherAtomSet = otherAtoms[0].atomSet
              else:
                otherAtomSet = NmrConstraint.FixedAtomSet(self.nmrConstraintStore,atoms = otherAtoms)

              otherProchiralResonanceSet = NmrConstraint.FixedResonanceSet(self.nmrConstraintStore, resonances = [otherProchiralResonance], atomSets = [otherAtomSet])

              prochiralResonances.append(otherProchiralResonance)
              self.prochiralResonancesDict[otherProchiralResonance] = prochiralKey
            
            violatedItems = constraintsViolated[distConstr][1]
            
            for violatedItem in violatedItems:
              
              #
              # Don't redo the item if it was already reset..
              #
              
              if (prochiralKey,violatedItem) in constraintItemsReset:
                continue
                
              violatedResonances = getResonancesFromPairwiseConstraintItem(violatedItem)
              
              for resonance in prochiralResonances:
                if resonance in violatedResonances:
                  otherResonanceIndex = not violatedResonances.index(resonance)
                  otherResonance = violatedResonances[otherResonanceIndex]
                  
                  otherProchiralResonance = prochiralResonances[not prochiralResonances.index(resonance)]
                  
                  # Put these the wrong way around on purpose!
                  if otherResonanceIndex == 1:
                    newResonances = [otherResonance,otherProchiralResonance]
                  else:
                    newResonances = [otherProchiralResonance,otherResonance]
                    
                  break
                  
              constraintExists = distConstr.findFirstItem(resonances = tuple(newResonances))
              
              if not constraintExists:
                newResonances.reverse()
                
                constraintExists = distConstr.findFirstItem(resonances = tuple(newResonances))
                
                if not constraintExists and newResonances[0] != newResonances[1]:
                  
                  NmrConstraint.DistanceConstraintItem(distConstr,resonances = newResonances)
                  
                  prochiralText = "%s.%d.%s" % (prochiralKey[0],prochiralKey[1],prochiralKey[2].name)
                  infoLine = "Deassigned constraint %d to prochiral %s: violation > %.1f in %.1f%% of structures.\n" % (distConstr.serial,prochiralText,self.violationCodes[violationCode]['violation'],fractionViolated * 100)
                  infoLine += "   --> added new item for '%s' to '%s'" % (getResNameText(newResonances[0]),getResNameText(newResonances[1]))
                  infoText.append(infoLine)
                  
                  constraintItemsReset.append((prochiralKey,violatedItem))
      
      #
      # Reset based on swapStatus
      #

      if swapStatus == 'swap':

        #
        # Switch the assignments...
        #

        prochiralResonances = []
        for resonance in self.prochiralResonancesDict.keys():
          if self.prochiralResonancesDict[resonance] == prochiralKey:
            prochiralResonances.append(resonance)

        if len(prochiralResonances) == 2:
        
          resSet1 = prochiralResonances[0].resonanceSet
          atomSet1 = resSet1.sortedAtomSets()[0]
          resSet2 = prochiralResonances[1].resonanceSet
          atomSet2 = resSet2.sortedAtomSets()[0]

          resSet1.addAtomSet(atomSet2)
          resSet1.removeAtomSet(atomSet1)
          resSet2.addAtomSet(atomSet1)
          resSet2.removeAtomSet(atomSet2)

        else:
          resSet = prochiralResonances[0].resonanceSet
          atomSet1 = resSet.sortedAtomSets()[0]

          otherAtoms = self.resAtomSwapDict[prochiralResonances[0]]
          if otherAtoms[0].atomSet:
            otherAtomSet = otherAtoms[0].atomSet
          else:
            otherAtomSet = NmrConstraint.FixedAtomSet(self.nmrConstraintStore,atoms = otherAtoms)

          resSet.addAtomSet(otherAtomSet)
          resSet.removeAtomSet(atomSet1)

    infoText.sort()
    for line in infoText:
      print line
Exemple #9
0
    def setPeakFilePeakDimInfo(self):

        ppm = self.peakDim.getValue()

        if self.peakDim.decayRate:
            decayRate = self.peakDim.decayRate * self.dataDimRef.valuePerPoint  # TODO: this is NOT correct - shouldn't be stored in points in data model
        else:
            decayRate = None

        self.ppm.append(ppm)
        self.widths.append(decayRate)

        #
        # Transfer assignment
        #

        peakDimContribs = self.peakDim.peakDimContribs

        resNameText = ""

        if self.writeAssignments and peakDimContribs != ():

            resNames = []
            resAtomSetNames = []

            for peakDimContrib in peakDimContribs:

                if isinstance(peakDimContrib, Nmr.PeakDimContribN):
                    print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored."
                    continue

                resonance = peakDimContrib.resonance
                resName = None

                if self.resonanceToAtoms.has_key(resonance):

                    for resonanceToAtom in self.resonanceToAtoms[resonance]:

                        #
                        # Don't use chainCode for sparky output
                        # Using chain and seqCode mapping for output
                        # Note that code same whether original res names
                        # are being used or not...
                        #

                        chain = resonanceToAtom.chain
                        seqId = resonanceToAtom.seqId

                        seqCode = self.getExportSeqCode(
                            self.chainDict[chain][1],
                            chain.findFirstResidue(seqId=seqId))
                        residueLabel = self.getResidueLabelOneLetter(
                            resonanceToAtom)

                        resName = residueLabel + str(
                            seqCode) + resonanceToAtom.atomName

                        if resName not in resNames:
                            resNames.append(resName)

                        #
                        # Also check atomSet: use this if the same for all...
                        #

                        atomSetId = resonanceToAtom.getAtomSetId()

                        if atomSetId:

                            atomName = atomSetId[2]

                            resName = residueLabel + str(seqCode) + atomName

                            if resName not in resAtomSetNames:
                                resAtomSetNames.append(resName)

                if not resName:

                    print "  Can't handle resonance %s" % getResNameText(
                        resonance)

            #
            # Use atomSet if same for all (and more than one different contrib)
            #

            if len(resNames) > 1 and len(
                    resAtomSetNames) == 1 and self.compressResonances:

                resNameText = resAtomSetNames[0]

            elif resNames:

                resNameText = resNames[0]

                if len(resNames) > 1:
                    print "  Warning: Multiple assignments currently not supported for %s. Only using first one." % self.format

        self.assign.append(resNameText)
Exemple #10
0
    def setPeakFilePeakDimInfo(self):

        ppm = self.peakDim.getValue()

        if self.peakDim.boxWidth:
            boxWidth = self.peakDim.boxWidth * self.dataDimRef.valuePerPoint
        else:
            boxWidth = 0.05

        if self.peakDim.decayRate:
            decayRate = self.peakDim.decayRate * self.dataDimRef.valuePerPoint  # TODO: this is NOT correct - shouldn't be stored in points in data model
        else:
            decayRate = 0.05

        self.ppm.append(ppm)
        self.box.append(boxWidth)
        self.width.append(decayRate)
        self.shape.append(
            '?')  # TODO: if appldata for nmrView, get from there?

        #
        # Transfer assignment. Code by Gary Thompson, should handle NmrView correctly!
        #
        # Refactored by rasmus fogh, July 2012
        #

        resNameTexts = []
        peakContribs = self.peakDim.peak.sortedPeakContribs()

        if (self.writeAssignments
                and not (self.skipMultiAssignments and len(peakContribs) > 1)):

            peakDim = self.peakDim.dim
            peakDimContribSets = []

            for peakContrib in peakContribs:

                if len(peakContrib.peakDimContribs) == 0:
                    continue

                peakDimContribSet = []
                peakDimContribSets.append(peakDimContribSet)

                for peakDimContrib in peakContrib.peakDimContribs:
                    if peakDimContrib.dim == peakDim:
                        peakDimContribSet.append(peakDimContrib)

            # get and filter resonanceToAtoms
            for peakDimContribs in peakDimContribSets:
                # loop over contribs

                if not peakDimContribs:
                    continue

                resonanceToAtoms = []
                for peakDimContrib in peakDimContribs:
                    ll = self.resonanceToAtoms.get(peakDimContrib.resonance)
                    if ll is None:
                        print("  Can't handle resonance %s for peak %d" %
                              (getResNameText(
                                  peakDimContrib.resonance), self.peak.serial))
                    else:
                        resonanceToAtoms.extend(ll)

                #  sort, filter, and transform
                if self.presetResonanceMapping:
                    nameInfo = filteredNameInfo(resonanceToAtoms,
                                                mode='preset')
                elif self.compressResonances:
                    nameInfo = filteredNameInfo(resonanceToAtoms,
                                                mode='compress')
                else:
                    nameInfo = filteredNameInfo(resonanceToAtoms)

                # now get names
                resNames = []
                for resonanceToAtom, atomName in nameInfo:
                    chain = resonanceToAtom.chain
                    seqId = resonanceToAtom.seqId
                    seqCode = self.getExportSeqCode(
                        self.chainDict[chain][1],
                        chain.findFirstResidue(seqId=seqId))
                    resName = str(seqCode) + tagSep + atomName
                    resNames.append(resName)
                resNames.sort()

                if not (len(resNames) > 1 and self.skipMultiAssignments):

                    # Make resNameText
                    resNameText = self.assignTagSep.join(resNames)

                    if len(resNames) > 1:
                        #if lenResNames > 1 and len(peakDimContribSets) > 1: # NBNB Rasmus try-out
                        resNameText = "{%s}" % resNameText

                    resNameTexts.append(resNameText)

        result = " ".join(resNameTexts)

        if not result.strip():
            result = "?"

        self.assign.append(result)
Exemple #11
0
    def setPeakFilePeakDimInfo(self):

        ppm = self.peakDim.getValue()

        if self.peakDim.decayRate:
            decayRate = self.peakDim.decayRate * self.dataDimRef.valuePerPoint  # TODO: this is NOT correct - shouldn't be stored in points in data model
        else:
            decayRate = None

        self.ppm.append(ppm)
        self.widths.append(decayRate)

        #
        # Transfer assignment
        #

        peakDimContribs = self.peakDim.peakDimContribs

        resNameText = ""

        #if self.writeAssignments and peakDimContribs != ():
        if self.writeAssignments and peakDimContribs:

            resNames = []
            resonanceToAtoms = []

            # get and filter resonanceToAtoms
            for peakDimContrib in peakDimContribs:

                if isinstance(peakDimContrib, Nmr.PeakDimContribN):
                    print "   Warning: cannot handle multiple resonances for one peakDim contribution. Ignored."
                    continue

                # get resonanceToAtoms
                ll = self.resonanceToAtoms.get(peakDimContrib.resonance)
                if ll is None:
                    print("  Can't handle resonance %s for peak %d" %
                          (getResNameText(
                              peakDimContrib.resonance), self.peak.serial))
                else:
                    resonanceToAtoms.extend(ll)

            #  sort, filter, and transform
            if self.presetResonanceMapping:
                nameInfo = filteredNameInfo(resonanceToAtoms, mode='preset')
            elif self.compressResonances:
                nameInfo = filteredNameInfo(resonanceToAtoms, mode='compress')
            else:
                nameInfo = filteredNameInfo(resonanceToAtoms)

            # make names

            for resonanceToAtom, atomName in nameInfo:

                #
                # Don't use chainCode for sparky output
                # Using chain and seqCode mapping for output
                # Note that code same whether original res names
                # are being used or not...
                #

                chain = resonanceToAtom.chain
                seqId = resonanceToAtom.seqId

                seqCode = self.getExportSeqCode(
                    self.chainDict[chain][1],
                    chain.findFirstResidue(seqId=seqId))
                residueLabel = self.getResidueLabelOneLetter(resonanceToAtom)

                resName = residueLabel + str(seqCode) + atomName

                if resName not in resNames:
                    resNames.append(resName)

            if resNames:
                resNameText = resNames[0]

                if len(resNames) > 1:
                    print "  Warning: Multiple assignments currently not supported for %s. Only using first one." % self.format

        self.assign.append(resNameText)