Exemple #1
0
 def setRawRdcConstraintItemMembers(self):
   
   for i in range(0,2):
           
     (chainCode,seqCode,spinSystemId,seqInsertCode,atomName) = getNameInfo(self.resSetNames[i])
     
     self.rawConstraintItem.members.append(self.rawConstraintItemMemberClass(chainCode,seqCode,atomName))
Exemple #2
0
    def resonanceInfo(self, guiParent, resonanceName):

        infoValues = getNameInfo(resonanceName)

        infoItems = [
            'Original chain code:', 'Original sequence code:',
            'Original atom name:'
        ]

        if infoValues[2] != None and infoValues[1] == None:
            infoValues = infoValues[0:1] + infoValues[2:3] + infoValues[4:]
            infoItems[1] = 'Original spin system code:'
        elif infoValues[3]:
            #Combine seqCode and seqInsertCode
            infoValues = infoValues[0:1] + (str(infoValues[1]) +
                                            infoValues[3], ) + infoValues[4:]
        else:
            infoValues = infoValues[0:2] + infoValues[4:]

        infoList = []
        infoDict = {}

        for i in range(0, len(infoItems)):

            infoList.append(infoItems[i])
            infoDict[infoItems[i]] = infoValues[i]

        infoText = "This name reflects the information from the imported file(s)."

        popup = InfoPopup(guiParent, 'Resonance name info', infoText, infoList,
                          infoDict)

        self.waitWindow(guiParent, popup)

        return popup
Exemple #3
0
    def findResonances(self, resName):
        (chainCode, seqCode, spinSystemId, seqInsertCode,
         atomName) = getNameInfo(resName)

        #print '\tsearch for resonance', (chainCode,seqCode,spinSystemId,seqInsertCode,atomName)
        resonance = None

        targetMolSystem = None
        if len(self.project.molSystems) == 1 and self.defaultMolSystem == None:
            targetMolSystem = self.project.molSystems[0]
        elif self.defaultMolSystem != None:
            targetMolSystem = self.project.findFirstMolSystem(
                name=self.defaultMolSystem)

        targetChain = None
        if targetMolSystem != None:
            if len(targetMolSystem.chains
                   ) == 1 and self.defaultChainCode == None:
                targetChain = targetMolSystem.chains[0]
            elif self.defaultChainCode != None:
                targetChain = targetMolSystem.findFirstChain(
                    code=self.defaultChainCode)

        targetResidue = None
        if seqCode != None and targetChain != None:
            targetResidue = targetChain.findFirstResidue(seqCode=seqCode)

        targetAtoms = []
        targetAtomSets = []

        #print atomName
        atomNameLength = len(atomName)
        while atomName[-1] == '*':
            #print 'pre',atomName
            atomName = atomName[:-1]
            #print 'post',atomName
        #print atomName

        if targetResidue != None:
            for atom in targetResidue.atoms:
                if atom.name.startswith(atomName) and len(
                        atom.name) == atomNameLength:
                    targetAtoms.append(atom)
                    targetAtomSets.append(atom.atomSet)

        targetResonances = set()

        for atom in targetAtoms:
            for resonanceSet in atom.atomSet.resonanceSets:
                #for resonance in resonanceSet.resonances:
                targetResonances.update(resonanceSet.resonances)
        #print ''

        if len(targetResonances) > 1:
            selectName = '.'.join((chainCode, ` seqCode `, atomName), )
            resonanceIds = [
                ` resonance.serial ` for resonance in targetResonances
            ]
            print 'Warning: found more than one resonance for peak (%s) %s' % (
Exemple #4
0
    def setRawRdcConstraintItemMembers(self):

        itemResonances = getResonancesFromPairwiseConstraintItem(self.item)

        for i in range(0, 2):

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])
            resLabel = self.getResonanceResLabel(itemResonances[i])

            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, seqCode, resLabel,
                                                  atomName))
Exemple #5
0
    def setRawDistanceConstraintItemMembers(self):

        for i in range(0, 2):

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])

            if atomName == allResidueAtoms_kw:
                atomName = None

            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, seqCode,
                                                  atomName))
Exemple #6
0
    def setRawRdcConstraintItemMembers(self):

        for coordSystem in ['OO', 'Z', 'X', 'Y']:
            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(self.refFrameSegId,
                                                  self.refFrameResId,
                                                  coordSystem))

        for i in range(0, 2):

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])

            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, seqCode,
                                                  atomName))
Exemple #7
0
    def setRawDistanceConstraintItemMembers(self):

        for i in range(2):

            resonanceToAtom = self.ccpInfo[i][3]
            residue = resonanceToAtom.getResidue()

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])

            if atomName == allResidueAtoms_kw:
                atomName = None

            # Using residue.seqCode - OK since useCcpnChainInfo = True for all exports
            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, residue.seqId,
                                                  atomName,
                                                  residue.ccpCode.upper()))
