Ejemplo n.º 1
0
    def makeInterConstraints(self, resonances, constraintSet):

        from ccpnmr.analysis.core.ConstraintBasic import getFixedResonance
        from ccpnmr.analysis.core.AssignmentBasic import findConnectedSpinSystem

        project = constraintSet.root
        constraintList = constraintSet.newDistanceConstraintList()
        constraintList.name = 'Seq connections'

        resDict = {}
        spinSystemDict = {}
        for resonance in resonances:
            resDict[resonance] = True
            spinSystem = resonance.resonanceGroup
            if spinSystem:
                spinSystemDict[spinSystem] = None

        spinSystems = spinSystemDict.keys()

        for spinSystem in spinSystems:
            nextSpinSystem = findConnectedSpinSystem(spinSystem, delta=1)
            if nextSpinSystem:
                ca = spinSystem.newAtoms.get('CA')
                c = spinSystem.newAtoms.get('C')
                n = nextSpinSystem.newAtoms.get('N')

                if ca and c and n:
                    if resDict.get(ca) is None:
                        resonances.append(ca)
                    if resDict.get(c) is None:
                        resonances.append(c)
                    if resDict.get(n) is None:
                        resonances.append(n)

                    c_n = constraintList.newDistanceConstraint(
                        weight=1.0,
                        origData=1.0,
                        targetValue=1.32,
                        upperLimit=1.35,
                        lowerLimit=1.29,
                        error=0.06)

                    # below based on angle constraints
                    ca_n = constraintList.newDistanceConstraint(
                        weight=1.0,
                        origData=1.0,
                        targetValue=2.415,
                        upperLimit=2.513,
                        lowerLimit=2.316,
                        error=0.197)

                    frCa = getFixedResonance(constraintSet, ca)
                    frC = getFixedResonance(constraintSet, c)
                    frN = getFixedResonance(constraintSet, n)

                    item = ca_n.newDistanceConstraintItem(
                        resonances=[frCa, frN])
                    item = c_n.newDistanceConstraintItem(resonances=[frC, frN])

        return resonances, constraintList
def record_constraint_list(optional_restraints, constraintSet):
    '''Take a list of OptionalRestraints and make
       more permanent restraints based on them that
       get stored in a constraintSet in CCPN.
       Done like this because the CCPN constraints
       do not have information about the direction
       of magnetization transfer.

    '''

    peak = optional_restraints[0].peak
    peakList = peak.peakList
    spectrum = peakList.dataSource
    experiment = spectrum.experiment

    distConstraintList = constraintSet.newDistanceConstraintList()
    distConstraintList.addExperimentSerial(experiment.serial)
    newConstraint = distConstraintList.newDistanceConstraint

    for optional_restraint in optional_restraints:

        constraint = newConstraint(weight=1.0,
                                   origData=optional_restraint.intensityValue,
                                   targetValue=optional_restraint.targetValue,
                                   upperLimit=optional_restraint.upperLimit,
                                   lowerLimit=optional_restraint.lowerLimit,
                                   error=optional_restraint.error)


        peak = optional_restraint.peak
        peakList = peak.peakList
        spectrum = peakList.dataSource
        experiment = spectrum.experiment

        constraint.newConstraintPeakContrib(experimentSerial=experiment.serial,
                                            dataSourceSerial=spectrum.serial,
                                            peakListSerial=peakList.serial,
                                            peakSerial=peak.serial)

        for contrib in optional_restraint.contributions:
            res0, res1 = contrib.restraint_resonances
            fixedResonance0 = getFixedResonance(constraintSet, res0)
            fixedResonance1 = getFixedResonance(constraintSet, res1)
            constraint.newDistanceConstraintItem(resonances=[fixedResonance0, fixedResonance1])

    return distConstraintList
