Example #1
0
    def commit(self):

        posDisp = self.numDims * [0]

        for i in range(self.numDims):
            posDisp[i] = float(self.dimensionEntries[i].get())
            if self.unit != 'point':
                dataDim = self.dataDims[i]
                if dataDim.className == 'FreqDataDim':
                    self.posn[i] = unit_converter[(self.unit, 'point')](
                        posDisp[i], getPrimaryDataDimRef(dataDim))

            else:
                self.posn[i] = posDisp[i]

        if self.peak:
            movePeak(self.peak, self.posn)
        else:
            self.peak = pickPeak(self.peakList, self.posn)

        height = self.heightEntry.get()
        volume = self.volumeEntry.get()
        setManualPeakIntensity(self.peak, height, intensityType='height')
        setManualPeakIntensity(self.peak, volume, intensityType='volume')

        details = self.detailEntry.get() or None

        self.peak.setDetails(details)

        self.close()
Example #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"
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))
Example #4
0
def initialiseAmideExpts(argServer, hsqc=None, tocsy=None, noesy=None):

    func = ExperimentBasic.getPrimaryDataDimRef

    xDim = 1

    peakSize = (0.09, 0.49)

    ratio = peakSize[0] / peakSize[1]
    tol = peakSize[0] / 5.0

    minPpmH = 6.0
    maxPpmH = 9.84

    waterRegion = [4.90, 4.92]

    #tocsy = argServer.getSpectrum()

    #nhsqcPl = getBlankPeakList(nhsqc)
    #tocsyPl = getBlankPeakList(tocsy)
    #noesyPl = getBlankPeakList(noesy)

    noesyPl = argServer.getPeakList()
    noesy = noesyPl.dataSource

    tocsyPl = argServer.getPeakList()
    tocsy = noesyPl.dataSource

    dataDims = noesy.sortedDataDims()

    if not noesyPl.peaks:
        print "Picking new NOE peaks"
        wholeRegion = [[
            pnt2ppm(dd.numPointsOrig, func(dd)),
            pnt2ppm(0, func(dd))
        ] for dd in dataDims]
        excludeRegion = [[0, dd.numPointsOrig] for dd in dataDims]

        dataDimRef = func(dataDims[xDim])
        excludeRegion[xDim] = [
            ppm2pnt(waterRegion[0], dataDimRef),
            ppm2pnt(waterRegion[1], dataDimRef)
        ]

        findPeaks(
            noesyPl,
            wholeRegion,
            argServer.parent,
            [1, 1, 1],
        )

    if not tocsyPl.peaks:
        print "Picking new TOCSY peaks"
        wholeRegion = [[
            pnt2ppm(dd.numPointsOrig, func(dd)),
            pnt2ppm(0, func(dd))
        ] for dd in dataDims]
        excludeRegion = [[0, dd.numPointsOrig] for dd in dataDims]

        dataDimRef = func(dataDims[xDim])
        excludeRegion[xDim] = [
            ppm2pnt(waterRegion[0], dataDimRef),
            ppm2pnt(waterRegion[1], dataDimRef)
        ]

        findPeaks(
            tocsyPl,
            wholeRegion,
            argServer.parent,
            [1, 1, 1],
        )

    nhsqcPl = argServer.getPeakList()
    nhsqc = nhsqcPl.dataSource

    noise = ExperimentBasic.getNoiseEstimate(nhsqc) * 2.0

    dataDims = nhsqc.sortedDataDims()
    dd0 = dataDims[0]
    dd1 = dataDims[1]

    ddr0 = ExperimentBasic.getPrimaryDataDimRef(dd0)
    ddr1 = ExperimentBasic.getPrimaryDataDimRef(dd1)

    print "Initial NOESY filter"
    amides = []

    allPeaks = list(noesyPl.peaks)
    allPeaks.extend(tocsyPl.peaks)

    for peak in allPeaks:
        peakDims = peak.sortedPeakDims()
        ppm0 = peakDims[0].value
        ppm2 = peakDims[2].value

        pnt0 = ppm2pnt(ppm0, ddr0)
        pnt1 = ppm2pnt(ppm2, ddr1)

        if ppm0 < minPpmH:
            peak.delete()
            continue

        if ppm0 > maxPpmH:
            peak.delete()
            continue

        if (pnt0 - 1 < 0) or (pnt0 > dd0.numPointsOrig):
            peak.delete()
            continue

        if (pnt1 - 1 < 0) or (pnt1 > dd1.numPointsOrig):
            peak.delete()
            continue

        height1 = nhsqc.block_file.getValue((pnt0 - 1, pnt1))
        height2 = nhsqc.block_file.getValue((pnt0, pnt1 - 1))
        height3 = nhsqc.block_file.getValue((pnt0 - 1, pnt1 - 1))
        height4 = nhsqc.block_file.getValue((pnt0, pnt1))

        if height1 < noise:
            peak.delete()
            continue
        if height2 < noise:
            peak.delete()
            continue
        if height3 < noise:
            peak.delete()
            continue
        if height4 < noise:
            peak.delete()
            continue

        if peak.peakList is noesyPl:
            amides.append((peak, ppm0, ppm2))

        peak.ppmH = ppm0
        peak.ppmN = ppm2

    print "Cluster %d amides" % len(amides)
    cluster = {}
    for i in range(len(amides) - 1):
        if i and i % 100 == 0:
            print i
        peak1, ppm0, ppm1 = amides[i]
        if cluster.get(peak1) is None:
            cluster[peak1] = [peak1]

        for j in range(i + 1, len(amides)):
            peak2, ppm2, ppm3 = amides[j]
            if peak1 is peak2:
                continue

            if cluster.get(peak2) is None:
                cluster[peak2] = [peak2]

            if cluster[peak1] == cluster[peak2]:
                continue

            deltaH = ppm2 - ppm0
            deltaN = ratio * (ppm3 - ppm1)
            delta = sqrt((deltaH * deltaH) + (deltaN * deltaN))

            if (delta <= tol):
                cluster[peak1].extend(cluster[peak2])

                for peak3 in cluster[peak2]:
                    cluster[peak3] = cluster[peak1]

    print "Remove isolated peaks"
    clusters2 = {}
    for peak in cluster.keys():
        c = cluster[peak]
        if len(c) < 2:
            peak.delete()
            del c
        else:
            clusters2[c[0]] = c

    clusters = clusters2.values()

    ss = {}
    centres = []
    print "Check for overlapped clusters"
    for peaks in clusters:

        p = peaks[0]
        print 'CLUSTER', p.ppmH, p.ppmN

        for n in range(1):
            print 'Iteration', n
            f = 0.30
            tolF = tol * f

            cluster = {}
            cluster2 = {}
            M = 0
            for i in range(len(peaks) - 1):

                peak1 = peaks[i]
                if cluster.get(peak1) is None:
                    cluster[peak1] = [peak1]
                    cluster2[peak1] = M
                    M += 1

                for j in range(i + 1, len(peaks)):
                    peak2 = peaks[j]
                    if peak1 is peak2:
                        continue

                    if cluster.get(peak2) is None:
                        cluster[peak2] = [peak2]
                        cluster2[peak2] = M
                        M += 1

                    if cluster2[peak1] == cluster2[peak2]:
                        continue

                    deltaH = peak1.ppmH - peak2.ppmH
                    deltaN = ratio * (peak1.ppmN - peak2.ppmN)
                    delta = sqrt((deltaH * deltaH) + (deltaN * deltaN))

                    if delta <= tolF:
                        cluster[peak1].extend(cluster[peak2])

                        for peak3 in cluster[peak2]:
                            cluster[peak3] = cluster[peak1]
                            cluster2[peak3] = cluster2[peak1]

            cluster3 = []
            for i in range(M):
                cluster3.append([])

            for peak in peaks:
                cluster3[cluster2[peak]].append(peak)

            print '  F %3f' % (f),
            for i in range(M):
                N = float(len(cluster3[i]))
                if N > 1.0:
                    aveH = 0.0
                    aveN = 0.0
                    for peak in cluster3[i]:
                        aveH += peak.ppmH
                        aveN += peak.ppmN

                    aveH /= N
                    aveN /= N
                    hsqcPeak = pickPeak(nhsqcPl, (aveH, aveN), unit='ppm')

                    centres.append([hsqcPeak, aveH, aveN])
                    ss[hsqcPeak] = []
                    print len(cluster3[i]),

    print "Assign 15N HSQC"
    #assignAllNewResonances(peaks=nhsqcPl.peaks)
    #assignSpinSystemPerPeak(peaks=nhsqcPl.peaks)

    print "Assign NOESY & TOCSY"
    for peak in allPeaks:
        minDist = tol
        best = centres[0][0]
        for hsqcPeak, aveH, aveN in centres:
            deltaH = peak.ppmH - aveH
            deltaN = ratio * (peak.ppmN - aveN)
            delta = sqrt((deltaH * deltaH) + (deltaN * deltaN))

            if delta < minDist:
                minDist = delta
                best = hsqcPeak

        ss[best].append(peak)

    for hsqcPeak in ss.keys():
        peaks = ss[hsqcPeak]
