def doExport(self): if self.exportFileName: chain = self.chainDict[self.chainSelect.getSelected()] returnValue = self.autoAssignFormat.writeProject( self.exportFileName, chain=chain, setTag=self.dateTimeFlag) if not returnValue: showError( "No export file written", "There were problems while exporting the %s project file." % self.format) else: showInfo("File written", "File written successfully") cdtsTag = "%s-%s" % (self.chainSelect.getSelected(), self.dateTimeFlag) if not cdtsTag in self.chainDateTimeSelect.entries: if "<None>" in self.chainDateTimeSelect.entries: self.chainDateTimeSelect.entries.pop( self.chainDateTimeSelect.entries.index("<None>")) self.chainDateTimeSelect.replace( [cdtsTag] + self.chainDateTimeSelect.entries) self.chainDateTimeStampDict[cdtsTag] = chain else: showError( "No export file defined", "Please define a name for the %s project file to export to." % self.format)
def save(self): projName = self.proj_name_entry.get() directory = self.proj_dir_select.getDirectory() directory = joinPath(directory, projName) if self.isProjectDirectory(directory): if not showOkCancel('Overwrite directory', 'Overwrite existing project directory?', parent=self): return self.updateInfo() self.did_save = False changeDataLocations = self.dataCheckButton.isSelected() done = False try: done = Io.saveProject(self.project, newPath=directory, newProjectName=projName, createFallback=True, showYesNo=showYesNo, changeDataLocations=changeDataLocations, showWarning=showWarning) if done: showInfo('Project saved', 'Project saved successfully') self.did_save = True if self.callback: self.callback(self.project) elif self.modal: return # give another chance except Implementation.ApiError, e: showError('Save project', e.error_msg)
def timedCheckStatus(self): if not self.serverCredentials: return if self.serverDone: return status = iCingRobot.iCingStatus(self.serverCredentials, self.getServerUrl(self.iCingBaseUrl)) if not status: #something broke, already warned self.run.status = 'failed' return result = status.get(iCingRobot.RESPONSE_RESULT) if result == iCingRobot.RESPONSE_DONE: self.serverDone = True self.run.status = 'completed' msg = 'CING run is complete!' showInfo('Completion', msg, parent=self) return self.after(CHECK_INTERVAL, self.timedCheckStatus)
def purgeCingServer(self): if not self.project: return if not self.run: msg = 'No CING run setup' showWarning('Failure', msg, parent=self) return if not self.serverCredentials: msg = 'No current iCing server job' showWarning('Failure', msg, parent=self) return url = self.iCingBaseUrl results = iCingRobot.iCingPurge(self.serverCredentials, self.getServerUrl(url)) if results: showInfo('Info','iCing server results cleared') self.serverCredentials = None self.iCingBaseUrl = None self.serverDone = False deleteRunParameter(self.run, iCingRobot.FORM_USER_ID) deleteRunParameter(self.run, iCingRobot.FORM_ACCESS_KEY) deleteRunParameter(self.run, HTML_RESULTS_URL) else: showInfo('Info','Purge failed') self.update()
def apply(self): shiftListLabel = self.shiftListSelect.getSelected() shiftList = self.shiftListDict[shiftListLabel] try: chainLabel = self.chainListSelect.getSelected() chain = self.chainDict[chainLabel] except: showError( "No chains", "No chains were present or selected. Try running linkResonances first." ) return False fileName = self.fileButton.__getitem__('text') if fileName == self.defaultText: return False fileCreated = writeBmrbChemShiftDeposition(self.guiParent, chain, shiftList, fileName) if fileCreated: showInfo("Success", "Succesfully wrote chemical shift deposition file") else: showError("Not written", "Error writing file %s. File not written" % fileName) return False return True
def storeSecondaryStructure(self): if not self.chain: return getSpinSystem = self.nmrProject.findFirstResonanceGroup newSpinSystem = self.nmrProject.newResonanceGroup predDict = self.predictionDict.get(self.chain, {}) n = 0 for residue in predDict: (ssCode, isReliable, probabilityDict) = predDict[residue] if isReliable: spinSystem = getSpinSystem(residue=residue) if not spinSystem: spinSystem = newSpinSystem(residue=residue, ccpCode=residue.ccpCode) spinSystem.secStrucCode = ssCode n += 1 showInfo('Info', 'Stored secondary structure types for %d residues.' % n, parent=self)
def finaliseImport(self): if not self.depositionImportNums[6]: showWarning('Failure', 'Need connected molecule and shift information first') return if showYesNo( "Save project and continue annotation", "Are you sure you want to save this project and continue?", parent=self): if self.depositionImportNums[5] or showYesNo( "No coordinates", "No coordinates are available - are you sure you want to continue?", parent=self): showInfo("Project name", "Your project will be saved in the %s directory." % self.project.name, parent=self) self.project.saveModified() #userData = self.project.findFirstRepository(name='userData') #currentPath = userData.url.path #currentProjectName = self.project.name #projectDir = os.path.join(currentPath,currentProjectName) eci = EntryCompletionGui(self.basePopup.root) eci.initProject(self.project)
def storeSecondaryStructure(self): if not self.dangleChain: return getSpinSystem = self.nmrProject.findFirstResonanceGroup newSpinSystem = self.nmrProject.newResonanceGroup n = 0 for dangleResidue in self.dangleChain.dangleResidues: ssCode = dangleResidue.secStrucCode if not ssCode: continue residue = dangleResidue.residue if not residue: continue spinSystem = getSpinSystem(residue=residue) if not spinSystem: spinSystem = newSpinSystem(residue=residue, ccpCode=residue.ccpCode) spinSystem.secStrucCode = ssCode n += 1 showInfo('Info', 'Stored secondary structure types for %d residues.' % n, parent=self)
def printStructure(self): w = self.winfo_width() h = self.winfo_height() popup = PrintPopup(self, width=w, height=h, title='Print Structure', modal=True, project=self.project, getOption=self.getPrintOption, setOption=self.setPrintOption) outputHandler = popup.outputHandler popup.destroy() if (not outputHandler): return (x0, y0, x1, y1) = self.handler.getRegion() try: printHandler = PrintHandler.PrintHandler(outputHandler, xRegion=(x0, x1), yRegion=(y0, y1)) self.drawStructure(handler=printHandler) file_name = outputHandler.file_name printHandler.close( ) # clears file_name, hence first need to save, as above showInfo('Wrote file', 'Successfully wrote file "%s"' % file_name, parent=self) except IOError, e: showError('IO Error', str(e), parent=self)
def write_npc(self, pcsValues): fileName = os.path.abspath(self.expPCSEntry.get()) with open(fileName, 'w') as o: for key in sorted(pcsValues): seq, atom = key value = pcsValues[key] line = "{0:<4d}{1:<2}{2:15.8f} 0.0\n".format(seq, atom, value) o.write(line) o.close() showInfo("Wrote PCS", "Wrote experimental PCS to: {}".format(fileName))
def saveSchemes(self): schemes = [x for x in self.project.labelingSchemes if x.isModified] if schemes: for scheme in schemes: scheme.save() showInfo('Notice', 'Successfully saved %d schemes' % len(schemes)) self.updateSchemes() else: showWarning('Notice', 'No modified schemes to save')
def showMdProgress(self): n = 0 m = self.numClouds for i in range(m): pdbFileName = '%s%3.3d.pdb' % (self.filePrefix, i) if os.path.exists(pdbFileName): n += 1 p = n * 100 / float(m) text = 'Done %d of %d clouds (%1.2f)%%' % (n, m, p) showInfo('MD Progress', text)
def getSelected(): chemComp = frame.getSelectedChemComp() if (chemComp): if hasattr(chemComp,'chemComp'): ccType = 'chemCompVar' chemComp = chemComp.chemComp else: ccType = 'chemComp' showInfo('ChemComp', 'Selected %s = (%s, %s)' % (ccType,chemComp.molType, chemComp.ccpCode), parent=root) else: showInfo('ChemComp', 'No chemComp selected', parent=root)
def openLicense(self): licenseUrl = 'http://www.ccpn.ac.uk/license' try: import webbrowser except ImportError: showInfo('License Agreement', 'The CCPN License Agreement is available at %s' % licenseUrl, parent=self) return wb = webbrowser.get() wb.open(licenseUrl)
def apply(self): if self.frame.getSelectedChemComp(): return True else: showInfo( 'No selection', 'Please select a chemCompVar from the bottom half of the window, or press Cancel to quit.' ) return False
def apply(self): self.selectedFormats = self.formatListBox.getSelectedItems() fileName = self.fileButton.__getitem__('text') if fileName == self.defaultText: return False fileCreated = writeMappingFile(self.project,fileName,originalFormats = self.selectedFormats) if fileCreated: showInfo("Success","Succesfully wrote mapping file") else: showError("Not written","Error writing file %s. File not written" % fileName) return False return True
def apply(self): selectedPeakLists = self.peakListBox.getSelectedItems() for peakListLabel in selectedPeakLists: self.peakLists.append(self.peakListDict[peakListLabel]) chemShiftList = self.shiftListDict[self.shiftListSelect.getSelected()] if not chemShiftList: chemShiftListName = askString("Enter chemical shift list name", "New chemical shift list name", '', self) else: chemShiftListName = chemShiftList.name useAllContribs = self.useAllContribs.isSelected() defaultShiftError = {} for nucl in self.defaultShiftError.keys(): defaultShiftError[nucl] = returnFloat( self.defaultShiftError[nucl].get()) listCreated = createChemShifts(self.peakLists, guiParent=self.parent, multiDialog=self.parent.multiDialog, shiftList=chemShiftList, useAllContribs=useAllContribs, defaultShiftError=defaultShiftError, shiftListName=chemShiftListName) if listCreated: showInfo( "Success", "Succesfully created a chemical shift list from peaklist(s)") return True
def timedCheckStatus(self): if not self.serverCredentials: return if self.serverDone: return status = iCingRobot.iCingStatus(self.serverCredentials, self.getServerUrl(self.iCingBaseUrl)) if not status: #something broke, already warned return result = status.get(iCingRobot.RESPONSE_RESULT) if result == iCingRobot.RESPONSE_DONE: self.serverDone = True msg = 'CING run is complete!' showInfo('Completion', msg, parent=self) return self.after(CHECK_INTERVAL, self.timedCheckStatus)
def checkStatus(self): if not self.serverCredentials: return status = iCingRobot.iCingStatus(self.serverCredentials, self.getServerUrl(self.iCingBaseUrl)) if not status: #something broke, already warned return result = status.get(iCingRobot.RESPONSE_RESULT) if result == iCingRobot.RESPONSE_DONE: msg = 'CING run is complete!' showInfo('Completion', msg, parent=self) self.serverDone = True return else: msg = 'CING job is not done.' showInfo('Processing', msg, parent=self) self.serverDone = False return
def importSequenceOrCoords(self): dataTypes = ['sequence', 'coordinates'] fileTypes = self.createFileTypes(dataTypes) if self.getFileName('Import sequence or coordinate file', fileTypes): formatNameSuggestions = {} for dataType in dataTypes: tmpList = self.fcWrapper.determineFormatNamesForFile( dataType, self.fileName) if tmpList: formatNameSuggestions[dataType] = tmpList if not formatNameSuggestions: showWarning( 'Failure', 'This file cannot be read by this software.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False # # Let user select if multiple options, otherwise take default # if len(formatNameSuggestions) == 1 and len(formatNameSuggestions[ formatNameSuggestions.keys()[0]]) == 1: dataType = formatNameSuggestions.keys()[0] formatName = formatNameSuggestions[dataType][0] if not showYesNo( 'File type detected', 'Reading as %s file in %s format. Is this correct?' % (dataType, formatName), parent=self): showWarning( 'Failure', 'This file cannot be read by this software.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False else: # # Create a selection (hopefully user-understandable) # selectionList = [] selectionDict = {} for dataType in dataTypes: dataTypeString = dataType if formatNameSuggestions.has_key(dataType): formatNames = formatNameSuggestions[dataType] formatNames.sort() for formatName in formatNames: selectionString = "%s file in %s format." % ( dataTypeString, formatName) selectionList.append(selectionString) selectionDict[selectionString] = (dataType, formatName) interaction = SelectionListPopup(self, selectionList, title='File format selection', text='This is a:', selectionDict=selectionDict, dismissButton=True, modal=True) # # Check if anything was selected... # dataType = formatName = None if interaction.isSelected: (dataType, formatName) = interaction.selection else: showWarning( 'Failure', 'This file cannot by read without a format selection.\nIf the correct format is not available, please send the file with an explanation to %s' % self.email, parent=self) return False # # Now read the file, need to do some field updates! # (fileRead, fileInformation) = self.fcWrapper.readFile( dataType, formatName, self.fileName) if not fileRead: showWarning( 'Failure', 'This file cannot be read by this software:%s\nPlease send the file with an explanation to %s.' % (fileInformation, self.email), parent=self) return False (conversionInfo, conversionSuccess) = ( self.fcWrapper.formatConversion.conversionInfo, self.fcWrapper.formatConversion.conversionSuccess) if not conversionSuccess: showWarning( 'Failure', 'This file was read by the software but contains invalid information.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False # # Set info if import worked OK # conversionLines = conversionInfo.split(": ") showInfo("Import coordinate and/or sequence information", ":\n".join(conversionLines), parent=self) if dataType == 'sequence': chains = self.fcWrapper.importReturns[dataType] models = [] elif dataType == 'coordinates': models = self.fcWrapper.importReturns[dataType] chains = [ cChain.chain for cChain in models[0].structureEnsemble.coordChains ] self.sequenceCoordinatesImport.setText( self.fileName) # TODO change color or something? self.sequenceCoordinatesImport.configure( foreground=self.fontOkColor) self.sequenceCoordinatesLoaded = True # # Reset to list selector for further use # moleculeName = None for chain in chains: if chain in self.moleculeDict.values(): continue numResidues = len(chain.residues) if numResidues == 1: residueText = "%s residue" % chain.findFirstResidue( ).ccpCode else: residueText = "%d residues" % numResidues moleculeName = "%s (chain '%s', %s)" % ( chain.molecule.name, chain.code, residueText) self.moleculeList.append(moleculeName) self.moleculeDict[moleculeName] = chain self.moleculeList.sort() self.moleculeSelect.destroy() if len(chains) == 1 and moleculeName: selectedIndex = self.moleculeList.index(moleculeName) else: selectedIndex = 0 self.moleculeSelect = PulldownList(self.frameA, texts=self.moleculeList, index=selectedIndex, sticky='ew') self.moleculeSelect.grid(row=self.moleculeSelectRow, column=0) # # Now update Deposition tab # molecules = [] for chain in chains: if not chain.molecule in molecules: molecules.append(chain.molecule) numCoords = 0 for model in models: numCoords += len(model.coords) self.updateDepositionImportLabel(molecules=len(molecules), chains=len(chains), models=len(models), coordinates=numCoords) # Add the molSystem to the entry! if chains and not chains[0].molSystem == self.entry.molSystem: self.entry.molSystem = chains[0].molSystem self.updateAll()
def notYetImplemented(text=''): if (text): text = '"' + text + '" ' showInfo('Not Yet Implemented', text + 'not yet implemented')
class RegisterPopup(BasePopup): """ **Register User with CCPN** The purpose of this dialog is to allow the user to register with CCPN. This is mainly to allow CCPN to keep track of the number of users, which is important for grant applications. This information is saved both in a file on your computer but also in a private CCPN server database if your computer is connected to the internet. (So unfortunately you will need to register once for each computer you use.) The required information: the user name, organisation and email address. The other information stored on the CCPN server: the version number, the first time and most recent time the server has been notifed. If you are registered, then the server is notified every time a project is opened or saved (if connected to the internet). Click "Register Now" to register, or "Register Later" not to register. """ def __init__(self, parent, isModal=False, *args, **kw): title = 'Project : Register with CCPN' BasePopup.__init__(self, parent=parent, title=title, modal=isModal, **kw) def body(self, guiFrame): self.geometry('600x250+600+250') analysisProfile = self.analysisProfile userName = analysisProfile.userName userOrganisation = analysisProfile.userOrganisation userEmail = analysisProfile.userEmail guiFrame.grid_rowconfigure(0, weight=1) guiFrame.grid_columnconfigure(1, weight=1) explainText = 'To keep track of our users and which versions are being used\n' \ 'we would like you to register your details with us.\n' \ 'Collating the number of users is important for grant applications.\n' \ 'Please do not use accents in any of the information\n' \ 'because Python does not handle it gracefully.' row = 0 label = Label(guiFrame, text=explainText, grid=(row, 0), gridSpan=(1, 2), sticky='ew') row += 1 licenseAgreeText = 'I agree to abide by the rules of the CCPN licensing agreement.' self.agreeButton = CheckButton(guiFrame, licenseAgreeText, tipText=licenseAgreeText) self.agreeButton.grid(row=row, column=1, columnspan=1, sticky='nsew') row += 1 self.entryWidgets = [] for (text, value) in (('Name', userName), ('Organisation', userOrganisation), ('Email', userEmail)): label = Label(guiFrame, text=text + ':', grid=(row, 0)) entry = Entry(guiFrame, text=value or '', grid=(row, 1), sticky='ew', tipText='Your ' + text) self.entryWidgets.append(entry) row += 1 texts = ['Register Now', 'Read License', 'Register Later'] tipTexts = ['Register now', 'Read License', 'Register later'] commands = [self.register, self.openLicense, self.close] buttons = UtilityButtonList(guiFrame, helpUrl=self.help_url, grid=(row, 0), gridSpan=(1, 2), commands=commands, texts=texts, tipTexts=tipTexts) self.buttons = buttons def openLicense(self): licenseUrl = 'http://www.ccpn.ac.uk/license' try: import webbrowser except ImportError: showInfo('License Agreement', 'The CCPN License Agreement is available at %s' % licenseUrl, parent=self) return wb = webbrowser.get() wb.open(licenseUrl) def register(self): if not self.agreeButton.get(): showError( 'License Agreement', 'Please tick the box indicating that you agree to the CCPN licensing terms and conditions.', parent=self) return analysisProfile = self.analysisProfile attrs = ('userName', 'userOrganisation', 'userEmail') for n, entry in enumerate(self.entryWidgets): attr = attrs[n] value = entry.get().strip() if not value: showError('Blank value', '%s is blank, value required' % attr[4:], parent=self) return if attr == 'userEmail' and '@' not in value: showError('Illegal email', 'Email must have "@" in it', parent=self) return try: setattr(analysisProfile, attr, value) except Exception, e: showError('Attribute setting', 'Error setting %s: %s' % (attr[4:], e), parent=self) return analysisProfile.save() try: result = updateRegister(analysisProfile) showInfo('Registering', result, parent=self) self.close() except Exception, e: showError('Registering', str(e), parent=self)
def importShifts(self): currentChain = self.getCurrentChain() if not currentChain: showWarning( 'Failure', 'Please first read in a sequence or coordinate file and select the molecule relevant for this shift list.', parent=self) return elif self.currentShiftList: shiftListChainPair = (self.currentShiftList, currentChain) if shiftListChainPair in self.shiftListChainPairs: showWarning( 'Failure', "You already read in chemical shifts for this chain.\nPlease read in related shifts for the other chain(s), if present, or press the 'Import new set of shifts' button to read in a new set of shifts.", parent=self) return dataType = 'shifts' fileTypes = self.createFileTypes([dataType]) if self.getFileName('Import chemical shift file', fileTypes): formatNameSuggestions = self.fcWrapper.determineFormatNamesForFile( dataType, self.fileName) if not formatNameSuggestions: showWarning( 'Failure', 'This file cannot be read by this software.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False # # Let user select if multiple options, otherwise take default # if len(formatNameSuggestions) == 1: formatName = formatNameSuggestions[0] if not showYesNo( 'File type detected', 'Reading as a chemical shift file in %s format. Is this correct?' % formatName, parent=self): showWarning( 'Failure', 'This file cannot be read by this software.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False else: # # Create a selection (hopefully user-understandable) # selectionList = [] selectionDict = {} formatNameSuggestions.sort() for formatName in formatNameSuggestions: selectionString = "chemical shift file in %s format." % ( formatName) selectionList.append(selectionString) selectionDict[selectionString] = formatName interaction = SelectionListPopup(self, selectionList, title='File format selection', text='This is a:', selectionDict=selectionDict, dismissButton=True, modal=True) # # Check if anything was selected... # formatName = None if interaction.isSelected: formatName = interaction.selection else: showWarning( 'Failure', 'This file cannot by read without a format selection.\nIf the correct format is not available, please send the file with an explanation to %s' % self.email, parent=self) return False # # Now read the file, need to do some field updates! Also make sure to re-use shift list for other molecules... # (fileRead, fileInformation) = self.fcWrapper.readFile( dataType, formatName, self.fileName, addKeywords={'measurementList': self.currentShiftList}) if not fileRead: showWarning( 'Failure', 'This file cannot be read by this software:%s\nPlease send the file with an explanation to %s.' % (fileInformation, self.email), parent=self) return False (conversionInfo, conversionSuccess) = ( self.fcWrapper.formatConversion.conversionInfo, self.fcWrapper.formatConversion.conversionSuccess) if not conversionSuccess: showWarning( 'Failure', 'This file was read by the software but contains invalid information.\nPlease send the file with an explanation to %s.' % self.email, parent=self) return False # # Set info if import worked OK # conversionLines = conversionInfo.split(": ") showInfo("Import chemical shift information", ":\n".join(conversionLines), parent=self) self.shiftImport.setText( self.fileName) # TODO change color or something? self.shiftImport.configure(foreground=self.fontOkColor) self.shiftsLoaded = True self.shiftsFormatName = formatName shiftList = self.fcWrapper.importReturns[dataType] if not self.currentShiftList: self.currentShiftList = shiftList self.shiftListChainPairs.append( (self.currentShiftList, currentChain)) self.updateDepositionImportLabel(shiftList=shiftList) if not shiftList in self.entry.measurementLists: print shiftList self.entry.addMeasurementList(shiftList) print self.entry.measurementLists self.updateAll()
def showVersion(self): showInfo('Version', 'Version ' + self.versionInfo, parent=self)
def writeFile(self,format,tasks): self.updateAcqProcParsWidget() self.updateAcqProcPars() # # Get or set up format classes # if self.formatObjectDict[self.format]: formatObject = self.formatObjectDict[self.format] else: formatLabel = allFormatsDict[self.format] formatModule = __import__('ccpnmr.format.converters.%sFormat' % formatLabel,{},{},['%sFormat' % formatLabel]) formatClass = getattr(formatModule,'%sFormat' % formatLabel) formatObject = formatClass(self.project,self.guiParent,verbose = 1) self.formatObjectDict[self.format] = formatObject # Bit cumbersome... is there a better way to define writeFile, ... ? dataDimRefs = self.getDataDimRefs(format) for task in tasks: parFile = None addKeywds = {'dataDimRefs': dataDimRefs} if format == self.nmrPipe: if task == 'conversion': function = 'writeProcPars' self.fileName = self.buttons[0].__getitem__('text') outputFile = self.buttons[1].__getitem__('text') addKeywds['outputFile'] = outputFile elif task == 'processing': function = 'writeProcScript' self.fileName = self.buttons[2].__getitem__('text') inputFile = self.buttons[1].__getitem__('text') outputFile = self.buttons[3].__getitem__('text') addKeywds['outputFile'] = outputFile addKeywds['inputFile'] = inputFile if format == self.azara: if task == 'processingPars': function = 'writeProcPars' self.fileName = self.buttons[0].__getitem__('text') elif task == 'processingScript': function = 'writeProcScript' self.fileName = self.buttons[1].__getitem__('text') inputFile = self.buttons[0].__getitem__('text') outputFile = self.buttons[2].__getitem__('text') parFile = self.buttons[3].__getitem__('text') addKeywds['outputFile'] = outputFile addKeywds['inputFile'] = inputFile addKeywds['parFile'] = parFile # Write for each task in list exportFunc = getattr(formatObject,function) if exportFunc(self.fileName, **addKeywds): showInfo("Success","Successfully exported file:\n%s." % self.fileName,self) else: showError("Error","Error while exporting file:\n%s." % self.fileName,self)
def importExportFile(self,checkComponent): returnFlag = True importFuncs = [] for component in self.components: # # Pass if no info... # if not self.IOkeywords[component]: continue # # If component passed in, only do that one # if checkComponent and checkComponent != component: continue else: # # Otherwise, if import, then only do so if checkButton is pressed # if self.importExportFlag == 'import' and not self.component: if not self.checkButton.has_key(component): continue elif not self.checkButton[component].isSelected(): continue # # Get or set up format classes # if self.formatObjectDict[self.format]: formatObject = self.formatObjectDict[self.format] else: formatClass = getattr(self.formatModule,'%sFormat' % self.formatLabel) # # ...and create the format class instance # formatObject = formatClass(self.project,self.guiParent,verbose = 0) self.formatObjectDict[self.format] = formatObject # # Add input keyword information... # addArgs = [] addKeywds = {} inputValid = True if self.widgets[component]: for inputKeyWord in self.widgets[component].keys(): (widgetInfo,selectionDict) = self.widgetInfo[component][inputKeyWord] value = getIoInfo(self.widgets[component][inputKeyWord],widgetInfo,self.project,selectionDict) # # File name is a special case... # if inputKeyWord in ('fileName','fileNames'): self.fileName = self.fileNames = False if value == widgetInfo[3]: setattr(self,inputKeyWord,None) else: if inputKeyWord == 'fileName': self.fileName = value else: self.fileNames = self.decomposeMultipleFileText(value) addArgs.append(getattr(self,inputKeyWord)) elif value != None: # Do not set as keyword for FileButtons that haven't been set! if widgetInfo[0] not in ('FileButton','FileMultiButton','DirButton') or widgetInfo[3] != value: if widgetInfo[0] == 'FileMultiButton': addKeywds[inputKeyWord] = self.decomposeMultipleFileText(value) else: addKeywds[inputKeyWord] = value else: if self.IOkeywords[component][inputKeyWord][1]: showWarning("Error","Nothing selected for %s writing, mandatory input %s!" % (component,inputKeyWord),self) inputValid = False break if not inputValid: break # # exportFunctions # if self.importExportFlag == 'export' and self.exportFunc[component]: for exportFuncLine in self.exportFunc[component]: if exportFuncLine == 'return': return if type(exportFuncLine) == type(''): eval(exportFuncLine) else: exportFuncLine() # # First check if a file name was selected? # Here add other checks for mandatory input to function? # if hasattr(self,'fileNames') and self.fileNames == False and not self.fileName: showWarning("Error","Please select a valid file name.",self) elif hasattr(self,'fileName') and self.fileName == False and not self.fileNames: showWarning("Error","Please select valid file names.",self) else: # # Do the read/write # rwFunc = getattr(formatObject,self.function[component]) returnValue = None if self.threading: curThread = Thread(target = rwFunc,args = addArgs,kwargs = addKeywds) curThread.start() curThread.join() if curThread and curThread.returnValue: returnValue = curThread.returnValue else: returnValue = rwFunc(*addArgs,**addKeywds) # # Do some prep here... # fileNameText = "" if hasattr(self,'fileNames'): if self.fileNames == False: (tPathName,tFileName) = os.path.split(self.fileName) fileNameText = " file with name: %s." % tFileName else: fileNameText = " multiple files." # # Now show popup and set info depending on return value # if returnValue: conversionSuccess = True if formatObject.convertCount.keys(): conversionSuccess = False for convertMainObj in formatObject.convertCount.keys(): conversionInfo = formatObject.convertCount[convertMainObj] if conversionInfo[1].keys(): for convertSubObj in conversionInfo[1].keys(): if conversionInfo[1][convertSubObj]: conversionSuccess = True break elif conversionInfo[0]: conversionSuccess = True if conversionSuccess: break convertInfoString = formatObject.getConvertCountString(startIndent = "") if conversionSuccess: if fileNameText: showInfo("Success","Successfully %sed %s\n\n%s" % (self.importExportFlag,fileNameText,convertInfoString),self) returnFlag = True if self.importExportFlag == 'import': # TODO: this is a hack... needs to be more sophisticated than this (format selection, # even format dependent on particular resonance (!?!?!) if component != 'sequence': self.guiParent.resonanceFormat = self.format if self.importFunc[component]: for importFunc in self.importFunc[component]: if importFunc not in importFuncs: importFuncs.append(importFunc) else: if fileNameText: showInfo("Not finished","The %s did not finish correctly for %s\n\n%s" % (self.importExportFlag,fileNameText,convertInfoString),self) elif self.winfo_exists(): if fileNameText: showError("Error","Error while %sing %s" % (self.importExportFlag,fileNameText),self) # # TODO: this might not be the best way to handle this!! # if returnFlag: if self.importExportFlag == 'import': if importFuncs: for importFuncLine in importFuncs: if type(importFuncLine) == type(''): eval(importFuncLine) else: importFuncLine() if hasattr(self.guiParent,'setMenuState'): self.guiParent.setMenuState() return returnFlag
def saveFile(self): windowPane = self.windowPulldown.getObject() if not windowPane: return axisPanels = windowPane.sortedAxisPanels() aspectRatio = self.getPrintAspectRatio() pixelWidth = self.totalSize(axisPanels[0]) pixelHeight = aspectRatio*self.totalSize(axisPanels[1]) unitWidth = self.totalOverrideRegion(axisPanels[0]) unitHeight = self.totalOverrideRegion(axisPanels[1]) printFrame = self.printFrame isOverrideSpectrumSelected = self.overrideSpectrum.isSelected() if isOverrideSpectrumSelected: spectrumWindowViews = self.spectrumTable.objectList # alternatively, spectrumWindowViews = windowPane.spectrumWindowViews analysisSpectra = set() for spectrumWindowView in spectrumWindowViews: spectrumWindowView.printPositive = PrintBasic.getPrintOption(spectrumWindowView, 'PositiveOn', spectrumWindowView.isPosVisible) spectrumWindowView.printNegative = PrintBasic.getPrintOption(spectrumWindowView, 'NegativeOn', spectrumWindowView.isNegVisible) analysisSpectra.add(spectrumWindowView.analysisSpectrum) for analysisSpectrum in analysisSpectra: analysisSpectrum.printPositiveColors = PrintBasic.getPrintOption(analysisSpectrum, 'PositiveColors', analysisSpectrum.posColors) analysisSpectrum.printNegativeColors = PrintBasic.getPrintOption(analysisSpectrum, 'NegativeColors', analysisSpectrum.negColors) isOverridePeakListSelected = self.overridePeakList.isSelected() if isOverridePeakListSelected: windowPeakLists = self.peakListTable.objectList analysisPeakLists = set() for windowPeakList in windowPeakLists: windowPeakList.printPeaks = PrintBasic.getPrintOption(windowPeakList, 'PeaksOn', windowPeakList.isSymbolDrawn) if windowPeakList.isAnnotationDrawn: default = windowPeakList.analysisPeakList.analysisSpectrum.font else: default = no_peak_text windowPeakList.printFont = PrintBasic.getPrintOption(windowPeakList, 'PeakFont', default) analysisPeakLists.add(windowPeakList.analysisPeakList) for analysisPeakList in analysisPeakLists: analysisPeakList.printColor = PrintBasic.getPrintOption(analysisPeakList, 'PeakColor', analysisPeakList.symbolColor) xrr = axisPanels[0].findFirstAxisRegion().region dxx = abs(xrr[0]-xrr[1]) yrr = axisPanels[1].findFirstAxisRegion().region dyy = abs(yrr[0]-yrr[1]) try: outputHandler = printFrame.getOutputHandler(pixelWidth, pixelHeight, unitWidth, unitHeight, fonts=printNames) if not outputHandler: return analysisProject = self.analysisProject major_minor_dict = {} spacing_choice = PrintBasic.getPrintOption(analysisProject, 'SpacingChoice', spacing_choices[0]) if spacing_choice != spacing_choices[0]: for attr in ('XMajor', 'XMinor', 'XDecimal', 'YMajor', 'YMinor', 'YDecimal',): val = PrintBasic.getPrintOption(analysisProject, attr, None) if val is not None: major_minor_dict[attr] = val tick_length_choice = PrintBasic.getPrintOption(analysisProject, 'TickLengthChoice', tick_length_choices[0]) if tick_length_choice != tick_length_choices[0]: for attr in ('TickMajor', 'TickMinor'): val = PrintBasic.getPrintOption(analysisProject, attr, None) if val is not None: major_minor_dict[attr] = val windowDraw = WindowDraw(self.parent, windowPane) PrintBasic.printWindow(windowDraw, outputHandler, printFrame.tick_location, printFrame.tick_placement, aspectRatio, printFrame.tick_font, major_minor_dict) msg = 'Saved to file "%s"' % printFrame.file_name showInfo('Success', msg, parent=self) except IOError, e: showError('IO Error', str(e), parent=self)
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)
class AddContourFilePopup(BasePopup): """ **Add Existing Contour Files to Project** The purpose of this dialog is to allow the user to add pre-existing contour files to the project. Contour files only depend on the spectrum data so the same contour files can be used across multiple projects, and that is the reason this dialog might be used. See also: `Spectrum Contour Files`_, `Creating Contour Files`_. .. _`Spectrum Contour Files`: EditContourFilesPopup.html .. _`Creating Contour Files`: CreateContourFilePopup.html """ def __init__(self, parent, *args, **kw): self.spectrum = None BasePopup.__init__(self, parent=parent, title='Add existing contour file', **kw) def body(self, master): self.geometry('600x130') master.grid_columnconfigure(1, weight=1) for n in range(5): master.grid_rowconfigure(n, weight=1) row = 0 label = Label(master, text='Spectrum: ') label.grid(row=row, column=0, sticky='e') tipText = 'The spectrum for which the contour file is being added' self.expt_spectrum = PulldownList(master, callback=self.updateContourDir, tipText=tipText) self.expt_spectrum.grid(row=row, column=1, sticky='w') row = row + 1 tipText = 'The location of the directory where contour files are stored on disk' label = Label(master, text='Contour dir: ') label.grid(row=row, column=0, sticky='e') self.dir_label = Label(master, text='', tipText=tipText) self.dir_label.grid(row=row, column=1, sticky='w') row = row + 1 label = Label( master, text= '(file will be copied into Contour dir if it is not already in there)' ) label.grid(row=row, column=1, sticky='w') row = row + 1 tipText = 'Browse for a file store contour data' button = Button(master, text='File name: ', command=self.selectFile, tipText=tipText) button.grid(row=row, column=0, sticky='e') tipText = 'Enter the name of the file to store contour data' self.file_entry = Entry(master, tipText=tipText) self.file_entry.grid(row=row, column=1, sticky='ew') row = row + 1 texts = ['Add File'] commands = [self.addFile] tipTexts = [ 'Use the selected contour file in the current project, copying it to the contour directory if required', ] self.buttons = UtilityButtonList(master, texts=texts, doClone=False, tipTexts=tipTexts, commands=commands, helpUrl=self.help_url) self.buttons.grid(row=row, column=0, columnspan=2, sticky='ew') self.curateNotifiers(self.registerNotify) self.updateSpectrum() def destroy(self): self.curateNotifiers(self.unregisterNotify) BasePopup.destroy(self) def curateNotifiers(self, notifyFunc): for clazz in ('Experiment', 'DataSource'): for func in ('__init__', 'delete', 'setName'): notifyFunc(self.updateNotifier, 'ccp.nmr.Nmr.%s' % clazz, func) def updateSpectrum(self, spectrum=None): if not spectrum: spectrum = self.spectrum spectra = self.parent.getSpectra() if spectra: if spectrum not in spectra: spectrum = spectra[0] index = spectra.index(spectrum) names = ['%s:%s' % (x.experiment.name, x.name) for x in spectra] else: index = 0 names = [] self.expt_spectrum.setup(names, spectra, index) self.updateContourDir(spectrum) def updateNotifier(self, *extra): self.updateSpectrum() def updateContourDir(self, spectrum): if spectrum is self.spectrum: return self.spectrum = spectrum if spectrum: path = spectrum.analysisSpectrum.contourDir.dataLocation else: path = '' self.dir_label.set(path) def selectFile(self): spectrum = self.spectrum if spectrum: directory = spectrum.analysisSpectrum.contourDir.dataLocation else: directory = os.getcwd() popup = FileSelectPopup(self, directory=directory) fileName = popup.getFile() popup.destroy() if fileName: self.file_entry.set(fileName) def addFile(self): spectrum = self.spectrum if not spectrum: return dataStore = spectrum.dataStore if not dataStore: showError('No dataStore', 'Spectrum does not have associated dataStore', parent=self) return if not isinstance(dataStore, BlockedBinaryMatrix): showError('No blockedBinaryMatrix', 'Spectrum dataStore is not a blockedBinaryMatrix', parent=self) return if not dataStore.blockSizes: showError('No blockSize', 'Spectrum dataStore does not have blockSize set', parent=self) return blockSize = list(dataStore.blockSizes) fileName = self.file_entry.get() if not fileName: showError('No filename', 'No filename given', parent=self) return fileName = normalisePath(fileName, makeAbsolute=True) contourDir = spectrum.analysisSpectrum.contourDir.dataLocation if fileName.startswith(contourDir): path = fileName[len(contourDir) + 1:] else: path = os.path.basename(fileName) if not os.path.exists(contourDir): os.makedirs(contourDir) print 'Copying %s to %s' % (fileName, contourDir) shutil.copy(fileName, contourDir) try: header = getStoredContourHeader(fileName) except Exception, e: showError('File error', str(e), parent=self) return if header['ndim'] != spectrum.numDim: showError( 'Number of dimensions', 'Number of dimensions in file (%d) does not match spectrum (%d)' % (header['ndim'], spectrum.numDim), parent=self) return dataDims = spectrum.sortedDataDims() npoints = [x.numPoints for x in dataDims] if header['npoints'] != npoints: showError( 'Number of points', 'Number of points in file (%s) does not match spectrum (%s)' % (header['npoints'], npoints), parent=self) return if header['blockSize'] != blockSize: showError('Block size', 'Block size in file (%s) does not match spectrum (%s)' % (header['blockSize'], blockSize), parent=self) return createStoredContour(spectrum, path, header['xdim'], header['ydim']) showInfo('Added file', 'Successfully added stored contour file', parent=self)
try: (firstInt[i], lastInt[i]) = self.convertToPoints(spectrum, i, region[i]) except Exception, e: showError('Invalid region', str(e), parent=self) try: #print 'about to saveSpectrumContours', fullPath, xdim, ydim, levels, firstInt, lastInt saveSpectrumContours(spectrum, fullPath, xdim, ydim, levels, firstInt, lastInt, mem_cache=self.parent.mem_cache) except Exception, e: showError('Save error', str(e), parent=self) return createStoredContour(spectrum, fileName, xdim, ydim) showInfo('Created file', 'Successfully created stored contour file', parent=self) def convertToPoints(self, spectrum, n, region): (rMin, rMax) = region dim = n + 1 dataDim = spectrum.findFirstDataDim(dim=dim) if dataDim.className != 'SampledDataDim': converter = UnitConverter.ppm2pnt dataDimRef = ExperimentBasic.getPrimaryDataDimRef(dataDim) (rMin, rMax) = (converter(rMax, dataDimRef), converter(rMin, dataDimRef)) rMin = max(1, rMin) rMax = min(dataDim.numPoints, rMax) rMin = rMin - 1 rMin = int(rMin+0.5)