Ejemplo n.º 3
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
Ejemplo n.º 4
0
def assignResonances(resonances, atomToResonanceMap, molSystem, ccpnShiftList,
                     AnalysisProject, nmrConstraintStore):

    print "assigning resonances"
    atomTupleDict = {}
    resonanceDict = {}
    fixedResonanceDict = {}
    cingFixedResonanceDict = {}

    for cingResonance in resonances:

        ccpnResidueArray = cingResonance.atom.residue.typeIdentifier.translate(
            'CCPN').split()
        ccpnResidueName = ccpnResidueArray[1]
        if cingResonance.stereo == True:
            ### find the ccpnResonance from which the cingResonance originated and assign it.

            ringAtoms = [
                'CD1', 'CD2', 'CE1', 'CE2', 'HD1', 'HD2', 'HE1', 'HE2'
            ]
            ccpnRealAtomName = cingResonance.atom.typeIdentifier.translate(
                'CCPN')
            if ccpnResidueName == 'Phe' and ccpnRealAtomName in ringAtoms:
                ccpnRealAtomName = ccpnRealAtomName[:2] + "*"
            if ccpnResidueName == 'Tyr' and ccpnRealAtomName in ringAtoms:
                ccpnRealAtomName = ccpnRealAtomName[:2] + "*"
                ccpnMappingAtomName = ccpnRealAtomName[0] + ccpnRealAtomName[
                    1:].lower()
            if len(ccpnRealAtomName) == 1:
                ccpnMappingAtomName = ccpnRealAtomName
            else:
                ccpnMappingAtomName = ccpnRealAtomName[0] + ccpnRealAtomName[
                    1:].lower()

            ccpnChainCode = molSystem.findFirstChain(
                code=cingResonance.atom.chainId)
            ccpnResNum = cingResonance.atom.sequenceId
            ccpnResidue = molSystem.findFirstChain().findFirstResidue(
                seqCode=ccpnResNum)
            ccpnResidueMapping = AnalysisProject.findFirstChainMapping(
                molSystemCode=molSystem.code,
                chainCode=cingResonance.atom.chainId).findFirstResidueMapping(
                    seqId=ccpnResidue.seqId)
            ccpnAtomMapping = ccpnResidueMapping.findFirstAtomSetMapping(
                name=ccpnMappingAtomName)

            atomTuple = (ccpnChainCode, ccpnResidue.seqId, ccpnRealAtomName)
            if atomTuple not in atomTupleDict:
                atomTupleDict[atomTuple] = cingResonance
            resonance = atomToResonanceMap[atomTuple]
            assignAtomsToRes(ccpnAtomMapping.atomSets, resonance)

            # except KeyError:
            #   pass

        else:
            ### find the ccpnResonance from which the cingResonance originated and assign it.
            ringAtoms = [
                'CD1', 'CD2', 'CE1', 'CE2', 'HD1', 'HD2', 'HE1', 'HE2'
            ]
            ccpnRealAtomName = cingResonance.atom.typeIdentifier.translate(
                'CCPN')
            if ccpnResidueName == 'Phe' and ccpnRealAtomName in ringAtoms:
                ccpnRealAtomName = ccpnRealAtomName[:2] + "*"

            if ccpnResidueName == 'Tyr' and ccpnRealAtomName in ringAtoms:
                ccpnRealAtomName = ccpnRealAtomName[:2] + "*"

            ccpnChainCode = molSystem.findFirstChain(
                code=cingResonance.atom.chainId)
            ccpnResNum = cingResonance.atom.sequenceId
            ccpnResidue = molSystem.findFirstChain().findFirstResidue(
                seqCode=ccpnResNum)
            atomTuple = (ccpnChainCode, ccpnResidue.seqId, ccpnRealAtomName)
            if atomTuple not in atomTupleDict:
                atomTupleDict[atomTuple] = cingResonance

    for atomTuple in atomTupleDict:
        cingResonance = atomTupleDict[atomTuple]
        try:
            resonance = atomToResonanceMap[atomTuple]
            shift = ccpnShiftList.newShift(value=cingResonance.value,
                                           resonance=resonance)
            if resonance is not None:
                resonanceDict[cingResonance] = resonance
                fixedResonance = getFixedResonance(nmrConstraintStore,
                                                   resonance)
                fixedResonanceDict[resonance] = fixedResonance
                cingFixedResonanceDict[cingResonance.atom] = fixedResonance

        except KeyError:
            pass
    return {
        "resonanceDict": resonanceDict,
        "fixedResonanceDict": fixedResonanceDict,
        "cingFixedResonanceDict": cingFixedResonanceDict
    }

    print "Resonances assigned"
