Ejemplo n.º 1
0
  def makeNoeList(self):

    if self.refPeakList is self.satPeakList:
      showWarning('Same Peak List',
                  'Ref Peak List and Sat Peak List cannot be the same',
                  parent=self)
      return

    if self.peakPairs:
      s1 = self.refPeakList.dataSource
      s2 = self.satPeakList.dataSource
      noiseRef = getSpectrumNoise(s1)
      noiseSat = getSpectrumNoise(s2)
      
      es = '%s-%s' % (s1.experiment.name,s2.experiment.name)
      if len(es) > 50:
        es = 'Expt(%d)-Expt(%d)' % (s1.experiment.serial,s2.experiment.serial)

      noeList = self.nmrProject.newNoeList(unit='None',name='Hetero NOE list for %s' % es)
      noeList.setExperiments([s1.experiment,])
      if s1.experiment is not s2.experiment:
        noeList.addExperiment( s2.experiment )
      # TBD: sf, noeValueType, refValue, refDescription
    
      resonancePairsSeen = set()
      for (peakA,peakB) in self.peakPairs: # peakA is sat
        intensA    = getPeakIntensity(peakA,self.intensityType)
        intensB    = getPeakIntensity(peakB,self.intensityType)
        value      = float(intensA)/intensB
        error      = abs(value) * sqrt((noiseSat/intensA)**2 + (noiseRef/intensB)**2)
        resonances = tuple(self.getPeakResonances(peakA))
        frozenResonances = frozenset(resonances)
        if len(resonances) < 2:
          pl = peakA.peakList
          sp = pl.dataSource
          msg = 'Skipping %s:%s:%d peak %d it has too few resonances assigned'
          data = (sp.experiment.name, sp.name, pl.serial, peakA.serial)
          showWarning('Warning',msg % data, parent=self)
        
        elif len(resonances) > 2:
          pl = peakA.peakList
          sp = pl.dataSource
          resonanceText = ' '.join([makeResonanceGuiName(r) for r in resonances])
          msg = 'Skipping %s:%s:%d peak %d it has too many resonances assigned (%s)'
          data = (sp.experiment.name, sp.name, pl.serial, peakA.serial, resonanceText)
          showWarning('Warning', msg % data, parent=self)
        
        elif frozenResonances not in resonancePairsSeen:
          resonancePairsSeen.add(frozenResonances)
          noeList.newNoe(value=value,resonances=resonances,peaks=[peakA,peakB],error=error)
          
        else:
          resonanceText = ' '.join([makeResonanceGuiName(r) for r in resonances])
          msg = 'Skipping duplicate entry for resonances %s' % resonanceText
          showWarning('Warning', msg, parent=self)

      self.parent.editMeasurements(measurementList=noeList)
    def create_name(self, full=True):
        '''Returns a resonance name where deuterated and
           protonated are distinguishable.
           returns: str name description

        '''

        name = makeResonanceGuiName(self.resonance, fullName=full)

        if not self.deuterated:
            return name
        else:
            return '{} (D)'.format(name)
Ejemplo n.º 3
0
    def create_name(self, full=True):
        '''Returns a resonance name where deuterated and
           protonated are distinguishable.
           returns: str name description

        '''

        name = makeResonanceGuiName(self.resonance, fullName=full)

        if not self.deuterated:
            return name
        else:
            return '{} (D)'.format(name)
Ejemplo n.º 4
0
def getCouplingDimAnnotation(cluster, dim):
    """
  Get a text string representing the assignment 
  status of couplings in a specified dimension
  represented by a peak cluster
  
  .. describe:: Input
  
  Nmr.PeakCluster, Int
  
  .. describe:: Output
  
  String
  """

    from ccpnmr.analysis.core.AssignmentBasic import makeResonanceGuiName

    annotation = ''

    if cluster.clusterType == MULTIPLET_TYPE:
        dimResonances = set([])
        dimResonancesAdd = dimResonances.add
        dimResonancesUpdate = dimResonances.update

        for peak in cluster.peaks:
            peakDim = peak.findFirstPeakDim(dim=dim)

            if peakDim:
                for component in peakDim.peakDimComponents:
                    for contrib in component.peakDimContribs:
                        if isinstance(contrib, Nmr.PeakDimContribN):
                            dimResonancesUpdate(contrib.resonances)

                        else:
                            dimResonancesAdd(contrib.resonance)

        names = [makeResonanceGuiName(r) for r in dimResonances]
        names.sort()

        # TBD: Set and use component annotations

        annotation = 'J:' + ','.join(names)

    # Peak cluster annotations could carry couplings in Hz and possibly isotopes...

    return annotation