Exemple #8
0
    def setRawDistanceConstraintItemMembers(self):

        itemResonances = getResonancesFromPairwiseConstraintItem(self.item)

        for i in range(0, 2):

            resonance = itemResonances[i]

            resLabel = self.getResonanceResLabel(resonance)

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])

            if atomName == allResidueAtoms_kw:
                print "  Error: not handling residue level constraints for %s." % self.format
                continue

            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, seqCode, resLabel,
                                                  atomName))
Exemple #9
0
def writeMappingFile(project, outFile, originalFormats=None):

    if originalFormats:
        checkFormatList = originalFormats

    else:
        checkFormatList = allFormatsDict.keys()

    #
    # First check if there's any mapping info at all...
    #

    formatList = []
    allResonances = project.currentNmrProject.sortedResonances()

    for format in checkFormatList:
        resonancesDict = getApplResNames(format, allResonances)

        if resonancesDict != {}:
            formatList.append(format)

    if formatList == []:

        #
        # No resonances linked
        #

        return False

    formatList.sort()

    fout = open(outFile, 'w')

    #
    # Write top header with time/user info
    #

    fout.write("#" + newline)
    fout.write("# CcpNmr atom name mapping file." + newline)
    fout.write("#" + newline)
    fout.write(
        "# Contains list of original names from the imported file(s) and the" +
        newline)
    fout.write("# atom names they were mapped to in the data model." + newline)
    fout.write("#" + newline)
    fout.write("# File written on %s." % time.ctime() + newline)
    fout.write("#" + newline * 2)

    for format in formatList:

        resonancesDict = getApplResNames(format, allResonances)
        resonanceNames = []

        #
        # Do some sorting...
        #

        resonancesSortDict = {}

        for resonanceName in resonancesDict.keys():

            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(resonanceName)

            if seqCode == None:
                continue

            seqCode = returnInt(seqCode)

            if not resonancesSortDict.has_key(chainCode):
                resonancesSortDict[chainCode] = {}

            if not resonancesSortDict[chainCode].has_key(seqCode):
                resonancesSortDict[chainCode][seqCode] = {}

            if not resonancesSortDict[chainCode][seqCode].has_key(
                    seqInsertCode):
                resonancesSortDict[chainCode][seqCode][seqInsertCode] = {}

            resonancesSortDict[chainCode][seqCode][seqInsertCode][
                atomName] = resonanceName

        chainCodeList = resonancesSortDict.keys()
        chainCodeList.sort()

        for chainCode in chainCodeList:

            seqCodeList = resonancesSortDict[chainCode].keys()
            seqCodeList.sort()

            for seqCode in seqCodeList:

                seqInsertCodeList = resonancesSortDict[chainCode][
                    seqCode].keys()
                seqInsertCodeList.sort()

                for seqInsertCode in seqInsertCodeList:

                    atomNameList = resonancesSortDict[chainCode][seqCode][
                        seqInsertCode].keys()
                    atomNameList.sort()

                    for atomName in atomNameList:

                        resonanceNames.append(
                            resonancesSortDict[chainCode][seqCode]
                            [seqInsertCode][atomName])

        #
        # Write it all out
        #

        if resonancesDict != {}:

            fout.write(drawBox("Origin file format: %s" % format, liner="*"))
            fout.write(newline)

            fout.write("  %-15s    %-15s  %s" %
                       ('Original name', 'Mapped to atoms',
                        'Molecules:chains:residues'))
            fout.write(newline * 2)

            for resonanceName in resonanceNames:

                resonances = resonancesDict[resonanceName]
                atomNames = []

                resCodes = []
                moleculeNames = []
                chainCodes = []

                for resonance in resonances:
                    atomName = ""

                    resonanceSet = resonance.resonanceSet

                    if resonanceSet:

                        for atomSet in resonanceSet.atomSets:

                            #
                            # Get some info out of data model for clarity...
                            #

                            residue = atomSet.findFirstAtom().residue
                            resCode = residue.molResidue.ccpCode + str(
                                residue.seqCode) + string.strip(
                                    residue.seqInsertCode)
                            chainCode = residue.chain.code
                            moleculeName = residue.chain.molecule.name

                            if resCode not in resCodes:
                                resCodes.append(resCode)

                            if chainCode not in chainCodes:
                                chainCodes.append(chainCode)

                            if moleculeName not in moleculeNames:
                                moleculeNames.append(moleculeName)

                            #
                            # Get name of atom(s) this resonance was mapped to
                            #

                            atomName += atomSet.name + "/"

                        if atomName:
                            atomName = atomName[:-1]

                            if atomName not in atomNames:
                                atomNames.append(atomName)

                if atomNames != []:

                    moleculeText = string.join(moleculeNames, ',')
                    chainText = string.join(chainCodes, ',')
                    resCodesText = string.join(resCodes, ',')

                    addText = moleculeText + ':' + chainText + ':' + resCodesText

                    fout.write("  %-15s -> %-15s  %s" %
                               ("'" + resonanceName + "'",
                                string.join(atomNames, ','), addText))

                else:
                    fout.write("  %-15s    %-15s" %
                               ("'" + resonanceName + "'", 'NOT LINKED'))

                fout.write(newline)

    return True