Ejemplo n.º 5
0
def optimiseRelaxation(resonances,amat,tmix=60,sf=500,tcor=3,rleak=2,C13=1,N15=1,minConnectivity=1,maxIter=50):

  n = len(resonances) # number of H 'atoms'
  
  assert n == len(amat)
  assert n == len(amat[0])
 
  atom_types  = { 'CH3': 1, 'Haro': 3, 'HN': 4 }
  protonNumbs = { 'CH3': 3, 'Haro': 2, 'HN': 1, 'H': 1}

  # make blank matrices
  nhs   = n * [0]
  types = n * [0]
  atoms = n * [0]

  for i in range(n):
    typ      = resonances[i].name
    atoms[i] = typ
    nhs[i]   = protonNumbs[typ]
    types[i] = atom_types.get(typ, 0)
  
  symmetriseNoeMatrix(amat)
  removeOutliers(amat)  

  exclude={}
  for a in range(len(amat)):
    nonZero = 0
    for b in range(len(amat[a])):
      if amat[a][b] > 0:
        nonZero += 1
    if nonZero < minConnectivity:
      exclude[a] = 1
      
  amatNew=[]
  for a in range(len(amat)):
    if exclude.get(a) is None:
      new = []
      for b in range(len(amat[a])):
        if exclude.get(b) is None:
          new.append(amat[a][b])
      amatNew.append(new)
      
  for a in range(len(amat)-1,-1,-1):
    if exclude.get(a):
      resonances.pop(a)
      atoms.pop(a)
      nhs.pop(a)
      types.pop(a)

  print len(atoms), len(nhs), len(types), len(amat), len(amatNew)

  n = len(resonances) # number of atoms
  rmat  = n * [0]
  for i in range(n):
    rmat[i] = n * [0]

  amat = amatNew      
  #print amat
  num = 0
  for i in range(n):
    for j in range(n):
      if amat[i][j] != 0.0:
        num += 1
  
  fp = open('noe01.inp', 'w')
  fp.write('%6.1d\n' % (num))
  for i in range(n):
    amat[i][i] = nhs[i]
    for j in range(n):
      if amat[i][j] != 0.0:
        fp.write('%3.1d  %3.1d   %9.2e\n' % (i+1,j+1,amat[i][j]))
    #fp.write('\n')
  fp.close()

  fp = open('symbols.inp', 'w')
  for i in range(n):
    fp.write('%3.1d %-4s %d\n' % (i+1,resonances[i].name,nhs[i]))
  fp.close()
  

  m = Midge(nhs, types)
  err = m.run(amat, rmat, maxIter, sf, tmix, tcor, rleak, N15, C13)
  print 'error = %3.2e' % err

  """
  fp = open('amat.out', 'w')
  for i in range(n):
    for j in range(n):
      fp.write('%8.3e ' % amat[i][j])
    fp.write('\n')
  fp.close()

  fp = open('rmat.out', 'w')
  for i in range(n):
    for j in range(n):
      fp.write('%8.3e ' % rmat[i][j])
    fp.write('\n')
  fp.close()
  """

  PI = math.pi
  GH = 2.6752e4
  if N15:
    GN = -2.7126e3
  else:
    GN = 1.9340e3
  HB = 1.05459e-27
  CONST = GH*GH*GH*GH * HB*HB
  tc = 1.0e-9 * tcor
  wh = 2.0 * PI * sf * 1.0e6
  wn = wh * GN / GH
  j0 = CONST * tc
  j1 = CONST * tc / (1.0 + wh*wh*tc*tc)
  j2 = CONST * tc / (1.0 + 4.0*wh*wh*tc*tc)
  #jself = 6.0*j2 + 3.0*j1 + j0
  jcross = 6.0*j2 - j0

  project             = resonances[0].root
  constraintHead      = project.newNmrConstraintStore(nmrProject=resonances[0].topObject)
  distConstraintList  = NmrConstraint.DistanceConstraintList(constraintHead)
  for i in range(n-1):
    for j in range(i+1, n):
      if ((amatNew[i][j] != 0) and (rmat[i][j] != 0.0)):
        dist = 1.0e8 * ((10*abs(rmat[i][j]/(jcross*nhs[j])))**(-1.0/6.0))
        if dist > 6.0:
          continue
        fixedResonanceI = getFixedResonance(constraintHead,resonances[i])
        fixedResonanceJ = getFixedResonance(constraintHead,resonances[j])
        #fp.write('%3d %3d %3d %4s %3d %4s  %5.2f\n' % (i+1, j+1, i+1, atoms[i], j+1, atoms[j], d))
        constraint = NmrConstraint.DistanceConstraint(distConstraintList, weight=1, targetValue=dist, upperLimit=dist+(dist/2.0), lowerLimit=dist-(dist/2.0), error=dist/5)
        item = NmrConstraint.DistanceConstraintItem(constraint, resonances=[fixedResonanceI,fixedResonanceJ])
        
  print "Midge for CcpNmr Done"
  return distConstraintList, resonances
