Beispiel #1
0
def filterPeakListWithCloud(argServer,
                            peakList=None,
                            pattern='t_intra_0\d+.pdb'):

    from ccpnmr.analysis.core.ExperimentBasic import getSpectrumIsotopes

    if peakList is None:
        peakList = argServer.getPeakList()

    fileNames = getFileNamesFromPattern(pattern, '.')
    project = peakList.root
    clouds = getCloudsFromFile(fileNames, project)
    isotopes = getSpectrumIsotopes(peakList.dataSource)

    hDims = []
    for i in range(len(isotopes)):
        if isotopes[i] == '1H':
            hDims.append(i)

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

        hDim1 = peakDims[hDims[0]]
        hDim2 = peakDims[hDims[1]]

        contribs1 = hDim1.peakDimContribs
        contribs2 = hDim2.peakDimCOntribs

        if contribs1 and contribs2:
            resonances1 = [c.resonance for c in contribs1]
            resonances2 = [c.resonance for c in contribs2]

            coords1 = getResonanceCoords(clouds, resonances1)
            coords2 = getResonanceCoords(clouds, resonances2)
            dist = getEnsembleCoordsDist(coord1, coord2)
Beispiel #2
0
 def gethNoesys(self):
 
   peakLists = []
   if self.project:
     for experiment in self.project.currentNmrProject.experiments:
       for spectrum in experiment.dataSources:
         isotopes = getSpectrumIsotopes(spectrum)
         if isotopes == ['1H', '1H']:
           for peakList in spectrum.peakLists:
             #if 'NOE' in experiment.name.upper():
             #  peakLists.insert(0, peakList)
             #else:
             peakLists.append(peakList)
   
   return peakLists
Beispiel #3
0
def initialiseHNCOorHNCOCA(argServer=None, spectrum=None):

    assert argServer or spectrum
    if not spectrum:
        spectra = getSpectraByType(argServer.getProject(), 'H[N[CO]]')
        spectra.extend(getSpectraByType(argServer.getProject(),
                                        'H[N[co[CA]]]'))
        spectrum = argServer.getSpectrum(spectra)

    if spectrum:
        peakList = argServer.getPeakList(spectrum)
        isotopes = getSpectrumIsotopes(spectrum)
        dims = []
        for isotope in ('1H', '15N'):
            if isotope in isotopes:
                dims.append(isotopes.index(isotope))

        peaks = peakList.peaks
        if peaks and dims:
            assignAllNewResonances(peaks=peaks)
            assignSpinSystemPerPeak(peaks=peaks, dims=dims)

    else:
        argServer.showWarning('Spectrum not found')