Exemple #10
0
  def getFormatFileInformation(self,resonances,importFormatName):
 
    """
    This function will pull the original chain/residue/atom names from the resonances
    that were created on file import (and input to this function).
    
    Created are:
    
    self.formatFileChainDict = {'chainCode': [(seqCode1,seqInsertCode1),(seqCode2,seqInsertCode2), ...]}
    self.formatFileResidueDict = {'chainCode': {(seqCode,seqInsertCode): [residueLabel, [atomName1, atomName2, ...]]}}
    
    self.formatFileHasResLabels  True/False, indicates whether residue labels are available.
    
    """
 
    self.formatFileChainDict = {}
    self.formatFileResidueDict = {}

    self.formatFileHasResLabels = False

    for resonance in resonances:

      #
      # Now set up resonance stuff... for either normal or fixed resonances
      #

      resonanceLinked = False
      resonanceSet = resonance.resonanceSet
      
      # This should never be true, keep anyway.
      if resonanceSet:
        atomSets = resonanceSet.atomSets
        for atomSet in atomSets:
          if atomSet.atoms:
            resonanceLinked = True
            break

      #
      # Only handle if not linked
      #

      if not resonanceLinked:

        resNames = updateResonanceNamesDict(resonance,{},importFormatName)

        resLabel = None
        resLabelAppData = resonance.findFirstApplicationData(application = importFormatName, keyword = 'origResLabel')
        if resLabelAppData:
          resLabel = resLabelAppData.value

        for resName in resNames:

          # 
          # Check if the name can be decomposed or not (no use if not!)
          #

          (chainCode,seqCode,spinSystemId,seqInsertCode,atomName) = getNameInfo(resName,verbose = 0)

          if seqCode != None:

            # Keep track of reported chainCodes for linking later on
            if not self.formatFileChainDict.has_key(chainCode):
              self.formatFileChainDict[chainCode] = []
              self.formatFileResidueDict[chainCode] = {}

            seqCodeKey = (seqCode,seqInsertCode)

            # Also keep track of reported seqCodes and seqInsertCodes
            if seqCodeKey not in self.formatFileChainDict[chainCode]:
              self.formatFileChainDict[chainCode].append(seqCodeKey)
              self.formatFileResidueDict[chainCode][seqCodeKey] = [resLabel,[]] 
              if resLabel:
                self.formatFileHasResLabels = True

            if atomName not in self.formatFileResidueDict[chainCode][seqCodeKey][1]:
              self.formatFileResidueDict[chainCode][seqCodeKey][1].append(atomName)

            if not self.formatFileResidueDict[chainCode][seqCodeKey][0] and resLabel:
              self.formatFileResidueDict[chainCode][seqCodeKey][0] = resLabel
              self.formatFileHasResLabels = True