Ejemplo n.º 6
0
def makeConstraintsFromStructure(argServer,
                                 structure=None,
                                 atomRoots=None,
                                 threshold=5.5,
                                 tolerance=0.1,
                                 adcThreshold=7.0,
                                 atomTypes=('H', ),
                                 adcAtoms=('H', )):
    # find all NMR visible atom pairs within a specified distance to
    # generate distance constraints

    if not structure:
        structure = argServer.getStructure()

    from ccpnmr.analysis.core.AssignmentBasic import newResonance
    from ccpnmr.analysis.core.StructureBasic import getAtomSetsDistance
    from ccpnmr.analysis.core.ConstraintBasic import getFixedResonance, makeNmrConstraintHead

    notVisible = {
        'Lys': ["H''", "HZ1", "HZ2", "HZ3"],
        'Arg': ["H''", "HH11", "HH12", "HH21", "HH22", "CZ"],
        'Ser': [
            "H''",
            "HG",
        ],
        'Cys': [
            "H''",
            "HG",
        ],
        'His': ["H''", "HD1", "CG"],
        'Thr': [
            "H''",
            "HG1",
        ],
        'Tyr': ["H''", "HH", "CG"],
        'Phe': ["H''", "CG"],
        'Glu': [
            "H''",
            "HE2",
        ],
        'Asp': [
            "H''",
            "HD2",
        ],
        'Trp': ["H''", "CG", "CD2", "CE2"],
    }

    project = structure.root
    chain = structure.findFirstCoordChain().chain

    atomSetDict = {}
    anchorAtomSets = {}
    amideAtomSets = []
    resonanceDict = {}
    adcAtomSets = {}

    print "Getting atomSets and resonances"
    for residue in chain.residues:
        atomSetDict[residue] = []
        exclude = notVisible.get(residue.ccpCode) or [
            "H''",
        ]
        for atom in residue.atoms:
            if atom.name[0] not in atomTypes:
                continue
            if atom.name in exclude:
                continue

            atomSet = atom.atomSet
            if atomSet:
                if resonanceDict.get(atomSet) is None:
                    if atomSet.resonanceSets:
                        resonanceSet = atomSet.findFirstResonanceSet()
                        i = list(resonanceSet.atomSets).index(atomSet)
                        if i >= len(resonanceSet.resonances):
                            i = 0
                        resonance = resonanceSet.resonances[i]

                    else:
                        resonance = newResonance(project, isotopeCode='1H')

                    resonanceDict[atomSet] = resonance
                    atomSetDict[residue].append(atomSet)

                if atom.name in ('H', 'H1'):
                    amideAtomSets.append(atomSet)
                elif (residue.ccpCode == 'PRO') and (atom.name == 'HD2'):
                    amideAtomSets.append(atomSet)

                if atomRoots:
                    if atom.name in atomRoots:
                        anchorAtomSets[atomSet] = 1
                else:
                    anchorAtomSets[atomSet] = 1

                if adcAtoms and (atom.name in adcAtoms):
                    adcAtomSets[atomSet] = 1

    print "Calculating distances"
    resonanceDists = []
    resonanceDists2 = []
    for amide1 in amideAtomSets:
        residue1 = amide1.finsFirstAtom().residue
        print "  %d %s" % (residue1.seqCode, residue1.ccpCode)

        for amide2 in amideAtomSets:
            residue2 = amide2.findFirstAtom().residue
            if amide1 is amide2:
                amideDist = 0.0
            else:
                amideDist = getAtomSetsDistance((amide1, ), (amide2, ),
                                                structure)

            if (amideDist is not None) and (amideDist <= 25.0):
                for atomSet1 in atomSetDict[residue1]:
                    if anchorAtomSets.get(atomSet1) is None:
                        continue

                    for atomSet2 in atomSetDict[residue2]:
                        if atomSet1 is atomSet2:
                            continue

                        dist = getAtomSetsDistance((atomSet1, ), (atomSet2, ),
                                                   structure)
                        if dist and dist <= threshold:
                            resonanceDists.append(
                                (dist, resonanceDict[atomSet1],
                                 resonanceDict[atomSet2]))

            if adcAtoms:
                for atomSet1 in atomSetDict[residue1]:
                    if anchorAtomSets.get(atomSet1) is None:
                        continue
                    if adcAtomSets.get(atomSet1) is None:
                        continue

                    for atomSet2 in atomSetDict[residue2]:
                        if adcAtomSets.get(atomSet2) is None:
                            continue
                        if atomSet1 is atomSet2:
                            continue

                        dist = getAtomSetsDistance((atomSet1, ), (atomSet2, ),
                                                   structure)
                        if dist >= adcThreshold:
                            resonanceDists2.append(
                                (dist, resonanceDict[atomSet1],
                                 resonanceDict[atomSet2]))

    print "Generating constraints"
    if resonanceDists:
        constraintHead = makeNmrConstraintHead(project)
        constraintList = constraintHead.newDistanceConstraintList()

        for dist, resonance1, resonance2, in resonanceDists:
            if resonance1 is resonance2:
                continue
            fixedResonance1 = getFixedResonance(constraintHead, resonance1)
            fixedResonance2 = getFixedResonance(constraintHead, resonance2)
            delta = tolerance * dist
            minDist = max(0.0, dist - delta)
            maxDist = dist + delta

            constraint = constraintList.newDistanceConstraint(
                weight=1.0,
                origData=dist,
                targetValue=dist,
                upperLimit=maxDist,
                lowerLimit=minDist,
                error=delta)
            item = constraint.newDistanceConstraintItem(
                resonances=[fixedResonance1, fixedResonance2])

        if adcAtoms:
            constraintList2 = constraintHead.newDistanceConstraintList()
            # make ADCs
            for dist, resonance1, resonance2, in resonanceDists2:
                if resonance1 is resonance2:
                    continue
                dist = 75.0
                fixedResonance1 = getFixedResonance(constraintHead, resonance1)
                fixedResonance2 = getFixedResonance(constraintHead, resonance2)
                minDist = 5.0
                maxDist = 150
                delta = maxDist - minDist

                constraint = constraintList2.newDistanceConstraint(
                    weight=1.0,
                    origData=dist,
                    targetValue=dist,
                    upperLimit=maxDist,
                    lowerLimit=minDist,
                    error=delta)
                item = constraint.newDistanceConstraintItem(
                    resonances=[fixedResonance1, fixedResonance2])

    print "Done"