Beispiel #4
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
Beispiel #5
0
    def predictAmidePairs(self):

        self.amidePair = None
        isAmide = self.isAmide = {}
        amidePairs = self.amidePairs = []
        peakList = self.peakList

        if peakList:
            tol = self.tolEntry.get() or 0.001
            spectrum = self.peakList.dataSource
            dimPairs = getOnebondDataDims(spectrum)

            if not dimPairs:
                return

            isotopes = getSpectrumIsotopes(spectrum)

            hDim = None
            for dimA, dimB in dimPairs:
                i = dimA.dim - 1
                j = dimB.dim - 1

                if ('1H' in isotopes[i]) and ('1H' not in isotopes[j]):
                    hDim = i
                    nDim = j

                elif ('1H' in isotopes[j]) and ('1H' not in isotopes[i]):
                    hDim = j
                    nDim = i

                if hDim is not None:
                    break

            isAssigned = {}
            matchPeaks = []
            for peak in peakList.peaks:
                if isAmide.get(peak):
                    continue

                peakDims = peak.sortedPeakDims()
                ppmN = peakDims[nDim].realValue
                ppmH = peakDims[hDim].realValue

                for contrib in peakDims[nDim].peakDimContribs:
                    resonance = contrib.resonance

                    for contrib2 in resonance.peakDimContribs:
                        peak2 = contrib2.peakDim.peak
                        if (peak2.peakList is peakList) and (peak2
                                                             is not peak):
                            isAmide[peak] = peak2
                            isAmide[peak2] = peak

                            if hasattr(peak, 'amideConfirmed'):
                                peak2.amideConfirmed = peak.amideConfirmed
                            else:
                                peak.amideConfirmed = True
                                peak2.amideConfirmed = True

                            ppmH2 = peak2.findFirstPeakDim(dim=hDim + 1).value
                            ppmN2 = peak2.findFirstPeakDim(dim=nDim + 1).value
                            ppmNm = 0.5 * (ppmN + ppmN2)
                            deltaN = abs(ppmN - ppmN2)
                            amidePairs.append(
                                (peak, peak2, deltaN, ppmNm, ppmH, ppmH2))
                            break

                    else:
                        continue
                    break

                else:
                    if ppmN > 122.0:
                        continue
                    elif ppmN < 103:
                        continue

                    if ppmH > 9.0:
                        continue
                    elif ppmH < 5.4:
                        continue

                    if not hasattr(peak, 'amideConfirmed'):
                        peak.amideConfirmed = False
                    matchPeaks.append((ppmN, ppmH, peak))

            N = len(matchPeaks)
            unassignedPairs = []
            for i in range(N - 1):
                ppmN, ppmH, peak = matchPeaks[i]

                for j in range(i + 1, N):
                    ppmN2, ppmH2, peak2 = matchPeaks[j]

                    deltaN = abs(ppmN2 - ppmN)
                    if deltaN > tol:
                        continue

                    if abs(ppmH - ppmH2) > 1.50:
                        continue

                    ppmNm = 0.5 * (ppmN + ppmN2)

                    isAmide[peak] = peak2
                    isAmide[peak2] = peak
                    unassignedPairs.append(
                        (deltaN, peak, peak2, ppmNm, ppmH, ppmH2))

            unassignedPairs.sort()
            done = {}
            for deltaN, peak, peak2, ppmNm, ppmH, ppmH2 in unassignedPairs:
                if done.get(peak):
                    continue
                if done.get(peak2):
                    continue

                done[peak] = True
                done[peak2] = True

                amidePairs.append((peak, peak2, deltaN, ppmNm, ppmH, ppmH2))

            peaks = isAmide.keys()
            for peak in peaks:
                if done.get(peak) is None:
                    del isAmide[peak]

            self.updateAfter()
Beispiel #6
0
def getClusterCoupling(peakCluster, dim):
    """
  Determine the coupling value in Hz for the peaks of an input peak cluster
  along the dimension corresponding to the input dimension number.
  
  .. describe:: Input
  
  Nmr.PeakCluster, Int (Nmr.DataDim.dim)
  
  .. describe:: Output
  
  Float (coupling value in Hz)
  """

    coupling = None

    peaks = list(peakCluster.peaks)
    peak0 = peaks[0]

    peakList0 = peak0.peakList
    isotopes0 = getSpectrumIsotopes(peakList0.dataSource)

    componentDict = {}

    for peak in peaks:
        peakList = peak.peakList

        if peakList is not peakList0:
            if getSpectrumIsotopes(peakList.dataSource) != isotopes0:
                showWarning(
                    'Clustering Failed',
                    'Selected peaks have different isotope dimensions')
                return

        peakDim = peak.findFirstPeakDim(dim=dim)
        dataDimRef = getCouplingDataDimRef(peakDim.dataDim)

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

            if component:
                scale = component.scalingFactor

                if componentDict.get(scale) is None:
                    componentDict[scale] = []

                componentDict[scale].append(component)

    scaleFactors = componentDict.keys()
    N = len(scaleFactors)
    num = 0.0
    zum = 0.0

    for i in range(N - 1):
        scaleA = scaleFactors[i]
        componentsA = componentDict[scaleA]

        for j in range(i + 1, N):
            scaleB = scaleFactors[j]
            componentsB = componentDict[scaleB]

            jFactor = abs(scaleA - scaleB)

            for componentA in componentsA:
                peakDimA = componentA.peakDim
                positionA = peakDimA.position

                for componentB in componentsB:
                    peakDimB = componentB.peakDim
                    positionB = peakDimB.position
                    deltaPoints = abs(positionA - positionB)
                    value = jFactor * dataDimRef.pointToValue(deltaPoints)

                    num += 1.0
                    zum += value

    if num > 0.0:
        coupling = zum / num

    return coupling
