Пример #1
0
def assignPeaksAutomatic(argServer,
                         ambiguous=True,
                         peaks=None,
                         shiftRanges=None,
                         tolerances=None,
                         aliasing=True,
                         findAssigned=False):

    from ccpnmr.analysis.core.AssignmentAdvanced import possiblePeakAssigments
    from ccpnmr.analysis.core.AssignmentBasic import assignResToDim

    if not peaks:
        peaks = argServer.getCurrentPeaks()

    for peak in peaks:

        resonances = possiblePeakAssigments(peak,
                                            shiftRanges=shiftRanges,
                                            tolerances=tolerances,
                                            aliasing=aliasing,
                                            findAssigned=findAssigned)

        hasMultiple = bool([ll for ll in resonances if len(ll) > 1])

        print ambiguous, hasMultiple, resonances, [
            ll for ll in resonances if len(ll) > 1
        ]

        if ambiguous or not hasMultiple:
            for ii, peakDim in enumerate(peak.sortedPeakDims()):
                for resonance in resonances[ii]:
                    assignResToDim(peakDim, resonance)
Пример #2
0
def pickPeaksFromCing(cingPeakList, peakList, resonanceDict):


  for cingPeak in cingPeakList:
    peakList.root.override = True
    peak = pickPeak(peakList, cingPeak.positions, unit='ppm', doFit=False,
                    serial=cingPeak.xeasyIndex)
    peakList.root.override = False
    setManualPeakIntensity(peak, value=cingPeak.height.value, intensityType="height")
    if len(peak.peakDims) == len(cingPeak.resonances):
      for j, peakDim in enumerate(peak.sortedPeakDims()):
        cingResonance = cingPeak.resonances[j]

        resonance = resonanceDict.get(cingResonance)
        if resonance is not None:
          assignResToDim(peakDim, resonance)

    else:
      # original, fixed
      for j, peakDim in enumerate(peak.sortedPeakDims()):
        numAssignments = len(cingPeak.resonances) / len(peak.peakDims)
        ccpnResonances = []
        indx = j
        for k in range(numAssignments):
          cingResonance = cingPeak.resonances[indx]
          resonance = resonanceDict.get(cingResonance)
          ccpnResonances.append(resonance)
          indx += len(peak.peakDims)
        for res in ccpnResonances:
          if res is not None:
            assignResToDim(peakDim, res)

  print "Peaks Picked"
Пример #3
0
def assignAllNewResonances(argServer=None, peaks=None):
    assert argServer or peaks
    if not peaks:
        peaks = argServer.getCurrentPeaks()
    # e.g. Assign all of an unassigned HSQC to different Hn and N resonances

    for peak in peaks:
        for peakDim in peak.peakDims:
            if len(peakDim.peakDimContribs) < 1:
                assignResToDim(peakDim)
Пример #4
0
def assign3dTocsyF2NewResonances(argServer,
                                 peakList=None,
                                 diagTolerance=0.5,
                                 waterMinPpm=4.88,
                                 waterMaxPpm=4.94):

    assert argServer or peakList

    if argServer:
        diagTolerance = argServer.askFloat('Diagonal exclusion tolerance', 0.5)
        waterMinPpm = argServer.askFloat('Minimum water exclusion ppm ', 4.88)
        waterMaxPpm = argServer.askFloat('Maximum water exclusion ppm ', 4.96)

    if not peakList:
        project = argServer.getProject()
        spectra = getSpectraByType(project, 'H[N]_H.TOCSY')
        spectra += getSpectraByType(project, 'H_H[N].TOCSY')
        if not spectra:
            argServer.showWarning('Cannot find any 3d H H N spectra')
            return

        if len(spectra) > 1:
            argServer.showInfo('Choose 3d TOCSY spectrum')
            spectrum = argServer.getSpectrum(spectra)
        else:
            spectrum = spectra[0]
        peakList = argServer.getPeakList(spectrum)

    spectrum = peakList.dataSource

    resonances = []
    for peak in peakList.peaks:

        peakDims = peak.sortedPeakDims()
        peakDim0 = peakDims[0]
        peakDim = peakDims[1]
        ppm = peakDim.value

        if abs(ppm - peakDim0.value) < diagTolerance:
            continue

        if (ppm >= waterMinPpm) and (ppm <= waterMaxPpm):
            continue

        if len(peakDim.peakDimContribs) < 1:
            resonance = assignResToDim(peakDim).resonance
            resonances.append(resonance)
            contribs0 = list(peakDim0.peakDimContribs)
            if contribs0:
                resonance0 = contribs0[0].resonance
                if resonance0.resonanceGroup:
                    addSpinSystemResonance(resonance0.resonanceGroup,
                                           resonance)
        else:
            resonance = peakDim.findFirstPeakDimContrib().resonance
            resonances.append(resonance)

    return resonances
Пример #5
0
    def assignSelectedPeaks(self):

        selectedPeakLinks = self.displayPeakTable.currentObjects

        for pl in selectedPeakLinks:

            peak = pl.getPeak()

            if peak:

                for resonance, dimension in zip(pl.getResonances(),
                                                peak.getDimensions()):

                    ccpnResonance = resonance.getCcpnResonance()
                    ccpnDimension = dimension.getCcpnDimension()

                    if ccpnResonance and ccpnDimension:

                        assignResToDim(ccpnDimension, ccpnResonance)
Пример #6
0
def assignAmbigPeaks(peaks, resonances):

  tolerance = 0.015
  shifts = []
  
  N - len(resonances)
  for resonance in resonances:
    shifts.append(resonance.findFirstShift().value)
      
  for peak in peaks:
    for peakDim in peak.peakDims:
      ppm = pnt2ppm(peakDim.position,peakDim.dataDimRef)
      candidates = []
      for i in range(N):
        if abs(ppm-shift) <= tolerance:
          candidates.append(i)

      if len(candidates) == 1:
        resonance = resonances[candidates[0]]
        assignResToDim(peakDim,resonance)
Пример #7
0
def duplicateResidueAssignments(residueA, residueB, experimentChains=None):
    """
  Assign residueB to an equivalent set of resonances as residueA
  Optional dictionary, keyed by experiment to specifiy which chain (should be parent of residueA
  or residueB or None - for both) an experiment's peak assignments should go with.
 
  .. describe:: Input
  
  MolSystem.Residue, MolSystem.Residue, Dict of Nmr.Experiment:MolSystem.Chain (or None)

  .. describe:: Output
  
  None
  """

    from ccpnmr.analysis.core.AssignmentBasic import assignResToDim

    project = residueA.root
    nmrProject = project.currentNmrProject

    atomSetDict = {}
    for atom in residueB.atoms:
        atomSet = atom.atomSet
        if atomSet:
            atomSetDict[atomSet.name] = atomSet

    if experimentChains is None:
        experimentChains = {}
    else:
        for experiment in experimentChains:
            chain = experimentChains[experiment]
            molSystems = experiment.molSystems
            if chain and chain.molSystem not in molSystems:
                experiment.addMolSystem(chain.molSystem)
            else:
                if residueA.chain.molSystem not in molSystems:
                    experiment.addMolSystem(residueA.chain.molSystem)
                if residueB.chain.molSystem not in molSystems:
                    experiment.addMolSystem(residueB.chain.molSystem)

    resonancesA = getResidueResonances(residueA)
    resonancesB = getResidueResonances(residueB)

    resonancesDictA = {}
    for resonance in resonancesA:
        atomSetNames = [ass.name for ass in resonance.resonanceSet.atomSets]
        atomSetNames.sort()
        key = tuple(atomSetNames)
        resonancesDictA[key] = resonancesDictA.get(key, []) + [
            resonance,
        ]

    resonancesDictB = {}
    for resonance in resonancesB:
        atomSetNames = [ass.name for ass in resonance.resonanceSet.atomSets]
        atomSetNames.sort()
        key = tuple(atomSetNames)
        resonancesDictB[key] = resonancesDictB.get(key, []) + [
            resonance,
        ]

    transfers = []
    pureTransfer = True
    for key in resonancesDictA.keys():
        resonances1 = resonancesDictA[key]
        resonances2 = resonancesDictB.get(key, [])

        atomSets = []
        for atomSetName in key:
            if atomSetDict.has_key(atomSetName):
                atomSets.append(atomSetDict[atomSetName])

        if len(atomSets) == len(
                key
        ):  # If we find all equiv atom sets in destination (not always true if different res type)

            # Duplications of resonances is only done if needed at a per atomSet level
            doDuplicate = False
            contribs = set()

            for resonance1 in resonances1:
                contribs.update(resonance1.peakDimContribs)

            if contribs:
                for contrib in contribs:
                    experiment = contrib.peakDim.peak.peakList.dataSource.experiment
                    if experimentChains.get(
                            experiment, residueB.chain
                    ) is not residueB.chain:  # Not a plain transfer
                        doDuplicate = True
                        pureTransfer = False
                        break

            else:  # All orphans
                for experiment in experimentChains:
                    if experimentChains[experiment] is not residueB.chain:
                        doDuplicate = True
                        pureTransfer = False
                        break

            if doDuplicate:  # Not a plain transfer Need to make new resonances
                while len(resonances2) < len(resonances1):
                    resonances2.append(None)

                for i, resonance1 in enumerate(resonances1):
                    resonance2 = resonances2[i]
                    peakDimContribs = list(resonance1.peakDimContribs)

                    if peakDimContribs:
                        for peakDimContrib in peakDimContribs:
                            peakDim = peakDimContrib.peakDim
                            experiment = peakDim.peak.peakList.dataSource.experiment
                            chainB = experimentChains.get(experiment)

                            if chainB is None:  # Duplication on this peak
                                if resonance2 is None:
                                    resonance2 = nmrProject.newResonance(
                                        isotopeCode=resonances1[0].isotopeCode)
                                    assignAtomsToRes(atomSets, resonance2)
                                    resonances2[i] = resonance2

                                assignResToDim(peakDim,
                                               resonance2,
                                               doWarning=False)

                            elif chainB is residueB.chain:  # Transfer this peak
                                if resonance2 is None:
                                    resonance2 = nmrProject.newResonance(
                                        isotopeCode=resonances1[0].isotopeCode)
                                    assignAtomsToRes(atomSets, resonance2)
                                    resonances2[i] = resonance2

                                assignResToDim(peakDim,
                                               resonance2,
                                               doWarning=False)
                                for peakContrib in peakDimContrib.peakContribs:
                                    if len(peakContrib.peakDimContribs) < 2:
                                        peakContrib.delete()

                                if not peakDimContrib.isDeleted:
                                    peakDimContrib.delete()

                    else:
                        if resonance2 is None:
                            resonance2 = nmrProject.newResonance(
                                isotopeCode=resonances1[0].isotopeCode)
                            assignAtomsToRes(atomSets, resonance2)
                            resonances2[i] = resonance2

            else:
                # Plain transfer, move existing resonances to different atoms
                transfers.append((resonances1, atomSets))

    # Transfer original spin system to destination residue
    # to keep existing links and attrs (pure transfers only)
    spinSystem = nmrProject.findFirstResonanceGroup(residue=residueA)
    if spinSystem and pureTransfer:
        spinSystem.residue = residueB
        spinSystem.ccpCode = residueB.ccpCode
        spinSystem.chains = [
            residueB.chain,
        ]

    # Clear all resonance to spinSystem links first so
    # that assigniment can pickup the original spin system
    for resonances, atomSets in transfers:
        for resonance in resonances:
            resonance.resonanceGroup = None

    for resonances, atomSets in transfers:
        for resonance in resonances:
            assignAtomsToRes(atomSets, resonance)