Ejemplo n.º 7
0
    def storeDihedralConstraints(self):

        if not self.dangleChain:
            return

        # make a new dihedralConstraintList
        head = self.constraintSet

        if not head:
            head = self.project.newNmrConstraintStore(
                nmrProject=self.nmrProject)
            self.constraintSet = head

        chain = self.dangleChain.chain
        shiftList = self.dangleChain.shiftList
        name = 'DANGLE Chain %s:%s ShiftList %d' % (
            chain.molSystem.code, chain.code, shiftList.serial)
        constraintList = head.newDihedralConstraintList(name=name,
                                                        measureListSerials=[
                                                            shiftList.serial,
                                                        ])

        # traverse the sequence and make appropriate constraint objects
        residues = chain.sortedResidues()
        for residue in residues:
            # Ensure we have atomSets etc
            getResidueMapping(residue)

        residueList = [(dr.residue.seqCode, dr.residue, dr)
                       for dr in self.dangleChain.dangleResidues]
        residueList.sort()

        cnt = 0

        for seqCode, residue, dangleResidue in residueList:

            phi = dangleResidue.phiValue
            psi = dangleResidue.psiValue

            if (phi is None) and (psi is None):
                continue

            # Use below functions because residues may not be sequentially numbered
            prevRes = getLinkedResidue(residue, 'prev')
            nextRes = getLinkedResidue(residue, 'next')
            if (prevRes is None) or (nextRes is None):
                continue

            C__1 = prevRes.findFirstAtom(name='C')  # C (i-1)
            N_0 = residue.findFirstAtom(name='N')  # N (i)
            CA_0 = residue.findFirstAtom(name='CA')  # CA(i)
            C_0 = residue.findFirstAtom(name='C')  # N (i)
            N_1 = nextRes.findFirstAtom(name='N')  # C (i+1)

            # get fixedResonances
            fixedResonances = []
            for atom in (C__1, N_0, CA_0, C_0, N_1):
                atomSet = atom.atomSet

                if atomSet.resonanceSets:
                    resonance = atomSet.findFirstResonanceSet(
                    ).findFirstResonance()

                else:
                    # make new resonance
                    if not atom.chemAtom:
                        print 'no chem atom'

                    ic = atom.chemAtom.elementSymbol
                    if (ic == 'C'):
                        ic = '13' + ic
                    elif (ic == 'N'):
                        ic = '15' + ic

                    resonance = self.nmrProject.newResonance(isotopeCode=ic)
                    assignAtomsToRes([
                        atomSet,
                    ], resonance)
                fixedResonances.append(getFixedResonance(head, resonance))

            # make dihedralConstraints
            phiResonances = (fixedResonances[0], fixedResonances[1],
                             fixedResonances[2], fixedResonances[3])
            phiConstraint = constraintList.newDihedralConstraint(
                resonances=phiResonances)

            psiResonances = (fixedResonances[1], fixedResonances[2],
                             fixedResonances[3], fixedResonances[4])
            psiConstraint = constraintList.newDihedralConstraint(
                resonances=psiResonances)

            # make constraint items

            if phi is not None:
                phiConstraint.newDihedralConstraintItem(
                    targetValue=phi,
                    upperLimit=dangleResidue.phiUpper,
                    lowerLimit=dangleResidue.phiLower)
                cnt += 1

            if psi is not None:
                psiConstraint.newDihedralConstraintItem(
                    targetValue=psi,
                    upperLimit=dangleResidue.psiUpper,
                    lowerLimit=dangleResidue.psiLower)
                cnt += 1

        showInfo('Success',
                 'DANGLE has generated %d dihedral restraints.' % cnt,
                 parent=self)