Exemple #11
0
    def setRawDihedralConstraintItemMembers(self):

        #
        # For Dyana, set the angle name (and derive correct angle name from atom names if none found)
        #

        (chain, seqId, atomName, resToAtom) = self.ccpInfo[0]
        molecule = chain.molecule

        if not self.moleculeTorsions.has_key(molecule):
            if self.verbose:
                print "  Error: unknown molecule '%s'!" % (molecule.name)
            return

        #
        # Find out which residue this torsion angle is for and make a list of chemAtoms...
        #

        seqIds = {}
        chemAtoms = []

        constraintResonances = self.constraint.resonances

        for i in range(0, self.constraintResNum):
            (chain, seqId, atomName, resToAtom) = self.ccpInfo[i]

            if not seqIds.has_key(seqId):
                seqIds[seqId] = 0
            seqIds[seqId] += 1

            chemAtoms.append(resToAtom.chemAtom)

            resLabel = self.getResonanceResLabel(constraintResonances[i])
            (chainCode, seqCode, spinSystemId, seqInsertCode,
             atomName) = getNameInfo(self.resSetNames[i])

            self.rawConstraintItem.members.append(
                self.rawConstraintItemMemberClass(chainCode, seqCode, resLabel,
                                                  atomName))

        if len(seqIds) > 1:
            seqId = -99999999999
            maxNum = 0
            for tSeqId in seqIds.keys():
                if seqIds[tSeqId] > maxNum or (seqIds[tSeqId] == maxNum
                                               and tSeqId > seqId):
                    maxNum = seqIds[tSeqId]
                    seqId = tSeqId

        else:
            seqId = seqIds.keys()[0]

        residue = chain.findFirstResidue(seqId=seqId)

        if not residue:
            if self.verbose:
                print "  Error: could not identify residue with seqId %d in chain '%s'!" % (
                    seqId, chain.code)
            return

        molRes = residue.molResidue

        if not molRes or not self.moleculeTorsions[molecule].has_key(molRes):
            if self.verbose:
                print "  Error: no molresidue for residue with seqId %d in chain '%s'!" % (
                    seqId, chain.code)
            return

        #
        # Now get the relevant torsion angles for this molecule, molResidue, and determine which one it is...
        #
        # Note that (in torsion terms) H-N-CA-HA is the same as N-H-HA-CA! (described by _inout)
        #

        matchPatterns = {
            'forward': {},
            'backward': {},
            'forward_inout': {},
            'backward_inout': {}
        }
        matchInfo = (('forward', (0, 1, 2, 3)), ('backward', (3, 2, 1, 0)),
                     ('forward_inout', (1, 0, 3, 2)), ('backward_inout',
                                                       (2, 3, 0, 1)))
        torsion = None

        for (torsion, atomList) in self.moleculeTorsions[molecule][molRes]:

            #
            # Check matching atoms...
            #

            for (matchType, matchIndexes) in matchInfo:

                match = ""

                # AtomList sometimes not complete!
                if len(atomList) == self.constraintResNum:
                    for i in range(0, self.constraintResNum):
                        caIndex = matchIndexes[i]
                        if chemAtoms[caIndex] == atomList[i][1]:
                            match += "1"
                        else:
                            match += "0"

                if match == '1111':
                    # All is fine...
                    matchPatterns = {}
                    break
                else:
                    matchPatterns[matchType][match] = torsion

            if not matchPatterns:
                break

        #
        # Try to see if the angle can be converted...
        #

        if matchPatterns or not torsion:
            #print molRes.ccpCode
            #for ca in chemAtoms:
            #  print ca.name,
            #print

            torsion = None

            #for (matchType,matchIndexes) in matchInfo:
            #  patterns = matchPatterns[matchType].keys()
            #  patterns.sort()
            #  for pattern in patterns:
            #    print "  ",matchType,pattern,
            #    for ca in matchPatterns[matchType][pattern].chemAtoms:
            #      print ca.name,
            #    print

            for pattern in ("0111", "1110", "0110"):
                for (matchType, matchIndexes) in matchInfo:
                    if matchPatterns[matchType].has_key(pattern):
                        torsion = matchPatterns[matchType][pattern]

                        if matchType[:8] == 'backward':
                            chemAtoms.reverse()

                        if matchType[-5:] == 'inout':
                            tca = chemAtoms[:]
                            chemAtoms[0] = tca[1]
                            chemAtoms[1] = tca[0]
                            chemAtoms[2] = tca[3]
                            chemAtoms[3] = tca[2]

                        break

            #
            # Have to work 'locally' within chemComp for this... use prev/next coords as well
            #

            if torsion:

                # TODO: need something similar to chemComp XML file copying here?!??!
                ccc = None
                for coordSysName in ('ideal', 'pdb'):
                    ccc = self.project.findFirstChemCompCoord(
                        sourceName=coordSysName,
                        molType=molRes.molType,
                        ccpCode=molRes.ccpCode
                    )  # , showError = self.messageReporter.showError)
                    if ccc:
                        break

                # TODO: really need to calculate angle between two sets of 3 atoms, with 2 atoms shared (??)
                angles = {}
                #print torsion.name

                for (angleType, caList) in (('ref', torsion.chemAtoms),
                                            ('actual', chemAtoms)):

                    coords = []
                    angles[angleType] = None

                    for ca in caList:
                        if not ca:
                            coords.append(None)
                        else:
                            #print ca.name,
                            coord = ccc.findFirstChemAtomCoord(chemAtom=ca)
                            if coord:
                                coords.append((coord.x, coord.y, coord.z))
                            else:
                                coords.append(None)

                    #print
                    #print coords

                    if None not in coords:
                        angles[angleType] = calcTorsionAngleDegrees(
                            coords[0], coords[1], coords[2], coords[3])
                    else:
                        #
                        # Special case... O used instead of CA for OMEGA
                        #
                        if torsion.name == 'OMEGA' and angleType == 'actual':
                            if coords[2] and coords[3]:
                                angles['actual'] = angles['ref'] - 180.00

                                if chemAtoms[3].name == 'H':
                                    angles['actual'] += 180.00

                if None not in angles.values():

                    #
                    # Have all reference info, now reset the value...
                    #

                    #print angles

                    # TODO: IS THIS ALWAYS CORRECT??? CHECK WITH WAYNE!!
                    angleDiff = angles['ref'] - angles['actual']

                    lowerLimit = self.rawConstraint.lowerAngle + angleDiff
                    upperLimit = self.rawConstraint.upperAngle + angleDiff

                    if lowerLimit > 360.0 and upperLimit > 360.0:
                        lowerLimit -= 360.0
                        upperLimit -= 360.0

                    #print angleDiff, lowerLimit, upperLimit

                    self.rawConstraint.setAngleData(lowerLimit, upperLimit)

                else:
                    torsion = None

        if torsion:
            namingSystem = torsion.chemComp.findFirstNamingSystem(
                name=self.namingSystemName)

            if namingSystem:
                torsionSysName = torsion.findFirstSysName(
                    namingSystem=namingSystem)
                if torsionSysName:
                    self.rawConstraint.name = torsionSysName.sysName
                elif self.verbose:
                    print "  Error: could not find a %s sysName for %s, angle name %s" % (
                        self.namingSystemName, molRes.ccpCode, torsion.name)
            elif self.verbose:
                print "  Error: could not find a %s naming system for chemComp %s" % (
                    self.namingSystemName, molRes.ccpCode)
        else:
            if self.verbose:
                if None not in chemAtoms:
                    print "  Error: could not define a torsion angle name for %s, atoms %s-%s-%s-%s." % (
                        molRes.ccpCode, chemAtoms[0].name, chemAtoms[1].name,
                        chemAtoms[2].name, chemAtoms[3].name)
                else:
                    print "  Error: could not define a torsion angle name for %s because of missing chemAtoms" % (
                        molRes.ccpCode)