Ejemplo n.º 5
0
def analysePeaks(peakList):


  # Row per peak - Cols: height vs PL mean, vol vs PL mean,
  # sign check, F1 shift delta, F2 shift delta ++

  meanVolume = 0.0
  meanHeight = 0.0
  meanVolume2 = 0.0
  meanHeight2 = 0.0
  nVolume = 0
  nHeight = 0

  pos = 0
  tot = 0

  data0 = []
  for peak in peakList.sortedPeaks():
    
    volume = getPeakVolume(peak)
    height = getPeakHeight(peak)
    logVolume = None
    logHeight = None
        
    if volume:
      logVolume = log(abs(volume))
      meanVolume += logVolume
      meanVolume2 += logVolume * logVolume
      nVolume += 1
    else:
      volume = 0.0
    
    if height:
      logHeight = log(abs(height))
      meanHeight += logHeight
      meanHeight2 += logHeight * logHeight
      nHeight += 1
  
      tot += 1
      if height > 0:
        pos += 1
        
    else:
      height = 0.0
  
    data0.append([peak, volume,logVolume, height, logHeight])
  
  
  if nVolume:
    meanVolume /= float(nVolume)
    meanVolume2 /= float(nVolume)
  
  if nHeight:
    meanHeight /= float(nHeight)
    meanHeight2 /= float(nHeight)
  
  heightSd =  sqrt(abs(meanHeight2 - (meanHeight * meanHeight)))
  # abs() due to float point error - v small negs rather than zero 
  volumeSd =  sqrt(abs(meanVolume2 - (meanVolume * meanVolume)))
    
  shiftList = peakList.dataSource.experiment.shiftList
  
  boundDataDims = {}
  for dataDim1, dataDim2 in getOnebondDataDims(peakList.dataSource):
    boundDataDims[dataDim1] = dataDim2
    boundDataDims[dataDim2] = dataDim1

  data = []
  for peak, volume, logVolume, height, logHeight in data0:
  
    deltaLogVolume = None
    deltaLogHeight = None
    
    if volume:
      deltaLogVolume = abs(logVolume - meanVolume)

    if height:
      deltaLogHeight = abs(logHeight - meanHeight)

    maxDeltas = []
    assignErrors = {}
    # Row per peak: - Cols: Causes muli 1bond,
    # causes atom impossible 1bond, Partly assigned onebond,
    # missing/extra assign
    for peakDim in peak.sortedPeakDims():
      
      maxDelta = None
      isotopeCode  = None
      
      if shiftList:
        for contrib in peakDim.peakDimContribs:
          resonance = contrib.resonance
          isotopeCode = resonance.isotopeCode
          shift = resonance.findFirstShift(parentList=shiftList)
          if shift:
            delta = abs(peakDim.realValue - shift.value)
            
            if (maxDelta is None) or (delta > maxDelta):
              maxDelta = delta
      
      maxDeltas.append([maxDelta,isotopeCode])  
      
      for contrib in peakDim.peakDimContribs:
        resonance = contrib.resonance
        # Warn the user if prochirals have similar shifts
        # but only one is linked to the peak.
        resonanceSet = resonance.resonanceSet
        if resonanceSet:
          if len(resonanceSet.atomSets) > 1:
            resonances2 = list(resonanceSet.resonances)
            resonances2.remove(resonance)
            
            for resonance2 in resonances2:
              if peakDim.findFirstPeakDimContrib(resonance=resonance2):
                continue
              
              for contrib2 in resonance2.peakDimContribs:
                if contrib2.peakDim.peak.peakList is peakList:
                  break
              
              else:
                shift = resonance.findFirstShift(parentList=shiftList)
                shift2 = resonance2.findFirstShift(parentList=shiftList)
                if shift and shift2:
                  delta = abs(shift.value-shift2.value)
                  analysisDataDim = getAnalysisDataDim(peakDim.dataDim)
 
                  if analysisDataDim and (delta < analysisDataDim.assignTolerance/5.0):
                    name = makeResonanceGuiName(resonance2, fullName=False)
                    msg = 'Also expected dim %d %s assignment' % (peakDim.dim,name)
                    assignErrors[msg] = True

      boundDataDim = boundDataDims.get(peakDim.dataDim)
      if boundDataDim:
        peakDim2 = peak.findFirstPeakDim(dataDim=boundDataDim)
    
        if peakDim.peakDimContribs:
          if peakDim2.peakDimContribs:
            
            # Count number of atomSets to see if result makes sense
            atomSets1 = set()
            atomSets2 = set()
            for contrib2 in peakDim2.peakDimContribs:
              resonanceSet = contrib2.resonance.resonanceSet
              if resonanceSet:
                for atomSet in resonanceSet.atomSets:
                  atomSets2.add(atomSet)
          
            for contrib in peakDim.peakDimContribs:
              resonance = contrib.resonance
              resonanceSet = resonance.resonanceSet
              name = makeResonanceGuiName(resonance)
              bound = getBoundResonances(resonance, recalculate=True)
              impossibles  = []
              
              if resonanceSet:
                for atomSet in resonanceSet.atomSets:
                  atomSets1.add(atomSet)

              if bound:
        
                nBound = len(bound)
                
                for reson in bound:
                  # Correct for multiatom atomSets (CH3 resonances e,g,)
                  resSet = reson.resonanceSet
                  if resSet:
                    ll = [1]
                    for atomSet in resSet.atomSets:
                      length = len(atomSet.atoms)
                      cas = atomSet.findFirstAtom().chemAtom.chemAtomSet
                      if not cas or cas.isEquivalent is not None:
                        # Test excludes e.g. Tyr and Phe side chains
                        # that otherwise give spurious errors
                        ll.append(length)
                    # Add additional number of atoms for each bound resonance
                    nBound += min(ll) - 1
                    
                if isotopeCode in ('1H','2H','19F'):
                  if nBound > 1:
                    assignErrors['%s mutiple %s bonds' % (name,isotopeCode)] = True
 
                elif resonanceSet:
                  chemAtom = resonance.resonanceSet.findFirstAtomSet().findFirstAtom().chemAtom
                  if nBound > len(chemAtom.chemBonds):
                    assignErrors['%s excessive bonds' % name] = True
                    
                okAtoms = False
                foundBound = False
                for contrib2 in peakDim2.peakDimContribs:
                  resonance2 = contrib2.resonance
                  
                  if resonance2 in bound:
                    resonanceSet2 = resonance2.resonanceSet
                    foundBound = True
                    if resonanceSet and resonanceSet2:
                      if not areResonanceSetAtomsBound(resonanceSet, resonanceSet2):
                        names = [name,makeResonanceGuiName(resonance2)]
                        names.sort()
                        impossibles.append(names)
                        
                      else:
                        okAtoms = True
                        
                if not okAtoms:
                  for names in impossibles:
                    assignErrors['Impossible bond %s-%s' % tuple(names)] = True
                
                if not foundBound:
                  assignErrors['%s no bound partner' % name] = True
            
            if isotopeCode in ('1H','2H','19F'):
              if len(atomSets2) > len(atomSets1):
                assignErrors['Only %s H to bind %s Non-H' % (len(atomSets1), len(atomSets2))] = True
                
          else:
            assignErrors['Dim %d empty' % peakDim2.dataDim.dim] = True
        
        elif peakDim2.peakDimContribs:
          assignErrors['Dim %d empty' % peakDim.dataDim.dim] = True
      

    sortedPeakDims = peak.sortedPeakDims()
    annotation = ' '.join([pd.annotation or '-' for pd in sortedPeakDims])
    
    locations = []
    for pd in sortedPeakDims:
      if pd.value is None:
        if pd.position is None:
          locations.append('Error')
        else:
          locations.append('%.2f' % pd.position)
          
      else:
        locations.append('%.2f' % pd.value)
    
    location   = ' '.join(locations)

    nearestPeak, nearestDistance = findClosestOtherPeak(peak, scale=2.0)
    symmetryPeaks = findSymmetryPeaks(peak)

    datum = [peak.serial,annotation,assignErrors.keys(),location,
             volume,deltaLogVolume,
             height,deltaLogHeight,maxDeltas,
             nearestPeak, nearestDistance, symmetryPeaks]
    data.append([peak, datum])

  posProp = 1.0
  if tot:
    posProp = pos/float(tot)

  return posProp, volumeSd, heightSd, data