Пример #8
0
    def initialisePeakList(self):

        isAmide = self.isAmide
        peakList = self.peakList

        if not peakList:
            showWarning('Warning',
                        'No peak list available or selected',
                        parent=self)
            return

        experimentType = peakList.dataSource.experiment.refExperiment.name

        for peak in peakList.peaks:

            peakDims = peak.sortedPeakDims()

            spinSystem = None
            resonances = []

            for peakDim in peakDims:
                dataDimRef = peakDim.dataDimRef

                if not dataDimRef:
                    continue

                isotopes = dataDimRef.expDimRef.isotopeCodes

                if not peakDim.peakDimContribs:
                    if '15N' in isotopes:
                        if hasattr(
                                peak, 'amideConfirmed'
                        ) and peak.amideConfirmed and isAmide.get(peak):
                            peakDim2 = isAmide[peak].findFirstPeakDim(
                                dim=peakDim.dim)
                            contrib2 = peakDim2.findFirstPeakDimContrib()

                            if contrib2:
                                contrib = assignResToDim(
                                    peakDim, contrib2.resonance)
                            else:
                                contrib = assignResToDim(peakDim)
                                assignResToDim(peakDim2, contrib.resonance)

                        else:
                            contrib = assignResToDim(peakDim)
                    else:
                        contrib = assignResToDim(peakDim)
                else:
                    contrib = peakDim.findFirstPeakDimContrib()

                if not contrib:
                    continue

                resonance = contrib.resonance

                if '13C' in isotopes:
                    if experimentType == 'H[N[CO]]':
                        resonance.setAssignNames([
                            'C',
                        ])
                    elif experimentType == 'H[N[co[CA]]]':
                        resonance.setAssignNames([
                            'CA',
                        ])

                    continue

                resonances.append(resonance)

                if isAmide.get(peak) and hasattr(
                        peak, 'amideConfirmed') and peak.amideConfirmed:
                    continue

                if ('1H' in isotopes) and (experimentType != 'H[C]'):
                    resonance.setAssignNames([
                        'H',
                    ])
                elif '15N' in isotopes:
                    resonance.setAssignNames([
                        'N',
                    ])

            for resonance in resonances:
                if resonance.resonanceGroup:
                    spinSystem = resonance.resonanceGroup

            for resonance in resonances:
                if spinSystem is None:
                    spinSystem = findSpinSystem(resonance)
                addSpinSystemResonance(spinSystem, resonance)