Exemple #12
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 #13
0
def matchResonToMolSys(resonances,
                       molSystem,
                       assignFormat=None,
                       test=False,
                       matchMode=False):

    #
    # Some quick validity checks...
    #

    if not resonances or (type(resonances) not in (type(('',)),type([]))) or \
        not (isinstance(resonances[0],Nmr.Resonance) or isinstance(resonances[0],NmrConstraint.FixedResonance)):
        print "  Invalid resonance list input - aborting."
        return None

    #
    # Get info from the resonances
    #

    resChainDict = {}
    resResidueDict = {}

    for resonance in resonances:

        #
        # Now set up resonance stuff... for either normal or fixed resonances
        #

        resonanceLinked = 0
        resonanceSet = resonance.resonanceSet

        if resonanceSet:
            atomSets = resonanceSet.atomSets
            for atomSet in atomSets:
                atoms = atomSet.atoms
                if atoms:
                    resonanceLinked = 1
                    break

        #
        # Only handle if not linked - useless otherwise (???)
        #

        if not resonanceLinked:

            resNames = updateResonanceNamesDict(resonance, {}, assignFormat)

            resLabel = None
            resLabelAppData = resonance.findFirstApplicationData(
                application=assignFormat, keyword='origResLabel')
            if resLabelAppData:
                resLabel = resLabelAppData.value

            for resName in resNames:

                #
                # Check if the name can be decomposed or not (no use if not!)
                #

                (chainCode, seqCode, spinSystemId, seqInsertCode,
                 atomName) = getNameInfo(resName, verbose=0)

                if seqCode != None:

                    # Keep track of reported chainCodes for linking later on
                    if not resChainDict.has_key(chainCode):
                        resChainDict[chainCode] = []
                        resResidueDict[chainCode] = {}

                    seqCodeKey = (seqCode, seqInsertCode)

                    # Also keep track of reported seqCodes and seqInsertCodes
                    if seqCodeKey not in resChainDict[chainCode]:
                        resChainDict[chainCode].append(seqCodeKey)
                        resResidueDict[chainCode][seqCodeKey] = [resLabel, []]

                    if atomName not in resResidueDict[chainCode][seqCodeKey][
                            1]:
                        resResidueDict[chainCode][seqCodeKey][1].append(
                            atomName)

                    if not resResidueDict[chainCode][seqCodeKey][
                            0] and resLabel:
                        resResidueDict[chainCode][seqCodeKey][0] = resLabel

    if test:
        print resResidueDict

    return matchToMolSys(resChainDict,
                         resResidueDict,
                         molSystem,
                         test=test,
                         matchMode=matchMode)