Ejemplo n.º 6
0
def analyseChemicalShifts(shiftList):
    
    updateAllShifts(shiftList)
    
    # T1, shifts -  Row per resonance - Cols: shift, shiftSD,
    # maxPeak delta, SD per spectrum ++
    data = []
    
    duplicateAssign = {}
    data2 = []
    if shiftList:
      project = shiftList.root
    
      for shift in shiftList.measurements:
        resonance = shift.resonance
        assignTuple = getResonanceAtomTuple(resonance)
        data2.append(['%s%s%8.8s%s' % assignTuple,shift])
        duplicateAssign[assignTuple] = duplicateAssign.get(assignTuple, 0) + 1
    
    data2.sort()
    for name, shift in data2:
      resonance  = shift.resonance
      deltaMax   = None
      nContribs  = 0
      bmrbMean   = None
      randomCoil = None
      typeScore  = None
      
      resonanceSet = resonance.resonanceSet
      if resonanceSet:
        atomSet = resonanceSet.findFirstAtomSet()
        residue = atomSet.findFirstAtom().residue
        ccpCode = residue.ccpCode
        molType = residue.molResidue.molType
        atomName = atomSet.name
        chemAtomNmrRef = getChemAtomNmrRef(project, atomName, ccpCode, molType=molType)
        if chemAtomNmrRef is None:
          atomName = atomSet.findFirstAtom().name
          chemAtomNmrRef = getChemAtomNmrRef(project, atomName, ccpCode, molType=molType)
         
        if chemAtomNmrRef:
        
          # Horrid kludge until we have chem shift ref info per var
          if (ccpCode == 'Cys') and ('link:SG' in residue.chemCompVar.descriptor):
            ccpCode = 'Cyss'
                
          typeScore  = lookupAtomProbability(project, ccpCode, atomName, shift.value, molType)
          bmrbMean   = chemAtomNmrRef.meanValue
          randomCoil = chemAtomNmrRef.randomCoilValue
      
      for contrib in resonance.peakDimContribs:
        peakDim = contrib.peakDim
        shiftList1 = peakDim.peak.peakList.dataSource.experiment.shiftList
        if shiftList1 and (shiftList1 is shiftList):
          nContribs +=1
          delta = abs(peakDim.realValue-shift.value)
          if (deltaMax is None) or (delta > deltaMax):
            deltaMax = delta
            
      boundWarn = False      
      bound = getBoundResonances(resonance, recalculate=True)
      if bound:
        
        nBound = len(bound)
        
        for reson in bound:
          # Correct for multiatom atomSets (CH3 resonances e,g,)
          resSet = reson.resonanceSet
          if resSet:
            ll = [1]
            for atomSet in resSet.atomSets:
              length = len(atomSet.atoms)
              cas = atomSet.findFirstAtom().chemAtom.chemAtomSet
              if not cas or cas.isEquivalent is not None:
                # Test excludes e.g. Tyr and Phe side chains 
                # that otherwise give spurious errors
                ll.append(length)
            # Add additional number of atoms for each bound resonance
            nBound += min(ll) - 1
          
        if resonance.isotopeCode in ('1H','2H','19F'):
          if nBound > 1:
            boundWarn = True
 
        elif resonanceSet:
          chemAtom = resonance.resonanceSet.findFirstAtomSet().findFirstAtom().chemAtom
          if nBound > len(chemAtom.chemBonds):
            boundWarn = True
    
        if resonanceSet and not boundWarn:
          atom = resonanceSet.findFirstAtomSet().findFirstAtom()
          
          for resonance1 in bound:
            resonanceSet1 = resonance1.resonanceSet
            
            if resonanceSet1:
              for atomSet1 in resonanceSet1.atomSets:
                for atom1 in atomSet1.atoms:
                  if areAtomsBound(atom, atom1):
                    break
                    
                else:
                  continue
                break   
              
              else:
                boundWarn = True
    
      assignTuple = getResonanceAtomTuple(resonance)
      sameResBound = []
      otherBound   = []
      residue = getResonanceResidue(resonance)
      for resonance1 in bound:
        residue1 = getResonanceResidue(resonance1)
        if residue1 is residue:
          sameResBound.append(makeResonanceGuiName(resonance1,fullName=False))
        else:
          otherBound.append(makeResonanceGuiName(resonance1))
      
      boundResonances = ''
      if residue:
        ccpCode = getResidueCode(residue)
        resName1 = '%d%s' % (residue.seqCode,ccpCode)
        
        if len(sameResBound) > 1:
          boundResonances += '%s[%s] ' % (resName1,','.join([x for x in sameResBound]))
        elif sameResBound:
          boundResonances += '%s%s ' % (resName1,sameResBound[0])
      
      else:
         boundResonances += ','.join([x for x in sameResBound])
         
      boundResonances += ','.join([x for x in otherBound])
     
      isDuplicate = False
      if duplicateAssign.get(assignTuple, 0) > 1:
        isDuplicate = True
        
      resName = makeResonanceGuiName(resonance)
      datum = [resonance.serial,resonance.isotopeCode,resName,boundResonances,
               bmrbMean,randomCoil,typeScore,shift.value,shift.error,
               deltaMax,nContribs,isDuplicate,boundWarn]
      
      data.append([shift, datum])
      
    return data  