Beispiel #7
0
def makeMultipletPeakCluster(peaks, multipletPattern, windowPane):
    """
  Make a peak cluster comprising of the selected peaks.
  The multiplet pattern is a recursive list of sub lists to give an object
  with the same dimensionality as the peak dims. Each element is
  either +1, 0 or -1 to specify the sign or absence of a multiplet
  peak. How to interpret a multiplet pattern is relative to input
  window pane, e.g. if spectrum is rotated. Automatically makes
  coupling expDimRefs when required.
  
  .. describe:: Input
  
  List of Nmr.Peaks, List of (Lists of)^numDim-1 Ints(-1,0,+1),
  Analysis.SpectrumWindowPane
  
  .. describe:: Output
  
  Nmr.PeakCluster
  """
    peaks = list(peaks)
    peak0 = peaks[0]
    peakList0 = peak0.peakList
    nmrProject = peak0.topObject
    isotopes0 = getSpectrumIsotopes(peakList0.dataSource)
    shiftList = None

    for peak in peaks[1:]:
        peakList = peak.peakList
        experiment = peakList.dataSource.experiment
        refExperiment = experiment.refExperiment

        if shiftList:
            if experiment.shiftList is not shiftList:
                msg = 'Experiments of selected peaks not all using the same shift list'
                showWarning('Clustering Failed', msg)
                return

        elif experiment.shiftList:
            shiftList = experiment.shiftList

        if not refExperiment:
            msg = 'Experiment %s does not have a reference experiment type'
            showWarning('Clustering Failed', msg % experiment.name)
            return

        if peakList is not peakList0:
            if getSpectrumIsotopes(peakList.dataSource) != isotopes0:
                msg = 'Selected peaks have different isotope dimensions'
                showWarning('Clustering Failed', msg)
                return

    # All peaks have to match - some overlap OK.
    clusters = list(getPeaksClusters(peaks, clusterType=MULTIPLET_TYPE))

    if clusters:  # Use existing
        peakCluster = clusters[0]  # Arbitrary

        if len(clusters) > 1:
            for cluster in clusters[1:]:
                deleteCluster(cluster)  # Cleans up peakDimComponents too

    else:
        # Make a new one below after position checks
        peakCluster = None

    nDim = len(peak0.peakDims)
    dims = range(nDim)

    counts = [0.0 for x in dims]
    maxPos = [None for x in dims]
    minPos = [None for x in dims]
    centre = [None for x in dims]
    middle = [None for x in dims]

    boxWidths = [0.0 for x in dims]

    axisMapping = getDataDimAxisMapping(peakList0.dataSource, windowPane)

    for peak in peaks:
        for peakDim in peak.peakDims:
            i = peakDim.dim - 1
            position = peakDim.value
            counts[i] += 1.0

            if (maxPos[i] is None) or (position > maxPos[i]):
                maxPos[i] = position

            if (minPos[i] is None) or (position < minPos[i]):
                minPos[i] = position

    gridSizes = []

    numCells = 1
    element = multipletPattern
    while type(element) in (type(()), type([])):
        size = len(element)
        gridSizes.append(size)
        element = element[0]
        numCells *= size

    for i in dims:
        mean = (maxPos[i] + minPos[i]) / 2.0
        n = float(gridSizes[i]) - 1.0

        if n:
            width = (maxPos[i] - minPos[i]) / n
        else:
            width = (maxPos[i] - minPos[i]) * 3.0

        boxWidths[i] = width
        centre[i] = (mean - (width / 4.0), mean + (width / 4.0))
        middle[i] = mean

        if not counts[i]:
            showWarning('Clustering Failed', 'Peak dimension corrupt')
            return  # Ought never get here

    cellCoords = []
    for i in range(numCells):
        coords = []

        k = 1
        for size in gridSizes:
            coords.append((i / k) % size)
            k += 1

        cellCoords.append(coords)

    peakCell = {}
    peakSigns = []
    j = 0
    for coords in cellCoords:
        region = []
        multipletElement = list(multipletPattern)

        for i in dims:
            halfWidth = boxWidths[i] / 2.0
            multipletElement = multipletElement[coords[i]]

            if axisMapping['y'].dim == i + 1:
                midPt = minPos[i] + (coords[i] * boxWidths[i])
            else:
                midPt = maxPos[i] - (coords[i] * boxWidths[i])

            bounds = (midPt - halfWidth, midPt + halfWidth)
            region.append(bounds)

        for peak in peaks:

            if peakCell.get(peak) is None:
                for i in dims:
                    peakDim = peak.findFirstPeakDim(dim=i + 1)
                    value = peakDim.value

                    if (value < region[i][0]) or (value > region[i][1]):
                        break

                else:
                    peakCell[peak] = j

        peakSigns.append(multipletElement)
        j += 1

    centrePeaks = {}
    for size in gridSizes:
        if size % 2 == 0:
            for peak in peaks:
                for i in dims:
                    peakDim = peak.findFirstPeakDim(dim=i + 1)
                    value = peakDim.value

                    if (value < centre[i][0]) or (value > centre[i][1]):
                        break

                else:
                    centrePeaks[peak] = True

            break

    splitPeaks = [pk for pk in peaks if not centrePeaks.get(peak)]

    if len(splitPeaks) > len(peakSigns):
        patternText = '?'
        for pattern in MULTIPLET_PEAK_DICT:
            if MULTIPLET_PEAK_DICT[pattern] == multipletPattern:
                patternText = pattern
                break

        msg = 'More peaks selected than cluster pattern "%s"' % patternText
        msg += ' allows for (excluding any central peak).'
        showWarning('Clustering Failed', msg)
        return

    if peakCluster:
        # Redefine peaks to any new selection
        if peakCluster.peaks != frozenset(peaks):
            peakCluster.setPeaks(peaks)

    else:  # Make new
        peakCluster = nmrProject.newPeakCluster(peaks=peaks,
                                                clusterType=MULTIPLET_TYPE)

    assignments = {}

    for peak in splitPeaks:

        intensity = peak.findFirstPeakIntensity(intensityType='height')

        if not intensity:
            continue

        dataDimRefs = []
        spectrum = peak.peakList.dataSource
        for j in dims:
            dataDim = spectrum.findFirstDataDim(dim=j + 1)

            if dataDim.className == 'FreqDataDim':
                dataDimRef = getCouplingDataDimRef(dataDim)

                if not dataDimRef:
                    expDim = dataDim.expDim

                    expDimRef0 = expDim.findFirstExpDimRef(
                        measurementType='Shift')
                    if not expDimRef0:
                        expDimRef0 = expDim.findFirstExpDimRef(
                            measurementType='shift')

                    refExpDimRef = expDimRef0.refExpDimRef

                    if not refExpDimRef:
                        msg = 'Experiment %s is missing a reference dimension:'
                        msg += ' Check experiment type'
                        showWarning('Clustering Failed',
                                    msg % expDim.experiment.name)
                        return

                    isotopes = refExpDimRef.coupledIsotopeCodes
                    if not isotopes:
                        dataDimRefs.append(None)
                        continue

                    expDimRef = expDim.newExpDimRef(
                        sf=1.0,
                        isotopeCodes=isotopes,
                        measurementType='JCoupling',
                        isFolded=False,
                        unit='Hz',
                        isAxisReversed=False)

                    dataDimRef = dataDim.newDataDimRef(expDimRef=expDimRef,
                                                       refPoint=0,
                                                       refValue=0.0)

                dataDimRefs.append(dataDimRef)

            else:
                dataDimRefs.append(None)

        if dataDimRefs == [None for j in dims]:
            msg = 'Reference dimensions for experiment %s have no coupled isotopes'
            showWarning('Clustering Failed', msg % spectrum.experiment.name)

        height = intensity.value
        i = peakCell[peak]
        sign = peakSigns[i]

        gridSizes.reverse()

        if sign and (sign * height > 0):  # Same sign
            coord = cellCoords[i]

            for j in dims:
                dataDimRef = dataDimRefs[j]

                if not dataDimRef:
                    continue

                size = gridSizes[j]
                mid = (size - 1) / 2.0
                scaling = int(2 * (coord[j] - mid))
                peakDim = peak.findFirstPeakDim(dim=j + 1)
                component = peakDim.findFirstPeakDimComponent(
                    dataDimRef=dataDimRef)
                peakDim.realValue = middle[j]

                #print dataDimRef, height, i , sign, size, mid, scaling, peakDim

                if component:
                    component.scalingFactor = scaling

                else:
                    component = peakDim.newPeakDimComponent(
                        scalingFactor=scaling, dataDimRef=dataDimRef)

    # Spread assignments, make C objects, update shifts etc
    updateClusterAssignments(peakCluster)

    return peakCluster