Exemple #14
0
    def setRawDistanceConstraintItemMembers(self):

        #
        # Expand the information... is necessary for Concoord (only handles individual atoms)
        #

        atomNameLists = []

        for i in range(0, 2):

            atomNameLists.append([])

            resonanceToAtom = self.ccpInfo[i][3]
            chemAtomOrigName = self.ccpInfo[i][2]

            if resonanceToAtom.chemAtomSet:
                chemAtomOrSet = resonanceToAtom.chemAtomSet
            else:
                chemAtomOrSet = resonanceToAtom.chemAtom

            if chemAtomOrSet:

                chemCompVar = resonanceToAtom.getResidue().chemCompVar
                namingSystem = chemCompVar.chemComp.findFirstNamingSystem(
                    name=self.namingSystemName)
                if namingSystem:
                    chemAtomSysName = findChemAtomSysName(
                        namingSystem, {'sysName': chemAtomOrigName})
                else:
                    chemAtomSysName = None

                if chemAtomSysName:
                    chemAtom = chemCompVar.findFirstChemAtom(
                        name=chemAtomSysName.atomName,
                        subType=chemAtomSysName.atomSubType)
                else:
                    chemAtom = chemCompVar.findFirstChemAtom(
                        name=chemAtomOrigName)

                if not chemAtom:

                    chemAtomSetSysName = findChemAtomSetSysName(
                        namingSystem, {'sysName': chemAtomOrigName})

                    if chemAtomSetSysName:
                        chemAtomSet = chemCompVar.findFirstChemAtomSet(
                            name=chemAtomSetSysName.atomName,
                            subType=chemAtomSetSysName.atomSubType)
                    else:
                        chemAtomSet = chemCompVar.findFirstChemAtomSet(
                            name=chemAtomOrigName)

                    if chemAtomSet:

                        (chainCode, seqCode, spinSystemId, seqInsertCode,
                         atomName) = getNameInfo(self.resSetNames[i])

                        if chemAtomSet.chemAtomSets:
                            chemAtomSets = list(chemAtomSet.chemAtomSets)
                        else:
                            chemAtomSets = [chemAtomSet]

                        for chemAtomSet in chemAtomSets:

                            chemAtomSysNames = self.getChemAtomSysNamesFromSet(
                                chemAtomSet, chemCompVar, findIupac=1)

                            for chemAtomSysName in chemAtomSysNames:

                                if chemAtomSysName:
                                    atomNameLists[-1].append(
                                        getResName(
                                            chainCode,
                                            seqCode,
                                            chemAtomSysName,
                                            seqInsertCode=seqInsertCode))
                                else:
                                    print "  Error: problems with decompressing Concoord name %s - sysNames missing for %s" % (
                                        self.resSetNames[i], chemAtomSet.name)

                    else:
                        print "  Error: can't decompress Concoord name %s" % self.resSetNames[
                            i]

            #
            # If no names use default
            #

            if not atomNameLists[-1]:
                atomNameLists[-1].append(self.resSetNames[i])

        #
        # Now write them one by one...
        #

        itemResonances = getResonancesFromPairwiseConstraintItem(self.item)

        for resSetName0 in atomNameLists[0]:

            # TODO: bit risky this one! What if original names (eg GLU-) are being used?!
            resonance = itemResonances[0]
            resLabel0 = resonance.resonanceSet.findFirstAtomSet(
            ).findFirstAtom().residue.molResidue.chemComp.ccpCode.upper()

            (chainCode0, seqCode0, spinSystemId0, seqInsertCode0,
             atomName0) = getNameInfo(resSetName0)

            if atomName0 == allResidueAtoms_kw:
                print "  Error: not handling residue level constraints for %s." % self.format
                continue

            for resSetName1 in atomNameLists[1]:

                # TODO: bit risky this one! What if original names (eg GLU-) are being used?!
                resonance = itemResonances[1]
                resLabel1 = resonance.resonanceSet.findFirstAtomSet(
                ).findFirstAtom().residue.molResidue.chemComp.ccpCode.upper()

                (chainCode1, seqCode1, spinSystemId1, seqInsertCode1,
                 atomName1) = getNameInfo(resSetName1)

                if atomName1 == allResidueAtoms_kw:
                    print "  Error: not handling residue level constraints for %s." % self.format
                    continue

                #
                # Now set all items and members...
                #

                self.rawConstraint.items.append(self.rawConstraintItemClass())
                self.rawConstraintItem = self.rawConstraint.items[-1]

                self.rawConstraintItem.members.append(
                    self.rawConstraintItemMemberClass())
                self.rawConstraintItem.members[-1].setInfo(
                    chainCode0, seqCode0, resLabel0, atomName0)
                self.rawConstraintItem.members.append(
                    self.rawConstraintItemMemberClass())
                self.rawConstraintItem.members[-1].setInfo(
                    chainCode1, seqCode1, resLabel1, atomName1)