Ejemplo n.º 7
0
def fitSideChain(shifts, residue, clouds, distrib, useAssignNames=False):

    ccpCode = residue.ccpCode
    atomScores = {}
    project = residue.root

    from ccpnmr.analysis.core.SpinSystemTyping import getAtomNames, getAtomShiftScore

    atomSets = {}
    for shift in shifts:
        """scores[shift] = None
    
    name = None
    if shift.resonance.assignNames:
      name = shift.resonance.assignNames
      
    elif shift.resonance.name:
      name = shift.resonance.name  
      
    name = shift.resonance.name
    
    if name == 'HN':
      name = 'H'"""

        done = {}
        atomScores[shift] = {}

        for atom in residue.atoms:
            if not atom.chemAtom.waterExchangeable:
                atomSet = atom.atomSet
                if atomSet and (done.get(atomSet) is None):
                    atomSetName = atomSet.name
                    atomName = atom.name
                    done[atomSet] = True
                    atomSets[atomSet] = True

                    if atom.chemAtom.elementSymbol == shift.resonance.isotope.chemElement.symbol:
                        score = getAtomShiftScore(project, atomSetName,
                                                  ccpCode, shift)
                        if not score:
                            score = getAtomShiftScore(project, atomName,
                                                      ccpCode, shift)

                        if score:
                            atomScores[shift][atomSetName] = log(score)
                        else:
                            atomScores[shift][atomSetName] = None

                    else:
                        atomScores[shift][atomSetName] = None

    atomNames0 = [(ass.atoms[0].name, ass.name)
                  for ass in atomSets.keys()]  # getAtomNames(residue)

    best = -20000.0
    bestM = None
    passes = 0
    J = 0
    i = 0

    print "Fitting residue %d %s" % (residue.seqCode, residue.ccpCode)
    #print atomNames0

    while passes < (len(atomNames0) * len(atomNames0)):

        i += 1
        if bestM is None:
            bestM = {}
            shifts1 = list(shifts)

            for atomName, atomSetName in atomNames0:
                if shifts1:
                    j = randint(0, len(shifts1) - 1)
                    bestM[atomName] = shifts1.pop(j)
                else:
                    bestM[atomName] = None

            mapping = bestM.copy()

        else:
            mapping = bestM.copy()

            if len(atomNames0) < 2:
                break

            j = J
            J += 1
            if J >= len(atomNames0):
                J = 0

            k = j
            while k == j:
                k = randint(0, len(atomNames0) - 1)

            swap = mapping[atomNames0[j][0]]
            mapping[atomNames0[j][0]] = mapping[atomNames0[k][0]]
            mapping[atomNames0[k][0]] = swap

        prior = 0.0
        for atomName, atomSetName in atomNames0:
            shift = mapping[atomName]
            if shift:
                s = atomScores[shift][atomSetName]
                if s:
                    prior += s
                else:
                    prior += -50.0

        likelihood = 0.1 * getAtomCloudScores(mapping, ccpCode, clouds,
                                              distrib)

        score = prior + likelihood

        if score > best:
            #print i, score, likelihood, prior
            passes = 0
            best = score
            bestM = mapping

        else:
            passes += 1

    # do some provisional assignment
    if bestM:
        for atomName in bestM.keys():
            shift = bestM[atomName]
            if shift:
                resonance = shift.resonance
                resonance.setName(atomName)

                atomNames4 = []
                if resonance.resonanceSet:
                    for atomSet in resonance.resonanceSet.atomSets:
                        for atom4 in atomSet.atoms:
                            atomNames4.append(atom4.name)

                if atomNames4 and (atomName not in atomNames4):
                    #print i, best
                    print 'Error %5.5s %3.3f - %s' % (
                        atomName, shift.value, makeResonanceGuiName(resonance))
                    for atom4 in residue.atoms:
                        if not atom4.chemAtom.waterExchangeable:
                            print '     %3.3f %5.5s %.3f' % (
                                shift.value, atom4.atomSet.name,
                                atomScores[shift][atom4.atomSet.name]
                                or -1000.0)

    return bestM
