def make_resonanceGroup_string(resonanceGroup): '''Make a more human readable description of a spin system. args: resonanceGroup: spin system returns: str description ''' if resonanceGroup.residue: string = '{} {}'.format(resonanceGroup.residue.seqCode, getResidueCode(resonanceGroup.residue.molResidue)) elif resonanceGroup.residueProbs: substrings = [] for prob in resonanceGroup.residueProbs: if not prob.weight: continue res = prob.possibility substrings.append(' '.join([str(res.seqCode), getResidueCode(res), '?'])) string = ' / '.join(substrings) elif resonanceGroup.ccpCode: string = resonanceGroup.ccpCode else: string = '-' return string
def make_resonanceGroup_string(resonanceGroup): '''Make a more human readable description of a spin system. args: resonanceGroup: spin system returns: str description ''' if resonanceGroup.residue: string = '{} {}'.format( resonanceGroup.residue.seqCode, getResidueCode(resonanceGroup.residue.molResidue)) elif resonanceGroup.residueProbs: substrings = [] for prob in resonanceGroup.residueProbs: if not prob.weight: continue res = prob.possibility substrings.append(' '.join( [str(res.seqCode), getResidueCode(res), '?'])) string = ' / '.join(substrings) elif resonanceGroup.ccpCode: string = resonanceGroup.ccpCode else: string = '-' return string
def setResidue(self, residue): self.residue = residue shiftList = self.shiftList if residue: self.varFrame.update(self.residue.chemCompVar) cAtomDict = self.varFrame.cAtomDict for atom in self.residue.atoms: chemAtom = atom.chemAtom cAtom = cAtomDict.get(chemAtom) if cAtom and self.showAssign: shifts = getAtomSetShifts(atom.atomSet, shiftList) label = '/'.join( ['%3.3f' % (shift.value) for shift in shifts]) cAtom.setAnnotation(chemAtom.name + ' ' + label) self.varFrame.drawStructure() chain = self.residue.chain self.label.set('Residue: %d%s ( %s %s )' % (self.residue.seqCode, getResidueCode(self.residue), chain.molSystem.code, chain.code)) else: self.varFrame.update(None) self.label.set('Residue: <None>')
def update(self): textMatrix = [] objectList = [] if self.molSystem: chains = self.molSystem.sortedChains() if len(chains) > 1: doChains = False else: doChains = True for chain in chains: if doChains: chainCode = chain.code else: chainCode = '' for residue in chain.sortedResidues(): name = '%s%d%s' % (chainCode, residue.seqCode, getResidueCode(residue)) phi = 0.0 chiSq = 0.0 datum = [name, phi, chiSq] object = [ residue, ] for atomNames in couplingAtoms: couplingM = self.getResidueJCoupling( self.measureJCouplingList, residue, atomNames) couplingP = self.getResidueJCoupling( self.predictJCouplingList, residue, atomNames) pred = None expt = None if couplingM: expt = couplingM.value if couplingP: pred = couplingP.value datum.append(pred) datum.append(expt) object.append(couplingM) objectList.append(object) textMatrix.append(datum) self.couplingMatrix.update(textMatrix=textMatrix, objectList=objectList) self.updateCoefficients() self.waiting = False
def updateSpinSystems(self): textMatrix = [] objectList = [] colorMatrix = [] headingList = self.getHeadings() for spinSystem in self.getTentativeSpinSystems(): residueText = None residue, probability = self.getProbableResidue(spinSystem) if residue: residueText = '%d%s' % (residue.seqCode, getResidueCode(residue)) links = [] color = '#D04040' if findConnectedSpinSystem(spinSystem, delta=-1): links.append('-1') if findConnectedSpinSystem(spinSystem, delta=1): links.append('+1') if len(links) == 2: color = '#40B040' elif len(links) == 1: color = '#B0B040' datum = [] datum.append(spinSystem.serial) datum.append(residueText) datum.append(probability) datum.append(' '.join(links)) self.addShiftData(spinSystem, datum) colors = [None] * len(headingList) colors[3] = color objectList.append(spinSystem) textMatrix.append(datum) colorMatrix.append(colors) if self.spinSystem not in objectList: self.spinSystem = None self.spinSystemMatrix.update(headingList=headingList, objectList=objectList, textMatrix=textMatrix, colorMatrix=colorMatrix) self.updateButtons() self.waiting = False
def getLabels(self, residues): texts = [] for residue in residues: ccpCode = getResidueCode(residue) molType = residue.molType text = '%d %s' % (residue.seqCode, ccpCode) if self.doAtoms: for atom in residue.atoms: if atom.name in self.displayedAtoms: texts.append('%s %s' % (text, makeGuiName(atom.name, atom.chemAtom.elementSymbol, molType))) else: texts.append(text) return texts
def analyseChemicalShifts(shiftList): updateAllShifts(shiftList) # T1, shifts - Row per resonance - Cols: shift, shiftSD, # maxPeak delta, SD per spectrum ++ data = [] duplicateAssign = {} data2 = [] if shiftList: project = shiftList.root for shift in shiftList.measurements: resonance = shift.resonance assignTuple = getResonanceAtomTuple(resonance) data2.append(['%s%s%8.8s%s' % assignTuple,shift]) duplicateAssign[assignTuple] = duplicateAssign.get(assignTuple, 0) + 1 data2.sort() for name, shift in data2: resonance = shift.resonance deltaMax = None nContribs = 0 bmrbMean = None randomCoil = None typeScore = None resonanceSet = resonance.resonanceSet if resonanceSet: atomSet = resonanceSet.findFirstAtomSet() residue = atomSet.findFirstAtom().residue ccpCode = residue.ccpCode molType = residue.molResidue.molType atomName = atomSet.name chemAtomNmrRef = getChemAtomNmrRef(project, atomName, ccpCode, molType=molType) if chemAtomNmrRef is None: atomName = atomSet.findFirstAtom().name chemAtomNmrRef = getChemAtomNmrRef(project, atomName, ccpCode, molType=molType) if chemAtomNmrRef: # Horrid kludge until we have chem shift ref info per var if (ccpCode == 'Cys') and ('link:SG' in residue.chemCompVar.descriptor): ccpCode = 'Cyss' typeScore = lookupAtomProbability(project, ccpCode, atomName, shift.value, molType) bmrbMean = chemAtomNmrRef.meanValue randomCoil = chemAtomNmrRef.randomCoilValue for contrib in resonance.peakDimContribs: peakDim = contrib.peakDim shiftList1 = peakDim.peak.peakList.dataSource.experiment.shiftList if shiftList1 and (shiftList1 is shiftList): nContribs +=1 delta = abs(peakDim.realValue-shift.value) if (deltaMax is None) or (delta > deltaMax): deltaMax = delta boundWarn = False bound = getBoundResonances(resonance, recalculate=True) if bound: nBound = len(bound) for reson in bound: # Correct for multiatom atomSets (CH3 resonances e,g,) resSet = reson.resonanceSet if resSet: ll = [1] for atomSet in resSet.atomSets: length = len(atomSet.atoms) cas = atomSet.findFirstAtom().chemAtom.chemAtomSet if not cas or cas.isEquivalent is not None: # Test excludes e.g. Tyr and Phe side chains # that otherwise give spurious errors ll.append(length) # Add additional number of atoms for each bound resonance nBound += min(ll) - 1 if resonance.isotopeCode in ('1H','2H','19F'): if nBound > 1: boundWarn = True elif resonanceSet: chemAtom = resonance.resonanceSet.findFirstAtomSet().findFirstAtom().chemAtom if nBound > len(chemAtom.chemBonds): boundWarn = True if resonanceSet and not boundWarn: atom = resonanceSet.findFirstAtomSet().findFirstAtom() for resonance1 in bound: resonanceSet1 = resonance1.resonanceSet if resonanceSet1: for atomSet1 in resonanceSet1.atomSets: for atom1 in atomSet1.atoms: if areAtomsBound(atom, atom1): break else: continue break else: boundWarn = True assignTuple = getResonanceAtomTuple(resonance) sameResBound = [] otherBound = [] residue = getResonanceResidue(resonance) for resonance1 in bound: residue1 = getResonanceResidue(resonance1) if residue1 is residue: sameResBound.append(makeResonanceGuiName(resonance1,fullName=False)) else: otherBound.append(makeResonanceGuiName(resonance1)) boundResonances = '' if residue: ccpCode = getResidueCode(residue) resName1 = '%d%s' % (residue.seqCode,ccpCode) if len(sameResBound) > 1: boundResonances += '%s[%s] ' % (resName1,','.join([x for x in sameResBound])) elif sameResBound: boundResonances += '%s%s ' % (resName1,sameResBound[0]) else: boundResonances += ','.join([x for x in sameResBound]) boundResonances += ','.join([x for x in otherBound]) isDuplicate = False if duplicateAssign.get(assignTuple, 0) > 1: isDuplicate = True resName = makeResonanceGuiName(resonance) datum = [resonance.serial,resonance.isotopeCode,resName,boundResonances, bmrbMean,randomCoil,typeScore,shift.value,shift.error, deltaMax,nContribs,isDuplicate,boundWarn] data.append([shift, datum]) return data
def updatePhiPsi(self): # labels='outliers', '' if not self.structure: return model = self.model ccpCode = self.ccpCode residueSel = self.residue labelMode = self.labelMode getValue = self.plot.getIntensityValue ccpCode = self.ccpCode if self.residue: ccpCode = self.residue.residue.ccpCode self.plot.setAminoAcid(ccpCode) phiPsiAccept = [] plotObjects = [] resLabels = [] colors = [] if self.colorScheme: scheme = list(self.colorScheme.colors) else: scheme = ['#800000','#008000','#000080'] nCols = len(scheme) nCore = 0 nAllowed = 0 nDisallowed = 0 colorFrame = self.colorFrame colorLabels = self.colorLabels structure = self.structure if structure == 'All': structures = self.getStructures() nstructures = len(structures) ncolorLabels = len(colorLabels) n = nstructures - ncolorLabels if n > 0: for i in range(n): label = Label(colorFrame, grid=(0,i+ncolorLabels+1)) colorLabels.append(label) for i, structure0 in enumerate(structures): text = 'Structure %d' % structure0.ensembleId label = colorLabels[i] label.set(text) color = scheme[i % nCols] label.config(bg=color) if color == '#000000': label.config(fg='#FFFFFF') else: label.config(fg='#000000') colorFrame.grid(row=self.colorRow, column=0) else: structures = [structure] colorFrame.grid_forget() for structure0 in structures: if model: models = [model,] else: models = list(structure0.models) nModels = len(models) for chain in structure0.coordChains: for residue in chain.residues: sysResidue = residue.residue sysCode = getResidueCode(sysResidue) resLabel = '%d%s' % (sysResidue.seqCode,sysCode) if sysResidue.molResidue.molType != 'protein': continue if residue and residueSel and (residue.residue is not residueSel.residue): continue if ccpCode and (sysCode != ccpCode): continue for model0 in models: phi, psi = getResiduePhiPsi(residue, model=model0) if None in (phi,psi): continue value = getValue(phi,psi) if nModels == 1: resLabels.append(resLabel) else: resLabels.append( '%s:%d' % (resLabel, model0.serial) ) doLabel = False if value < 6.564e-5: if labelMode == LABEL_MODES[1]: doLabel = True nDisallowed += 1 elif value < 0.000821: nAllowed += 1 else: nCore += 1 if labelMode == LABEL_MODES[0]: doLabel = False elif labelMode == LABEL_MODES[2]: doLabel = True if structure == 'All': ind = structures.index(structure0) else: ind = model0.serial - 1 colors.append(scheme[ind % nCols]) plotObjects.append((residue, model0)) phiPsiAccept.append((phi,psi,doLabel)) spotSize = self.spotSizePulldown.getObject() nRes = 0.01*float(nDisallowed+nAllowed+nCore) if nRes: self.regionLabel.set(REGION_TEXT % (nCore/nRes,nAllowed/nRes,nDisallowed/nRes)) else: self.regionLabel.set(REGION_TEXT % (0.0, 0.0, 0.0)) self.plot.cirRadius = spotSize self.plot.updateObjects(phiPsiAccept, plotObjects, resLabels, colors)
def updateSpinSystems(self): textMatrix = [] objectList = [] if self.project: for spinSystem in self.nmrProject.resonanceGroups: if not spinSystem.resonances: continue if self.chain: if spinSystem.residue and (spinSystem.residue.chain is not self.chain): continue if spinSystem.chains and (self.chain not in spinSystem.chains): continue if hasattr(spinSystem, 'sstSelected'): includeText = spinSystem.sstSelected else: spinSystem.sstSelected = 'Yes' includeText = 'Yes' if not hasattr(spinSystem, 'sstTypes'): spinSystem.sstTypes = [] if not hasattr(spinSystem, 'ssScore'): spinSystem.ssScore = None if spinSystem.ssScore: scoreText = '%.2f' % spinSystem.ssScore else: scoreText = None typesText = ' '.join(spinSystem.sstTypes) residueText = '' if spinSystem.residue: resCode = getResidueCode(spinSystem.residue) residueText = '%d%s' % (spinSystem.residue.seqCode,resCode) elif spinSystem.residueProbs: resTexts = [] resSeqs = [] resCodes = set() for residueProb in spinSystem.residueProbs: if not residueProb.weight: continue residue = residueProb.possibility seq = residue.seqCode resCode = getResidueCode(residue) resText = '%d?%s' % (seq, resCode) resTexts.append(resText) resSeqs.append('%d?' % seq) resCodes.add(resCode) if len(resCodes) == 1: residueText = '/'.join(resSeqs) + resCodes.pop() else: residueText = '/'.join(resTexts) elif spinSystem.ccpCode: getResidueCode(spinSystem) shifts = [] if self.shiftList: for resonance in spinSystem.resonances: if resonance.isotopeCode in self.isotopes: shift = resonance.findFirstShift(parentList = self.shiftList) if shift: shifts.append('%.2f' % shift.value) shifts.sort() shiftsText = ' '.join(shifts) data = [] data.append(spinSystem.serial) data.append(residueText) data.append(includeText) data.append(scoreText) data.append(typesText) data.append(shiftsText) objectList.append(spinSystem) textMatrix.append(data) self.scrolledMatrix.update(textMatrix=textMatrix, objectList=objectList) self.updateButtons() self.waiting = False
def draw(self, *opt): if not self.shiftList: return nmrProject = self.shiftList.nmrProject shiftList = self.shiftList font = self.font bfont = self.boldFont symbolFont = self.symbolFont sFont = self.smallFont bbox = self.canvas.bbox doOthers = self.otherShiftsSelect.get() spc = 4 gap = 14 x = gap y = gap ct = self.canvas.create_text cl = self.canvas.create_line cc = self.canvas.coords self.canvas.delete('all') ssDict = {} formatDict = { 0.1: '%.1f', 0.01: '%.2f', 0.001: '%.3f', } protonFormat = formatDict[self.protonPrecisionSelect.getObject()] otherFormat = formatDict[self.otherPrecisionSelect.getObject()] uSpinSystems = [] chains = set() molSystems = set() for spinSystem in nmrProject.resonanceGroups: residue = spinSystem.residue if residue: ssDict[residue] = ssDict.get(residue, []) + [ spinSystem, ] else: uSpinSystems.append((spinSystem.serial, spinSystem)) uSpinSystems.sort() commonAtoms = self.optSelector.getSelected() N = len(commonAtoms) chain = self.chain if chain: spinSystems = [] for residue in chain.sortedResidues(): spinSystems0 = ssDict.get(residue, []) for spinSystem in spinSystems0: if spinSystem and spinSystem.resonances: spinSystems.append([residue, spinSystem]) else: spinSystems = uSpinSystems strings = [] doOneLetter = self.oneLetterSelect.get() if spinSystems: x = gap y += gap numItems = [] codeItems = [] commonItems = [] otherItems = [] numWidth = 0 codeWidth = 0 commonWidths = [0] * N commonCounts = [0] * N for residue, spinSystem in spinSystems: if type(residue) is type(1): seqNum = '{%d}' % residue if doOneLetter: ccpCode = '-' else: ccpCode = spinSystem.ccpCode or '' else: if doOneLetter: ccpCode = residue.chemCompVar.chemComp.code1Letter else: ccpCode = getResidueCode(residue) seqNum = str(residue.seqCode) subStrings = [] subStrings.append(seqNum) subStrings.append(ccpCode) item = ct(x, y, text=seqNum, font=font, anchor='se') box = bbox(item) iWidth = box[2] - box[0] numWidth = max(numWidth, iWidth) numItems.append(item) item = ct(x, y, text=ccpCode, font=font, anchor='sw') box = bbox(item) iWidth = box[2] - box[0] codeWidth = max(codeWidth, iWidth) codeItems.append(item) commonShifts, commonElements, otherShifts = self.getShiftData( spinSystem, shiftList, commonAtoms) items = [] for i in range(N): values = commonShifts[i] element = commonElements[i] if element == 'H': shiftFormat = protonFormat else: shiftFormat = otherFormat subItems = [] for value in values: text = shiftFormat % value if text: item = ct(x, y, text=text, font=font, anchor='se') box = bbox(item) iWidth = box[2] - box[0] commonWidths[i] = max(commonWidths[i], iWidth) commonCounts[i] += 1 subItems.append(item) subStrings.append( ','.join([shiftFormat % v for v in values]) or '-') items.append(subItems) commonItems.append(items) if doOthers: items0 = [] i = 0 I = len(otherShifts) for atomLabel, element, value in otherShifts: label = atomLabel if label[0] == '?': label = label[3:-1] if element == 'H': shiftFormat = protonFormat else: shiftFormat = otherFormat subStrings.append('%6s:%-4s' % (shiftFormat % value, label)) i += 1 atoms = atomLabel.split('|') items = [] j = 0 for atom in atoms: text = element if j > 0: text = '/' + text item = ct(x, y, text=text, font=font, anchor='sw') box = bbox(item) iWidth = box[2] - box[0] - 3 items.append((iWidth, item, 0)) p = len(element) if len(atom) > p: letter = atom[p] if letter not in ('0123456789'): item = ct(x, y, text=letter.lower(), font=symbolFont, anchor='sw') box = bbox(item) iWidth = box[2] - box[0] - 2 items.append((iWidth, item, -4)) p += 1 text = atom[p:] if text: item = ct(x, y, text=text, font=sFont, anchor='sw') box = bbox(item) iWidth = box[2] - box[0] - 2 items.append((iWidth, item, -4)) j += 1 text = ' ' + shiftFormat % value if i != I: text += ',' item = ct(x, y, text=text, font=font, anchor='sw') box = bbox(item) iWidth = box[2] - box[0] - 4 items.append((iWidth, item, 0)) items0.append(items) otherItems.append(items0) strings.append(subStrings) y0 = y x = x0 = gap + numWidth + codeWidth + spc + spc for i in range(N): if not commonCounts[i]: continue x += commonWidths[i] + spc + spc element = commonElements[i] iWidth = 0 text = commonAtoms[i][len(element):].lower() if text: item = ct(x, y, text=text, font=symbolFont, anchor='se') box = bbox(item) iWidth = box[2] - box[0] - 2 ct(x - iWidth, y, text=element, font=font, anchor='se') y += gap for i in range(len(numItems)): x = gap + numWidth + spc cc(numItems[i], x, y) x += spc cc(codeItems[i], x, y) x += codeWidth x1 = x + spc yM = y for j in range(N): if not commonCounts[j]: continue x += commonWidths[j] + spc + spc items = commonItems[i][j] yB = y - gap for item in items: yB += gap cc(item, x, yB) yM = max(yB, yM) x += gap if doOthers: x += spc x3 = x for items in otherItems[i]: if x > 550: x = x3 y += gap for iWidth, item, dy in items: cc(item, x, y + dy) x += iWidth y = max(y, yM) y += gap x = x0 for i in range(N): if not commonCounts[i]: continue x += commonWidths[i] + spc + spc cl(x + 8, y0, x + 8, y - gap, width=0.3, fill='#808080') cl(x1, y0, x1, y - gap, width=0.3, fill='#808080') cl(0, 0, 550, 0, width=0.3, fill='#FFFFFF') y += gap textWidths = {} for subStrings in strings: for i, text in enumerate(subStrings): if text and len(text) > textWidths.get(i, 0): textWidths[i] = len(text) else: textWidths[i] = 0 formats = {} for i in textWidths.keys(): formats[i] = ' %%%ds' % max(6, textWidths[i]) textOut = '!' textRow = ['', ''] textMatrix = [textRow] textOut += ' ' * (max(6, textWidths.get(0, 6)) + max(6, textWidths.get(1, 6)) + 1) i = 2 for atom in commonAtoms: if i in formats: textOut += formats[i] % atom textRow.append((formats[i] % atom).strip()) i += 1 textOut += '\n' for subStrings in strings: textRow = [] textMatrix.append(textRow) i = 0 for text in subStrings: textOut += formats[i] % text textRow.append((formats[i] % text).strip()) i += 1 textOut += '\n' self.textOut = textOut self.textMatrix = textMatrix
def getResidueCode(self, obj): """Analysis-specific version of getResidueCode - overrides generic version """ return getResidueCode(obj)