Example #5
0
def SeparatePeakRoutine(params, peakList, routine='bayesys'):
    """ Run Peak Separate Code and then add resultant peaks to CCPN PeakList (peakList) """

    # check that all C library parameters have been set up before proceeding
    fail = False
    for key in params.ClibKeys:
        if params.__dict__[key] == None:
            print '&&& C Library parameter %s not set, aborting.' % (key)
            fail = True

    if fail: return
    del (fail)

    # As the Lorentz/Gaussian model not in use
    (params.maxQ, params.minQ) = (1., 1.)

    # params.ClibKeys.sort()
    # for key in params.ClibKeys:
    #   print key, params.__dict__[key]

    if params.maxHeight <= params.minHeight:
        print '&&& Peak Separator height mismatch - please report to CCPN'
        return

    if routine == 'bayesys':

        # Maybe a quick parameter check so that no one is doing anything silly ?
        # Run the BayesPeakSeparator function in C
        results = BayesPeakSeparator.run_bayes(   \
                                        params.dataFile, params.Ndim, params.isBigEndian, params.nPoints,           #  4
                                        params.blockSize,                                                           #  1
                                        params.sampleStart, params.sampleEnd,                                       #  2
                                        params.maxHeight, params.minHeight,                                         #  2
                                        params.maxSigma, params.minSigma,                                           #  2
                                        params.maxQ, params.minQ,                                                   #  2
                                        params.dimWrapped,                                                          #  1
                                        params.peakShape, params.positivePeaks, params.minAtoms, params.maxAtoms,   #  2
                                        params.rate)                                                                #  1
        # 17

    elif routine == 'pymc':

        try:
            from PeakSeparatorPyMC import PeakSeparatorPyMC
        except ImportError:
            print 'Error, cannot import PeakSeparatorPyMC - PyMC peak separation will not work.'
            return

        if params.maxHeight <= params.minHeight:
            print '&&& Peak Separator height mismatch - please report to CCPN'
            return

        if params.Ndim != 2:
            print '&&& Peak Separator PyMC only in two dims currently'
            return

        results = PeakSeparatorPyMC(params)

    if (results == None) or (len(results) == 0):
        print '&&& SeparatePeakRoutine: failed.', results
        return 1

    shapeDict = {3: 'Gaussian', 4: 'Lorentzian', 5: 'Other'}

    peak_count = 0

    # tempNdim as nDim not correct for pseudo nD spectra
    sampledData = True if False in set([bool(t)
                                        for t in params.isFreqDim]) else False
    tempNdim = (params.Ndim - 1) if sampledData else params.Ndim

    # for each peak in the returned sample set
    for sample in getPeaksFromResults(results):

        height = float(sample[2])
        sigma = [float(sample[2 * i + 2 + 2]) for i in range(tempNdim)]
        position = [float(sample[2 * i + 1 + 2]) for i in range(tempNdim)]

        peak_count += 1

        cluster_peak_position_point = [0] * params.Ndim

        if params.peakShape == 3:  # Gaussian (nd)
            cluster_peak_volume = height
        if params.peakShape == 4:  # Lorentzian (nd)
            cluster_peak_volume = height
        else:  # Other (nd)
            cluster_peak_volume = height

        for i in range(tempNdim):

            # No longer a cluester peak! cluster_peak_position_point
            cluster_peak_position_point[i] = float(
                params.sampleStart[i]) + position[i] + 1.0

            # Gauss Volume
            if params.peakShape == 3:
                cluster_peak_volume *= sigma[i] * math.sqrt(2.0 * math.pi)

            # Lorentz Volume
            elif params.peakShape == 4:
                cluster_peak_volume *= sigma[i] * math.pi

            else:
                print '&&& Write code to integrate this shape: %d' % (
                    params.peakShape)

        # plane dim for pseudo 3d Analysis data (titrations / time lapse etc)
        if sampledData:
            for i in range(params.Ndim):
                if not params.isFreqDim[i]:
                    cluster_peak_position_point[i] = params.sampleEnd[i]

        # pickPeak from ccpnmr.analysis.core.PeakBasic
        peakListPeak = pickPeak(peakList,
                                cluster_peak_position_point,
                                unit='point',
                                doFit=False)

        for i, peakDim in enumerate(peakListPeak.sortedPeakDims()):

            if (sampledData) and (i == (params.Ndim - 1)): break

            cluster_peak_sigma = sigma[i]

            if peakDim.dataDimRef:
                a = pnt2hz(peakDim.position + cluster_peak_sigma,
                           peakDim.dataDimRef)
                b = pnt2hz(peakDim.position, peakDim.dataDimRef)

            peakDim.setLineWidth(2. * abs(a - b))

        # Add note to peak in CCPN peak list (so we know it's a BayeSys peak)
        peakListPeak.setDetails('PeakSeparator %s' %
                                shapeDict[params.peakShape])
        if sample[0] < 0.:
            merit = 0.
        else:
            merit = 1. / (1. + math.exp(-sample[0]))
        peakListPeak.setFigOfMerit(merit)

        # Add peak intensities (which have just been calculated)
        setManualPeakIntensity(peakListPeak, height, intensityType='height')
        setManualPeakIntensity(peakListPeak,
                               cluster_peak_volume,
                               intensityType='volume')