Ejemplo n.º 8
0
    def update(self,
               contrib,
               peakDim,
               aliasing=False,
               structure=None,
               limitedResonances=None,
               molSystems=None,
               component=None,
               noDisplay=False,
               doubleTol=False,
               resetScrollbars=True,
               showMolSystem=False):

        self.aliasing = aliasing
        self.contrib = contrib
        self.resonances = []
        self.jCouplings = []
        self.structure = structure
        self.component = component
        atomSets1 = []

        if peakDim:
            self.peakDim = peakDim
        elif contrib:
            self.peakDim = None
            peakDim = contrib.peakDim
        else:
            self.scrolledMatrix.update(objectList=[], textMatrix=[
                [],
            ])
            return

        if component and (component.dataDimRef.expDimRef.unit != 'ppm'):
            headingList = ['#', 'Names', 'Delta', 'Coupling', 'SD']
            tipTexts = TIP_TEXTS2
            isCoupling = True
        else:
            tipTexts = TIP_TEXTS
            headingList = ['#', 'Name', 'Delta', 'Shift', 'SD', 'Dist']
            isCoupling = False

        if showMolSystem:
            tipTexts = tipTexts[:]
            tipText = 'Mol System of resonance'
            if isCoupling:
                tipText += 's'
            tipTexts.append(tipText)
            headingList.append('MS')

        dataDimRef = peakDim.dataDimRef
        expDimRef = dataDimRef.expDimRef
        dataDim = dataDimRef.dataDim
        textMatrix = []
        colorMatrix = []

        if isCoupling:

            ppm = getAnalysisDataDim(peakDim.dataDim).assignTolerance
            points = peakDim.dataDimRef.valueToPoint(ppm)
            tolerance = component.dataDimRef.pointToValue(points)

            if doubleTol:
                tolerance *= 2

            # get couplings that might match the splitting
            for delta, coupling in findMatchingCouplings(component, tolerance):
                resonanceA, resonanceB = coupling.resonances
                nameA = makeResonanceGuiName(resonanceA)
                nameB = makeResonanceGuiName(resonanceB)

                self.jCouplings.append(coupling)

                colors = [None, None, None, None, None]
                if coupling.error >= tolerance:
                    colors[4] = '#d0a0a0'

                textMatrix.append([
                    '%d,%d' % (resonanceA.serial, resonanceB.serial),
                    '%s-%s' % (nameA, nameB),
                    '%5.3f' % round(delta, 3), coupling.value,
                    '%5.3f' % round(coupling.error, 3)
                ])
                colorMatrix.append(colors)

                if showMolSystem:
                    molSystemA = getResonanceMolSystem(resonanceA) or ''
                    molSystemB = getResonanceMolSystem(resonanceB) or ''
                    if molSystemA == molSystemB:
                        texts.append(molSystemA and molSystemA.code)
                    else:
                        texts.append('%s,%s' %
                                     (molSystemA and molSystemA.code,
                                      molSystemB and molSystemB.code))
                    colors.append(None)

            objectList = self.jCouplings

        else:
            # set up atomSets for distance calculations where possible
            if self.structure:
                for expTransfer in expDimRef.expTransfers:
                    if expTransfer.transferType in longRangeTransfers:
                        expDimRefs = list(expTransfer.expDimRefs)
                        expDimRefs.remove(expDimRef)

                        for peakDim1 in peakDim.peak.sortedPeakDims():
                            if peakDim1.dataDimRef.expDimRef is expDimRefs[0]:
                                for contrib1 in peakDim1.peakDimContribs:
                                    resonance1 = contrib1.resonance

                                    if resonance1 and resonance1.resonanceSet:
                                        for atomSet in resonance1.resonanceSet.atomSets:
                                            atomSets1.append(atomSet)

            if component:
                # E.g. MQ or reduced dimensionality
                dataDimRef2 = component.dataDimRef

                if dataDimRef is dataDimRef2:
                    ppm = abs(peakDim.value - peakDim.realValue)

                else:
                    realPoint = ppm2pnt(peakDim.realValue, dataDimRef)
                    deltaPoints = abs(peakDim.position - realPoint)
                    ppm = abs(component.scalingFactor *
                              dataDimRef2.pointToValue(deltaPoints))

                peakUnit = dataDimRef2.expDimRef.unit or 'point'

            else:
                ppm = peakDim.realValue
                peakUnit = expDimRef.unit or 'point'

            shiftList = peakDim.peak.peakList.dataSource.experiment.shiftList
            shiftUnit = shiftList.unit

            tolerance = getAnalysisDataDim(dataDim).assignTolerance
            if doubleTol:
                tolerance *= 2

            shifts = self.givePossAssignments(peakDim, tolerance, ppm)

            if len(shifts) > 0:  # resonance matches
                temp = []
                for shift in shifts:
                    resonance = shift.resonance
                    if limitedResonances is not None:
                        if resonance not in limitedResonances:
                            continue

                    if molSystems:
                        molSystem = getResonanceMolSystem(resonance)
                        if molSystem and (molSystem not in molSystems):
                            continue

                        # Kludge until chain states
                        if (
                                not molSystem
                        ) and resonance.resonanceGroup and resonance.resonanceGroup.chains:
                            molSystems2 = set([
                                ch.molSystem
                                for ch in resonance.resonanceGroup.chains
                            ])

                            if not molSystems2.intersection(molSystems):
                                continue

                    if peakUnit != shiftUnit:
                        shiftValue = unit_converter[(shiftUnit,
                                                     peakUnit)](shift.value,
                                                                dataDimRef)
                    else:
                        shiftValue = shift.value

                    points = unit_converter[(peakUnit, 'point')](shiftValue,
                                                                 dataDimRef)

                    numAliasing = findNumAliasing(dataDimRef, points)
                    deltaAliasing = numAliasing - peakDim.numAliasing

                    if deltaAliasing:
                        points -= dataDim.numPointsOrig * deltaAliasing
                        shiftValue = unit_converter[('point',
                                                     peakUnit)](points,
                                                                dataDimRef)
                        shift.isDiffAliasing = 1
                    else:
                        shift.isDiffAliasing = 0

                    delta = abs(ppm - shiftValue)
                    temp.append((delta, shift))
                    shift.delta = delta

                temp.sort()
                shifts = [x[1] for x in temp]

                textMatrix = []
                colorMatrix = []
                for shift in shifts:
                    resonance = shift.resonance
                    if limitedResonances is not None:
                        if resonance not in limitedResonances:
                            continue

                    # wb104, 13 Apr 2016, added below (could check this instead in if statement
                    # but the problem is that shift.delta also needs to exist further down
                    # and also both attributes get deleted at bottom of the loop)

                    if not hasattr(shift, 'isDiffAliasing'):
                        continue

                    if shift.isDiffAliasing:
                        colors = [None, None, '#d0d0a0', None, None, None]
                    else:
                        colors = [None, None, None, None, None, None]

                    name = makeResonanceGuiName(resonance)
                    self.resonances.append(resonance)

                    if shift.error >= tolerance:
                        colors[4] = '#d0a0a0'

                    if self.structure and atomSets1:
                        if resonance.resonanceSet:
                            atomSets2 = list(resonance.resonanceSet.atomSets)
                            dist = getAtomSetsDistance(atomSets1,
                                                       atomSets2,
                                                       self.structure,
                                                       method='noe')
                        else:
                            dist = None
                    else:
                        dist = None

                    texts = [
                        resonance.serial, name,
                        '%5.3f' % round(shift.delta, 3), shift.value,
                        '%5.3f' % round(shift.error, 3), dist or ' '
                    ]

                    if showMolSystem:
                        molSystem = getResonanceMolSystem(resonance)
                        texts.append(molSystem and molSystem.code)
                        colors.append(None)

                    textMatrix.append(texts)
                    colorMatrix.append(colors)

                    del shift.isDiffAliasing
                    del shift.delta

            objectList = self.resonances

        if not noDisplay:
            self.scrolledMatrix.update(headingList=headingList,
                                       tipTexts=tipTexts,
                                       objectList=objectList,
                                       textMatrix=textMatrix,
                                       colorMatrix=colorMatrix,
                                       resetScrollbars=resetScrollbars)