Пример #9
0
    def transferAssignments(self):
        '''Transfer assignments to project depending
           on the settings from the GUI.
        '''

        self.fetchOptions()

        if not self.dataModel or (not self.resonanceToDimension
                                  and not self.spinSystemToResidue):

            return

        strategy = self.strategy

        lookupSpinSystem = [
            self.getAssignedSpinSystem, self.getBestScoringSpinSystem,
            self.getUserDefinedSpinSystem, self.getSelectedSolutionSpinSystem
        ][self.spinSystemType]

        residues = self.dataModel.chain.residues

        spinSystemSequence = [lookupSpinSystem(res) for res in residues]

        ccpnSpinSystems = []
        ccpnResidues = []

        # if self.spinSystemType == 0 it means that it for sure already
        # assigned like this
        if self.spinSystemToResidue and not self.spinSystemType == 0:

            for spinSys, res in zip(spinSystemSequence, residues):

                if spinSys and res:

                    ccpnSpinSystems.append(spinSys.getCcpnResonanceGroup())
                    ccpnResidues.append(res.getCcpnResidue())

            assignSpinSystemstoResidues(ccpnSpinSystems,
                                        ccpnResidues,
                                        strategy=strategy,
                                        guiParent=self.guiParent)

        if self.resonanceToDimension:

            allSpectra = self.allSpectra

            if self.intra:

                for residue, spinSystem in zip(residues, spinSystemSequence):

                    if not spinSystem:

                        continue

                    intraLink = residue.getIntraLink(spinSystem)

                    for pl in intraLink.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum(
                        ) is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(
                                set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(
                                resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()
                            assignResToDim(ccpnDimension, ccpnResonance)

            if self.sequential:

                for residue, spinSystemA, spinSystemB in zip(
                        residues, spinSystemSequence, spinSystemSequence[1:]):

                    if not spinSystemA or not spinSystemB:

                        continue

                    link = residue.getLink(spinSystemA, spinSystemB)

                    for pl in link.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum(
                        ) is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(
                                set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(
                                resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()

                            assignResToDim(ccpnDimension, ccpnResonance)

        self.guiParent.resultsTab.update()
Пример #10
0
def pickAssignSpecFromRoot(argServer, rootPeakList=None, targetPeakList=None):

    toleranceDict = {'1H': 0.03, '13C': 0.1, '15N': 0.15}

    assert argServer or (rootPeakList and targetPeakList)

    if argServer:
        project = argServer.getProject()
    else:
        project = rootPeakList.root

    spectra = []
    for experiment in project.currentNmrProject.sortedExperiments():
        for spectrum in experiment.sortedDataSources():
            spectra.append(spectrum)

    if not rootPeakList:
        rootSpec = argServer.getSpectrum(spectra)
        rootPeakList = argServer.getPeakList(rootSpec)

    rootSpec = rootPeakList.dataSource
    rootIsotopes = getSpectrumIsotopes(rootSpec)

    tolerances = []
    for isotope in rootIsotopes:
        tolerance = argServer.askFloat(
            '%s tolerance' % isotope, toleranceDict.get(
                isotope, 0.1)) or toleranceDict.get(isotope, 0.1)
        tolerances.append(tolerance)

    if not targetPeakList:
        targetSpectra = []
        for experiment in project.currentNmrProject.experiments:
            for spectrum in experiment.dataSources:
                isotopes = getSpectrumIsotopes(spectrum)
                n = 0
                for isotope in rootIsotopes:
                    if isotope in isotopes:
                        isotopes.remove(isotope)
                        n += 1

                if n == len(rootIsotopes):
                    targetSpectra.append(spectrum)

        targetSpec = argServer.getSpectrum(targetSpectra)
        targetPeakList = argServer.getPeakList(targetSpec)

    targetSpec = targetPeakList.dataSource

    if not targetSpec:
        argServer.showWarning('No suitable target spectra found.')

    # Determine mapping of root to target dimensions according to data dim isotopes.
    #  - Only ask user if there are multiple possibilities.

    mapping = []
    targetIsotopes = getSpectrumIsotopes(targetSpec)
    i = 0

    for isotope in rootIsotopes:
        if targetIsotopes.count(isotope) == 1:
            mapping.append(targetIsotopes.index(isotope))

        else:
            j = 0
            matches = []
            for targetIsotope in targetIsotopes:
                if targetIsotope == isotope:
                    matches.append(j)
                j += 1

            for j in matches[:-1]:
                if argServer.askYesNo(
                        'Match root dimension %d (%s) to target dimension %d?'
                        % (i + 1, isotope, j + 1)):
                    mapping.append(j)
                    break

            else:
                mapping.append(matches[-1])

        i += 1

    fullRegion = []
    for dataDim in targetSpec.sortedDataDims():

        if dataDim.className == 'FreqDataDim':
            dataDimRef = getPrimaryDataDimRef(dataDim)
            valueMax = pnt2ppm(1, dataDimRef)
            valueMin = pnt2ppm(dataDim.numPoints, dataDimRef)
            fullRegion.append([valueMin, valueMax])
        else:
            fullRegion.append([1, dataDim.numPoints])

    M = len(rootPeakList.peaks)
    c = 0

    foundPeaks = 0
    for peak in rootPeakList.peaks:

        region = list(fullRegion)

        for i, peakDim in enumerate(peak.sortedPeakDims()):
            if peakDim.dataDimRef:
                error = tolerances[i]
                value = peakDim.value
                region[mapping[i]] = (value - error, value + error)

        peaks = searchPeaks([
            targetPeakList,
        ], region)
        peaks.extend(findPeaks(targetPeakList, region))

        # possible to grow the region here of no peaks are found

        for peak2 in peaks:
            for intens in peak.peakIntensities:
                if str(intens.value) == 'inf':
                    peaks.remove(peak2)
                    peak2.delete()
                    break

        foundPeaks += len(peaks)
        c += 1

        for i, peakDim in enumerate(peak.sortedPeakDims()):
            for peak2 in peaks:
                peakDim2 = peak2.sortedPeakDims()[mapping[i]]
                if len(peakDim2.peakDimContribs) < 1:
                    for contrib in peakDim.peakDimContribs:
                        assignResToDim(peakDim2,
                                       contrib.resonance,
                                       doWarning=0)

        print 'Root peak %d of %d' % (c, M)

    if argServer:
        name = '%s:%s' % (targetPeakList.dataSource.experiment.name,
                          targetPeakList.dataSource.name)
        argServer.showInfo('Picked %d peaks in %s' % (foundPeaks, name))

    return targetPeakList.peaks
Пример #11
0
def linkSpinSystemInterIntraResonances(spinSystem,
                                       activeLists,
                                       tolerances=None):

    nmrProject = spinSystem.topObject
    prevSpinSystem = findConnectedSpinSystem(spinSystem)
    allowedRefExps, coRefExps = getSeqAssignRefExperiments(nmrProject.root)

    if not prevSpinSystem:
        if spinSystem.residue:
            residueB = getLinkedResidue(spinSystem.residue, linkCode='prev')
            prevSpinSystem = nmrProject.findFirstResonanceGroup(
                residue=residueB)

    if not prevSpinSystem:
        prevSpinSystem = nmrProject.newResonanceGroup()
        makeSeqSpinSystemLink(prevSpinSystem, spinSystem)

    peaks = []
    found = {}
    expTypes = {}
    linkDims = {}

    # go though the peaks associated with this spin system
    # within the selected peak lists
    # find the indirect, linking dimension
    for resonance in spinSystem.resonances:
        if resonance.isotopeCode != '15N':
            continue

        if not isResonanceAmide(resonance):
            continue

        for contrib in resonance.peakDimContribs:
            peakDim = contrib.peakDim
            peak = peakDim.peak

            if found.get(peak):
                continue

            peakList = peak.peakList
            if peakList not in activeLists:
                continue

            setupPeakHeight(peak)
            intensity = peak.findFirstPeakIntensity(intensityType='height')
            if not intensity:
                continue

            spectrum = peakList.dataSource
            expType = expTypes.get(peakList, spectrum.experiment.refExperiment)
            expTypes[peakList] = expType

            linkDim = linkDims.get(peakList)
            if linkDim is None:
                boundDict = {}
                for dataDimA, dataDimB in getOnebondDataDims(spectrum):
                    boundDict[dataDimA] = dataDimB
                    boundDict[dataDimB] = dataDimA

                dims = []
                for dataDim in spectrum.dataDims:
                    dataDimRef = getPrimaryDataDimRef(dataDim)

                    if not dataDimRef:
                        continue

                    isotopes = '/'.join(dataDimRef.expDimRef.isotopeCodes)
                    dims.append((isotopes, dataDim))

                dims.sort()
                for isotopes, dataDim in dims:
                    if '13C' == isotopes:
                        linkDim = (dataDim.dim, isotopes)
                        break

                    elif '1H' == isotopes:
                        dataDimB = boundDict.get(dataDim)

                        if dataDimB:
                            dataDimRefB = getPrimaryDataDimRef(dataDimB)

                            if '15N' in dataDimRefB.expDimRef.isotopeCodes:
                                continue

                        linkDim = (dataDim.dim, isotopes)
                        break

                linkDims[peakList] = linkDim

            if linkDim is None:
                continue

            if peakDim.dim is linkDim[0]:
                continue

            found[peak] = True
            peakDimL = peak.findFirstPeakDim(dim=linkDim[0])
            isotope = linkDim[1]

            peaks.append((peak, expType, peakDimL, isotope, intensity.value))

    peakTypes = []
    interResonances = {}
    intraResonances = {}
    for peak, expType, peakDim, isotope, height in peaks:

        ppm = peakDim.value
        atomType = None

        if expType in coRefExps:
            isInter = True
        elif 'N[coca]' in expType.name:
            isInter = False
        elif 'N_' in expType.name:
            isInter = False
        else:
            isInter = None

        resonance = None
        contrib = peakDim.findFirstPeakDimContrib()
        if contrib:
            resonance = contrib.resonance

            if isInter and resonance.assignNames:
                atomType = resonance.assignNames[0]
                interResonances[atomType] = (resonance, ppm, prevSpinSystem)

            if (isInter is False) and resonance.assignNames:
                atomType = resonance.assignNames[0]
                intraResonances[atomType] = (resonance, ppm, spinSystem)

        if not atomType:
            atomType = guessAtomType(expType, ppm, height)

        peakTypes.append((peakDim, atomType, contrib, isotope, isInter, ppm))

    # Get known inter/intra resonance assignments
    # for each atom type
    for peakDim, atomType, contrib, isotope, isInter, ppm in peakTypes:
        if isInter is None:
            continue
        elif isInter:
            resDict = interResonances
            uniqSpinSystem = prevSpinSystem
        else:
            resDict = intraResonances
            uniqSpinSystem = spinSystem

        if atomType:
            resonance, ppm2, ss = resDict.get(atomType, (None, None, None))

            if (resonance is None) and contrib:
                resDict[atomType] = (contrib.resonance, ppm, uniqSpinSystem)

    # Make any new assignments for the unambig peaks
    untypedIntra = []
    untypedInter = []
    for i, data in enumerate(peakTypes):
        (peakDim, atomType, contrib, isotope, isInter, ppm) = data

        if isInter is None:
            continue

        elif isInter:
            untyped = untypedInter
            resDict = interResonances
            uniqSpinSystem = prevSpinSystem

        else:
            resDict = intraResonances
            untyped = untypedIntra
            uniqSpinSystem = spinSystem

        if atomType:
            # Get any previously used resonances for this atom type
            resonance, ppm2, ss = resDict.get(atomType, (None, None, None))

            # If no prev resonance, look at the peak assignment
            if (not resonance) and contrib:
                resonance = contrib.resonance

            # Check to ensure that any existing resonance
            # is from the correct, this/prev spin system
            if resonance:
                spinSystem2 = resonance.resonanceGroup
                if spinSystem2 and (spinSystem2 is not uniqSpinSystem):
                    resonance = None

            # If no valid reasonance yet, check named ones
            # in the required spin system
            if not resonance:
                for resonance2 in uniqSpinSystem.resonances:
                    if atomType in resonance2.assignNames:
                        resonance = resonance2
                        break

            # If no valid resonance yet, make a new one
            if not resonance:
                resonance = nmrProject.newResonance(isotopeCode=isotope)

            # If peak dim is assigned to the wrong resonance
            # clear the assignment
            if contrib and contrib.resonance is not resonance:
                clearPeakDim(peakDim)
                contrib = None

            # Ensure the peak dim is assigned correctly
            if not contrib:
                assignResToDim(peakDim, resonance)

            # Check type of resonance set correctly
            if not resonance.assignNames:
                assignResonanceType(resonance, assignNames=(atomType, ))

            # Check spin system set correctly
            if resonance.resonanceGroup is not uniqSpinSystem:
                addSpinSystemResonance(uniqSpinSystem, resonance)

            # Store resonance by atom type, so that it can
            # be picked up later
            resDict[atomType] = (resonance, ppm, uniqSpinSystem)

        else:
            untyped.append((peakDim, contrib, isotope, isInter, ppm, i))

    uniqResonances = interResonances.values() + intraResonances.values()

    # Cluster untyped peaks
    interCluster = {}
    intraCluster = ()

    interData = (untypedInter, interCluster, prevSpinSystem)
    intraData = (untypedIntra, intraCluster, spinSystem)

    for untyped, clusters, uniqSpinSystem in (interData, intraData):

        for peakDim, contrib, isotope, isInter, ppm, i in untyped:

            if peakDim in clusters:
                continue

            if tolerances:
                tolerance = tolerances[isotope]
            else:
                tolerance = getAnalysisDataDim(peakDim.dataDim).assignTolerance

            if contrib:
                resonance = contrib.resonance
            else:
                resonance = None

            cluster = [peakDim]
            interCluster[peakDim] = True
            for peakDimB, contribB, isotopeB, isInterB, ppmB, i in untyped:
                if isotope != isotopeB:
                    continue

                if abs(ppmB - ppm) > tolerance:
                    continue

                if peakDim.peak.peakList == peakDimB.peak.peakList:
                    continue

                if contribB:
                    if not resonance:
                        resonance = contribB.resonance
                    if resonance is not contribB.resonance:
                        clearPeakDim(peakDimB)
                        assignResToDim(peakDimB,
                                       resonance,
                                       tolerance=tolerance)

                cluster.append(peakDimB)
                clusters[peakDimB] = True

            if not resonance:
                # Try to macth to any typed peaks
                for peakDimB, atomType, contribB, isotopeB, isInterB, ppmB in peakTypes:
                    if not contribB:
                        continue

                    if not atomType:
                        continue

                    if isotope != isotopeB:
                        continue

                    if abs(ppmB - ppm) > tolerance:
                        continue

                    if peakDim.peak.peakList == peakDimB.peak.peakList:
                        continue

                    resonance = contribB.resonance

                    # Set type for this peak
                    peakTypes[i] = (peakDim, atomType, contrib, isotope,
                                    isInter, ppm)
                    break

            if not resonance:
                resonance = nmrProject.newResonance(isotopeCode=isotope)

            for peakDimC in cluster:
                clearPeakDim(peakDimC)
                assignResToDim(peakDimC, resonance, tolerance=tolerance)

            uniqResonances.append((resonance, ppm, uniqSpinSystem))

            if resonance.resonanceGroup is not uniqSpinSystem:
                addSpinSystemResonance(uniqSpinSystem, resonance)

    # E.g. Find the HNCA peaks which best match the HNcoCA/iHNCA resonances
    matchDict = {}
    closestDict = {}
    for peakDim, atomType, contrib, isotope, isInter, ppm in peakTypes:
        if isInter is not None:
            # Not through HNcoCA or iHNCA
            continue

        if tolerances:
            tolerance = tolerances[isotope]
        else:
            tolerance = getAnalysisDataDim(peakDim.dataDim).assignTolerance

        matches = []
        shiftList = peakDim.peak.peakList.dataSource.experiment.shiftList
        for resonanceB, ppm2, uniqSpinSystem in uniqResonances:

            if resonanceB.isotopeCode != isotope:
                continue

            assignNames = resonanceB.assignNames
            if assignNames and (atomType not in assignNames):
                continue

            if not ppm2:
                shift = resonanceB.findFirstShift(parentList=shiftList)
                if not shift:
                    continue
                ppm2 = shift.value

            delta = abs(ppm - ppm2)
            prevDelta = closestDict.get(peakDim)
            if (prevDelta is None) or (delta < prevDelta):
                closestDict[peakDim] = delta

            if delta > tolerance:
                continue

            matches.append((delta, resonanceB, uniqSpinSystem))

        # Best match has smallest delta
        if matches:
            matches.sort()
            delta, resonance, uniqSpinSystem = matches[0]

            prevDelta, peakDimB, ss = matchDict.get(resonance,
                                                    (None, None, None))
            if not peakDimB or (delta < prevDelta):
                matchDict[resonance] = (delta, peakDim, uniqSpinSystem)

    uniqResonanceDict = {}
    for resonance in matchDict.keys():
        delta, peakDim, uniqSpinSystem = matchDict[resonance]
        uniqResonanceDict[peakDim] = resonance, uniqSpinSystem

    # E.g. go through HNCA peaks and assign to
    # HNcoCA or iHNCA resonances if required
    nonMatched = {}
    for peakDim, atomType, contrib, isotope, isInter, ppm in peakTypes:
        if isInter is not None:
            continue

        if closestDict.get(peakDim) is None:
            # No inter residue peaks at all
            intensity = peak.findFirstPeakIntensity(intensityType='height')

            if intensity:
                if not nonMatched.has_key(atomType):
                    nonMatched[atomType] = []
                nonMatched[atomType].append(
                    (-abs(intensity.value), peakDim, contrib, isotope))

            continue

        match = uniqResonanceDict.get(peakDim)
        if match:
            resonance, uniqSpinSystem = match

            if tolerances:
                tolerance = tolerances[isotope]
            else:
                tolerance = getAnalysisDataDim(peakDim.dataDim).assignTolerance

            # untyped through-carbonyl resonance can interit type
            # by matching typed peaks

            if atomType and not resonance.assignNames:
                resonance.addAssignName(atomType)

            # e.g. the HNcoCA resonance is the one to put on this HNCA peak
            if contrib:
                if contrib.resonance is not resonance:
                    clearPeakDim(peakDim)
                    assignResToDim(peakDim, resonance, tolerance=tolerance)
            else:
                assignResToDim(peakDim, resonance, tolerance=tolerance)

        else:
            # No match to an unambig peak
            # store to work out which is best for each atom type
            # e.g. just in case we have two intra residue CA possibilites
            if not nonMatched.has_key(atomType):
                nonMatched[atomType] = []

            nonMatched[atomType].append(
                (closestDict[peakDim], peakDim, contrib, isotope))

    for atomType in nonMatched.keys():

        if (atomType in intraResonances) and (atomType in interResonances):
            # Both resonances already found, peak is spurious
            continue

        if (atomType in intraResonances) and (atomType not in interResonances):
            # E.g. there was iHNCA but no HNcoCA
            otherSpinSystem = prevSpinSystem

        elif (atomType not in intraResonances) and (atomType
                                                    in interResonances):
            # E.g. there was HNcoCA but no iHNCA
            otherSpinSystem = spinSystem

        else:
            # No info
            continue

        peakDimList = nonMatched[atomType]
        peakDimList.sort()
        # Assume that if we have two possible ambiguous peaks
        # for any given atom type, then the one furthest from an
        # unambigous peak is the best to take
        deltaPpm, peakDim, contrib, isotope = peakDimList[-1]

        if tolerances:
            tolerance = tolerances[isotope]
        else:
            tolerance = getAnalysisDataDim(peakDim.dataDim).assignTolerance

        # E.g. this HNCA peak matches no HNcoCA/iHNCA resonances
        resonance = None
        if contrib:
            resonance = contrib.resonance

        if resonance:
            # Already have an assignment
            spinSystem2 = resonance.resonanceGroup
            if spinSystem2 is None:
                addSpinSystemResonance(otherSpinSystem, resonance)

            elif spinSystem2 is not otherSpinSystem:
                resonance = nmrProject.newResonance(isotopeCode=isotope)
                addSpinSystemResonance(otherSpinSystem, resonance)
                clearPeakDim(peakDim)
                contrib = assignResToDim(peakDim,
                                         resonance,
                                         tolerance=tolerance)

        else:
            # Needs a new assignment
            for resonance2 in otherSpinSystem.resonances:
                if atomType in resonance2.assignNames:
                    resonance = resonance2
                    break

            if not resonance:
                resonance = nmrProject.newResonance(isotopeCode=isotope)
                contrib = assignResToDim(peakDim,
                                         resonance,
                                         tolerance=tolerance)
                addSpinSystemResonance(otherSpinSystem, resonance)

        if not contrib:
            # Resonance has come from the spin system due to its atomTypes
            contrib = assignResToDim(peakDim,
                                     resonance,
                                     tolerance=2 * tolerance)

        if not contrib:
            # Existing resonance on spin system was too far away
            resonance = nmrProject.newResonance(isotopeCode=isotope)
            contrib = assignResToDim(peakDim, resonance, tolerance=tolerance)
            addSpinSystemResonance(otherSpinSystem, resonance)

        if atomType:
            assignNames = (atomType, )
        else:
            assignNames = []

        if not resonance.assignNames:
            assignResonanceType(resonance, assignNames=assignNames)
Пример #12
0
def fixProchiralSwaps(project, sdt=0.04):
  # Threshold shift SD for action

  nmr = project.currentNmrProject

  prochirals = set()
  for resonance in nmr.resonances:
    resonanceSet = resonance.resonanceSet

    if not resonanceSet:
      continue

    resonances = resonanceSet.resonances

    if len(resonances) == 2:
      prochirals.add(resonances)

  shiftLists = nmr.findAllMeasurementLists(className='ShiftList')
  shiftLists = [(len(sl.measurements), sl) for sl in shiftLists if sl.experiments]
  shiftLists.sort()

  shiftList = shiftLists[-1][1]

  nSwaps = 0

  for resonanceA, resonanceB in prochirals:
    shiftA = resonanceA.findFirstShift(parentList=shiftList)
    shiftB = resonanceB.findFirstShift(parentList=shiftList)

    if not (shiftA and shiftB):
      continue


    sdA = shiftA.error
    sdB = shiftB.error

    if (sdA > sdt) or (sdB > sdt):

      if shiftB.value < shiftA.value:
        resonanceA, resonanceB = resonanceB, resonanceA

      contribsA = resonanceA.peakDimContribs
      contribsB = resonanceB.peakDimContribs

      peakDimsA = set([c.peakDim for c in contribsA])
      peakDimsB = set([c.peakDim for c in contribsB])

      #peakDimsA = [pd for pd in peakDimsA0 if pd not in peakDimsB0]
      #peakDimsB = [pd for pd in peakDimsB0 if pd not in peakDimsA0]

      ppms = []
      peakDims = []
      for peakDim in peakDimsA:
        ppms.append(peakDim.value)
        peakDims.append(peakDim)
      for peakDim in peakDimsB:
        ppms.append(peakDim.value)
        peakDims.append(peakDim)

      if not ppms:
        continue

      centers, clusters, clusterIndices = kMeansPlusPlus(ppms, 2) #@UnusedVariable clusters
      centerA, centerB = centers

      if abs(centerA - centerB) < sdt:
        continue

      peakDimsA = [peakDims[i] for i in clusterIndices[0]]
      peakDimsB = [peakDims[i] for i in clusterIndices[1]]

      if centerB < centerA:
        peakDimsA, peakDimsB = peakDimsB, peakDimsA

      for peakDim in peakDimsA:
        contribA = peakDim.findFirstPeakDimContrib(resonance=resonanceA)
        contribB = peakDim.findFirstPeakDimContrib(resonance=resonanceB)

        if contribB:
          peakContribs = contribB.peakContribs
          contribB.delete()

          if not contribA:
            assignResToDim(peakDim, resonanceA, peakContribs=peakContribs)
          nSwaps += 1

      for peakDim in peakDimsB:
        contribB = peakDim.findFirstPeakDimContrib(resonance=resonanceB)
        contribA = peakDim.findFirstPeakDimContrib(resonance=resonanceA)

        if contribA:
          peakContribs = contribA.peakContribs
          contribA.delete()

          if not contribB:
            assignResToDim(peakDim, resonanceB, peakContribs=peakContribs)
          nSwaps += 1

  return nSwaps
Пример #13
0
def assignCloseSingleShiftMatches(peakList):

    spectrum = peakList.dataSource
    experiment = spectrum.experiment
    shiftList = experiment.shiftList
    hDims = findSpectrumDimsByIsotope(spectrum, '1H')
    tolerances = getDimTolerances(spectrum)
    bondedDims = getBondedDimsDict(spectrum)

    info = (experiment.name, spectrum.name, peakList.serial,
            len(peakList.peaks))
    print 'Assigning obvious shift matches for %s:%s:%d - %d peaks' % info

    c = 0
    for peak in peakList.peaks:
        if c and (c % 100 == 0):
            print '   %d' % (c, )
        c += 1

        peakDims = peak.sortedPeakDims()
        boundResonances = {}
        for dim in hDims:
            peakDim = peakDims[dim]
            if not peakDim.peakDimContribs:
                resonances = []
                shifts = findMatchingPeakDimShifts(peakDim,
                                                   shiftRanges=None,
                                                   tolerance=tolerances[dim],
                                                   aliasing=True,
                                                   findAssigned=False)
                dim2 = bondedDims.get(dim)
                peakDim2 = None
                if dim2 is not None:
                    peakDim2 = peakDims[dim2]
                    shifts2 = []

                    if peakDim2.peakDimContribs:
                        for contrib in peakDim2.peakDimContribs:
                            shift = contrib.resonance.findFirstShift(
                                parentList=shiftList)
                            if shift:
                                shifts2.append(shift)

                    else:
                        shifts2 = findMatchingPeakDimShifts(
                            peakDim2,
                            shiftRanges=None,
                            tolerance=tolerances[dim2],
                            aliasing=True,
                            findAssigned=False)
                    for shift in shifts:
                        resonance1 = shift.resonance
                        for shift2 in shifts2:
                            resonance2 = shift2.resonance
                            if areResonancesBound(resonance1, resonance2):
                                resonances.append(resonance1)
                                boundResonances[resonance1] = resonance2
                                break

                else:
                    for shift in shifts:
                        resonances.append(shift.resonance)

                if len(resonances) == 1:
                    resonance = resonances[0]
                    assignResToDim(peakDim, resonance, doWarning=False)

                    resonance2 = boundResonances.get(resonance)
                    if peakDim2 and (resonance2 is not None):
                        assignResToDim(peakDim2, resonance2, doWarning=False)
Пример #14
0
def fixProchiralSwaps(project, sdt=0.04):
    # Threshold shift SD for action

    nmr = project.currentNmrProject

    prochirals = set()
    for resonance in nmr.resonances:
        resonanceSet = resonance.resonanceSet

        if not resonanceSet:
            continue

        resonances = resonanceSet.resonances

        if len(resonances) == 2:
            prochirals.add(resonances)

    shiftLists = nmr.findAllMeasurementLists(className='ShiftList')
    shiftLists = [(len(sl.measurements), sl) for sl in shiftLists
                  if sl.experiments]
    shiftLists.sort()

    shiftList = shiftLists[-1][1]

    nSwaps = 0

    for resonanceA, resonanceB in prochirals:
        shiftA = resonanceA.findFirstShift(parentList=shiftList)
        shiftB = resonanceB.findFirstShift(parentList=shiftList)

        if not (shiftA and shiftB):
            continue

        sdA = shiftA.error
        sdB = shiftB.error

        if (sdA > sdt) or (sdB > sdt):

            if shiftB.value < shiftA.value:
                resonanceA, resonanceB = resonanceB, resonanceA

            contribsA = resonanceA.peakDimContribs
            contribsB = resonanceB.peakDimContribs

            peakDimsA = set([c.peakDim for c in contribsA])
            peakDimsB = set([c.peakDim for c in contribsB])

            #peakDimsA = [pd for pd in peakDimsA0 if pd not in peakDimsB0]
            #peakDimsB = [pd for pd in peakDimsB0 if pd not in peakDimsA0]

            ppms = []
            peakDims = []
            for peakDim in peakDimsA:
                ppms.append(peakDim.value)
                peakDims.append(peakDim)
            for peakDim in peakDimsB:
                ppms.append(peakDim.value)
                peakDims.append(peakDim)

            if not ppms:
                continue

            centers, clusters, clusterIndices = kMeansPlusPlus(
                ppms, 2)  #@UnusedVariable clusters
            centerA, centerB = centers

            if abs(centerA - centerB) < sdt:
                continue

            peakDimsA = [peakDims[i] for i in clusterIndices[0]]
            peakDimsB = [peakDims[i] for i in clusterIndices[1]]

            if centerB < centerA:
                peakDimsA, peakDimsB = peakDimsB, peakDimsA

            for peakDim in peakDimsA:
                contribA = peakDim.findFirstPeakDimContrib(
                    resonance=resonanceA)
                contribB = peakDim.findFirstPeakDimContrib(
                    resonance=resonanceB)

                if contribB:
                    peakContribs = contribB.peakContribs
                    contribB.delete()

                    if not contribA:
                        assignResToDim(peakDim,
                                       resonanceA,
                                       peakContribs=peakContribs)
                    nSwaps += 1

            for peakDim in peakDimsB:
                contribB = peakDim.findFirstPeakDimContrib(
                    resonance=resonanceB)
                contribA = peakDim.findFirstPeakDimContrib(
                    resonance=resonanceA)

                if contribA:
                    peakContribs = contribA.peakContribs
                    contribA.delete()

                    if not contribB:
                        assignResToDim(peakDim,
                                       resonanceB,
                                       peakContribs=peakContribs)
                    nSwaps += 1

    return nSwaps
Пример #15
0
def pickAssignSpecFromRoot(rootPeaks,
                           targetPeakList,
                           tolerances=None,
                           progressBar=None,
                           pickNew=True,
                           diagTolerance=None,
                           waterExclusion=None):
    """Descrn: Pick peaks in a spectrum based upon a root peak list
             and assign picked peaks to root resonances.
     Inputs: List of Nmr.Peaks, Nmr.PeakList, List of Floats (target dim order),
             memops.gui.ProgressBar, Boolean, Float or None,
             2-Tuple of Floats (min, max) or None
     Output: Nmr.Peaks, Dict of Int:Int (dim mapping root:target)
  """

    # TBD: perhaps a list of peaks rather than a set should be passed in
    rootPeakList = tuple(rootPeaks)[0].peakList
    project = rootPeakList.root

    spectrum0 = rootPeakList.dataSource
    spectrum1 = targetPeakList.dataSource

    if not tolerances:
        tolerances = []
        for dataDim in spectrum1.sortedDataDims():
            tolerances.append(getAnalysisDataDim(dataDim).assignTolerance)

    expDimRefs0 = ExperimentBasic.getOnebondExpDimRefs(spectrum0.experiment)
    expDimRefs1 = ExperimentBasic.getOnebondExpDimRefs(spectrum1.experiment)

    if not expDimRefs0:
        msg = 'Spectrum %s:%s has no directly bonded dims.'
        showWarning('Failure',
                    msg % (spectrum0.experiment.name, spectrum0.name))
        return

    if not expDimRefs1:
        msg = 'Spectrum %s:%s has no directly bonded dims.'
        showWarning('Failure',
                    msg % (spectrum1.experiment.name, spectrum1.name))
        return

    # could really do with a generic get matching dataDims function

    # TBD try PeakBasic.getDataDimMapping()

    dimMapping = {}

    for expDimRef0, expDimRef1 in expDimRefs0:
        dataDim0 = spectrum0.findFirstDataDim(expDim=expDimRef0.expDim)
        dataDim1 = spectrum0.findFirstDataDim(expDim=expDimRef1.expDim)
        isotopes0 = expDimRef0.isotopeCodes
        isotopes1 = expDimRef1.isotopeCodes
        if '1H' in isotopes0 or '1H' in isotopes1:
            break

    boundDims = set([dataDim0.dim, dataDim1.dim])

    for expDimRef2, expDimRef3 in expDimRefs1:

        isotopes2 = expDimRef2.isotopeCodes
        isotopes3 = expDimRef3.isotopeCodes
        dataDim2 = spectrum1.findFirstDataDim(expDim=expDimRef2.expDim)
        dataDim3 = spectrum1.findFirstDataDim(expDim=expDimRef3.expDim)

        if not (dataDim2 and dataDim3):
            continue

        if (isotopes0 == isotopes2) and (isotopes1 == isotopes3):
            dimMapping[dataDim0.dim] = dataDim2.dim
            dimMapping[dataDim1.dim] = dataDim3.dim
            break

        elif (isotopes0 == isotopes3) and (isotopes1 == isotopes2):
            dimMapping[dataDim0.dim] = dataDim3.dim
            dimMapping[dataDim1.dim] = dataDim2.dim
            break

    if not dimMapping:
        msg = 'Could not find equivalent dims in spectra %s:%s & %s:%s'
        data = (spectrum0.experiment.name, spectrum0.name,
                spectrum1.experiment.name, spectrum1.name)
        showWarning('Failure', msg % data)
        return

    if progressBar:
        progressBar.total = len(rootPeaks)
        progressBar.set(0)
        progressBar.open()

    fullRegion = []
    getDimRef = ExperimentBasic.getPrimaryDataDimRef
    targetDims = targetPeakList.dataSource.sortedDataDims()
    targetDims = [(getDimRef(dd), dd) for dd in targetDims]
    targetIsotopes = [
        ','.join(ddr.expDimRef.isotopeCodes) for (ddr, dd) in targetDims
    ]

    for dataDimRef, dataDim in targetDims:
        valueMax = pnt2ppm(1, dataDimRef)
        valueMin = pnt2ppm(dataDim.numPoints, dataDimRef)
        fullRegion.append([valueMin, valueMax])

    foundPeaks = []
    for peak in rootPeaks:

        peakRegion = list(fullRegion)
        rootIsotopes = []
        rootMapDims = set()
        values = []

        boundPeakDims = [
            pd for pd in peak.sortedPeakDims() if pd.dim in boundDims
        ]

        for i, peakDim in enumerate(boundPeakDims):
            error = tolerances[i]
            value = peakDim.value
            j = dimMapping[peakDim.dim] - 1
            peakRegion[j] = (value - error, value + error)

            rootIsotopes.append(targetIsotopes[j])
            rootMapDims.add(j)
            values.append(value)

        regions = [
            peakRegion,
        ]
        if diagTolerance:
            for i, isotopes in enumerate(targetIsotopes):
                if (i not in rootMapDims) and (isotopes in rootIsotopes):
                    value = values[rootIsotopes.index(isotopes)]

                    # Chop in two at diagonal
                    regions2 = []
                    for region in regions:
                        regionA = list(region)
                        regionB = list(region)
                        valueMin, valueMax = region[i]
                        regionA[i] = (valueMin, value - diagTolerance)
                        regionB[i] = (value + diagTolerance, valueMax)
                        regions2.append(regionA)
                        regions2.append(regionB)

                    regions = regions2

        if waterExclusion:
            waterMin, waterMax = waterExclusion
            for i, isotopes in enumerate(targetIsotopes):
                if (i not in rootMapDims) and (isotopes in rootIsotopes):
                    regions2 = []

                    # Chop at water
                    for region in regions:
                        valueMin, valueMax = region[i]

                        if valueMin < waterMin < valueMax:
                            regionA = list(region)
                            regionA[i] = (valueMin, waterMin)
                            regions2.append(regionA)

                            if valueMin < waterMax < valueMax:
                                regionB = list(region)
                                regionB[i] = (waterMax, valueMax)
                                regions2.append(regionB)

                        elif valueMin < waterMax < valueMax:
                            regionB = list(region)
                            regionB[i] = (waterMax, valueMax)
                            regions2.append(regionB)

                        else:
                            regions2.append(region)

                    regions = regions2

        peaks = []
        for region in regions:
            peaks.extend(searchPeaks([
                targetPeakList,
            ], region))

            if pickNew:
                peaks.extend(findPeaks(targetPeakList, region))

        # possible to grow the region here if no peaks are found

        for peak2 in peaks:
            for intens in peak.peakIntensities:
                if str(intens.value) == 'inf':
                    peaks.remove(peak2)
                    peak2.delete()
                    break

        foundPeaks.extend(peaks)

        for i, peakDim in enumerate(boundPeakDims):
            dim2 = dimMapping[peakDim.dim]
            resonances = [c.resonance for c in peakDim.peakDimContribs]
            tolerance = tolerances[i]

            for peak2 in peaks:
                peakDim2 = peak2.findFirstPeakDim(dim=dim2)
                if not peakDim2.peakDimContribs:
                    for resonance in resonances:
                        assignResToDim(peakDim2,
                                       resonance,
                                       tolerance=10 * tolerance,
                                       doWarning=False)

        if progressBar:
            progressBar.increment()

    if progressBar:
        progressBar.close()

    return foundPeaks, dimMapping
Пример #16
0
def assignDimNewResonances(peaks,
                           dimNum,
                           diagTolerance=0.5,
                           waterMinPpm=4.88,
                           waterMaxPpm=4.92,
                           assignType=False):
    """Descrn: 
     Inputs: 
     Output: 
  """

    resonances = []
    for peak in peaks:
        peakDims = peak.sortedPeakDims()
        peakDim = peak.findFirstPeakDim(dim=dimNum)
        ppm = peakDim.value

        # Check for 1H diagonal peaks and water range
        if '1H' in peakDim.dataDimRef.expDimRef.isotopeCodes:
            if (ppm >= waterMinPpm) and (ppm <= waterMaxPpm):
                continue

            ignore = False
            for peakDim0 in peak.peakDims:
                if peakDim0 is not peakDim:
                    if '1H' in peakDim0.dataDimRef.expDimRef.isotopeCodes:
                        if abs(ppm - peakDim0.value) < diagTolerance:
                            ignore = True
                            break

            if ignore:
                continue

        refExperiment = peak.peakList.dataSource.experiment.refExperiment

        if len(peakDim.peakDimContribs) < 1:
            resonance = assignResToDim(peakDim).resonance
            resonances.append(resonance)

            if refExperiment and (refExperiment.nmrExpPrototype.name
                                  in intraSpinSystemExperiments):
                contrib0 = None
                for peakDim0 in peak.peakDims:
                    if (peakDim0 is not peakDim) and peakDim0.peakDimContribs:
                        contrib0 = peakDim0.findFirstPeakDimContrib()

                if contrib0:
                    resonance0 = contrib0.resonance
                    if resonance0.resonanceGroup:
                        addSpinSystemResonance(resonance0.resonanceGroup,
                                               resonance)

            if assignType:
                refExpDimRef = peakDim.dataDimRef.expDimRef.refExpDimRef
                if refExpDimRef:
                    setResonanceTypeFromRefExp(resonance, refExpDimRef)

        else:
            resonance = peakDim.findFirstPeakDimContrib().resonance

            if assignType:
                refExpDimRef = peakDim.dataDimRef.expDimRef.refExpDimRef
                if refExpDimRef:
                    setResonanceTypeFromRefExp(resonance, refExpDimRef)

            resonances.append(resonance)

    return resonances
Пример #17
0
def disambiguateNoesyPeaks(noesy2dPeakList,noesy3dPeakList,tocsy3dPeakList,hsqcPeakList):

  # assign HSQC resonances and spin systems
  # assign pick 3d tocsy F1 F3
  # assign tocsy F2
  # assign pick 3d noesy F1 F3

  tolerances = [0.04, 0.04, 0.4]
  t1 = tolerances[0]/2.0
  t2 = tolerances[1]/2.0

  spinSystems = []
  for peak in hsqcPeakList.peaks:
    for peakDim in peak.peakDims:
      if peakDim.dataDim.expDim.isAcquisition:
        resonance = peakDim.findFirstpeakDimContrib().resonance
        spinSystems.append(resonance.resonanceGroup)
        break
  
  ii = 0
  for spinSystem in spinSystems:
    resonances = spinSystem.resonances
  
    intraPeaks = []
    interPeaks = []
    anchors = []
    t3peaks = []
    n3peaks = []
    matched = []
    
    # find 3d tocsy and 3d noesy peaks for spin system
    for resonance in resonances:
      for contrib in resonance.peakDimContribs:
        peak = contrib.peakDim.peak
	
	if peak.peakList is noesy3dPeakList:
	  n3peaks.append(peak) 
	elif peak.peakList is tocsy3dPeakList:
	  t3peaks.append(peak)
	  
    # get intra list
    for pn in n3peaks:
      match = None
      score = 0
      for pt in t3peaks:
        s = matchPeaks(pt,pn,tolerances)
	if s and (s>score):
	  score = s
	  match = pt
	  
      if match and match.sortedPeakDims()[1].peakDimContribs:
        assignResToDim(pn.sortedPeakDims()[1],match.sortedPeakDims()[1].findFirstpeakDimContrib().resonance)
        intraPeaks.append(pn)
    
    # get unambiguous inter list
    for pn in n3peaks:
      if pn not in intraPeaks:
        peakDim = pn.sortedPeakDims()[1]
        if peakDim.peakDimContribs and peakDim.findFirstpeakDimContrib().resonance:
          interPeaks.append(pn)
        
	ppm = getPeakDimPpm(peakDim)
        position  = peakDim.position + (peakDim.numAliasing*peakDim.dataDimRef.dataDim.numPointsOrig)
	shifts = findMatchingShifts(peakDim.dataDimRef,position,tolerance=t1)
                
	if shifts and len(shifts) == 1:
	  assignResToDim(pn.sortedPeakDims()[1],shifts[0].resonance)
	  interPeaks.append(pn)
        else:
 	  shifts = findMatchingShifts(peakDim.dataDimRef,position,tolerance=t1)
          if not shifts:
            pass
            #assignResToDim(peakDim)
	    #interPeaks.append(pn)
            
          elif len(shifts) == 1:
	    assignResToDim(peakDim,shifts[0].resonance)
	    interPeaks.append(pn)
            
            
    peaks3d = intraPeaks
    peaks3d.extend(interPeaks)
    
    ii += 1
    print "SS", ii, spinSystem
    
    # pick assign 2d equivalents to intra and unambiguous 3d and find anchor point peaks
    for p3 in peaks3d:
      matched = {}
      f = 0.0
      n = 0
      pd1 = p3.sortedPeakDims()[0]
      pd2 = p3.sortedPeakDims()[1]
      ppm1 = getPeakDimPpm(pd1)
      ppm2 = getPeakDimPpm(pd2)
      
      region = [[ppm1-t1,ppm1+t1],[ppm2-t2,ppm2+t2]]
      n2peaks = searchPeaks([noesy2dPeakList,], region)
      n2peaks.extend( findPeaks(noesy2dPeakList, region))
      match = None
      score = 0
      
      if len(n2peaks) == 1:
        match = n2peaks[0]
      else:
        for p2 in n2peaks:
          s = matchPeakDims(p3.peakDims,p2.peakDims,tolerances[:2])
          if s and (s>score):
            score = s
            match = p2
          
      if match:
        anchors.append( (match,p3) )
        f += match.findFirstPeakIntensity().value/p3.findFirstPeakIntensity().value
        n += 1
        peakDimsM = match.sortedPeakDims()
        
        clearPeakDim(peakDimsM[0])
        clearPeakDim(peakDimsM[1])
        assignResToDim(peakDimsM[0],pd1.findFirstpeakDimContrib().resonance)
        assignResToDim(peakDimsM[1],pd2.findFirstpeakDimContrib().resonance)
        matched[p3] = 1

      region = [[ppm2-t1,ppm2+t1],[ppm1-t2,ppm1+t2]]
      n2peaks = searchPeaks([noesy2dPeakList,], region)
      n2peaks.extend(findPeaks(noesy2dPeakList, region))
      match = None
      score = 0
      
      if len(n2peaks) == 1:
        match = n2peaks[0]
      else:
        for p2 in n2peaks:
          s = matchPeakDims(p3.peakDims,p2.peakDims,tolerances[:2])
          if s and (s>score):
            score = s
            match = p2
          
      if match:
        peakDimsM = match.sortedPeakDims()
        anchors.append( (match,p3) )
        f += match.findFirstPeakIntensity().value/p3.findFirstPeakIntensity().value
        n += 1
        clearPeakDim(peakDimsM[0])
        clearPeakDim(peakDimsM[1])
        assignResToDim(peakDimsM[0],pd1.findFirstpeakDimContrib().resonance)
        assignResToDim(peakDimsM[1],pd2.findFirstpeakDimContrib().resonance)
        matched[p3] = 1
        
    if matched:
         
      f /= n
      
      # use the peaks that intially failed in the 2d picking 
           
      for p3 in peaks3d:
        if not matched.get(p3):
          pd1 = p3.sortedPeakDims()[0]
          pd2 = p3.sortedPeakDims()[1]
        
          r1 = pd1.findFirstpeakDimContrib().resonance
          r2 = pd2.findFirstpeakDimContrib().resonance
        
          ppm1 = getPeakDimPpm(pd1)
          ppm2 = getPeakDimPpm(pd2)
        
          region = [[ppm1-tolerances[0],ppm1+tolerances[0]],[ppm2-tolerances[1],ppm2+tolerances[1]]]
          peaks = searchPeaks([noesy2dPeakList,], region)
          peaks.extend( findPeaks(noesy2dPeakList, region) )
          for p2 in peaks:
            p2.annotation = '*'
            p2.findFirstPeakIntensity().value = p3.findFirstPeakIntensity().value * f
            assignResToDim(p2.sortedPeakDims()[0],r1)
            assignResToDim(p2.sortedPeakDims()[1],r2)
          
          region = [[ppm2-tolerances[0],ppm2+tolerances[0]],[ppm1-tolerances[1],ppm1+tolerances[1]]]
          peaks = searchPeaks([noesy2dPeakList,], region)
          for p2 in peaks:
            p2.annotation = '*'
            p2.findFirstPeakIntensity().value = p3.findFirstPeakIntensity().value * f
            assignResToDim(p2.sortedPeakDims()[0],r2)
            assignResToDim(p2.sortedPeakDims()[1],r1)
  
  return noesy2dPeakList
  resonances = list(noesy2dPeakList.root.resonances)
  N = len(resonances)
  
  print "Final 2d matches for %d resonances" % N
  
  for i in range(N-1):
    print "R", i
    for j in range(i+1,N):
      ppm1 = resonances[i].findFirstShift().value
      ppm2 = resonances[j].findFirstShift().value
      region = [[ppm1-t1,ppm1+t1],[ppm2-t2,ppm2+t2]]
      
      peaks = searchPeaks([noesy2dPeakList,], region)
      if not peaks:
        peaks = findPeaks(noesy2dPeakList, region)
        
      if len(peaks) == 1:
        for peakDim in peaks[0].peakDims:
          shifts = findMatchingShifts(peakDim.dataDimRef,position,tolerance=t1)
          if len(shifts) == 1:
            assignResToDim(peakDim,shifts[0].resonance)
        
  return noesy2dPeakList
Пример #18
0
def networkAnchorAssign(peakLists,
                        intensityType='height',
                        strictness=2,
                        threshold=1.0,
                        isotopeTolerances=None,
                        assignPeakList=True,
                        constraintSet=None,
                        labelling=None,
                        minLabelFraction=0.1,
                        scale=None,
                        distParams=None,
                        structure=None,
                        progressBar=None,
                        nexus=None):

    if not peakLists:
        return

    if isotopeTolerances:
        TOLERANCE_DICT = isotopeTolerances

    distanceFunction = None
    if distParams:
        distanceFunction = lambda val: getNoeDistance(val, distParams)

    project = peakLists[0].root
    nmrProject = peakLists[0].topObject
    molSystem = project.findFirstMolSystem()
    shiftList = peakLists[0].dataSource.experiment.shiftList
    isotopes = set([])

    # Get known network of connectivities inc covalent and NOE
    network = {}
    covalent = {}

    # Assign some peaks with uniquely matching shifts
    for peakList in peakLists:
        if labelling is True:
            expLabelling = peakList.dataSource.experiment
        else:
            expLabelling = labelling

        network, covalent = getCloseSingleShiftMatches(
            peakList,
            network,
            covalent,
            labelling=expLabelling,
            minLabelFraction=minLabelFraction,
            intensityType=intensityType,
            progressBar=progressBar)

    # Get existing assigned NOE network
    totalPeaks = 0
    for peakList in peakLists:
        if not peakList.peaks:
            continue

        meanIntensity = getMeanPeakIntensity(peakList.peaks,
                                             intensityType=intensityType)
        if scale:
            meanIntensity = scale

        spectrum = peakList.dataSource
        distDims = getThroughSpaceDataDims(spectrum)
        for dataDim in distDims:
            isotopes.update(getDataDimIsotopes(dataDim))

        hDims = [dd.dim - 1 for dd in distDims]

        numPeaks = len(peakList.peaks)
        totalPeaks += numPeaks
        info = (spectrum.experiment.name, spectrum.name, peakList.serial,
                numPeaks)

        if progressBar:
            progressBar.setText(
                'Get existing NOE network\nfor %s:%s:%d - %d peaks' % info)
            progressBar.set(0)
            progressBar.total = numPeaks
            progressBar.open()
            progressBar.update_idletasks()

        else:
            print 'Get existing NOE network for %s:%s:%d - %d peaks' % info

        if len(hDims) != 2:
            continue

        for peak in peakList.peaks:
            if progressBar:
                progressBar.increment()

            peakDims = peak.sortedPeakDims()
            peakDim1 = peakDims[hDims[0]]
            contribs1 = peakDim1.peakDimContribs
            if contribs1:
                peakDim2 = peakDims[hDims[1]]
                contribs2 = peakDim2.peakDimContribs
                if contribs2:
                    peakIntensity = peak.findFirstPeakIntensity(
                        intensityType=intensityType)
                    if peakIntensity:
                        intensity = peakIntensity.value
                        intensity /= float(len(contribs1))
                        intensity /= float(len(contribs2))
                        #intensity /= meanIntensity

                        for contrib1 in contribs1:
                            resonance1 = contrib1.resonance
                            if network.get(resonance1) is None:
                                covalent[resonance1] = {}
                                network[resonance1] = {}

                            intensity2 = intensity
                            if resonance1.resonanceSet:
                                intensity2 /= float(
                                    len(resonance1.resonanceSet.
                                        findFirstAtomSet().atoms))

                            for contrib2 in contribs2:
                                resonance2 = contrib2.resonance
                                if network.get(resonance2) is None:
                                    network[resonance2] = {}
                                    covalent[resonance2] = {}

                                if resonance2.resonanceSet:
                                    intensity2 /= float(
                                        len(resonance2.resonanceSet.
                                            findFirstAtomSet().atoms))

                                if not contrib2.peakContribs:
                                    if not contrib1.peakContribs:
                                        network[resonance1][resonance2] = [
                                            intensity2, peak
                                        ]
                                        network[resonance2][resonance1] = [
                                            intensity2, peak
                                        ]

                                else:
                                    for peakContrib in contrib2.peakContribs:
                                        if peakContrib in contrib1.peakContribs:
                                            network[resonance1][resonance2] = [
                                                intensity2, peak
                                            ]
                                            network[resonance2][resonance1] = [
                                                intensity2, peak
                                            ]
                                            break

                    else:
                        pass  # Should warn

    covalentIntensity = 5.0  # Need to optimise this

    # Get covalent network
    if progressBar:
        progressBar.setText('Getting covalent network')
        progressBar.set(0)
        progressBar.total = len(nmrProject.resonances)
        progressBar.open()
        progressBar.update_idletasks()

    else:
        print 'Getting covalent network - %d resonances' % len(
            nmrProject.resonances)

    neighbours = {}
    chemAtomToAtom = {}

    c = 0
    for resonance in nmrProject.resonances:
        if progressBar:
            progressBar.increment()

        if resonance.isotopeCode not in isotopes:
            continue

        resonanceSet = resonance.resonanceSet
        if not resonanceSet:
            continue

        if network.get(resonance) is None:
            network[resonance] = {}
            covalent[resonance] = {}

        for atomSet in resonanceSet.atomSets:
            for atom in atomSet.atoms:
                residue = atom.residue

                if chemAtomToAtom.get(residue) is None:
                    chemAtomToAtom[residue] = {}
                    for atom2 in residue.atoms:
                        chemAtomToAtom[residue][atom2.chemAtom] = atom2

                chemAtom = atom.chemAtom
                if chemAtom.waterExchangeable:
                    continue

                chemAtoms = neighbours.get(chemAtom)

                if chemAtoms is None:
                    chemAtoms = []
                    for atom2 in residue.atoms:
                        if atom2 is atom:
                            continue

                        chemAtom2 = atom2.chemAtom
                        if DEFAULT_ISOTOPES.get(
                                chemAtom2.elementSymbol) not in isotopes:
                            continue

                        numBonds = getNumConnectingBonds(atom, atom2, limit=6)
                        if numBonds < 5:
                            chemAtoms.append(chemAtom2)

                    neighbours[chemAtom] = chemAtoms

                atoms = []
                for chemAtomB in chemAtoms:
                    atom2 = chemAtomToAtom[residue].get(chemAtomB)
                    if atom2 is not None:
                        atoms.append(atom2)

                residue2 = getLinkedResidue(residue, 'prev')
                if residue2:
                    for atom2 in residue2.atoms:
                        chemAtom2 = atom2.chemAtom
                        if DEFAULT_ISOTOPES.get(
                                chemAtom2.elementSymbol) not in isotopes:
                            continue

                        numBonds = getNumConnectingBonds(atom, atom2, limit=6)
                        if numBonds < 5:
                            atoms.append(atom2)

                residue2 = getLinkedResidue(residue, 'next')
                if residue2:
                    for atom2 in residue2.atoms:
                        chemAtom2 = atom2.chemAtom
                        if DEFAULT_ISOTOPES.get(
                                chemAtom2.elementSymbol) not in isotopes:
                            continue

                        numBonds = getNumConnectingBonds(atom, atom2, limit=6)
                        if numBonds < 5:
                            atoms.append(atom2)

                for atom2 in atoms:
                    atomSet2 = atom2.atomSet
                    if atomSet2 and (atomSet2 is not atomSet):
                        for resonanceSet2 in atomSet2.resonanceSets:
                            for resonance2 in resonanceSet2.resonances:
                                if network.get(resonance2) is None:
                                    network[resonance2] = {}
                                    covalent[resonance2] = {}

                                if network[resonance].get(
                                        resonance2
                                ) is None:  # Not already in network
                                    network[resonance][resonance2] = [
                                        covalentIntensity, None
                                    ]
                                    network[resonance2][resonance] = [
                                        covalentIntensity, None
                                    ]
                                    covalent[resonance][resonance2] = True
                                    covalent[resonance2][resonance] = True
                                    c += 1

    #print 'Atom pair network connections %d' % c

    c = 0
    for ss in nmrProject.resonanceGroups:
        ss2 = findConnectedSpinSystem(ss, delta=-1)
        if ss2:
            for r1 in ss.resonances:
                if r1.isotopeCode not in isotopes:
                    continue

                for r2 in ss.resonances:
                    if r2.isotopeCode not in isotopes:
                        continue

                    if network.get(r1) is None:
                        network[r1] = {}
                        covalent[r1] = {}
                    if network.get(r2) is None:
                        network[r2] = {}
                        covalent[r2] = {}

                    if network[r1].get(r2) is None:
                        network[r1][r2] = [covalentIntensity, None]
                        network[r2][r1] = [covalentIntensity, None]
                        covalent[r1][r2] = True
                        covalent[r2][r1] = True
                        c += 1

    #print 'Anonymous intra residue connections %d' % c

    done = {}
    iter = 0
    nAssign = 1
    k = 0
    dataSets = []
    while nAssign > 0:
        #while iter < 1:
        data = []

        nAssign = 0
        iter += 1

        if progressBar:
            progressBar.setText('Anchoring iteration %d' % iter)
            progressBar.set(0)
            progressBar.total = totalPeaks
            progressBar.open()
            progressBar.update_idletasks()
        else:
            print 'Anchoring iteration %d' % iter

        closeResonancesDict = {}

        for peakList in peakLists:
            if not peakList.peaks:
                continue

            spectrum = peakList.dataSource
            distDims = getThroughSpaceDataDims(spectrum)
            hDims = [dd.dim - 1 for dd in distDims]
            tolerances = getDimTolerances(spectrum)
            bondedDims = getBondedDimsDict(spectrum)
            #meanIntensity = getMeanPeakIntensity(peakList.peaks, intensityType=intensityType)

            info = (spectrum.experiment.name, spectrum.name, peakList.serial,
                    len(peakList.peaks))
            #print '  Using %s:%s:%d - %d peaks' % info
            if len(hDims) != 2:
                continue

            for peak in peakList.peaks:
                if progressBar:
                    progressBar.increment()

                if done.get(peak):
                    continue

                peakDims = peak.sortedPeakDims()

                if peakDims[hDims[0]].peakDimContribs:
                    if peakDims[hDims[1]].peakDimContribs:
                        continue

                boundResonances = {}

                if closeResonancesDict.get(peak) is None:
                    possibles = []
                    for dim in hDims:
                        peakDim = peakDims[dim]
                        if peakDim.peakDimContribs:
                            possibles.append([
                                contrib.resonance
                                for contrib in peakDim.peakDimContribs
                            ])
                            continue

                        resonances = []
                        shifts = findMatchingPeakDimShifts(
                            peakDim,
                            shiftRanges=None,
                            tolerance=tolerances[dim],
                            aliasing=True,
                            findAssigned=False)
                        dim2 = bondedDims.get(dim)
                        peakDim2 = None
                        if dim2 is not None:
                            peakDim2 = peakDims[dim2]
                            shifts2 = findMatchingPeakDimShifts(
                                peakDim2,
                                shiftRanges=None,
                                tolerance=tolerances[dim2],
                                aliasing=True,
                                findAssigned=False)

                            for shift in shifts:
                                resonance1 = shift.resonance
                                for shift2 in shifts2:
                                    resonance2 = shift2.resonance
                                    if areResonancesBound(
                                            resonance1, resonance2):
                                        if labelling:
                                            fraction = getResonancePairLabellingFraction(
                                                resonance1, resonance2,
                                                expLabelling)
                                            if fraction < minLabelFraction:
                                                continue

                                        resonances.append(resonance1)
                                        boundResonances[
                                            resonance1] = resonance2
                                        break

                        else:
                            for shift in shifts:
                                resonance = shift.resonance

                                if labelling:
                                    fraction = getResonanceLabellingFraction(
                                        resonance, expLabelling)

                                    if fraction < minLabelFraction:
                                        continue

                                resonances.append(resonance)

                        possibles.append(resonances)
                    closeResonancesDict[peak] = possibles

                else:
                    possibles = closeResonancesDict[peak]

                if not possibles[0]:
                    continue  # warn

                if not possibles[1]:
                    continue  # warn

                peakIntensity = peak.findFirstPeakIntensity(
                    intensityType=intensityType)
                if not peakIntensity:
                    print 'Peak missing intensity', peak
                    continue

                else:
                    intensity = peakIntensity.value  #/meanIntensity

                scores = {}
                numbers = {}

                bestScore = None
                bestPair = None
                for resonance1 in possibles[0]:
                    if not resonance1.resonanceGroup:
                        continue

                    if network.get(resonance1) is None:
                        continue

                    anchors1 = network[resonance1].keys()
                    spinSystem1 = resonance1.resonanceGroup

                    for resonance2 in possibles[1]:
                        if not resonance2.resonanceGroup:
                            continue

                        if network.get(resonance2) is None:
                            continue

                        anchors2 = network[resonance2].keys()
                        pair = (resonance1, resonance2)
                        spinSystem2 = resonance2.resonanceGroup

                        for resonance3 in anchors1:

                            spinSystem3 = resonance3.resonanceGroup
                            if (strictness > 0) and spinSystem3:
                                check = False
                                if (spinSystem3 is spinSystem1) or (
                                        spinSystem3 is spinSystem2):
                                    check = True

                                if (strictness > 1) and spinSystem3.residue:
                                    if spinSystem1.residue:
                                        if abs(spinSystem1.residue.seqCode -
                                               spinSystem3.residue.seqCode
                                               ) < 2:
                                            check = True

                                    if spinSystem2.residue:
                                        if abs(spinSystem2.residue.seqCode -
                                               spinSystem3.residue.seqCode
                                               ) < 2:
                                            check = True

                            else:
                                check = True

                            if check and (resonance3 in anchors2):
                                intensityA, peakA = network[resonance1][
                                    resonance3]
                                intensityB, peakB = network[resonance2][
                                    resonance3]

                                if scores.get(pair) is None:
                                    scores[pair] = 0.0
                                    numbers[pair] = 0.0

                                shift1 = resonance1.findFirstShift(
                                    parentList=shiftList)
                                shift2 = resonance2.findFirstShift(
                                    parentList=shiftList)

                                if shift1 and shift2:

                                    delta1 = abs(peakDims[hDims[0]].realValue -
                                                 shift1.value)
                                    delta2 = abs(peakDims[hDims[1]].realValue -
                                                 shift2.value)

                                    tol1 = TOLERANCE_DICT[
                                        resonance1.isotopeCode]
                                    tol2 = TOLERANCE_DICT[
                                        resonance2.isotopeCode]

                                    match1 = (tol1 - delta1) / tol1
                                    match2 = (tol2 - delta2) / tol2

                                    scores[
                                        pair] += intensityA * intensityB * match1 * match2
                                    numbers[pair] += 1

                nGood = 0
                for pair in scores.keys():
                    resonance1, resonance2 = pair

                    score = scores[pair]

                    if score > threshold:
                        nGood += 1

                    if (bestScore is None) or (score > bestScore):
                        bestScore = score
                        bestPair = pair

                #if bestScore and (nGood < 2):
                for pair in scores.keys():
                    resonance1, resonance2 = pair

                    if scores[pair] < threshold:
                        #if len(scores.keys()) > 1:
                        continue
                    else:
                        intensity2 = intensity / nGood

                    bestPair = pair
                    bestScore = scores[pair]

                    for i in (0, 1):
                        resonance = bestPair[i]

                        if assignPeakList:
                            assignResToDim(peakDims[hDims[i]],
                                           resonance,
                                           doWarning=False)

                            bound = boundResonances.get(resonance)
                            if bound:
                                dim2 = bondedDims.get(hDims[i])
                                if dim2 is not None:
                                    assignResToDim(peakDims[dim2],
                                                   bound,
                                                   doWarning=False)

                        if network.get(resonance) is None:
                            network[resonance] = {}

                    #name1 = makeResonanceGuiName(bestPair[0])
                    #name2 = makeResonanceGuiName(bestPair[1])

                    if resonance1.resonanceSet:
                        intensity2 /= float(
                            len(resonance1.resonanceSet.findFirstAtomSet().
                                atoms))
                    if resonance2.resonanceSet:
                        intensity2 /= float(
                            len(resonance2.resonanceSet.findFirstAtomSet().
                                atoms))

                    if labelling:
                        intensity2 /= getResonanceLabellingFraction(
                            resonance1, expLabelling)
                        intensity2 /= getResonanceLabellingFraction(
                            resonance2, expLabelling)

                    nAssign += 1

                    covalent[bestPair[0]][bestPair[1]] = None
                    covalent[bestPair[1]][bestPair[0]] = None
                    network[bestPair[0]][bestPair[1]] = [intensity2, peak]
                    network[bestPair[1]][bestPair[0]] = [intensity2, peak]
                    done[peak] = True

        #print '  Assigned:', nAssign
        dataSets.append(data)

    from ccpnmr.analysis.core.ConstraintBasic import getDistancesFromIntensity, getIntensityDistanceTable
    from ccpnmr.analysis.core.ConstraintBasic import makeNmrConstraintStore, getFixedResonance

    if constraintSet is None:
        constraintSet = makeNmrConstraintStore(nmrProject)

    if not constraintSet:
        return

    constraintList = constraintSet.newDistanceConstraintList()

    peakConstraints = {}
    doneResonances = {}
    for resonance1 in network.keys():
        fixedResonance1 = getFixedResonance(constraintSet, resonance1)

        for resonance2 in network[resonance1].keys():
            if resonance1 is resonance2:
                continue

            key = [resonance1.serial, resonance2.serial]
            key.sort()
            key = tuple(key)

            if doneResonances.get(key):
                continue
            else:
                doneResonances[key] = True

            if covalent.get(resonance1):
                if covalent[resonance1].get(resonance2):
                    # J connected are close so what do we do...?
                    #print "Skip", makeResonanceGuiName(resonance1), makeResonanceGuiName(resonance2)
                    continue

            fixedResonance2 = getFixedResonance(constraintSet, resonance2)
            intensity, peak = network[resonance1][resonance2]

            if peak:
                peakList = peak.peakList
                spectrum = peakList.dataSource
                experiment = spectrum.experiment

                if not distanceFunction:
                    noeDistClasses = getIntensityDistanceTable(spectrum)
                    distanceFunction = lambda val: getDistancesFromIntensity(
                        noeDistClasses, val)

                constraint = peakConstraints.get(peak)
                if not constraint:
                    constraint = constraintList.newDistanceConstraint(
                        weight=1.0, origData=intensity)
                    peakContrib = constraint.newConstraintPeakContrib(
                        experimentSerial=experiment.serial,
                        dataSourceSerial=spectrum.serial,
                        peakListSerial=peakList.serial,
                        peakSerial=peak.serial)
                    peakConstraints[peak] = constraint
                else:
                    intensity += constraint.origData

                dist, minDist, maxDist = distanceFunction(intensity /
                                                          meanIntensity)
                error = abs(maxDist - minDist)

                constraint.origData = intensity
                constraint.targetValue = dist
                constraint.upperLimit = maxDist
                constraint.lowerLimit = minDist
                constraint.error = error

                item = constraint.newDistanceConstraintItem(
                    resonances=[fixedResonance1, fixedResonance2])

    return constraintList
Пример #19
0
def makeDecoupledPeakList(argServer):

    peakList = argServer.getPeakList()
    spectrum = peakList.dataSource

    peakAssignDict = {}

    for peak in peakList.peaks:

        assignKey = []
        for peakDim in peak.sortedPeakDims():
            resonances = [c.resonance for c in peakDim.peakDimContribs]
            resonances = frozenset(resonances)
            assignKey.append(resonances)

        assignKey = tuple(assignKey)

        if assignKey not in peakAssignDict:
            peakAssignDict[assignKey] = []

        peakAssignDict[assignKey].append(peak)

    if not peakAssignDict:
        argServer.showWarning('No assignments detected')
        return

    newPeakList = spectrum.newPeakList()
    nDim = spectrum.numDim

    for assignKey in peakAssignDict:
        peaks = peakAssignDict[assignKey]
        position = [0.0] * nDim
        height = 0.0
        volume = 0.0

        for peak in peaks:
            peakDims = peak.sortedPeakDims()

            for i, peakDim in enumerate(peakDims):
                position[i] += peakDim.position

            heightIntensity = peak.findFirstPeakIntensity(
                intensityType='height')
            volumeIntensity = peak.findFirstPeakIntensity(
                intensityType='volume')

            if heightIntensity:
                height += heightIntensity.value

            if volumeIntensity:
                volume += volumeIntensity.value

        n = float(len(peaks))
        for i in range(nDim):
            position[i] /= n

        newPeak = pickPeak(newPeakList, position, doFit=False)
        newPeakDims = newPeak.sortedPeakDims()

        setManualPeakIntensity(newPeak, height, 'height')
        setManualPeakIntensity(newPeak, volume, 'volume')

        for i, peakDim in enumerate(newPeakDims):
            resonances = assignKey[i]

            for resonance in resonances:
                assignResToDim(peakDim,
                               resonance,
                               tolerance=1.0,
                               doWarning=False)

    argServer.showWarning('Made new peak list with %d peaks' %
                          len(newPeakList.peaks))
Пример #20
0
    def transferAssignments(self):
        '''Transfer assignments to project depending
           on the settings from the GUI.
        '''

        self.fetchOptions()

        if not self.dataModel or (not self.resonanceToDimension and not self.spinSystemToResidue):

            return

        strategy = self.strategy

        lookupSpinSystem = [self.getAssignedSpinSystem,
                            self.getBestScoringSpinSystem,
                            self.getUserDefinedSpinSystem,
                            self.getSelectedSolutionSpinSystem][self.spinSystemType]

        residues = self.dataModel.chain.residues

        spinSystemSequence = [lookupSpinSystem(res) for res in residues]

        ccpnSpinSystems = []
        ccpnResidues = []

        # if self.spinSystemType == 0 it means that it for sure already
        # assigned like this
        if self.spinSystemToResidue and not self.spinSystemType == 0:

            for spinSys, res in zip(spinSystemSequence, residues):

                if spinSys and res:

                    ccpnSpinSystems.append(spinSys.getCcpnResonanceGroup())
                    ccpnResidues.append(res.getCcpnResidue())

            assignSpinSystemstoResidues(ccpnSpinSystems,
                                        ccpnResidues,
                                        strategy=strategy,
                                        guiParent=self.guiParent)

        if self.resonanceToDimension:

            allSpectra = self.allSpectra

            if self.intra:

                for residue, spinSystem in zip(residues, spinSystemSequence):

                    if not spinSystem:

                        continue

                    intraLink = residue.getIntraLink(spinSystem)

                    for pl in intraLink.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum() is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()
                            assignResToDim(ccpnDimension, ccpnResonance)

            if self.sequential:

                for residue, spinSystemA, spinSystemB in zip(residues,
                                                             spinSystemSequence,
                                                             spinSystemSequence[1:]):

                    if not spinSystemA or not spinSystemB:

                        continue

                    link = residue.getLink(spinSystemA, spinSystemB)

                    for pl in link.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum() is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()

                            assignResToDim(ccpnDimension, ccpnResonance)

        self.guiParent.resultsTab.update()
Пример #21
0
def updateClusterAssignments(cluster, refPeak=None):
    """
  Initialise a peak cluster object by enforcing consistent assignments
  across its component peaks and by setting its annotation approprately.
  
  .. describe:: Input
  
  Nmr.PeakCluster, Nmr.Peak
  
  .. describe:: Output
  
  None
  """

    from ccpnmr.analysis.core.AssignmentBasic import assignResToDim

    dimResonances = {}
    components = {}

    peaks = list(cluster.peaks)

    if refPeak:
        if len(refPeak.peakClusters) > 1:
            return

        inPeaks = [
            refPeak,
        ]

    else:
        # Avoid mixing assignments
        inPeaks = [pk for pk in peaks if len(pk.peakClusters) < 2]

    for peak in inPeaks:
        for peakDim in peak.peakDims:
            dim = peakDim.dim

            if dimResonances.get(dim) is None:
                dimResonances[dim] = set([])
                components[dim] = set([])

            for contrib in peakDim.peakDimContribs:

                if isinstance(contrib, Nmr.PeakDimContribN):
                    component = contrib.peakDimComponent

                    if component:
                        resonances = contrib.resonances
                        components[dim].add(resonances)

                else:
                    resonance = contrib.resonance
                    component = contrib.peakDimComponent

                    if component:
                        components[dim].add((resonance, ))

                    else:
                        dimResonances[dim].add(resonance)

    clusterType = cluster.clusterType
    for peak in peaks:

        for peakDim in peak.peakDims:
            if not peakDim.dataDimRef:
                continue

            dim = peakDim.dim

            dataDimRef = None
            if clusterType == MULTIPLET_TYPE:
                dataDimRef = getCouplingDataDimRef(peakDim.dataDim)

            if dataDimRef:
                resonancesList = components.get(dim, [])

                if resonancesList:
                    component = peakDim.findFirstPeakDimComponent(
                        dataDimRef=dataDimRef)

                    if not component:
                        continue  # Scaling factor unkown

                    if component.dataDimRef.expDimRef.unit != 'Hz':
                        continue

                    for resonances in resonancesList:
                        if len(resonances) != 2:
                            continue

                        contrib = component.findFirstPeakDimContrib(
                            resonances=resonances)

                        if not contrib:
                            contrib = peakDim.newPeakDimContribN(
                                resonances=resonances,
                                peakDimComponent=component)

                #else:
                # For non split dim, or non multiplet cluster: propagate assignments
                # Split dims assigned differently bacause simple position based
                # shift values are not appropriate

                # TBD: Symmetry requires mapping

            # Ensure consistent assignments, with refPeak when avail
            resonances = dimResonances[dim]
            for contrib in peakDim.peakDimContribs:
                if isinstance(contrib, Nmr.PeakDimContribN):
                    continue

                if contrib.resonance not in resonances:
                    for peakContrib in contrib.peakContribs:
                        if len(peakContrib.peakDimContribs) < 2:
                            peakContrib.delete()

                    contrib.delete()

            for resonance in resonances:
                #if resonance not in existingResonancesA[peak][dim]:
                assignResToDim(peakDim, resonance)

    updateClusterAnnotation(cluster)