Exemple #15
0
    def setChainLinks(self,
                      forceChainMappings=None,
                      resetMapping=False,
                      verbose=0):

        self.status = True

        #
        # Don't bother if no chains...
        #

        if not self.molSystem.chains:
            self.messageReporter.showError(
                "Error",
                "No chains present in molecular system, cannot link CCPN to external format information.",
                parent=self.guiParent)
            self.status = False
            return self.status

        #
        # Delete if available and resetting mapping
        #

        if self.nameMapping and resetMapping:
            self.nameMapping.delete()
            self.nameMapping = None

        #
        # Set name mapping (if not yet available)
        #

        if not self.nameMapping:

            #
            # This also includes selection of correct name mapping (namingSys)
            # TODO: always set isOriginalImport to True?
            #

            if hasattr(self, 'namingSystemName'):
                namingSystemName = self.namingSystemName
            else:
                namingSystemName = None

            self.getNameMapping(namingSystemName=namingSystemName,
                                isOriginalImport=True,
                                resetMapping=resetMapping)

        #
        # Force chain mapping, this is always tried even if mappings available.
        # Everything has to match or won't work.
        #

        if forceChainMappings:

            forceMapping = 1

            for forceChainMapping in forceChainMappings:

                chainCode = forceChainMapping[0]
                chain = self.molSystem.findFirstChain(code=chainCode)

                if not chain:
                    print "  Error: forceChainMappings chain code '%s' is not present in molSystem! Aborting..." % chainCode
                    forceMapping = 0
                    break

            if forceMapping:

                # TODO: formatLastSeqCode necessary here? Currently not implemented....

                for forceChainMapping in forceChainMappings:

                    chainCode = forceChainMapping[0]
                    chain = self.molSystem.findFirstChain(code=chainCode)

                    formatChainCode = forceChainMapping[1]
                    firstSeqId = forceChainMapping[2]
                    offset = forceChainMapping[3]

                    if len(forceChainMapping) == 5:
                        seqInsertCode = forceChainMapping[4]
                    else:
                        seqInsertCode = defaultSeqInsertCode

                    self.setChainMappingDicts(chain,
                                              formatChainCode,
                                              firstSeqId=firstSeqId,
                                              offset=offset,
                                              seqInsertCode=seqInsertCode)

                return self.status

        #
        # Check for chain mapping - take from name mapping if available *and* complete
        #

        self.setMappingFromChainMappings = False

        if self.nameMapping.chainMappings:

            deleteFormatChains = []
            setChainMappings = []
            doSet = 1

            for chainMapping in self.nameMapping.chainMappings:

                #print "CHAIN MAPPING", chainMapping.chainCode, chainMapping.formatChainCode, chainMapping.formatFirstSeqCode

                chain = self.molSystem.findFirstChain(
                    code=chainMapping.chainCode)

                if chain:

                    #
                    # Additional check to see whether these codes make sense or not...
                    #

                    residueMatches = 1
                    totalResidues = 1

                    if hasattr(self, 'resUnassignedNames'):
                        residueMatches = 0
                        totalResidues = 0
                        residueList = []

                        formatChainCode = chainMapping.formatChainCode
                        formatFirstSeqCode = chainMapping.formatFirstSeqCode
                        formatSeqInsertCode = chainMapping.formatSeqInsertCode

                        if chainMapping.formatLastSeqCode != None:
                            formatLastSeqCode = chainMapping.formatLastSeqCode
                        else:
                            formatLastSeqCode = formatFirstSeqCode + chain.molecule.seqLength

                        for resName in self.resUnassignedNames.keys():
                            (chainCode, seqCode, spinSystemId, seqInsertCode,
                             atomName) = getNameInfo(resName, verbose=0)

                            if (seqCode, seqInsertCode) not in residueList:
                                residueList.append((seqCode, seqInsertCode))
                                totalResidues += 1

                                if formatChainCode == chainCode and formatSeqInsertCode == seqInsertCode and seqCode >= formatFirstSeqCode and seqCode <= formatLastSeqCode:
                                    residueMatches += 1

                    if residueMatches == totalResidues:

                        setChainMappings.append(
                            (chain, chainMapping.formatChainCode,
                             chainMapping))
                        if not chainMapping.formatChainCode in deleteFormatChains:
                            deleteFormatChains.append(
                                chainMapping.formatChainCode)

                    else:

                        doSet = 0
                        break

                else:

                    doSet = 0
                    print "  Error invalid chain codes for this molecular system - doing manual selection"
                    self.formatChainCodeDict = {}
                    self.ccpChainDict = {}
                    break

            #
            # Now check whether all is good and set dicts if so...
            #

            if doSet:

                self.setMappingFromChainMappings = True

                for (chain, formatChainCode, chainMapping) in setChainMappings:
                    self.setChainMappingDicts(chain,
                                              formatChainCode,
                                              chainMapping=chainMapping,
                                              verbose=verbose)

                for formatChainCode in deleteFormatChains:
                    #print formatChainCode,
                    if self.formatChains.has_key(formatChainCode):
                        #print " DELETED",
                        del self.formatChains[formatChainCode]
                    #print

            #
            # If no format chains left, mapping is set so continue
            #

            if chain and not self.formatChains:
                return self.status

        #
        # Only go ahead if one chain in project and one chain reported,
        # otherwise USER INTERACTION to link up!
        #

        linkChains = 1

        if len(self.molSystem.chains) == 1 and len(
                self.formatChains.keys()) == 1:

            #
            # Do some initialization
            #

            formatChainCode = (self.formatChains.keys())[0]
            chain = self.molSystem.sortedChains()[0]

            #
            # Now check for the first seqCode in the data model chain that matches the
            # first seqCode of the format.
            #

            if self.formatChains[formatChainCode]:

                (seqCode,
                 seqInsertCode) = self.formatChains[formatChainCode][0]

                residues = chain.sortedResidues()

                for resPos in range(len(residues)):
                    residue = residues[resPos]

                    if residue.seqCode == seqCode and residue.seqInsertCode == seqInsertCode:

                        #
                        # Additional check: is the number of residues left big enough?
                        #

                        if len(chain.residues) - resPos >= len(
                                self.formatChains[formatChainCode]):

                            #
                            # And does the last sequence code match as well?
                            #

                            residue = chain.sortedResidues()[
                                resPos +
                                len(self.formatChains[formatChainCode]) - 1]
                            (seqCode, seqInsertCode
                             ) = self.formatChains[formatChainCode][-1]

                            if residue.seqCode == seqCode and residue.seqInsertCode == seqInsertCode:

                                self.setSeqAndInsertCodeToChainMapping(
                                    formatChainCode,
                                    self.formatChains[formatChainCode],
                                    chain,
                                    resPos,
                                    verbose=verbose)

                                linkChains = 0
                                break

        if linkChains == 1:

            #
            # User interaction
            # Link chains to chains that were reported for new resonances
            #

            interaction = self.multiDialog.ChainLink(
                self.guiParent,
                self.formatChains,
                self.molSystem,
                forceDefaultChainMapping=self.forceDefaultChainMapping,
                doInteraction=self.allowPopups)

            #
            # Chain mapping returned?
            #

            if hasattr(interaction,
                       'chainDict') and interaction.chainDict != {}:

                for chain in interaction.chainDict:

                    (formatChainCode, firstSeqId,
                     seqAndInsertCodesList) = interaction.chainDict[chain]

                    #
                    # Quick check to see if possibly seqCodes have to be reset... could be more
                    # sophisticated.
                    #

                    nmrRes = chain.findFirstResidue(seqId=firstSeqId)

                    firstResidueSeqId = chain.sortedResidues()[0].seqId

                    if self.allowPopups and not self.minimalPrompts and nmrRes.seqCode != seqAndInsertCodesList[
                            0][0]:

                        if self.messageReporter.showYesNo(
                                "Reset sequence codes",
                                "Do you want to reset the sequence codes for chain '%s' in the data model to reflect the original ones?"
                                % chain.code):

                            #
                            # Reset seqCode for nmrResidues
                            #

                            for seqCodeIndex in range(
                                    0, len(seqAndInsertCodesList)):
                                (seqCode, seqInsertCode
                                 ) = seqAndInsertCodesList[seqCodeIndex]

                                nmrRes = chain.sortedResidues()[
                                    firstSeqId - firstResidueSeqId +
                                    seqCodeIndex]
                                nmrRes.seqCode = seqCode
                                nmrRes.seqInsertCode = seqInsertCode

                    #
                    # Setting chain mapping in formatChainCodeDict
                    #

                    self.setSeqAndInsertCodeToChainMapping(
                        formatChainCode,
                        seqAndInsertCodesList,
                        chain,
                        firstSeqId - firstResidueSeqId,
                        verbose=verbose)

            else:
                # Only really bomb out if nothing set, otherwise try to at least map what we can...
                if not self.setMappingFromChainMappings:
                    self.status = False
                else:
                    print "  Missing mappings for format chains: %s. Continuing because other mappings were set." % str(
                        self.formatChains.keys())

            interaction.destroy()

        #
        # Setting self.formatChainCodeDict to {} is a way to invalidate this routine! ??
        #

        if self.formatChainCodeDict == {}:
            self.status = False

        #
        # Return status
        #

        return self.status