Ejemplo n.º 9
0
 def getResonanceGuiName(self, resonance, fullName=True):
     """ Analysis resonance name - overrides default version
 """
     return makeResonanceGuiName(resonance, fullName)
Ejemplo n.º 10
0
    def updateMeasurements(self, measurementList=None):

        headingList = [
            '#', 'Resonance', 'Value', 'SD', 'Chain', 'Isotope',
            'Fig of\nMerit', 'Peaks', 'Details'
        ]

        if measurementList is not None:
            self.measurementListB = measurementList
            self.updateListPulldown()

        if self.measurementListB is None:
            self.measurement = None
            measurements = []
        else:
            if self.measurementListB.unit:
                headingList[2] = 'Value\n(%s)' % (self.measurementListB.unit)
            measurements = self.measurementListB.sortedMeasurements()
            if measurements and hasattr(measurements[0], 'resonances'):
                headingList[1] = 'Resonances'
                headingList[5] = 'Isotopes'

        if self.measurement:
            self.measurementButtons.buttons[0].enable()
            self.measurementButtons.buttons[2].enable()
            if self.measurementListB.className == 'ShiftList':
                self.measurementButtons.buttons[1].enable()
            else:
                self.measurementButtons.buttons[1].disable()
        else:
            self.measurementButtons.buttons[0].disable()
            self.measurementButtons.buttons[1].disable()
            self.measurementButtons.buttons[2].disable()

        objectList = []
        textMatrix = []
        i = 0
        for measurement in measurements:
            i += 1
            resonanceText = ''
            isotopeText = ''
            chainText = ''
            if hasattr(measurement, 'resonances'):
                resonanceText = ' '.join(
                    [makeResonanceGuiName(r) for r in measurement.resonances])
                isotopeText = ' '.join(
                    [r.isotopeCode for r in measurement.resonances])
                residueDict = {}
                for resonance in measurement.resonances:
                    if resonance.resonanceSet:
                        residue = resonance.resonanceSet.findFirstAtomSet(
                        ).findFirstAtom().residue
                        residueDict[residue] = None

                keys = residueDict.keys()
                if len(keys) == 1:
                    residue = keys[0]
                    residueNum = residue.seqCode
                    chainText = '%s:%s' % (residue.chain.molSystem.code,
                                           residue.chain.code)

            elif hasattr(measurement, 'resonance'):
                resonance = measurement.resonance
                resonanceText = makeResonanceGuiName(resonance)
                isotopeText = measurement.resonance.isotopeCode
                if resonance.resonanceSet:
                    residue = resonance.resonanceSet.findFirstAtomSet(
                    ).findFirstAtom().residue
                    chainText = '%s:%s' % (residue.chain.molSystem.code,
                                           residue.chain.code)

            datum = [
                i, resonanceText, measurement.value, measurement.error,
                chainText, isotopeText, measurement.figOfMerit,
                len(measurement.peaks), measurement.details or ' '
            ]

            objectList.append(measurement)
            textMatrix.append(datum)

        if not objectList:
            textMatrix.append([])

        tipTexts = self.measurementsMatrix.tipTexts  # unchanged, despite variable headings

        self.measurementsMatrix.update(headingList=headingList,
                                       objectList=objectList,
                                       textMatrix=textMatrix,
                                       tipTexts=tipTexts)

        self.waitingMeasurement = False