Ejemplo n.º 8
0
    def makeIntraConstraints(self, resonances, constraintSet):

        from ccpnmr.analysis.core.ConstraintBasic import getFixedResonance

        project = constraintSet.root
        constraintList = constraintSet.newDistanceConstraintList()
        constraintList.name = 'Backbone intra'

        dict = {}
        for resonance in resonances:
            if resonance.resonanceGroup and resonance.assignNames:
                dict[resonance] = 1
                resonance.resonanceGroup.newAtoms = {}

        for resonance in dict.keys():
            ss = resonance.resonanceGroup
            if resonance.assignNames[0] == 'H':
                for resonance2 in ss.resonances:
                    if dict.get(resonance2
                                ) and resonance2.assignNames[0][:2] == 'HA':

                        ca = ss.newAtoms.get('CA')
                        if ca is None:
                            ca = project.newResonance(isotopeCode='13C',
                                                      assignNames=[
                                                          'CA',
                                                      ])
                            resonances.append(ca)

                        c = ss.newAtoms.get('C')
                        if c is None:
                            c = project.newResonance(isotopeCode='13C',
                                                     assignNames=[
                                                         'C',
                                                     ])
                            resonances.append(c)

                        n = ss.newAtoms.get('N')
                        if n is None:
                            n = project.newResonance(isotopeCode='15N',
                                                     assignNames=[
                                                         'N',
                                                     ])
                            resonances.append(n)

                        ss.newAtoms['C'] = c
                        ss.newAtoms['CA'] = ca
                        ss.newAtoms['N'] = n

                        frCa = getFixedResonance(constraintSet, ca)
                        frC = getFixedResonance(constraintSet, c)
                        frN = getFixedResonance(constraintSet, n)
                        frH = getFixedResonance(constraintSet, resonance)
                        frha = getFixedResonance(constraintSet, resonance2)

                        h_n = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=1.01,
                            upperLimit=1.1,
                            lowerLimit=0.9,
                            error=0.2)
                        n_ca = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=1.465,
                            upperLimit=1.50,
                            lowerLimit=1.43,
                            error=0.07)
                        ca_c = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=1.525,
                            upperLimit=1.55,
                            lowerLimit=1.50,
                            error=0.05)

                        # below based on angle constraints
                        n_c = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=2.464,
                            upperLimit=2.572,
                            lowerLimit=2.356,
                            error=0.216)

                        item = h_n.newDistanceConstraintItem(
                            resonances=[frH, frN])
                        item = n_ca.newDistanceConstraintItem(
                            resonances=[frN, frCa])
                        item = ca_c.newDistanceConstraintItem(
                            resonances=[frCa, frC])
                        item = n_c.newDistanceConstraintItem(
                            resonances=[frN, frC])

                        if ss.newAtoms.get('CAHA') is None:
                            ca_ha = constraintList.newDistanceConstraint(
                                weight=1.0,
                                origData=1.0,
                                targetValue=1.09,
                                upperLimit=1.19,
                                lowerLimit=0.99,
                                error=0.2)
                            item = ca_ha.newDistanceConstraintItem(
                                resonances=[frC, frha])
                            ss.newAtoms['CAHA'] = 1

            if resonance.assignNames[0][:2] == 'HA':
                for resonance2 in ss.resonances:
                    if dict.get(resonance2
                                ) and resonance2.assignNames[0][:2] == 'HB':

                        ca = ss.newAtoms.get('CA')
                        if ca is None:
                            ca = project.newResonance(isotopeCode='13C',
                                                      assignNames=[
                                                          'CA',
                                                      ])
                            resonances.append(ca)

                        cb = ss.newAtoms.get('CB')
                        if cb is None:
                            cb = project.newResonance(isotopeCode='13C',
                                                      assignNames=[
                                                          'CB',
                                                      ])
                            resonances.append(cb)

                        ss.newAtoms['CA'] = cb
                        ss.newAtoms['CB'] = ca
                        ss.newAtoms['CAHA'] = 1

                        frCA = getFixedResonance(constraintSet, ca)
                        frCB = getFixedResonance(constraintSet, cb)
                        frHA = getFixedResonance(constraintSet, resonance)
                        frHB = getFixedResonance(constraintSet, resonance2)

                        c_b = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=1.09,
                            upperLimit=1.19,
                            lowerLimit=0.99,
                            error=0.2)
                        c_c = constraintList.newDistanceConstraint(
                            weight=1.0,
                            origData=1.0,
                            targetValue=1.53,
                            upperLimit=1.56,
                            lowerLimit=1.51,
                            error=0.05)

                        item = c_b.newDistanceConstraintItem(
                            resonances=[frCB, frHB])
                        item = c_c.newDistanceConstraintItem(
                            resonances=[frCA, frCB])

                        if ss.newAtoms.get('CAHA') is None:
                            c_a = constraintList.newDistanceConstraint(
                                weight=1.0,
                                origData=1.0,
                                targetValue=1.09,
                                upperLimit=1.19,
                                lowerLimit=0.99,
                                error=0.2)
                            item = c_a.newDistanceConstraintItem(
                                resonances=[frCA, frHA])
                            ss.newAtoms['CAHA'] = 1

        return resonances, constraintList