Ejemplo n.º 11
0
  def update(self, t1List, t2List, cSize, cDist, sf, lenNh, ict,
             csaN, paramsS2, paramsRct, graphBounds):
    
    self.calcContourLines(sf, lenNh, ict, csaN, paramsS2, paramsRct)
    
    self.minT1, self.maxT1, self.minT2, self.maxT2 = graphBounds
    
    dataSets = []
    dataColors = []
    symbols = []
    outliers = []
    nColors = len(CLUSTER_COLORS)
    nSymbols = len(CLUSTER_SYMBOLS)
    cDist2 = cDist**2
    
    if t1List and t2List:
      t1t2Points = []
      resonancesT1 = {}

      t1Unit = MS_UNIT_MULTIPLIERS[t1List.unit]
      t2Unit = MS_UNIT_MULTIPLIERS[t2List.unit]
      
      for t1 in t1List.measurements:
        resonancesT1[t1.resonance] = t1
         
      for t2 in t2List.measurements:
        resonance = t2.resonance
        t1 = resonancesT1.get(resonance)
        
        if t1:
          xyr = (t1Unit*t1.value,t2Unit*t2.value, resonance)
          t1t2Points.append(xyr)
      
      # Do clustering
      clusters = [[pt,] for pt in t1t2Points]
      
      nMerge = 1
      while nMerge:
        nMerge = 0
        
        for i, clusterA in enumerate(clusters[:-1]):
          for j in range(i+1,len(clusters)):
            clusterB = clusters[j]
            
            for x1, y1, r1 in clusterA:
              for x2, y2, r2 in clusterB:
                dx = x2-x1
                dy = y2-y1
                
                if (dx*dx) + (dy*dy) <= cDist2:
                  clusterA += clusterB
                  clusters[j] = []
                  nMerge += 1
                  break
              
              else:
                continue
              break      
        
        clusters = [c for c in clusters if c]
      
      self.outlierLabels = []
      for c in clusters:
        if len(c) < cSize:
          for x,y,r in c:
            outliers.append((x,y))
            label =  makeResonanceGuiName(r)
            self.outlierLabels.append((label,x,y))
        else:
          data = [xyr[:2] for xyr in c]
          dataSets.append(data)
               
      dataSets.append(outliers)
      
      for i, dataSet in enumerate(dataSets):
        dataSet.sort()
        dataColors.append(CLUSTER_COLORS[i % nColors])
        symbols.append(CLUSTER_SYMBOLS[i % nSymbols])
    
    if outliers:
      symbols[-1] = 'star'
      
    #else:
    #  dataSets.append([(0,0),(1000,1000)])

    
    ScrolledGraph.update(self, dataSets, dataColors, symbols=symbols)