Beispiel #1
0
    def body(self, master):

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self.table = ObjectTable(master, self.metaclass)
        self.table.grid(row=0, column=0, sticky=Tkinter.NSEW)

        if (self.onlyShow):
            texts = ['Close']
            commands = [self.close]
        else:
            texts = ['Ok', 'Cancel']
            commands = [self.ok, self.close]

        self.buttons = ButtonList(master,
                                  texts=texts,
                                  commands=commands,
                                  direction=Tkinter.HORIZONTAL,
                                  expands=True)
        self.buttons.grid(row=1, column=0, sticky=Tkinter.EW)

        self.selected = None

        self.setObjects()

        self.doRegisters()
Beispiel #2
0
    def body(self, guiParent):

        self.geometry('600x300')

        guiParent.grid_columnconfigure(1, weight=1)

        url = ''
        if self.server:
            url = self.server.url
        label = Label(guiParent, text='Server location: %s' % url)
        label.grid(row=0, column=0, sticky='w', columnspan=2)

        label = Label(guiParent,
                      text='Installation root: %s%s' %
                      (self.installRoot, os.sep))
        label.grid(row=1, column=0, sticky='w', columnspan=2)

        editWidgets = [None] * 5
        editGetCallbacks = [None, self.toggleSelected, None, None, None]
        editSetCallbacks = [None] * 5

        guiParent.grid_rowconfigure(2, weight=1)
        headingList = [
            'File', 'Install?', 'Date', 'Relative Path', 'Priority', 'Comments'
        ]
        self.scrolledMatrix = ScrolledMatrix(guiParent,
                                             headingList=headingList,
                                             highlightType=0,
                                             editWidgets=editWidgets,
                                             callback=self.selectCell,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)

        self.scrolledMatrix.grid(row=2, column=0, columnspan=2, sticky='nsew')

        if self.exitOnClose:
            txt = 'Quit'
            cmd = sys.exit
        else:
            txt = 'Close'
            cmd = self.close

        texts = ['Refresh List', 'Select All', 'Install Selected', txt]
        commands = [self.updateFiles, self.selectAll, self.install, cmd]
        self.buttonList = ButtonList(guiParent,
                                     texts=texts,
                                     commands=commands,
                                     expands=True)
        self.buttonList.grid(row=3, column=0, columnspan=2, sticky='ew')

        if self.server:
            for fileUpdate in self.server.fileUpdates:
                fileUpdate.isSelected = False

        #self.update()
        # need self.updateFiles, not just self.update
        # because otherwise the 2.0.5 to 2.0.6 upgrades do not work
        # (self.server not set on first pass so need call to updateFiles here)
        self.updateFiles()
Beispiel #3
0
 def drawButtons(self, okText='OK', cancelText='Cancel'):
     
   texts    = [okText, cancelText]
   commands = [self.ok, self.cancel]
   
   buttonList = ButtonList(self, texts=texts, commands=commands)
   buttonList.buttons[0].config(default=Tkinter.ACTIVE)
   buttonList.pack()
Beispiel #4
0
class SaveLoadTab(object):
    """The tab that lets the user FileSelect
       a file to open or to save.
    """

    def __init__(self, parent, frame):
        """Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        """

        self.guiParent = parent
        self.frame = frame
        self.project = parent.project
        self.nmrProject = parent.nmrProject
        self.loadAndSaveButtons = None
        self.fileselectionBox = None
        self.body()

    def body(self):
        """Setting up the body of this view."""

        frame = self.frame

        file_types = [FileType("pyc", ["*.pyc"])]
        self.fileselectionBox = FileSelect(frame, multiSelect=False, file_types=file_types)
        self.fileselectionBox.grid(row=0, column=0, columnspan=6, sticky="nsew")

        texts = ["Load", "Save"]
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame, commands=commands, texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky="nsew")

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

    def saveDataToPyc(self):
        """Save the data to the selected file."""

        if self.guiParent.connector.results:

            fileName = self.fileselectionBox.getFile()
            self.guiParent.connector.saveDataToPyc(fileName)
            self.fileselectionBox.updateFileList()

        else:

            string = """There are no results to save, """ """the algorithm has not run yet."""

            showWarning("No Results to Save", string, parent=self.guiParent)

    def loadDataFromPyc(self):
        """Load the data from the selected file."""

        fileName = self.fileselectionBox.getFile()
        self.guiParent.connector.loadDataFromPyc(fileName)
        self.guiParent.resultsTab.update()
Beispiel #5
0
    def body(self, guiParent):

        row = 0
        self.graph = ScrolledGraph(guiParent)
        self.graph.grid(row=row, column=0, sticky='NSEW')

        row += 1
        texts = ['Draw graph', 'Goodbye']
        commands = [self.draw, self.destroy]
        buttons = ButtonList(guiParent, texts=texts, commands=commands)
        buttons.grid(row=row, column=0, sticky='NSEW')
Beispiel #6
0
    def __init__(self,
                 parent,
                 width=70,
                 height=20,
                 xscroll=False,
                 yscroll=True,
                 *args,
                 **kw):

        apply(Frame.__init__, (self, parent) + args, kw)

        self.grid_columnconfigure(1, weight=1)

        row = 0
        texts = ('back', 'forward', 'load')
        commands = (self.prevUrl, self.nextUrl, self.loadUrl)
        self.buttons = ButtonList(self, texts=texts, commands=commands)
        self.buttons.grid(row=row, column=0)
        self.url_entry = Entry(self, returnCallback=self.loadUrl)
        self.url_entry.grid(row=row, column=1, columnspan=2, sticky=Tkinter.EW)
        row = row + 1

        frame = Frame(self)
        frame.grid(row=row, column=0, columnspan=3, sticky=Tkinter.W)
        self.createFindFrame(frame)
        row = row + 1

        self.grid_rowconfigure(row, weight=1)
        self.help_text = ScrolledHtml(self,
                                      width=width,
                                      height=height,
                                      xscroll=xscroll,
                                      yscroll=yscroll,
                                      startUrlCallback=self.startOpenUrl,
                                      endUrlCallback=self.endOpenUrl,
                                      enterLinkCallback=self.setLinkLabel,
                                      leaveLinkCallback=self.setLinkLabel)
        self.help_text.grid(row=row,
                            column=0,
                            columnspan=3,
                            sticky=Tkinter.NSEW)
        row = row + 1

        self.link_label = Label(self)
        self.link_label.grid(row=row, column=0, columnspan=2, sticky=Tkinter.W)
        button = memops.gui.Util.createDismissButton(self,
                                                     dismiss_cmd=self.close)
        button.grid(row=row, column=2)

        self.urls = []
        self.current = -1
        self.updateUrlList = True

        self.setButtonState()
    def body(self, guiFrame):
        '''Describes where all the GUI element are.'''

        self.geometry('400x500')
        guiFrame.expandGrid(0, 0)
        tableFrame = Frame(guiFrame)
        tableFrame.grid(
            row=0,
            column=0,
            sticky='nsew',
        )
        tableFrame.expandGrid(0, 0)
        buttonFrame = Frame(guiFrame)
        buttonFrame.grid(
            row=1,
            column=0,
            sticky='nsew',
        )
        headingList = ['Spinsystem Number', 'Assignment', 'Residue Type Probs']
        self.table = ScrolledMatrix(tableFrame,
                                    headingList=headingList,
                                    callback=self.updateSpinSystemSelection,
                                    multiSelect=True)
        self.table.grid(row=0, column=0, sticky='nsew')
        texts = ['Add Prob']
        commands = [self.addProb]
        self.AddProbButton = ButtonList(buttonFrame,
                                        commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=0, sticky='nsew')
        texts = ['Remove Prob']
        commands = [self.removeProb]
        self.AddProbButton = ButtonList(buttonFrame,
                                        commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=2, sticky='nsew')
        selectCcpCodes = sorted(self.chemCompDict.keys())
        tipText = 'select ccpCode'
        self.selectCcpCodePulldown = PulldownList(buttonFrame,
                                                  texts=selectCcpCodes,
                                                  grid=(0, 1),
                                                  tipText=tipText)

        selectCcpCodes = ['All Residue Types']

        tipText = 'select ccpCode'
        self.selectCcpCodeRemovePulldown = PulldownList(buttonFrame,
                                                        texts=selectCcpCodes,
                                                        index=0,
                                                        grid=(0, 3),
                                                        tipText=tipText)
        self.updateTable()
Beispiel #8
0
    def body(self, guiFrame):

        self.geometry('700x400')

        guiFrame.grid_columnconfigure(0, weight=1)
        guiFrame.grid_rowconfigure(0, weight=1)

        interfaceGroups, interfaceGroupDict = self.getInterfaceGroups()

        if len(interfaceGroups) > 1:
            mainFrame = TabbedFrame(guiFrame,
                                    options=interfaceGroups,
                                    grid=(0, 0))
            frames = mainFrame.frames
        else:
            mainFrame = Frame(guiFrame, grid=(0, 0))
            frames = [mainFrame]

        for n, interfaceGroup in enumerate(interfaceGroups):
            frame = frames[n]

            interfaceObjects = interfaceGroupDict[interfaceGroup]
            for interfaceObject in interfaceObjects:
                self.makeInterfaceWidget(frame, interfaceObject)

        texts = ('Ok', 'Cancel')
        commands = (self.setupRun, self.cancelRun)
        buttonList = ButtonList(guiFrame,
                                texts=texts,
                                commands=commands,
                                grid=(1, 0))
Beispiel #9
0
  def body(self, guiFrame):

    ProgressBar.body(self, guiFrame)
    guiFrame.expandGrid(2,3)
    
    self.stepLabel = Label(guiFrame, text='Best step:  ', grid=(0,3))

    
    frame = LabelFrame(guiFrame, text='Best mappings', grid=(1,0), gridSpan=(1,4))

    row = 0
    for i in range(self.ensembleSize):
      label = Label(frame, text='', pady=0, font='Courier 10',
                    borderwidth=0, grid=(row,0), sticky='ew')
      self.labels.append(label)
      row +=1

    guiFrame.grid_rowconfigure(2, weight=1)
    self.graph = ScrolledGraph(guiFrame, width=450, height=300,
                               graphType='scatter', title='Typing Scores',
                               xLabel='Spin System', yLabel='Score',
                               grid=(2,0), gridSpan=(1,4))


    self.buttonList = ButtonList(guiFrame, texts=['Close',], commands=[self.done],
                                 grid=(3,0), gridSpan=(1,4))
    self.buttonList.buttons[0].disable() 
Beispiel #10
0
    def body(self, guiFrame):

        guiFrame.grid_rowconfigure(0, weight=1)
        guiFrame.grid_columnconfigure(1, weight=1)

        row = 0
        if self.message:
            label = Label(guiFrame,
                          text=self.message,
                          gridSpan=(1, 2),
                          grid=(row, 0))
            row += 1

        if self.label:
            label = Label(guiFrame, text=self.label, grid=(row, 0))

        self.itemMenu = PulldownList(guiFrame,
                                     texts=self.entries,
                                     objects=self.entries,
                                     index=self.default,
                                     grid=(row, 1))

        row += 1
        texts = [self.select_text, 'Cancel']
        commands = [self.ok, self.cancel]
        buttons = ButtonList(guiFrame,
                             texts=texts,
                             commands=commands,
                             gridSpan=(1, 2),
                             grid=(row, 0))
Beispiel #11
0
  def __init__(self, guiParent, basePopup):
    # Base popup required to handle notification of data model changes
    # e.g. new peak lists, so that the GUI can update to the latest
    # state
    self.basePopup = basePopup
    self.guiParent = guiParent

    self.basePopup.frameShortcuts['Workflow'] = self

    #self.registerNotify=basePopup.registerNotify
    #self.unregisterNotify=basePopup.unregisterNotify

    Frame.__init__(self, guiParent)
  
    self.grid_rowconfigure(0, weight=0)
    self.grid_rowconfigure(1, weight=0, minsize=100)
    self.grid_rowconfigure(2, weight=1)
    self.grid_rowconfigure(3, weight=0, minsize=30)
    
    self.grid_columnconfigure(0, weight=0)
    self.grid_columnconfigure(1, weight=1)
    self.grid_columnconfigure(2, weight=0)

    # build up the body.

    self.lcA = LinkChart(self, background='#8080B0', height=110)
    self.lcB = LinkChart(self, background='#8080B0')

    lcButtonOpts=['Load','Save','Clear','New Protocol']
    lcButtonCmds=[self.tmpCall,self.tmpCall,self.tmpCall,self.tmpCall]
    self.lcButtons = ButtonList(self, lcButtonOpts, lcButtonCmds)

    # hack for now. This should come from db of meta-tasks
    self.expts=['Test1','Test2','ARIA','CING','ISD']

    # needs custom version
    self.filter = FilterFrame(self, self.basePopup, text='Filter')

    # no bean udnerneath for now so mock up nodes    
    self.wfTree = Tree(self, width=35)

    wfButtonOpts=['Load','Save']
    wfButtonCmds=[self.tmpCall,self.tmpCall]
    self.wfButtons = ButtonList(self, wfButtonOpts, wfButtonCmds)
    

    self.drawFrame()
Beispiel #12
0
def createHelpButtonList(parent, texts = None, commands = None,
                          direction=Tkinter.HORIZONTAL,
                          help_text = '',
                          help_msg = '', help_url = '',
                          buttonBorderwidth=True, expands=True,
                          webBrowser = None,
                          *args, **kw):
  
  if (texts is None):
    texts = []

  if (commands is None):
    commands = []
 
  if not help_text:
    help_text = ''

  texts = list(texts) + [help_text]

  popup = getPopup(parent)

  if not webBrowser:
    webBrowser = WebBrowser(popup.top, popup=popup)

  if (help_url):
    help_cmd   = lambda url=help_url: webBrowser.open(url)
  else:
    help_cmd = lambda top=popup.top, message=help_msg: memops.gui.HelpPopup.showHelpText(top, message, popup=popup)

  if (type(commands) is types.DictType):
    commands = commands.copy()
    commands[help_text] = help_cmd
  else:
    commands = list(commands) + [help_cmd]

  button_list = ButtonList(parent, texts=texts, commands=commands, buttonBorderwidth=buttonBorderwidth,
                           expands=expands, direction=direction, *args, **kw)

  
  if not help_text:
    button_list.helpIcon = Tkinter.PhotoImage(file=os.path.join(gfxDir,'help.gif'))
    button_list.buttons[-1].config(image=button_list.helpIcon)

  return button_list
    def body(self, guiFrame):
        '''Describes where all the GUI element are.'''

        self.geometry('400x500')
        guiFrame.expandGrid(0, 0)
        tableFrame = Frame(guiFrame)
        tableFrame.grid(row=0, column=0, sticky='nsew', )
        tableFrame.expandGrid(0, 0)
        buttonFrame = Frame(guiFrame)
        buttonFrame.grid(row=1, column=0, sticky='nsew', )
        headingList = ['Spinsystem Number', 'Assignment', 'Residue Type Probs']
        self.table = ScrolledMatrix(tableFrame, headingList=headingList,
                                    callback=self.updateSpinSystemSelection,
                                    multiSelect=True)
        self.table.grid(row=0, column=0, sticky='nsew')
        texts = ['Add Prob']
        commands = [self.addProb]
        self.AddProbButton = ButtonList(buttonFrame, commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=0, sticky='nsew')
        texts = ['Remove Prob']
        commands = [self.removeProb]
        self.AddProbButton = ButtonList(buttonFrame, commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=2, sticky='nsew')
        selectCcpCodes = sorted(self.chemCompDict.keys())
        tipText = 'select ccpCode'
        self.selectCcpCodePulldown = PulldownList(buttonFrame,
                                                  texts=selectCcpCodes,
                                                  grid=(0, 1),
                                                  tipText=tipText)

        selectCcpCodes = ['All Residue Types']

        tipText = 'select ccpCode'
        self.selectCcpCodeRemovePulldown = PulldownList(buttonFrame,
                                                        texts=selectCcpCodes,
                                                        index=0,
                                                        grid=(0, 3),
                                                        tipText=tipText)
        self.updateTable()
Beispiel #14
0
  def body(self, guiFrame):

    guiFrame.grid_rowconfigure(0, weight=1)
    guiFrame.grid_columnconfigure(0, weight=1)
  
    row = 0 
    frame = LabelFrame(guiFrame, text='Matched Peak Groups')
    frame.grid_rowconfigure(0, weight=1)
    frame.grid_columnconfigure(0, weight=1)
    frame.grid(row=row, sticky='nsew')
    
    headingList, tipTexts = self.getHeadingList()
    self.scrolledMatrix = ScrolledMatrix(frame, initialRows=15, multiSelect=True, 
                                        headingList=headingList, tipTexts=tipTexts,
                                        grid=(0,0), gridSpan=(1,3))
 
    tipTexts = ['Remove the selected peak groups from the table',
                'Show 1D positional ruler lines for the selected groups',
                'Remove any ruler lines previously added for peak group',
                'Display selected peak groups within strips of selected window']
    texts = ['Remove\nGroups','Show\nRulers',
             'Delete\nRulers','Display Groups\nIn Strips']
    commands = [self.removeGroups,self.addRulers,
                self.removeRulers,self.stripGroups]
    self.buttons = ButtonList(frame, texts=texts, commands=commands, tipTexts=tipTexts)
    self.buttons.grid(row=1, column=0, sticky='ew')
    
    tipText = 'Selects the spectrum window in which to display strips & ruler lines'
    label = Label(frame, text='Target window:', grid=(1,1))
    self.windowPulldown = PulldownList(frame, callback=None,
                                       grid=(1,2), tipText=tipText)
    
    row+= 1
    bottomButtons = UtilityButtonList(guiFrame, helpUrl=self.help_url, expands=True, doClone=False)
    bottomButtons.grid(row = row, sticky = 'ew')

    self.update()

    for func in ('__init__', 'delete', 'setName'):
      self.registerNotify(self.updateWindowsAfter, 'ccpnmr.Analysis.SpectrumWindow', func)
Beispiel #15
0
    def createBottomButtons(self, parent):

        if (self.editMode):
            texts = []
            commands = []
            if (self.metaclass.parentRole):
                texts.extend(['Parent', 'Siblings'])
                commands.extend([self.gotoParent, self.showSiblings])
                if (self.metaclass.parentRole.otherClass.parentRole):
                    texts.extend(['All'])
                    commands.extend([self.showAll])
            texts.extend(['Delete', 'Close'])
            commands.extend([self.deleteObject, self.close])
        else:
            texts = ['Create', 'Cancel']
            commands = [self.createObject, self.close]
        bottom_buttons = ButtonList(parent,
                                    texts=texts,
                                    commands=commands,
                                    direction=Tkinter.HORIZONTAL,
                                    expands=True)
        bottom_buttons.grid(row=2, column=0, columnspan=2, sticky=Tkinter.EW)
Beispiel #16
0
    def body(self):
        '''Setting up the body of this view.'''

        frame = self.frame

        file_types = [FileType('pyc', ['*.pyc'])]
        self.fileselectionBox = FileSelect(frame,
                                           multiSelect=False,
                                           file_types=file_types)
        self.fileselectionBox.grid(row=0,
                                   column=0,
                                   columnspan=6,
                                   sticky='nsew')

        texts = ['Load', 'Save']
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame,
                                             commands=commands,
                                             texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky='nsew')

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)
Beispiel #17
0
    def body(self):
        """Setting up the body of this view."""

        frame = self.frame

        file_types = [FileType("pyc", ["*.pyc"])]
        self.fileselectionBox = FileSelect(frame, multiSelect=False, file_types=file_types)
        self.fileselectionBox.grid(row=0, column=0, columnspan=6, sticky="nsew")

        texts = ["Load", "Save"]
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame, commands=commands, texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky="nsew")

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)
    def body(self):
        '''Describes the body of this tab. It consists
           out of a number of radio buttons, check buttons
           and number entries that allow the user to
           indicate which assignments should be transferred.
        '''

        # self.frame.expandColumn(0)
        self.frame.expandGrid(8, 0)
        self.frame.expandGrid(8, 1)

        typeOfAssignmentFrame = LabelFrame(
            self.frame, text='type of assignment')
        typeOfAssignmentFrame.grid(row=0, column=0, sticky='nesw')
        # typeOfAssignmentFrame.expandGrid(0,5)

        peakSelectionFrame = LabelFrame(
            self.frame, text='which peaks to assign')
        peakSelectionFrame.grid(row=0, column=1, sticky='nesw', rowspan=2)

        spinSystemSelectionFrame = LabelFrame(self.frame,
                                              text='Which spin-systems to use')
        spinSystemSelectionFrame.grid(row=2, column=0, sticky='nesw')

        tipText = 'What to do when a residue has already a spin system assigned to it.'
        assignedResidueFrame = LabelFrame(self.frame,
                                          text='if residue already has spin-system',
                                          tipText=tipText)
        assignedResidueFrame.grid(row=2, column=1, sticky='nesw')

        spectrumSelectionFrame = LabelFrame(self.frame, text='spectra')
        spectrumSelectionFrame.grid(row=1, column=0, sticky='nesw')

        row = 0

        Label(typeOfAssignmentFrame,
              text='Resonances to Peak Dimensions',
              grid=(row, 0))
        self.peaksCheckButton = CheckButton(typeOfAssignmentFrame,
                                            selected=True,
                                            grid=(row, 1))

        row += 1

        Label(typeOfAssignmentFrame,
              text='SpinSystems to Residues',
              grid=(row, 0))
        self.residuesCheckButton = CheckButton(
            typeOfAssignmentFrame, selected=True, grid=(row, 1))

        row = 0

        Label(peakSelectionFrame, text='Intra-Residual', grid=(row, 0))
        self.intraCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        row += 1

        Label(peakSelectionFrame, text='Sequential', grid=(row, 0))
        self.sequentialCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        row += 1

        Label(peakSelectionFrame,
              text='Do not assign diagonal peaks',
              grid=(row, 0))
        self.noDiagonalCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        entries = ['Only assigned spin systems',
                   'All that have a score of at least: ',
                   'User Defined',
                   'Solution number:']
        tipTexts = ['Only assign resonances of spin systems that already have a sequential assignment for the assignment of peak dimensions. Spin system to residue assignment is not relevant in this case.',
                    'Assign all spin systems that have a score of at least a given percentage. 50% or lower is not possible, because than spin systems might have to be assigned to more than 1 residue, which is impossible.',
                    "As defined in the lower row of buttons in the 'results' tab.",
                    'One of the single solutions of the annealing.']
        self.spinSystemTypeSelect = RadioButtons(spinSystemSelectionFrame,
                                                 entries=entries, grid=(0, 0),
                                                 select_callback=None,
                                                 direction=VERTICAL,
                                                 gridSpan=(4, 1),
                                                 tipTexts=tipTexts)

        tipText = 'The minimal amount of colabelling the different nuclei should have in order to still give rise to a peak.'
        self.minScoreEntry = FloatEntry(spinSystemSelectionFrame,
                                        grid=(1, 1), width=7,
                                        text=str(self.minScore),
                                        returnCallback=self.changeMinScore,
                                        tipText=tipText)
        self.minScoreEntry.bind('<Leave>', self.changeMinScore, '+')

        self.solutionNumberEntry = IntEntry(spinSystemSelectionFrame,
                                            grid=(3, 1), width=7, text=1,
                                            returnCallback=self.solutionUpdate,
                                            tipText=tipText)
        self.solutionNumberEntry.bind('<Leave>', self.solutionUpdate, '+')

        #self.solutionPullDown = PulldownList(spinSystemSelectionFrame, None, grid=(3,1), sticky='w')

        entries = ['all spectra', 'only:']
        tipTexts = ['Assign peaks in all the spectra that where selected before the annealing ran.',
                    'Only assign peaks in one particular spectrum. You can of course repeat this multiple times for different spectra.']
        self.spectrumSelect = RadioButtons(spectrumSelectionFrame,
                                           entries=entries,
                                           grid=(0, 0),
                                           select_callback=None,
                                           direction=VERTICAL,
                                           gridSpan=(2, 1), tipTexts=tipTexts)

        self.spectraPullDown = PulldownList(spectrumSelectionFrame,
                                            self.changeSpectrum,
                                            grid=(1, 1), sticky='w')

        entries = ['skip this residue',
                   'de-assign old spin system from residue',
                   'assign, but never merge',
                   'warn to merge']
        tipTexts = ["Don't assign the new spin system to the residue. The residue is not skipped when the old spin system does not contain any resonances",
                    "De-assign old spin system from residue, unless the old spin system is a spin system without any resonances.",
                    "Don't merge any spin systems, merging can be performed later if nescesary in the Resonance --> SpinSystems window.",
                    "Ask to merge individually for each spin system, this might result in clicking on a lot of popups."]
        self.assignedResidueStrategySelect = RadioButtons(assignedResidueFrame,
                                                          entries=entries,
                                                          grid=(0, 0),
                                                          select_callback=None,
                                                          direction=VERTICAL,
                                                          gridSpan=(2, 1),
                                                          tipTexts=tipTexts)

        texts = ['Transfer Assignments']
        commands = [self.transferAssignments]
        self.transferButton = ButtonList(
            self.frame, commands=commands, texts=texts)
        self.transferButton.grid(row=5, column=0, sticky='nsew', columnspan=2)
Beispiel #19
0
    def body(self, guiFrame):

        self.geometry('600x350')

        guiFrame.expandGrid(0, 0)

        tipTexts = ['', '', '', '']
        options = [
            'Find Parameters', 'Spectrum Widths', 'Diagonal Exclusions',
            'Region Peak Find'
        ]
        tabbedFrame = TabbedFrame(guiFrame, options=options, grid=(0, 0))

        frameA, frameB, frameC, frameD = tabbedFrame.frames
        self.tabbedFrame = tabbedFrame

        # Find Params

        frameA.expandGrid(2, 0)

        row = 0
        label = LabelFrame(frameA,
                           text='Extrema to search for:',
                           grid=(row, 0),
                           gridSpan=(1, 2))
        label.expandGrid(0, 1)

        entries = ['positive and negative', 'positive only', 'negative only']
        tipTexts = [
            'Sets whether peak picking within spectra find intensity maxima, minima or both maxima and minima',
        ]
        self.extrema_buttons = RadioButtons(label,
                                            entries=entries,
                                            select_callback=self.apply,
                                            direction='horizontal',
                                            grid=(0, 0),
                                            tipTexts=tipTexts)

        row += 1
        label = LabelFrame(frameA,
                           text='Nearby points to check:',
                           grid=(row, 0),
                           gridSpan=(1, 2))
        label.expandGrid(None, 1)

        entries = ['+-1 in at most one dim', '+-1 allowed in any dim']
        tipTexts = [
            'Sets how permissive the peak picking in when searching for intensity extrema; by adding extra points to the selected search region',
        ]
        self.adjacent_buttons = RadioButtons(label,
                                             entries=entries,
                                             select_callback=self.apply,
                                             direction='horizontal',
                                             grid=(0, 0),
                                             tipTexts=tipTexts)

        row += 1
        labelFrame = LabelFrame(frameA,
                                text='Other parameters:',
                                grid=(row, 0),
                                gridSpan=(1, 2))
        labelFrame.expandGrid(5, 2)

        frow = 0
        label = Label(labelFrame,
                      text='Scale relative to contour levels:',
                      grid=(frow, 0),
                      sticky='e')
        tipText = 'Threshold above which peaks are picked, relative to the lowest displayed contour; 1.0 means picking exactly what is visible'
        self.scale_entry = FloatEntry(labelFrame,
                                      grid=(frow, 1),
                                      tipText=tipText,
                                      returnCallback=self.apply,
                                      width=10)
        self.scale_entry.bind('<Leave>', self.apply, '+')

        frow += 1
        label = Label(labelFrame,
                      text='Exclusion buffer around peaks (in points):',
                      grid=(frow, 0),
                      sticky='e')
        tipText = 'The size of the no-pick region, in data points, around existing picked peaks; eliminates duplicate picking'
        self.buffer_entry = IntEntry(labelFrame,
                                     returnCallback=self.apply,
                                     grid=(frow, 1),
                                     width=10,
                                     tipText=tipText)
        self.buffer_entry.bind('<Leave>', self.apply, '+')

        frow += 1
        label = Label(labelFrame,
                      text='Extra thickness in orthogonal dims (in points):',
                      grid=(frow, 0),
                      sticky='e')
        tipText = 'Sets whether to consider any additional planes (Z dimension) when calculating peak volume integrals'
        self.thickness_entry = IntEntry(labelFrame,
                                        returnCallback=self.apply,
                                        width=10,
                                        grid=(frow, 1),
                                        tipText=tipText)
        self.thickness_entry.bind('<Leave>', self.apply, '+')

        frow += 1
        label = Label(labelFrame,
                      text='Minimum drop factor (0.0-1.0):',
                      grid=(frow, 0),
                      sticky='e')
        tipText = ''
        self.drop_entry = FloatEntry(labelFrame,
                                     returnCallback=self.apply,
                                     width=10,
                                     grid=(frow, 1),
                                     tipText=tipText)
        self.drop_entry.bind('<Leave>', self.apply, '+')

        frow += 1
        label = Label(labelFrame,
                      text='Volume method:',
                      grid=(frow, 0),
                      sticky='e')
        tipText = 'Selects which method to use to calculate peak volume integrals when peaks are picked; box sizes are specified in "Spectrum Widths"'
        self.method_menu = PulldownList(labelFrame,
                                        texts=PeakBasic.PEAK_VOLUME_METHODS,
                                        grid=(frow, 1),
                                        callback=self.apply,
                                        tipText=tipText)

        # Spectrum widths

        frameB.expandGrid(1, 1)

        label = Label(frameB, text='Spectrum: ')
        label.grid(row=0, column=0, sticky='e')

        tipText = 'The spectrum which determines the widths being shown'
        self.expt_spectrum = PulldownList(frameB,
                                          tipText=tipText,
                                          callback=self.setSpectrumProperties)
        self.expt_spectrum.grid(row=0, column=1, sticky='w')

        self.editLinewidthEntry = FloatEntry(self,
                                             text='',
                                             returnCallback=self.setLinewidth,
                                             width=10)
        self.editBoxwidthEntry = FloatEntry(self,
                                            text='',
                                            returnCallback=self.setBoxwidth,
                                            width=10)
        tipTexts = [
            'The number of the spectrum dimension to which the settings apply',
            'The nuclear isotope measures in the spectrum dimension',
            'The smallest value for the linewidth of a peak for it to be picked',
            'The size of the spectrum region to perform the volume integral over'
        ]
        headingList = [
            'Dimension', 'Isotope', 'Minimum Linewidth (Hz)', 'Boxwidth'
        ]
        editSetCallbacks = [None, None, self.setLinewidth, self.setBoxwidth]
        editGetCallbacks = [None, None, self.getLinewidth, self.getBoxwidth]
        editWidgets = [
            None, None, self.editLinewidthEntry, self.editBoxwidthEntry
        ]
        self.spectrumMatrix = ScrolledMatrix(frameB,
                                             initialRows=6,
                                             editSetCallbacks=editSetCallbacks,
                                             editGetCallbacks=editGetCallbacks,
                                             editWidgets=editWidgets,
                                             headingList=headingList,
                                             callback=self.selectCell,
                                             tipTexts=tipTexts)
        self.spectrumMatrix.grid(row=1, column=0, columnspan=2, sticky='nsew')

        # Diagonal Exclusions

        frameC.expandGrid(0, 0)

        tipTexts = [
            'The isotope as measures on the axis of a spectrum window',
            'The distance from the homonuclear diagonal line within which no peak picking can occur'
        ]
        self.exclusionEntry = FloatEntry(self,
                                         text='',
                                         returnCallback=self.setExclusion,
                                         width=10)
        headingList = ['Isotope', 'Diagonal Exclusion (ppm)']
        editSetCallbacks = [None, self.setExclusion]
        editGetCallbacks = [None, self.getExclusion]
        editWidgets = [None, self.exclusionEntry]
        self.isotopeMatrix = ScrolledMatrix(frameC,
                                            editSetCallbacks=editSetCallbacks,
                                            editGetCallbacks=editGetCallbacks,
                                            editWidgets=editWidgets,
                                            headingList=headingList,
                                            grid=(0, 0),
                                            tipTexts=tipTexts)

        # Region peak find

        self.regionFindPeakList = None
        self.regionCondition = None
        self.regionConditions = []
        self.regionCol = 1

        row = 0

        label = Label(frameD, text='Peak List: ', grid=(0, 0))
        tipText = 'Selects which peak list to perform region-wide peak picking for'
        self.regionPeakListPulldown = PulldownList(
            frameD,
            callback=self.changeRegionPeakList,
            grid=(0, 1),
            tipText=tipText)

        row += 1
        frameD.expandGrid(row, 1)

        self.regionEntry = FloatEntry(self,
                                      text='',
                                      returnCallback=self.setRegion,
                                      width=10)
        self.conditionMenu = PulldownList(self,
                                          texts=('include', 'exclude'),
                                          callback=self.setCondition)

        tipTexts = [
            'Whether to include or exclude the states region from region-wide peak picking',
        ]
        headingList = ['Condition']
        editSetCallbacks = [None]
        editGetCallbacks = [None]
        editWidgets = [self.conditionMenu]
        self.regionFindMatrix = ScrolledMatrix(
            frameD,
            headingList=headingList,
            callback=self.selectRegionCell,
            editWidgets=editWidgets,
            editGetCallbacks=editGetCallbacks,
            editSetCallbacks=editSetCallbacks,
            grid=(row, 0),
            gridSpan=(1, 2))

        row += 1
        tipTexts = [
            'Sets the currently selected region row to cover the whole spectrum',
            'Add a new region row, which may them be set for exclusion or inclusion when peak picking large areas',
            'Remove the selected region specification',
            'Go to the panel for setting the parameters that control how peaks extrema are picked',
            'Using the stated regions and parameters, perform region-wide peak picking'
        ]
        texts = [
            'Whole Region', 'Add Region', 'Delete Region', 'Adjust Params',
            'Find Peaks!'
        ]
        commands = [
            self.wholeRegion, self.addCondition, self.deleteCondition,
            self.adjustParams, self.regionFindPeaks
        ]

        buttons = ButtonList(frameD,
                             texts=texts,
                             commands=commands,
                             grid=(row, 0),
                             gridSpan=(1, 2),
                             tipTexts=tipTexts)
        buttons.buttons[4].config(bg='#B0FFB0')

        utilButtons = UtilityButtonList(tabbedFrame.sideFrame,
                                        grid=(0, 0),
                                        helpUrl=self.help_url,
                                        sticky='e')

        self.dataDim = None
        self.setParamsEntries()
        self.updateSpectrum()
        self.setIsotopeProperties()
        self.updateRegionPeakLists()

        self.administerNotifiers(self.registerNotify)
Beispiel #20
0
class UpdatePopup(BasePopup, UpdateAgent):
    def __init__(self,
                 parent,
                 serverLocation=UPDATE_SERVER_LOCATION,
                 serverDirectory=UPDATE_DIRECTORY,
                 dataFile=UPDATE_DATABASE_FILE,
                 exitOnClose=False):

        self.exitOnClose = exitOnClose
        UpdateAgent.__init__(self,
                             serverLocation,
                             serverDirectory,
                             dataFile,
                             isStandAlone=exitOnClose)
        self.fileUpdate = None

        if exitOnClose:
            quitFunc = sys.exit
        else:
            quitFunc = None

        BasePopup.__init__(self,
                           parent=parent,
                           title='CcpNmr Software Updates',
                           quitFunc=quitFunc)

    def body(self, guiParent):

        self.geometry('600x300')

        guiParent.grid_columnconfigure(1, weight=1)

        url = ''
        if self.server:
            url = self.server.url
        label = Label(guiParent, text='Server location: %s' % url)
        label.grid(row=0, column=0, sticky='w', columnspan=2)

        label = Label(guiParent,
                      text='Installation root: %s%s' %
                      (self.installRoot, os.sep))
        label.grid(row=1, column=0, sticky='w', columnspan=2)

        editWidgets = [None] * 5
        editGetCallbacks = [None, self.toggleSelected, None, None, None]
        editSetCallbacks = [None] * 5

        guiParent.grid_rowconfigure(2, weight=1)
        headingList = [
            'File', 'Install?', 'Date', 'Relative Path', 'Priority', 'Comments'
        ]
        self.scrolledMatrix = ScrolledMatrix(guiParent,
                                             headingList=headingList,
                                             highlightType=0,
                                             editWidgets=editWidgets,
                                             callback=self.selectCell,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)

        self.scrolledMatrix.grid(row=2, column=0, columnspan=2, sticky='nsew')

        if self.exitOnClose:
            txt = 'Quit'
            cmd = sys.exit
        else:
            txt = 'Close'
            cmd = self.close

        texts = ['Refresh List', 'Select All', 'Install Selected', txt]
        commands = [self.updateFiles, self.selectAll, self.install, cmd]
        self.buttonList = ButtonList(guiParent,
                                     texts=texts,
                                     commands=commands,
                                     expands=True)
        self.buttonList.grid(row=3, column=0, columnspan=2, sticky='ew')

        if self.server:
            for fileUpdate in self.server.fileUpdates:
                fileUpdate.isSelected = False

        #self.update()
        # need self.updateFiles, not just self.update
        # because otherwise the 2.0.5 to 2.0.6 upgrades do not work
        # (self.server not set on first pass so need call to updateFiles here)
        self.updateFiles()

    def toggleSelected(self, fileUpdate):

        boolean = fileUpdate.isSelected

        fileUpdate.isSelected = not boolean

        self.update()

    def install(self):

        if self.server:
            self.installUpdates()
            self.updateFiles()

    def selectAll(self):

        if self.server:
            for fileUpdate in self.scrolledMatrix.objectList:
                fileUpdate.isSelected = True

        self.update()

    def selectCell(self, object, row, col):

        self.fileUpdate = object

    def updateButtons(self):

        buttons = self.buttonList.buttons

        if self.server:
            selected = False
            if self.server and self.server.fileUpdates:
                for fileUpdate in self.scrolledMatrix.objectList:
                    if fileUpdate.isSelected:
                        selected = True
                        break

                buttons[1].enable()
            else:
                buttons[1].disable()

            if selected:
                buttons[2].enable()
                buttons[2].config(bg='#A0FFA0')
            else:
                buttons[2].disable()
                buttons[2].config(bg=buttons[1].cget('bg'))

        else:
            for button in buttons[:-1]:
                button.disable()

    def updateFiles(self):

        if self.server:
            if not self.server.fileUpdates:
                self.server.getFileUpdates()

            for fileUpdate in self.server.fileUpdates:
                fileUpdate.isSelected = False

        self.update()

    def update(self):

        self.updateButtons()

        self.fileUpdate = None
        textMatrix = []
        objectList = []
        colorMatrix = []

        if self.server:

            for fileUpdate in self.server.fileUpdates:

                if fileUpdate.getIsUpToDate():
                    continue

                color = [None, '#A04040', None, None, None]
                yesNo = 'No'
                if fileUpdate.isSelected:
                    color = [None, '#A0FFA0', None, None, None]
                    yesNo = 'Yes'

                datum = []
                datum.append(fileUpdate.fileName)
                datum.append(yesNo)
                datum.append(fileUpdate.date)
                datum.append(fileUpdate.filePath + os.sep)
                datum.append(fileUpdate.priority)
                datum.append(fileUpdate.details)

                colorMatrix.append(color)
                textMatrix.append(datum)
                objectList.append(fileUpdate)

        self.scrolledMatrix.update(textMatrix=textMatrix,
                                   objectList=objectList,
                                   colorMatrix=colorMatrix)
Beispiel #21
0
    def body(self, guiFrame):

        guiFrame.grid_columnconfigure(2, weight=1)

        row = 0
        label = Label(guiFrame, text='Template window: ', grid=(row, 0))
        tipText = 'Selects which window to use as the basis for making a new spectrum window; sets the axis types accordingly'
        self.window_list = PulldownList(guiFrame,
                                        grid=(row, 1),
                                        callback=self.setAxisTypes,
                                        tipText=tipText)
        frame = LabelFrame(guiFrame,
                           text='Strips',
                           grid=(row, 2),
                           gridSpan=(2, 1))
        buttons = UtilityButtonList(guiFrame,
                                    doClone=False,
                                    helpUrl=self.help_url,
                                    grid=(row, 3))

        row += 1
        label = Label(guiFrame, text='New window name: ', grid=(row, 0))
        tipText = 'A short name to identify the spectrum window, which will appear in the graphical interface'
        self.nameEntry = Entry(guiFrame,
                               width=16,
                               grid=(row, 1),
                               tipText=tipText)

        row += 1

        label = Label(frame, text='Columns: ', grid=(0, 0))
        tipText = 'The number of vertical strips/dividers to initially make in the spectrum window'
        self.cols_menu = PulldownList(frame,
                                      objects=STRIP_NUMS,
                                      grid=(0, 1),
                                      texts=[str(x) for x in STRIP_NUMS],
                                      tipText=tipText)

        label = Label(frame, text='Rows: ', grid=(0, 2))
        tipText = 'The number of horizontal strips/dividers to initially make in the spectrum window'
        self.rows_menu = PulldownList(frame,
                                      objects=STRIP_NUMS,
                                      grid=(0, 3),
                                      texts=[str(x) for x in STRIP_NUMS],
                                      tipText=tipText)
        row += 1
        div = LabelDivider(guiFrame,
                           text='Axes',
                           grid=(row, 0),
                           gridSpan=(1, 4))

        row += 1
        self.axis_lists = {}
        frame = Frame(guiFrame, grid=(row, 0), gridSpan=(1, 4))

        col = 0
        self.axisTypes = {}
        self.axisTypesIncludeNone = {}
        for label in AXIS_LABELS:
            self.axisTypes[label] = None
            w = Label(frame, text=' ' + label)
            w.grid(row=0, column=col, sticky='w')
            col += 1

            if label in ('x', 'y'):
                includeNone = False
                tipText = 'Sets the kind of measurement (typically ppm for a given isotope) that will be used along the window %s axis' % label
            else:
                includeNone = True
                tipText = 'Where required, sets the kind of measurement (typically ppm for a given isotope) that will be used along the window %s axis' % label
            self.axisTypesIncludeNone[label] = includeNone

            getAxisTypes = lambda label=label: self.getAxisTypes(label)
            callback = lambda axisType, label=label: self.changedAxisType(
                label, axisType)
            self.axis_lists[label] = PulldownList(frame,
                                                  callback=callback,
                                                  tipText=tipText)
            self.axis_lists[label].grid(row=0, column=col, sticky='w')
            col += 1

        frame.grid_columnconfigure(col, weight=1)

        row += 1
        div = LabelDivider(guiFrame,
                           text='Viewed Spectra',
                           grid=(row, 0),
                           gridSpan=(1, 4))

        row += 1
        guiFrame.grid_rowconfigure(row, weight=1)

        editWidgets = [None, None, None, None]
        editGetCallbacks = [None, self.toggleVisible, self.toggleToolbar, None]
        editSetCallbacks = [None, None, None, None]
        tipTexts = [
            'The "experiment:spectrum" name for the spectrum that may be viewed in the new window, given the axis selections',
            'Sets whether the spectrum contours will be visible in the new window',
            'Sets whether the spectrum appears at all in the window; if not in the toolbar it cannot be displayed',
            'The number of peak lists the spectrum contains'
        ]
        headingList = ['Spectrum', 'Visible?', 'In Toolbar?', 'Peak Lists']

        self.scrolledMatrix = ScrolledMatrix(guiFrame,
                                             headingList=headingList,
                                             editWidgets=editWidgets,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks,
                                             multiSelect=True,
                                             grid=(row, 0),
                                             gridSpan=(1, 4),
                                             tipTexts=tipTexts)

        row += 1
        tipTexts = [
            'Creates a new spectrum window with the specified parameters',
            'Sets the contours of the selected spectra to be visible when the new window is made',
            'Sets the contours of the selected spectra to not be displayed when the new window is made',
            'Sets the selected spectra as absent from the window toolbar, and thus not displayable at all'
        ]
        texts = [
            'Create Window!', 'Selected\nVisible', 'Selected\nNot Visible',
            'Selected\nNot In Toolbar'
        ]
        commands = [
            self.ok, self.setSelectedDisplay, self.setSelectedHide,
            self.setSelectedAbsent
        ]
        buttonList = ButtonList(guiFrame,
                                texts=texts,
                                grid=(row, 0),
                                commands=commands,
                                gridSpan=(1, 4),
                                tipTexts=tipTexts)
        buttonList.buttons[0].config(bg='#B0FFB0')

        self.updateAxisTypes()
        self.updateWindow()
        self.updateWindowName()

        self.administerNotifiers(self.registerNotify)
        self.updateAfter()
Beispiel #22
0
  def __init__(self, parent, application, *args, **kw):

    project = application.project
    simStore = project.findFirstNmrSimStore(application=APP_NAME) or \
               project.newNmrSimStore(application=APP_NAME, name=APP_NAME)

    self.application = application
    self.residue = None
    self.structure = None
    self.serverCredentials = None
    self.iCingBaseUrl = DEFAULT_URL
    self.resultsUrl = None
    self.chain = None
    self.nmrProject = application.nmrProject
    self.serverDone = False

    NmrSimRunFrame.__init__(self, parent, project, simStore, *args, **kw)

    # # # # # # New Structure Frame # # # # #

    self.structureFrame.grid_forget()

    tab = self.tabbedFrame.frames[0]

    frame = Frame(tab, grid=(1,0))
    frame.expandGrid(2,1)

    div = LabelDivider(frame, text='Structures', grid=(0,0), gridSpan=(1,2))

    label = Label(frame, text='Ensemble: ', grid=(1,0))
    self.structurePulldown = PulldownList(frame, callback=self.changeStructure, grid=(1,1))

    headingList = ['Model','Use']
    editWidgets      = [None,None]
    editGetCallbacks = [None,self.toggleModel]
    editSetCallbacks = [None,None,]
    self.modelTable = ScrolledMatrix(frame, grid=(2,0), gridSpan=(1,2),
                                     callback=self.selectStructModel,
                                     editWidgets=editWidgets,
                                     editGetCallbacks=editGetCallbacks,
                                     editSetCallbacks=editSetCallbacks,
                                     headingList=headingList)

    texts = ['Activate Selected','Inactivate Selected']
    commands = [self.activateModels, self.disableModels]
    buttons = ButtonList(frame, texts=texts, commands=commands, grid=(3,0), gridSpan=(1,2))


    # # # # # # Submission frame # # # # # #

    tab = self.tabbedFrame.frames[1]
    tab.expandGrid(1,0)

    frame = LabelFrame(tab, text='Server Job Submission', grid=(0,0))
    frame.expandGrid(None,2)

    srow = 0
    label = Label(frame, text='iCing URL:', grid=(srow, 0))
    urls = [DEFAULT_URL,]
    self.iCingBaseUrlPulldown = PulldownList(frame, texts=urls, objects=urls, index=0, grid=(srow,1))


    srow +=1
    label = Label(frame, text='Results File:', grid=(srow, 0))
    self.resultFileEntry = Entry(frame, bd=1, text='', grid=(srow,1), width=50)
    self.setZipFileName()
    button = Button(frame, text='Choose File', bd=1, sticky='ew',
                    command=self.chooseZipFile, grid=(srow, 2))

    srow +=1
    label = Label(frame, text='Results URL:', grid=(srow, 0))
    self.resultUrlEntry = Entry(frame, bd=1, text='', grid=(srow,1), width=50)
    button = Button(frame, text='View Results HTML', bd=1, sticky='ew',
                    command=self.viewHtmlResults, grid=(srow, 2))

    srow +=1
    texts    = ['Submit Project!', 'Check Run Status',
                'Purge Server Result', 'Download Results']
    commands = [self.runCingServer, self.checkStatus,
                self.purgeCingServer, self.downloadResults]

    self.buttonBar = ButtonList(frame, texts=texts, commands=commands,
                                grid=(srow, 0), gridSpan=(1,3))

    for button in self.buttonBar.buttons[:1]:
      button.config(bg=CING_BLUE)

    # # # # # # Residue frame # # # # # #

    frame = LabelFrame(tab, text='Residue Options', grid=(1,0))
    frame.expandGrid(1,1)

    label = Label(frame, text='Chain: ')
    label.grid(row=0,column=0,sticky='w')
    self.chainPulldown = PulldownList(frame, callback=self.changeChain)
    self.chainPulldown.grid(row=0,column=1,sticky='w')

    headingList = ['#','Residue','Linking','Decriptor','Use?']
    editWidgets      = [None,None,None,None,None]
    editGetCallbacks = [None,None,None,None,self.toggleResidue]
    editSetCallbacks = [None,None,None,None,None,]
    self.residueMatrix = ScrolledMatrix(frame,
                                        headingList=headingList,
                                        multiSelect=True,
                                        editWidgets=editWidgets,
                                        editGetCallbacks=editGetCallbacks,
                                        editSetCallbacks=editSetCallbacks,
                                        callback=self.selectResidue)
    self.residueMatrix.grid(row=1, column=0, columnspan=2, sticky = 'nsew')

    texts = ['Activate Selected','Inactivate Selected']
    commands = [self.activateResidues, self.deactivateResidues]
    self.resButtons = ButtonList(frame, texts=texts, commands=commands,)
    self.resButtons.grid(row=2, column=0, columnspan=2, sticky='ew')

    """
    # # # # # # Validate frame # # # # # #

    frame = LabelFrame(tab, text='Validation Options', grid=(2,0))
    frame.expandGrid(None,2)

    srow = 0
    self.selectCheckAssign = CheckButton(frame)
    self.selectCheckAssign.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckAssign.set(True)
    label = Label(frame, text='Assignments and shifts')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckResraint = CheckButton(frame)
    self.selectCheckResraint.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckResraint.set(True)
    label = Label(frame, text='Restraints')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckQueen = CheckButton(frame)
    self.selectCheckQueen.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckQueen.set(False)
    label = Label(frame, text='QUEEN')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckScript = CheckButton(frame)
    self.selectCheckScript.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckScript.set(False)
    label = Label(frame, text='User Python script\n(overriding option)')
    label.grid(row=srow,column=1,sticky='nw')

    self.validScriptEntry = Entry(frame, bd=1, text='')
    self.validScriptEntry.grid(row=srow,column=2,sticky='ew')

    scriptButton = Button(frame, bd=1,
                          command=self.chooseValidScript,
                          text='Browse')
    scriptButton.grid(row=srow,column=3,sticky='ew')
    """

    # # # # # # # # # #

    self.update(simStore)

    self.administerNotifiers(application.registerNotify)
Beispiel #23
0
    def __init__(self,
                 parent,
                 file_types=None,
                 directory=None,
                 single_callback=None,
                 double_callback=None,
                 select_dir_callback=None,
                 change_dir_callback=None,
                 should_change_dir_callback=None,
                 prompt=None,
                 show_file=True,
                 file='',
                 multiSelect=False,
                 default_dir=None,
                 getRowColor=None,
                 getExtraCell=None,
                 extraHeadings=None,
                 extraJustifies=None,
                 displayExtra=True,
                 manualFileFilter=False,
                 extraTipTexts=None,
                 *args,
                 **kw):

        if file_types is None:
            file_types = [FileType("All", ["*"])]

        if manualFileFilter:
            self.manualFilter = FileType("Manual")
            file_types.append(self.manualFilter)
        else:
            self.manualFilter = None

        if directory is None:
            directory = normalisePath(os.getcwd())

        if extraHeadings is None:
            extraHeadings = ()
        else:
            extraHeadings = tuple(extraHeadings)

        if extraJustifies is None:
            extraJustifies = ()
        else:
            extraJustifies = tuple(extraJustifies)

        if extraHeadings or extraJustifies:
            assert len(extraHeadings) == len(extraJustifies)
            assert getExtraCell

        self.extraHeadings = extraHeadings
        self.extraJustifies = extraJustifies
        self.extraTipTexts = extraTipTexts or []
        self.displayExtra = displayExtra

        Frame.__init__(self, parent, *args, **kw)

        self.file_types = file_types
        self.fileType = file_types[0]
        self.single_callback = single_callback
        self.double_callback = double_callback
        self.select_dir_callback = select_dir_callback
        self.change_dir_callback = change_dir_callback
        self.should_change_dir_callback = should_change_dir_callback
        self.show_file = show_file
        self.directory = None
        self.historyBack = []
        self.historyFwd = []
        self.determineDir(directory)
        self.default_dir = default_dir
        self.getRowColor = getRowColor
        self.getExtraCell = getExtraCell

        self.grid_columnconfigure(0, weight=1)

        row = 0
        if prompt:
            label = Label(self, text=prompt, grid=(row, 0))
            row += 1

        self.grid_rowconfigure(row, weight=1)
        if show_file:
            headings = ('Name', 'Size', 'Date')
            justifies = ('left', 'right', 'right')
            tipTexts = [
                'Name of file, directory or link', 'Size of file in bytes',
                'Date of last modification'
            ]
        else:
            headings = ('Directory', )
            justifies = ('left', )
            tipTexts = ['Name of directory']

        self.normalHeadings = headings
        self.normalJustifies = justifies
        self.normalTipTexts = tipTexts
        headings = headings + extraHeadings
        justifies = justifies + extraJustifies
        tipTexts += [None] * len(extraHeadings)

        self.fileList = ScrolledMatrix(self,
                                       headingList=headings,
                                       justifyList=justifies,
                                       initialRows=10,
                                       callback=self.singleCallback,
                                       doubleCallback=self.doubleCallback,
                                       tipTexts=tipTexts,
                                       multiSelect=multiSelect,
                                       grid=(row, 0))

        row += 1
        tipTexts = [
            'Go to previous location in history',
            'Go forward in location history', 'Go up one directory level',
            'Go to root directory', 'Go to home directory',
            'Make a new directory', 'Refresh directory listing'
        ]

        texts = ['Back', 'Forward', 'Up', 'Top', 'Home', 'New', 'Refresh']
        commands = [
            self.backDir, self.fwdDir, self.upDir, self.topDir, self.homeDir,
            self.createDir, self.updateFileList
        ]

        if self.default_dir:
            texts.append('Default')
            commands.append(self.setDefaultDir)
            tipTexts.append('Set the current directory as the default')

        self.icons = []
        for name in ICON_NAMES:
            icon = Tkinter.PhotoImage(
                file=os.path.join(GFX_DIR, name + '.gif'))
            self.icons.append(icon)

        self.buttons = ButtonList(self,
                                  texts=texts,
                                  commands=commands,
                                  images=self.icons,
                                  grid=(row, 0),
                                  tipTexts=tipTexts)

        if show_file:
            row += 1
            self.file_entry = LabeledEntry(self,
                                           label='File name',
                                           label_width=10,
                                           entry_width=40,
                                           returnCallback=self.setSelectedFile)
            self.file_entry.grid(row=row, column=0, sticky=Tkinter.EW)
        else:
            self.file_entry = None

        row += 1
        self.directory_entry = LabeledEntry(self,
                                            label='Directory',
                                            entry=directory,
                                            label_width=10,
                                            entry_width=40,
                                            returnCallback=self.entryDir)
        self.directory_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        row += 1
        subFrame = Frame(self, grid=(row, 0))
        subFrame.expandGrid(None, 6)

        if show_file:

            label = Label(subFrame, text='File type:', grid=(0, 0))

            type_labels = self.determineTypeLabels()
            self.fileType_menu = PulldownList(
                subFrame,
                callback=self.typeCallback,
                texts=type_labels,
                objects=self.file_types,
                grid=(0, 1),
                tipText='Restrict listed files to selected suffix')

        label = Label(subFrame, text=' Show hidden:', grid=(0, 2))

        self.hidden_checkbutton = CheckButton(
            subFrame,
            text='',
            selected=False,
            callback=self.updateFileList,
            grid=(0, 3),
            tipText='Show hidden files beginning with "." etc.')

        label = Label(subFrame, text='Dir path:', grid=(0, 4))

        self.pathMenu = PulldownList(
            subFrame,
            callback=self.dirCallback,
            objects=range(len(self.dirs)),
            texts=self.dirs,
            index=len(self.dirs) - 1,
            indent='  ',
            prefix=dirsep,
            grid=(0, 5),
            tipText='Directory navigation to current location')

        if show_file and self.manualFilter is not None:
            row += 1
            self.manual_filter_entry = LabeledEntry(
                self,
                label='Manual Select',
                entry=defaultFilter,
                label_width=13,
                entry_width=40,
                returnCallback=self.entryFilter,
                tipText=
                'Path specification with wildcards to select multiple files')
            self.manual_filter_entry.grid(row=row, column=0, sticky=Tkinter.EW)

        self.updateFileList()
        self.updateButtons()

        if file:
            self.setFile(file)
Beispiel #24
0
  def body(self, guiFrame):

    self.geometry('700x700')
   
    guiFrame.expandGrid(0,0)
    
    options = ['Peak Lists & Settings','Peak Intensity Comparison']
    tabbedFrame = TabbedFrame(guiFrame, options=options, callback=self.changeTab)
    tabbedFrame.grid(row=0, column=0, sticky='nsew')
    self.tabbedFrame = tabbedFrame
    frameA, frameB = tabbedFrame.frames

    row = 0
    frameA.grid_columnconfigure(1, weight=1)
    frameA.grid_columnconfigure(3, weight=1)
    frameA.grid_columnconfigure(5, weight=1)
    frameA.grid_rowconfigure(5, weight=1)

    tipText = 'Number of reference peaks (no saturation)'
    self.peaksALabel = Label(frameA, text='Number of Ref Peaks: ', tipText=tipText)
    self.peaksALabel.grid(row=1,column=0,columnspan=2,sticky='w')

    tipText = 'Number of NOE saturation peaks'
    self.peaksBLabel = Label(frameA, text='Number of Sat Peaks: ', tipText=tipText)
    self.peaksBLabel.grid(row=1,column=2,columnspan=2,sticky='w')

    tipText = 'Number of peaks in assigned list'
    self.peaksCLabel = Label(frameA, text='Number of Assign Peaks: ', tipText=tipText)
    self.peaksCLabel.grid(row=1,column=4,columnspan=2,sticky='w')
    
    tipText = 'Selects which peak list is considered the NOE intensity reference (no saturation)'
    specALabel = Label(frameA, text='Ref Peak List: ')
    specALabel.grid(row=0,column=0,sticky='w')
    self.specAPulldown = PulldownList(frameA, callback=self.setRefPeakList, tipText=tipText)
    self.specAPulldown.grid(row=0,column=1,sticky='w')

    tipText = 'Selects which peak list is considered as NOE saturated.'
    specBLabel = Label(frameA, text='Sat Peak List: ')
    specBLabel.grid(row=0,column=2,sticky='w')
    self.specBPulldown = PulldownList(frameA, callback=self.setSatPeakList, tipText=tipText)
    self.specBPulldown.grid(row=0,column=3,sticky='w')

    tipText = 'Selects a peak list with assignments to use as a positional reference'
    specCLabel = Label(frameA, text='Assignment Peak List: ')
    specCLabel.grid(row=0,column=4,sticky='w')
    self.specCPulldown = PulldownList(frameA, callback=self.setAssignPeakList, tipText=tipText)
    self.specCPulldown.grid(row=0,column=5,sticky='w')

    frame0a = Frame(frameA)
    frame0a.grid(row=2,column=0,columnspan=6,sticky='nsew')
    frame0a.grid_columnconfigure(9, weight=1)
    
    tipText = '1H ppm tolerance for matching assigned peaks to reference & NOE saturation peaks'
    tolHLabel   = Label(frame0a, text='Tolerances: 1H')
    tolHLabel.grid(row=0,column=0,sticky='w')
    self.tolHEntry = FloatEntry(frame0a,text='0.02', width=6, tipText=tipText)
    self.tolHEntry .grid(row=0,column=1,sticky='w')  

    tipText = '15N ppm tolerance for matching assigned peaks to reference & NOE saturation peaks'
    tolNLabel   = Label(frame0a, text=' 15N')
    tolNLabel .grid(row=0,column=2,sticky='w')   
    self.tolNEntry = FloatEntry(frame0a,text='0.1', width=6, tipText=tipText)
    self.tolNEntry .grid(row=0,column=3,sticky='w')   

    tipText = 'Whether to peak new peaks in reference & NOE saturated lists (at assignment locations)'
    label = Label(frame0a, text=' Pick new peaks?', grid=(0,4)) 
    self.pickPeaksSelect = CheckButton(frame0a, tipText=tipText,
                                       grid=(0,5), selected=True)

    tipText = 'Whether to assign peaks in the peaks in the reference & NOE saturation lists, if not already assigned'
    label = Label(frame0a, text=' Assign peaks?')
    label.grid(row=0,column=6,sticky='w')   
    self.assignSelect = CheckButton(frame0a, tipText=tipText)
    self.assignSelect.set(1)
    self.assignSelect.grid(row=0,column=7,sticky='w')    

    tipText = 'Whether to consider peak height or volume in the heteronuclear NOE calculation'
    intensLabel = Label(frame0a, text=' Intensity Type:')
    intensLabel .grid(row=0,column=8,sticky='w')   
    self.intensPulldown = PulldownList(frame0a, texts=['height','volume'],
                                       callback=self.setIntensityType,
                                       tipText=tipText)
    self.intensPulldown.grid(row=0,column=9,sticky='w')    

    divider = LabelDivider(frameA, text='Peaks', grid=(3,0),
                           gridSpan=(1,6))

    tipTexts = ['Show the selected intensity reference peaks in the below table',
                'Show the selected NOE saturation peaks in the below table',
                'Show the selected assigned peak list in the below table',
                'Show the displayed peaks in a separate peak table, where assignments etc. may be adjusted']
    texts    = ['Show Ref Peaks','Show Sat Peaks',
                'Show Assign Peaks', 'Separate Peak Table']
    commands = [self.viewRefPeakList, self.viewSatPeakList,
                self.viewAssignPeakList, self.viewSeparatePeakTable]
    self.viewPeaksButtons = ButtonList(frameA, expands=True, tipTexts=tipTexts,
                                       texts=texts, commands=commands)
    self.viewPeaksButtons.grid(row=4,column=0,columnspan=6,sticky='nsew')

    self.peakTable = PeakTableFrame(frameA, self.guiParent, grid=(5,0),
                                    gridSpan=(1,6))
    self.peakTable.bottomButtons1.grid_forget()
    self.peakTable.bottomButtons2.grid_forget()
    #self.peakTable.topFrame.grid_forget()
    self.peakTable.topFrame.grid(row=2, column=0, sticky='ew')
    # Next tab

    frameB.expandGrid(0,0)
    
    tipTexts = ['Row number',
                'Assignment annotation for NOE saturation peak',
                'Assignment annotation for reference peak (no saturation)',
                '1H chemical shift of NOE saturation peak',
                '1H chemical shift of reference peak',
                '15N chemical shift of NOE saturation peak',
                '15N chemical shift of reference peak',
                'The separation between compared peaks: square root of the sum of ppm differences squared',
                'The intensity if the NOE saturation peak',
                'The intensity of the reference peak (no saturation)',
                'Ratio of peak intensities: saturated over reference',
                'Residue(s) for reference peak']
    colHeadings      = ['#','Sat Peak','Ref Peak','1H shift A',
                        '1H shift B','15N shift A','15N shift B',
                        'Closeness\nScore','Intensity A','Intensity B',
                        'Intensity\nRatio','Residue']
    self.scrolledMatrix = ScrolledMatrix(frameB, multiSelect=True, 
                                         headingList=colHeadings,
                                         callback=self.selectCell,
                                         tipTexts=tipTexts,
                                         grid=(0,0),
                                         deleteFunc=self.removePair)

    tipTexts = ['Force a manual update of the table; pair-up NOE saturation and reference peaks according to assigned peak positions',
                'Remove the selected rows of peak pairs',
                'Show peaks corresponding to the selected row in a table',
                'Save the Heteronuclear NOE values in the CCPN project as a data list']
    texts    = ['Refresh Table','Remove Pairs',
                'Show Peak Pair','Create Hetero NOE List']
    commands = [self.matchPeaks,self.removePair,
                self.showPeakPair,self.makeNoeList]
    self.pairButtons = ButtonList(frameB, tipTexts=tipTexts, grid=(1,0),
                                  texts=texts, commands=commands)


    bottomButtons = UtilityButtonList(tabbedFrame.sideFrame, helpUrl=self.help_url)
    bottomButtons.grid(row=0, column=0, sticky='e')
    
    self.updatePulldowns()
    self.updateAfter()

    self.administerNotifiers(self.registerNotify)
Beispiel #25
0
class CingFrame(NmrSimRunFrame):

  def __init__(self, parent, application, *args, **kw):

    project = application.project
    simStore = project.findFirstNmrSimStore(application=APP_NAME) or \
               project.newNmrSimStore(application=APP_NAME, name=APP_NAME)

    self.application = application
    self.residue = None
    self.structure = None
    self.serverCredentials = None
    self.iCingBaseUrl = DEFAULT_URL
    self.resultsUrl = None
    self.chain = None
    self.nmrProject = application.nmrProject
    self.serverDone = False

    NmrSimRunFrame.__init__(self, parent, project, simStore, *args, **kw)

    # # # # # # New Structure Frame # # # # #

    self.structureFrame.grid_forget()

    tab = self.tabbedFrame.frames[0]

    frame = Frame(tab, grid=(1,0))
    frame.expandGrid(2,1)

    div = LabelDivider(frame, text='Structures', grid=(0,0), gridSpan=(1,2))

    label = Label(frame, text='Ensemble: ', grid=(1,0))
    self.structurePulldown = PulldownList(frame, callback=self.changeStructure, grid=(1,1))

    headingList = ['Model','Use']
    editWidgets      = [None,None]
    editGetCallbacks = [None,self.toggleModel]
    editSetCallbacks = [None,None,]
    self.modelTable = ScrolledMatrix(frame, grid=(2,0), gridSpan=(1,2),
                                     callback=self.selectStructModel,
                                     editWidgets=editWidgets,
                                     editGetCallbacks=editGetCallbacks,
                                     editSetCallbacks=editSetCallbacks,
                                     headingList=headingList)

    texts = ['Activate Selected','Inactivate Selected']
    commands = [self.activateModels, self.disableModels]
    buttons = ButtonList(frame, texts=texts, commands=commands, grid=(3,0), gridSpan=(1,2))


    # # # # # # Submission frame # # # # # #

    tab = self.tabbedFrame.frames[1]
    tab.expandGrid(1,0)

    frame = LabelFrame(tab, text='Server Job Submission', grid=(0,0))
    frame.expandGrid(None,2)

    srow = 0
    label = Label(frame, text='iCing URL:', grid=(srow, 0))
    urls = [DEFAULT_URL,]
    self.iCingBaseUrlPulldown = PulldownList(frame, texts=urls, objects=urls, index=0, grid=(srow,1))


    srow +=1
    label = Label(frame, text='Results File:', grid=(srow, 0))
    self.resultFileEntry = Entry(frame, bd=1, text='', grid=(srow,1), width=50)
    self.setZipFileName()
    button = Button(frame, text='Choose File', bd=1, sticky='ew',
                    command=self.chooseZipFile, grid=(srow, 2))

    srow +=1
    label = Label(frame, text='Results URL:', grid=(srow, 0))
    self.resultUrlEntry = Entry(frame, bd=1, text='', grid=(srow,1), width=50)
    button = Button(frame, text='View Results HTML', bd=1, sticky='ew',
                    command=self.viewHtmlResults, grid=(srow, 2))

    srow +=1
    texts    = ['Submit Project!', 'Check Run Status',
                'Purge Server Result', 'Download Results']
    commands = [self.runCingServer, self.checkStatus,
                self.purgeCingServer, self.downloadResults]

    self.buttonBar = ButtonList(frame, texts=texts, commands=commands,
                                grid=(srow, 0), gridSpan=(1,3))

    for button in self.buttonBar.buttons[:1]:
      button.config(bg=CING_BLUE)

    # # # # # # Residue frame # # # # # #

    frame = LabelFrame(tab, text='Residue Options', grid=(1,0))
    frame.expandGrid(1,1)

    label = Label(frame, text='Chain: ')
    label.grid(row=0,column=0,sticky='w')
    self.chainPulldown = PulldownList(frame, callback=self.changeChain)
    self.chainPulldown.grid(row=0,column=1,sticky='w')

    headingList = ['#','Residue','Linking','Decriptor','Use?']
    editWidgets      = [None,None,None,None,None]
    editGetCallbacks = [None,None,None,None,self.toggleResidue]
    editSetCallbacks = [None,None,None,None,None,]
    self.residueMatrix = ScrolledMatrix(frame,
                                        headingList=headingList,
                                        multiSelect=True,
                                        editWidgets=editWidgets,
                                        editGetCallbacks=editGetCallbacks,
                                        editSetCallbacks=editSetCallbacks,
                                        callback=self.selectResidue)
    self.residueMatrix.grid(row=1, column=0, columnspan=2, sticky = 'nsew')

    texts = ['Activate Selected','Inactivate Selected']
    commands = [self.activateResidues, self.deactivateResidues]
    self.resButtons = ButtonList(frame, texts=texts, commands=commands,)
    self.resButtons.grid(row=2, column=0, columnspan=2, sticky='ew')

    """
    # # # # # # Validate frame # # # # # #

    frame = LabelFrame(tab, text='Validation Options', grid=(2,0))
    frame.expandGrid(None,2)

    srow = 0
    self.selectCheckAssign = CheckButton(frame)
    self.selectCheckAssign.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckAssign.set(True)
    label = Label(frame, text='Assignments and shifts')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckResraint = CheckButton(frame)
    self.selectCheckResraint.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckResraint.set(True)
    label = Label(frame, text='Restraints')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckQueen = CheckButton(frame)
    self.selectCheckQueen.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckQueen.set(False)
    label = Label(frame, text='QUEEN')
    label.grid(row=srow,column=1,sticky='nw')

    srow += 1
    self.selectCheckScript = CheckButton(frame)
    self.selectCheckScript.grid(row=srow, column=0,sticky='nw' )
    self.selectCheckScript.set(False)
    label = Label(frame, text='User Python script\n(overriding option)')
    label.grid(row=srow,column=1,sticky='nw')

    self.validScriptEntry = Entry(frame, bd=1, text='')
    self.validScriptEntry.grid(row=srow,column=2,sticky='ew')

    scriptButton = Button(frame, bd=1,
                          command=self.chooseValidScript,
                          text='Browse')
    scriptButton.grid(row=srow,column=3,sticky='ew')
    """

    # # # # # # # # # #

    self.update(simStore)

    self.administerNotifiers(application.registerNotify)

  def downloadResults(self):

    if not self.run:
      msg = 'No current iCing run'
      showWarning('Failure', msg, parent=self)
      return

    credentials = self.serverCredentials
    if not credentials:
      msg = 'No current iCing server job'
      showWarning('Failure', msg, parent=self)
      return

    fileName = self.resultFileEntry.get()
    if not fileName:
      msg = 'No save file specified'
      showWarning('Failure', msg, parent=self)
      return

    if os.path.exists(fileName):
      msg = 'File %s already exists. Overwite?' % fileName
      if not showOkCancel('Query', msg, parent=self):
        return

    url = self.iCingBaseUrl
    iCingUrl = self.getServerUrl(url)
    logText = iCingRobot.iCingFetch(credentials, url, iCingUrl, fileName)
    print logText

    msg = 'Results saved to file %s\n' % fileName
    msg += 'Purge results from iCing server?'
    if showYesNo('Query',msg, parent=self):
      self.purgeCingServer()


  def getServerUrl(self, baseUrl):

    iCingUrl = os.path.join(baseUrl, 'icing/serv/iCingServlet')
    return iCingUrl

  def viewHtmlResults(self):

    resultsUrl = self.resultsUrl
    if not resultsUrl:
      msg = 'No current iCing results URL'
      showWarning('Failure', msg, parent=self)
      return

    webBrowser = WebBrowser(self.application, popup=self.application)
    webBrowser.open(self.resultsUrl)


  def runCingServer(self):

    if not self.project:
      return

    run = self.run
    if not run:
      msg = 'No CING run setup'
      showWarning('Failure', msg, parent=self)
      return

    structure = self.structure
    if not structure:
      msg = 'No structure ensemble selected'
      showWarning('Failure', msg, parent=self)
      return

    ensembleText = getModelsString(run)
    if not ensembleText:
      msg = 'No structural models selected from ensemble'
      showWarning('Failure', msg, parent=self)
      return

    residueText = getResiduesString(structure)
    if not residueText:
      msg = 'No active residues selected in structure'
      showWarning('Failure', msg, parent=self)
      return

    url = self.iCingBaseUrlPulldown.getObject()
    url.strip()
    if not url:
      msg = 'No iCing server URL specified'
      showWarning('Failure', msg, parent=self)
      self.iCingBaseUrl = None
      return

    msg = 'Submit job now? You will be informed when the job is done.'
    if not showOkCancel('Confirm', msg, parent=self):
      return

    self.iCingBaseUrl = url
    iCingUrl = self.getServerUrl(url)
    self.serverCredentials, results, tarFileName = iCingRobot.iCingSetup(self.project, userId='ccpnAp', url=iCingUrl)

    if not results:
      # Message already issued on failure
      self.serverCredentials = None
      self.resultsUrl = None
      self.update()
      return

    else:
      credentials = self.serverCredentials
      os.unlink(tarFileName)

    entryId = iCingRobot.iCingProjectName(credentials, iCingUrl).get(iCingRobot.RESPONSE_RESULT)
    baseUrl, htmlUrl, logUrl, zipUrl = iCingRobot.getResultUrls(credentials, entryId, url)

    self.resultsUrl = htmlUrl

    # Save server data in this run for persistence

    setRunParameter(run, iCingRobot.FORM_USER_ID, self.serverCredentials[0][1])
    setRunParameter(run, iCingRobot.FORM_ACCESS_KEY, self.serverCredentials[1][1])
    setRunParameter(run, ICING_BASE_URL, url)
    setRunParameter(run, HTML_RESULTS_URL, htmlUrl)
    self.update()

    run.inputStructures = structure.sortedModels()

    # select residues from the structure's chain
    #iCingRobot.iCingResidueSelection(credentials, iCingUrl, residueText)

    # Select models from ensemble
    #iCingRobot.iCingEnsembleSelection(credentials, iCingUrl, ensembleText)

    # Start the actual run
    self.serverDone = False
    iCingRobot.iCingRun(credentials, iCingUrl)

    # Fetch server progress occasionally, report when done
    # this function will call itself again and again
    self.after(CHECK_INTERVAL, self.timedCheckStatus)

    self.update()

  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 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 chooseZipFile(self):

    fileTypes = [  FileType('Zip', ['*.zip']), ]
    popup = FileSelectPopup(self, file_types=fileTypes, file=self.resultFileEntry.get(),
                            title='Results zip file location', dismiss_text='Cancel',
                            selected_file_must_exist=False)

    fileName = popup.getFile()

    if fileName:
      self.resultFileEntry.set(fileName)
    popup.destroy()

  def setZipFileName(self):

    zipFile = '%s_CING_report.zip' % self.project.name
    self.resultFileEntry.set(zipFile)

  def selectStructModel(self, model, row, col):

    self.model = model

  def selectResidue(self, residue, row, col):

    self.residue = residue

  def deactivateResidues(self):

    for residue in self.residueMatrix.currentObjects:
      residue.useInCing = False

    self.updateResidues()

  def activateResidues(self):

    for residue in self.residueMatrix.currentObjects:
      residue.useInCing = True

    self.updateResidues()

  def activateModels(self):

    if self.run:
      for model in self.modelTable.currentObjects:
        if model not in self.run.inputStructures:
          self.run.addInputStructure(model)

      self.updateModels()

  def disableModels(self):

    if self.run:
      for model in self.modelTable.currentObjects:
        if model in self.run.inputStructures:
          self.run.removeInputStructure(model)

      self.updateModels()

  def toggleModel(self, *opt):

    if self.model and self.run:
      if self.model in self.run.inputStructures:
        self.run.removeInputStructure(self.model)
      else:
        self.run.addInputStructure(self.model)

      self.updateModels()

  def toggleResidue(self, *opt):

    if self.residue:
      self.residue.useInCing = not self.residue.useInCing
      self.updateResidues()


  def updateResidues(self):

    if self.residue and (self.residue.topObject is not self.structure):
      self.residue = None

    textMatrix = []
    objectList = []
    colorMatrix = []

    if self.chain:
      chainCode = self.chain.code

      for residue in self.chain.sortedResidues():
        msResidue = residue.residue

        if not hasattr(residue, 'useInCing'):
          residue.useInCing = True

        if residue.useInCing:
          colors = [None, None, None, None, CING_BLUE]
          use = 'Yes'

        else:
          colors = [None, None, None, None, None]
          use = 'No'

        datum = [residue.seqCode,
                 msResidue.ccpCode,
                 msResidue.linking,
                 msResidue.descriptor,
                 use,]

        textMatrix.append(datum)
        objectList.append(residue)
        colorMatrix.append(colors)

    self.residueMatrix.update(objectList=objectList,
                              textMatrix=textMatrix,
                              colorMatrix=colorMatrix)


  def updateChains(self):

    index = 0
    names = []
    chains = []
    chain = self.chain

    if self.structure:
      chains = self.structure.sortedCoordChains()
      names = [chain.code for chain in chains]

      if chains:
        if chain not in chains:
          chain = chains[0]
          index = chains.index(chain)

        self.changeChain(chain)

    self.chainPulldown.setup(names, chains, index)


  def updateStructures(self):

    index = 0
    names = []
    structures = []
    structure = self.structure

    if self.run:
      model = self.run.findFirstInputStructure()
      if model:
        structure = model.structureEnsemble

      structures0 = [(s.ensembleId, s) for s in self.project.structureEnsembles]
      structures0.sort()

      for eId, structure in structures0:
        name = '%s:%s' % (structure.molSystem.code, eId)
        structures.append(structure)
        names.append(name)

    if structures:
      if structure not in structures:
        structure = structures[-1]

      index = structures.index(structure)

    self.changeStructure(structure)

    self.structurePulldown.setup(names, structures, index)


  def updateModels(self):

    textMatrix = []
    objectList = []
    colorMatrix = []

    if self.structure and self.run:
      used = self.run.inputStructures

      for model in self.structure.sortedModels():


        if model in used:
          colors = [None, CING_BLUE]
          use = 'Yes'

        else:
          colors = [None, None]
          use = 'No'

        datum = [model.serial,use]

        textMatrix.append(datum)
        objectList.append(model)
        colorMatrix.append(colors)

    self.modelTable.update(objectList=objectList,
                           textMatrix=textMatrix,
                           colorMatrix=colorMatrix)


  def changeStructure(self, structure):

    if self.project and (self.structure is not structure):
      self.project.currentEstructureEnsemble = structure
      self.structure = structure

      if self.run:
        self.run.inputStructures = structure.sortedModels()

      self.updateModels()
      self.updateChains()


  def changeChain(self, chain):

    if self.project and (self.chain is not chain):
      self.chain = chain
      self.updateResidues()

  def chooseValidScript(self):

    # Prepend default Cyana file extension below
    fileTypes = [  FileType('Python', ['*.py']), ]
    popup = FileSelectPopup(self, file_types = fileTypes,
                            title='Python file', dismiss_text='Cancel',
                            selected_file_must_exist = True)

    fileName = popup.getFile()
    self.validScriptEntry.set(fileName)
    popup.destroy()

  def updateAll(self, project=None):

    if project:
      self.project = project
      self.nmrProject = project.currentNmrProject
      simStore = project.findFirstNmrSimStore(application='CING') or \
                 project.newNmrSimStore(application='CING', name='CING')
    else:
      simStore = None

    if not self.project:
      return

    self.setZipFileName()
    if not self.project.currentNmrProject:
      name = self.project.name
      self.nmrProject = self.project.newNmrProject(name=name)
    else:
      self.nmrProject = self.project.currentNmrProject

    self.update(simStore)

  def update(self, simStore=None):

    NmrSimRunFrame.update(self, simStore)

    run = self.run
    urls = [DEFAULT_URL,]
    index = 0

    if run:
      userId = getRunParameter(run, iCingRobot.FORM_USER_ID)
      accessKey = getRunParameter(run, iCingRobot.FORM_ACCESS_KEY)
      if userId and accessKey:
        self.serverCredentials = [(iCingRobot.FORM_USER_ID, userId),
                                  (iCingRobot.FORM_ACCESS_KEY, accessKey)]

      url = getRunParameter(run, ICING_BASE_URL)
      if url:
        htmlUrl = getRunParameter(run, HTML_RESULTS_URL)
        self.iCingBaseUrl = url
        self.resultsUrl = htmlUrl # May be None

      self.resultUrlEntry.set(self.resultsUrl)

      if self.iCingBaseUrl and self.iCingBaseUrl not in urls:
        index = len(urls)
        urls.append(self.iCingBaseUrl)

    self.iCingBaseUrlPulldown.setup(urls, urls, index)

    self.updateButtons()
    self.updateStructures()
    self.updateModels()
    self.updateChains()

  def updateButtons(self, event=None):

    buttons = self.buttonBar.buttons
    if self.project and self.run:
      buttons[0].enable()

      if self.resultsUrl and self.serverCredentials:
        buttons[1].enable()
        buttons[2].enable()
        buttons[3].enable()

      else:
        buttons[1].disable()
        buttons[2].disable()
        buttons[3].disable()

    else:
      buttons[0].disable()
      buttons[1].disable()
      buttons[2].disable()
      buttons[3].disable()
Beispiel #26
0
  def body(self, mainFrame):

    mainFrame.grid_columnconfigure(1, weight=1, minsize=100)
    mainFrame.config(borderwidth=5, relief='solid')

    row = 0
    label = Label(mainFrame, text="Frame (with sub-widgets):")
    label.grid(row=row, column=0, sticky=Tkinter.E)

    frame = Frame(mainFrame, relief='raised', border=2, background='#8080D0')
    # Frame expands East-West
    frame.grid(row=row, column=1, sticky=Tkinter.EW)
    # Last column expands => Widgets pusted to the West
    frame.grid_columnconfigure(3, weight=1)
    
    # Label is within the sub frame
    label = Label(frame, text='label ')
    label.grid(row=0, column=0, sticky=Tkinter.W)
    
    entry = Entry(frame, text='Entry', returnCallback=self.showWarning)
    entry.grid(row=0, column=1, sticky=Tkinter.W)
    
    self.check = CheckButton(frame, text='Checkbutton', selected=True, callback=self.updateObjects)
    self.check.grid(row=0, column=2, sticky=Tkinter.W)
    
    # stick a button to the East wall
    button = Button(frame, text='Button', command=self.pressButton)
    button.grid(row=0, column=3, sticky=Tkinter.E)
  
    row += 1
    label = Label(mainFrame, text="Text:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    self.textWindow = Text(mainFrame, text='Initial Text\n', width=60, height=5)
    self.textWindow.grid(row=row, column=1, sticky=Tkinter.NSEW)
    
    row += 1
    label = Label(mainFrame, text="CheckButtons:")
    label.grid(row=row, column=0, sticky=Tkinter.E)

    entries = ['Alpha','Beta','Gamma','Delta']
    selected = entries[2:]
    self.checkButtons = CheckButtons(mainFrame, entries, selected=selected,select_callback=self.changedCheckButtons)
    self.checkButtons.grid(row=row, column=1, sticky=Tkinter.W)
  
    row += 1
    label = Label(mainFrame, text="PartitionedSelector:")
    label.grid(row=row, column=0, sticky=Tkinter.E)

    labels   = ['Bool','Int','Float','String']
    objects  = [type(0),type(1),type(1.0),type('a')]
    selected = [type('a')]
    self.partitionedSelector= PartitionedSelector(mainFrame, labels=labels,
                                                  objects=objects,
                                                  colors = ['red','yellow','green','#000080'],
                                                  callback=self.toggleSelector,selected=selected)
    self.partitionedSelector.grid(row=row, column=1, sticky=Tkinter.EW)

    row += 1
    label = Label(mainFrame, text="PulldownMenu")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    
    entries = ['Frodo','Pipin','Merry','Sam','Bill','Gandalf','Strider','Gimli','Legolas']
    self.pulldownMenu = PulldownMenu(mainFrame, callback=self.selectPulldown,
                                     entries=entries, selected_index=2,
                                     do_initial_callback=False)
    self.pulldownMenu.grid(row=row, column=1, sticky=Tkinter.W)

    row += 1
    label = Label(mainFrame, text="RadioButtons in a\nScrolledFrame.frame:")
    label.grid(row=row, column=0, sticky=Tkinter.EW)
    
    frame = ScrolledFrame(mainFrame, yscroll = False, doExtraConfig = True, width=100)
    frame.grid(row=row, column=1, sticky=Tkinter.EW)
    frame.grid_columnconfigure(0, weight=1)

    self.radioButtons = RadioButtons(frame.frame, entries=entries,
                                     select_callback=self.checkRadioButtons,
                                     selected_index=1, relief='groove')
    self.radioButtons.grid(row=0, column=0, sticky=Tkinter.W)
    
    row += 1
    label = Label(mainFrame, text="LabelFrame with\nToggleLabels inside:")
    label.grid(row=row, column=0, sticky=Tkinter.E)

    labelFrame = LabelFrame(mainFrame, text='Frame Title')
    labelFrame.grid(row=row, column=1, sticky=Tkinter.NSEW)
    labelFrame.grid_rowconfigure(0, weight=1)
    labelFrame.grid_columnconfigure(3, weight=1)
    
        
    self.toggleLabel1 = ToggleLabel(labelFrame, text='ScrolledMatrix', callback=self.toggleFrame1)
    self.toggleLabel1.grid(row=0, column=0, sticky=Tkinter.W)
    self.toggleLabel1.arrowOn()

    self.toggleLabel2 = ToggleLabel(labelFrame, text='ScrolledGraph', callback=self.toggleFrame2)
    self.toggleLabel2.grid(row=0, column=1, sticky=Tkinter.W)

    self.toggleLabel3 = ToggleLabel(labelFrame, text='ScrolledCanvas', callback=self.toggleFrame3)
    self.toggleLabel3.grid(row=0, column=2, sticky=Tkinter.W)
    
    row += 1
    mainFrame.grid_rowconfigure(row, weight=1)

    label = Label(mainFrame, text="changing/shrinking frames:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    
    self.toggleRow = row
    self.toggleFrame = Frame(mainFrame)
    self.toggleFrame.grid(row=row, column=1, sticky=Tkinter.NSEW)
    self.toggleFrame.grid_rowconfigure(0, weight=1)
    self.toggleFrame.grid_columnconfigure(0, weight=1)
    
    # option 1
    
    self.intEntry = IntEntry(self, returnCallback = self.setNumber, width=8)
    
    self.multiWidget = MultiWidget(self, Entry, options=None, 
                                  values=None, callback=self.setKeywords,
                                  minRows=3, maxRows=5)

    editWidgets      = [None, None, self.intEntry,  self.multiWidget]
    editGetCallbacks = [None, None, self.getNumber, self.getKeywords]
    editSetCallbacks = [None, None, self.setNumber, self.setKeywords]
    
    headingList = ['Name','Color','Number','Keywords']
    self.scrolledMatrix = ScrolledMatrix(self.toggleFrame, headingList=headingList,
                                         editSetCallbacks=editSetCallbacks,
                                         editGetCallbacks=editGetCallbacks,
                                         editWidgets=editWidgets,
                                         callback=self.selectObject,
                                         multiSelect=False) 
                                         
    self.scrolledMatrix.grid(row=0, column=0, sticky=Tkinter.NSEW)

    # option 2
    self.scrolledGraph = ScrolledGraph(self.toggleFrame, width=400,
                                       height=300, symbolSize=5,
                                       symbols=['square','circle'],
                                       dataColors=['#000080','#800000'],
                                       lineWidths=[0,1] )

    self.scrolledGraph.setZoom(1.3)

    dataSet1 = [[0,0],[1,1],[2,4],[3,9],[4,16],[5,25]]
    dataSet2 = [[0,0],[1,3],[2,6],[3,9],[4,12],[5,15]]
    self.scrolledGraph.update(dataSets=[dataSet1,dataSet2],
                              xLabel = 'X axis label',
                              yLabel = 'Y axis label',
                              title  = 'Main Title')
    self.scrolledGraph.draw()

    # option 3
    self.scrolledCanvas = ScrolledCanvas(self.toggleFrame,relief = 'groove', borderwidth = 2, resizeCallback=None)
    canvas = self.scrolledCanvas.canvas
    font   = 'Helvetica 10'
    box    = canvas.create_rectangle(10,10,150,200, outline='grey', fill='grey90')
    line   = canvas.create_line(0,0,200,200,fill='#800000', width=2)
    text   = canvas.create_text(120,50, text='Text', font=font, fill='black')
    circle = canvas.create_oval(30,30,50,50,outline='#008000',fill='#404040',width=3)
     
    row += 1
    label = Label(mainFrame, text="FloatEntry:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    self.floatEntry = FloatEntry(mainFrame, text=3.14159265, returnCallback=self.floatEntryReturn)
    self.floatEntry.grid(row=row, column=1, sticky=Tkinter.W)
    
     
    row += 1
    label = Label(mainFrame, text="Scale:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    self.scale = Scale(mainFrame, from_=10, to=90, value=50, orient=Tkinter.HORIZONTAL)
    self.scale.grid(row=row, column=1, sticky=Tkinter.W)

    row += 1
    label = Label(mainFrame, text="Value Ramp:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    self.valueRamp = ValueRamp(mainFrame, self.valueRampCallback, speed = 1.5, delay = 50)
    self.valueRamp.grid(row=row, column=1, sticky=Tkinter.W)
  

    row += 1
    label = Label(mainFrame, text="ButtonList:")
    label.grid(row=row, column=0, sticky=Tkinter.E)
    
    texts    = ['Select File','Close','Quit']
    commands = [self.selectFile, self.close, self.quit]
    bottomButtons = ButtonList(mainFrame, texts=texts, commands=commands, expands=True) 
    bottomButtons.grid(row=row, column=1, sticky=Tkinter.EW)
  
    self.protocol('WM_DELETE_WINDOW', self.quit)
Beispiel #27
0
class SaveLoadTab(object):
    '''The tab that lets the user FileSelect
       a file to open or to save.
    '''
    def __init__(self, parent, frame):
        '''Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        '''

        self.guiParent = parent
        self.frame = frame
        self.project = parent.project
        self.nmrProject = parent.nmrProject
        self.loadAndSaveButtons = None
        self.fileselectionBox = None
        self.body()

    def body(self):
        '''Setting up the body of this view.'''

        frame = self.frame

        file_types = [FileType('pyc', ['*.pyc'])]
        self.fileselectionBox = FileSelect(frame,
                                           multiSelect=False,
                                           file_types=file_types)
        self.fileselectionBox.grid(row=0,
                                   column=0,
                                   columnspan=6,
                                   sticky='nsew')

        texts = ['Load', 'Save']
        commands = [self.loadDataFromPyc, self.saveDataToPyc]
        self.loadAndSaveButtons = ButtonList(frame,
                                             commands=commands,
                                             texts=texts)
        self.loadAndSaveButtons.grid(row=1, column=0, sticky='nsew')

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

    def saveDataToPyc(self):
        '''Save the data to the selected file.'''

        if self.guiParent.connector.results:

            fileName = self.fileselectionBox.getFile()
            self.guiParent.connector.saveDataToPyc(fileName)
            self.fileselectionBox.updateFileList()

        else:

            string = ('''There are no results to save, '''
                      '''the algorithm has not run yet.''')

            showWarning('No Results to Save', string, parent=self.guiParent)

    def loadDataFromPyc(self):
        '''Load the data from the selected file.'''

        fileName = self.fileselectionBox.getFile()
        self.guiParent.connector.loadDataFromPyc(fileName)
        self.guiParent.resultsTab.update()
Beispiel #28
0
  def __init__(self, parent, project, path = None,
               molTypeEntries = None, chemCompEntries = None,
               selectedChemComps = None, selectLinking = None,
               *args, **kw):

    Frame.__init__(self, parent, *args, **kw)

    self.project = project
    self.molTypeEntries = molTypeEntries
    self.chemCompEntries = chemCompEntries
    self.selectLinking = selectLinking

    if (not path):
      path = getDataPath()

    self.path = path
      
    # Check if all chemComps available locally
    self.path_allChemComps = getChemCompArchiveDataDir()
    if not os.path.exists(self.path_allChemComps):
      self.path_allChemComps = None

    self.chemCompInfoDict = {}
    self.chemCompInfoList = []
    self.chemCompDownload = False
    self.chem_comps_shown = {}

    for entry in chemCompList:
      self.chemCompClasses[entry] = getattr(ccp.api.molecule.ChemComp, entry)

    self.grid_columnconfigure(0, weight=1)

    row = 0
    
    if (molTypeEntries is None):
      headerText = "Show residues (select molecular type(s)):"
    else:
      headerText = "Show %s residues:" % (str(molTypeEntries))
    
    #
    #
    # TODO TODO: HERE need to do some niftier stuff for displaying!
    #
    #
    
    headerTextWidget = Label(self, text = headerText)
    headerTextWidget.grid(row=row, column=0, sticky=Tkinter.W)
    row = row + 1

    if (molTypeEntries is None):
      self.mol_type_buttons = CheckButtons(self, entries=molTypeList,
                                select_callback=self.updateTables)
      self.mol_type_buttons.grid(row=row, column=0, sticky=Tkinter.EW)
      row = row + 1
    else:
      self.mol_type_buttons = None

    #
    # The chemComps to display...
    #
    
    self.showLocalText = 'Show local'
    self.showWebText = 'Show available via web'
    self.display_buttons = CheckButtons(self, entries=[self.showLocalText,self.showWebText],
                                              select_callback=self.updateTables,
                                              selected = [self.showLocalText])
    self.display_buttons.grid(row=row, column=0, sticky=Tkinter.EW)
    row = row + 1

    self.grid_rowconfigure(row, weight=2)
    headings = ('number', 'show details', 'molType', 'ccpCode', 'code1Letter', 'cifCode', 'name')
    editWidgets = 7 * [ None ]
    editGetCallbacks = [ None, self.toggleShow, None, None, None, None, None ]
    editSetCallbacks = 7 * [ None ]
    self.chem_comp_table = ScrolledMatrix(self, headingList=headings,
                                  editWidgets=editWidgets,
                                  editGetCallbacks=editGetCallbacks,
                                  editSetCallbacks=editSetCallbacks)
    self.chem_comp_table.grid(row=row, column=0, sticky=Tkinter.NSEW)

    row = row + 1
    texts = [ 'Show all in details window', 'Clear details window' ]
    commands = [ self.showAll, self.showNone ]
    buttons = ButtonList(self, texts=texts, commands=commands)
    buttons.grid(row=row, column=0, sticky=Tkinter.EW)
    
    row = row + 1

    separator = Separator(self,height = 3)
    separator.setColor('black', bgColor = 'black')
    separator.grid(row=row, column=0, sticky=Tkinter.EW)

    row = row + 1
    
    headerTextWidget = Label(self, text = "Select the residue variant:")
    headerTextWidget.grid(row=row, column=0, sticky=Tkinter.W)

    row = row + 1
    if (chemCompEntries is None):
      self.chem_comp_buttons = CheckButtons(self, entries=chemCompList,
                                 selected=('ChemComp',),
                                 select_callback=self.updateChemCompVarTable)
      self.chem_comp_buttons.grid(row=row, column=0, sticky=Tkinter.EW)
      row = row + 1
    else:
      self.chem_comp_buttons = None

    self.grid_rowconfigure(row, weight=1)
    headings = ('number', 'molType', 'ccpCode', 'linking', 'descriptor', 'molecularMass', 'formula', 'nonStereoSmiles', 'stereoSmiles')
    self.chem_comp_var_table = ScrolledMatrix(self, headingList=headings)
    self.chem_comp_var_table.grid(row=row, column=0, sticky=Tkinter.NSEW)
    self.chem_comp_var_headings = headings[1:]
    
    if selectedChemComps:
      for chemComp in selectedChemComps:
        key = (chemComp.molType, chemComp.ccpCode)
        self.chem_comps_shown[key] = 1

    self.updateTables()
class AssignMentTransferTab(object):
    '''the tab in the GUI where assignments
       can be transferred in bulk to the ccpn analysis
       project. A difference is made between two types
       of assignments:
           1) spin systems to residues, which also
              implies resonanceSets to atomSets.
           2) resonances to peak dimensions.
       The user is able to configure which assignments
       should be transferred to the project.

      Attributes:

          guiParent: gui object this tab is part of.

          frame: the frame in which this element lives.

          dataModel(src.cython.malandro.DataModel): dataModel
              object describing the assignment proposed by
              the algorithm.

          selectedSolution (int): The index of the solution/run
              that is used asa the template to make the assignments.

          resonanceToDimension (bool): True if resonances should
              be assigned to peak dimensions. False if not.

          spinSystemToResidue (bool): True if spin system to
              residue assignment should be carried out.

          minScore (float): The minimal score of a spin system
              assignment to a residue to be allowed
              to transfer this assignment to the project

          intra (bool): True if intra-residual peaks should be
              assigned.

          sequential (bool): True if sequential peaks should be
              assigned.

          noDiagonal (bool): If True, purely diagonal peaks are
              ignored during the transfer of assignments.

          allSpectra (bool): If True, all spectra will be assigned.
              If False, one specified spectrum will be assigned.

          spectrum (src.cython.malandro.Spectrum): The spectrum
              that should be assigned.
    '''

    def __init__(self, parent, frame):
        '''Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        '''

        self.guiParent = parent
        self.frame = frame

        # Buttons and fields,
        # will be set in body():
        self.peaksCheckButton = None
        self.residuesCheckButton = None
        self.intraCheckButton = None
        self.sequentialCheckButton = None
        self.noDiagonalCheckButton = None
        self.spinSystemTypeSelect = None
        self.minScoreEntry = None
        self.solutionNumberEntry = None
        self.spectrumSelect = None
        self.spectraPullDown = None
        self.assignedResidueStrategySelect = None
        self.transferButton = None

        # Settings that determine how assignments
        # are transferred to the analysis project:
        self.minScore = 80.0
        self.dataModel = None
        self.spectrum = None
        self.selectedSolution = 1
        self.body()
        self.resonanceToDimension = True
        self.spinSystemToResidue = True
        self.intra = True
        self.sequential = True
        self.noDiagonal = True
        self.allSpectra = True
        self.spinSystemType = 0
        self.strategy = 0


    def body(self):
        '''Describes the body of this tab. It consists
           out of a number of radio buttons, check buttons
           and number entries that allow the user to
           indicate which assignments should be transferred.
        '''

        # self.frame.expandColumn(0)
        self.frame.expandGrid(8, 0)
        self.frame.expandGrid(8, 1)

        typeOfAssignmentFrame = LabelFrame(
            self.frame, text='type of assignment')
        typeOfAssignmentFrame.grid(row=0, column=0, sticky='nesw')
        # typeOfAssignmentFrame.expandGrid(0,5)

        peakSelectionFrame = LabelFrame(
            self.frame, text='which peaks to assign')
        peakSelectionFrame.grid(row=0, column=1, sticky='nesw', rowspan=2)

        spinSystemSelectionFrame = LabelFrame(self.frame,
                                              text='Which spin-systems to use')
        spinSystemSelectionFrame.grid(row=2, column=0, sticky='nesw')

        tipText = 'What to do when a residue has already a spin system assigned to it.'
        assignedResidueFrame = LabelFrame(self.frame,
                                          text='if residue already has spin-system',
                                          tipText=tipText)
        assignedResidueFrame.grid(row=2, column=1, sticky='nesw')

        spectrumSelectionFrame = LabelFrame(self.frame, text='spectra')
        spectrumSelectionFrame.grid(row=1, column=0, sticky='nesw')

        row = 0

        Label(typeOfAssignmentFrame,
              text='Resonances to Peak Dimensions',
              grid=(row, 0))
        self.peaksCheckButton = CheckButton(typeOfAssignmentFrame,
                                            selected=True,
                                            grid=(row, 1))

        row += 1

        Label(typeOfAssignmentFrame,
              text='SpinSystems to Residues',
              grid=(row, 0))
        self.residuesCheckButton = CheckButton(
            typeOfAssignmentFrame, selected=True, grid=(row, 1))

        row = 0

        Label(peakSelectionFrame, text='Intra-Residual', grid=(row, 0))
        self.intraCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        row += 1

        Label(peakSelectionFrame, text='Sequential', grid=(row, 0))
        self.sequentialCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        row += 1

        Label(peakSelectionFrame,
              text='Do not assign diagonal peaks',
              grid=(row, 0))
        self.noDiagonalCheckButton = CheckButton(
            peakSelectionFrame, selected=True, grid=(row, 1))

        entries = ['Only assigned spin systems',
                   'All that have a score of at least: ',
                   'User Defined',
                   'Solution number:']
        tipTexts = ['Only assign resonances of spin systems that already have a sequential assignment for the assignment of peak dimensions. Spin system to residue assignment is not relevant in this case.',
                    'Assign all spin systems that have a score of at least a given percentage. 50% or lower is not possible, because than spin systems might have to be assigned to more than 1 residue, which is impossible.',
                    "As defined in the lower row of buttons in the 'results' tab.",
                    'One of the single solutions of the annealing.']
        self.spinSystemTypeSelect = RadioButtons(spinSystemSelectionFrame,
                                                 entries=entries, grid=(0, 0),
                                                 select_callback=None,
                                                 direction=VERTICAL,
                                                 gridSpan=(4, 1),
                                                 tipTexts=tipTexts)

        tipText = 'The minimal amount of colabelling the different nuclei should have in order to still give rise to a peak.'
        self.minScoreEntry = FloatEntry(spinSystemSelectionFrame,
                                        grid=(1, 1), width=7,
                                        text=str(self.minScore),
                                        returnCallback=self.changeMinScore,
                                        tipText=tipText)
        self.minScoreEntry.bind('<Leave>', self.changeMinScore, '+')

        self.solutionNumberEntry = IntEntry(spinSystemSelectionFrame,
                                            grid=(3, 1), width=7, text=1,
                                            returnCallback=self.solutionUpdate,
                                            tipText=tipText)
        self.solutionNumberEntry.bind('<Leave>', self.solutionUpdate, '+')

        #self.solutionPullDown = PulldownList(spinSystemSelectionFrame, None, grid=(3,1), sticky='w')

        entries = ['all spectra', 'only:']
        tipTexts = ['Assign peaks in all the spectra that where selected before the annealing ran.',
                    'Only assign peaks in one particular spectrum. You can of course repeat this multiple times for different spectra.']
        self.spectrumSelect = RadioButtons(spectrumSelectionFrame,
                                           entries=entries,
                                           grid=(0, 0),
                                           select_callback=None,
                                           direction=VERTICAL,
                                           gridSpan=(2, 1), tipTexts=tipTexts)

        self.spectraPullDown = PulldownList(spectrumSelectionFrame,
                                            self.changeSpectrum,
                                            grid=(1, 1), sticky='w')

        entries = ['skip this residue',
                   'de-assign old spin system from residue',
                   'assign, but never merge',
                   'warn to merge']
        tipTexts = ["Don't assign the new spin system to the residue. The residue is not skipped when the old spin system does not contain any resonances",
                    "De-assign old spin system from residue, unless the old spin system is a spin system without any resonances.",
                    "Don't merge any spin systems, merging can be performed later if nescesary in the Resonance --> SpinSystems window.",
                    "Ask to merge individually for each spin system, this might result in clicking on a lot of popups."]
        self.assignedResidueStrategySelect = RadioButtons(assignedResidueFrame,
                                                          entries=entries,
                                                          grid=(0, 0),
                                                          select_callback=None,
                                                          direction=VERTICAL,
                                                          gridSpan=(2, 1),
                                                          tipTexts=tipTexts)

        texts = ['Transfer Assignments']
        commands = [self.transferAssignments]
        self.transferButton = ButtonList(
            self.frame, commands=commands, texts=texts)
        self.transferButton.grid(row=5, column=0, sticky='nsew', columnspan=2)

    def update(self):
        '''Update the nescesary elements in the
           tab. Is called when the algorithm
           has produced possible assignments.
           The only thing that has to be updated
           in practice in this tab is the pulldown
           with spectra.
        '''

        self.dataModel = self.guiParent.connector.results
        self.updateSpectra()

    def setDataModel(self, dataModel):
        '''Here the dataModel, which is the dataModel
           containing the suggested assignments body
           the algorithm, can be set.
        '''

        self.dataModel = dataModel
        self.update()

    def updateSpectra(self, *opt):
        '''Updates the spectra shown in the spectra
           pulldown. These are only the spectra that
           were used by the algorithm. All other spectra
           in the project are not relevant since for those
           no simulated peaks have been matched to real
           peaks.
        '''

        if not self.dataModel:

            return

        spectrum = self.spectrum

        spectra = self.dataModel.getSpectra()

        if spectra:

            names = [spectrum.name for spectrum in spectra]
            index = 0

            if self.spectrum not in spectra:

                self.spectrum = spectra[0]

            else:

                index = spectra.index(self.spectrum)

        self.spectraPullDown.setup(names, spectra, index)

    def changeSpectrum(self, spectrum):
        '''Select a spectum to be assigned.'''

        self.spectrum = spectrum

    def solutionUpdate(self, event=None, value=None):
        '''Select a solution. A solution is a
           one to one mapping of spin systems
           to residues produced by one run of
           the algorithm.
               args: event: event object, this is
                            one of the values the number
                            entry calls his callback
                            function with.
                     value: the index of the solution/run.
        '''

        if not self.dataModel:

            return

        Nsolutions = len(self.dataModel.chain.residues[0].solutions)

        if value is None:

            value = self.solutionNumberEntry.get()

        if value == self.selectedSolution:
            return
        else:
            self.selectedSolution = value
        if value < 1:
            self.solutionNumberEntry.set(1)
            self.selectedSolution = 1
        elif value > Nsolutions:
            self.selectedSolution = Nsolutions
            self.solutionNumberEntry.set(self.selectedSolution)
        else:
            self.solutionNumberEntry.set(self.selectedSolution)

    def fetchOptions(self):
        '''Fetches user set options from the gui in
           one go and stores them in their corresponding
           instance variables.
        '''

        self.resonanceToDimension = self.peaksCheckButton.get()
        self.spinSystemToResidue = self.residuesCheckButton.get()
        self.intra = self.intraCheckButton.get()
        self.sequential = self.sequentialCheckButton.get()
        self.noDiagonal = self.noDiagonalCheckButton.get()
        self.spinSystemType = self.spinSystemTypeSelect.getIndex()
        self.strategy = ['skip', 'remove', 'noMerge', None][
            self.assignedResidueStrategySelect.getIndex()]
        self.allSpectra = [True, False][self.spectrumSelect.getIndex()]

    def changeMinScore(self, event=None):
        '''Set the minimal score for which a spin system
           to residue assignment gets transferred to the
           ccpn analysis project.
        '''

        newMinScore = self.minScoreEntry.get()

        if self.minScore != newMinScore:

            if newMinScore <= 50.0:

                self.minScore = 51.0
                self.minScoreEntry.set(51.0)

            elif newMinScore > 100.0:

                self.minScore = 100.0
                self.minScoreEntry.set(100.0)

            else:

                self.minScore = newMinScore

    def transferAssignments(self):
        '''Transfer assignments to project depending
           on the settings from the GUI.
        '''

        self.fetchOptions()

        if not self.dataModel or (not self.resonanceToDimension and not self.spinSystemToResidue):

            return

        strategy = self.strategy

        lookupSpinSystem = [self.getAssignedSpinSystem,
                            self.getBestScoringSpinSystem,
                            self.getUserDefinedSpinSystem,
                            self.getSelectedSolutionSpinSystem][self.spinSystemType]

        residues = self.dataModel.chain.residues

        spinSystemSequence = [lookupSpinSystem(res) for res in residues]

        ccpnSpinSystems = []
        ccpnResidues = []

        # if self.spinSystemType == 0 it means that it for sure already
        # assigned like this
        if self.spinSystemToResidue and not self.spinSystemType == 0:

            for spinSys, res in zip(spinSystemSequence, residues):

                if spinSys and res:

                    ccpnSpinSystems.append(spinSys.getCcpnResonanceGroup())
                    ccpnResidues.append(res.getCcpnResidue())

            assignSpinSystemstoResidues(ccpnSpinSystems,
                                        ccpnResidues,
                                        strategy=strategy,
                                        guiParent=self.guiParent)

        if self.resonanceToDimension:

            allSpectra = self.allSpectra

            if self.intra:

                for residue, spinSystem in zip(residues, spinSystemSequence):

                    if not spinSystem:

                        continue

                    intraLink = residue.getIntraLink(spinSystem)

                    for pl in intraLink.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum() is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()
                            assignResToDim(ccpnDimension, ccpnResonance)

            if self.sequential:

                for residue, spinSystemA, spinSystemB in zip(residues,
                                                             spinSystemSequence,
                                                             spinSystemSequence[1:]):

                    if not spinSystemA or not spinSystemB:

                        continue

                    link = residue.getLink(spinSystemA, spinSystemB)

                    for pl in link.getPeakLinks():

                        peak = pl.getPeak()

                        if not allSpectra and peak.getSpectrum() is not self.spectrum:

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

                        if self.noDiagonal and len(set(resonances)) < len(resonances):

                            continue

                        for resonance, dimension in zip(resonances, peak.getDimensions()):

                            ccpnResonance = resonance.getCcpnResonance()
                            ccpnDimension = dimension.getCcpnDimension()

                            assignResToDim(ccpnDimension, ccpnResonance)

        self.guiParent.resultsTab.update()

    def getAssignedSpinSystem(self, residue):
        '''Get the spinSystem that is assigned in the project
           to a residue.
           args:  residue (src.cython.malandro.Residue)
           return: spinSystem (src.cython.malandro.SpinSystem)
        '''

        ccpCode = residue.ccpCode
        seqCode = residue.getSeqCode()
        spinSystems = self.dataModel.getSpinSystems()[ccpCode]

        ccpnResidue = residue.getCcpnResidue()
        if ccpnResidue:
            assignedResonanceGroups = ccpnResidue.getResonanceGroups()
            if len(assignedResonanceGroups) > 1:
                print 'There is more than one spin system assigned to residue %s, did not know which one to use to assign peaks. Therefor this residue is skipped.' % (seqCode)
                return

            assignedResonanceGroup = ccpnResidue.findFirstResonanceGroup()

            if assignedResonanceGroup:

                for spinSystem in spinSystems:

                    if spinSystem.getSerial() == assignedResonanceGroup.serial:
                        # Just checking to make sure, analysis project could
                        # have changed
                        if not self.skipResidue(residue, spinSystem):

                            return spinSystem

    def getBestScoringSpinSystem(self, residue):
        '''Get the spinSystem that scores the highest,
           i.e. is assigned in most of the runs to the
           given residue.
           args:  residue (src.cython.malandro.Residue)
           return: spinSystem (src.cython.malandro.SpinSystem)
        '''

        solutions = residue.solutions
        weigth = 1.0 / len(solutions)
        score, bestSpinSystem = max([(solutions.count(solution) * weigth * 100.0, solution) for solution in solutions])

        if score >= self.minScore and not bestSpinSystem.getIsJoker() and not self.skipResidue(residue, bestSpinSystem):

            return bestSpinSystem

        return None

    def getUserDefinedSpinSystem(self, residue):
        '''Get the spinSystem that is defined by the user
           (probably in the resultsTab) as the correct
           assignment of the given residue.
           args:  residue (src.cython.malandro.Residue)
           return: spinSystem (src.cython.malandro.SpinSystem)
        '''

        userDefinedSpinSystem = residue.userDefinedSolution

        if userDefinedSpinSystem and not userDefinedSpinSystem.getIsJoker() and not self.skipResidue(residue, userDefinedSpinSystem):

            return userDefinedSpinSystem

        return None

    def getSelectedSolutionSpinSystem(self, residue):
        '''I a solution corresponding to one specific run
           of the algorithm is defined, return which spinSystem
           in that run got assigned to the given residue.
           args:  residue (src.cython.malandro.Residue)
           return: spinSystem (src.cython.malandro.SpinSystem)
        '''

        solutions = residue.solutions

        spinSystem = solutions[self.selectedSolution - 1]

        if not spinSystem.getIsJoker() and not self.skipResidue(residue, spinSystem):

            return spinSystem

        return None

    def skipResidue(self, residue, spinSystem):
        '''One strategy is to skip all residues that
           already have a spin system assignment.
           If that is the case determine whether to
           skip the given residue.
           args: residue (src.cython.malandro.Residue)
                 spinSystem (src.cython.malandro.SpinSystem)
           return: boolean, True if residue should be skipped.
        '''

        if self.strategy == 0:

            assignedGroups = residue.getCcpnResidue().getResonanceGroups()
            assignedSerials = set([spinSys.serial for spinSys in assignedGroups])

            if assignedSerials and spinSystem.getSerial() not in assignedSerials:

                return True

        return False
  def body(self, guiFrame):

    self.geometry("500x500")

    self.nameEntry  = Entry(self, text='', returnCallback=self.setName,    width=12)
    self.detailsEntry = Entry(self, text='', returnCallback=self.setDetails, width=16)
    self.valueEntry = FloatEntry(self, text='', returnCallback=self.setValue, width=10)
    self.errorEntry = FloatEntry(self, text='', returnCallback=self.setError, width=8)
    
    self.conditionNamesPulldown = PulldownList(self, callback=self.setConditionName,
                                               texts=self.getConditionNames())
    self.unitPulldown = PulldownList(self, callback=self.setUnit,
                                     texts=self.getUnits())
    self.experimentPulldown = PulldownList(self, callback=self.setExperiment)

    guiFrame.grid_columnconfigure(0, weight=1)

    row = 0
    frame = Frame(guiFrame, grid=(row, 0))
    frame.expandGrid(None,0)
    div = LabelDivider(frame, text='Current Series', grid=(0, 0))
    utilButtons = UtilityButtonList(frame, helpUrl=self.help_url, grid=(0,1))

    row += 1
    frame0 = Frame(guiFrame, grid=(row, 0))
    frame0.expandGrid(0,0)
    tipTexts = ['The serial number of the experiment series, but left blank if the series as actually a pseudo-nD experiment (with a sampled non-frequency axis)',
                'The name of the experiment series, which may be a single pseudo-nD experiment',
                'The number of separate experiments (and hence spectra) present in the series',
                'The kind of quantity that varies for different experiments/planes within the NMR series, e.g. delay time, temperature, ligand concentration etc.',
                'The number of separate points, each with a separate experiment/plane and parameter value, in the series']
    headingList      = ['#','Name','Experiments','Parameter\nVaried','Num\nPoints']
    editWidgets      = [None, self.nameEntry, None, self.conditionNamesPulldown, None]
    editGetCallbacks = [None, self.getName,   None, self.getConditionName, None]
    editSetCallbacks = [None, self.setName,   None, self.setConditionName, None]
    self.seriesMatrix = ScrolledMatrix(frame0, tipTexts=tipTexts,
                                       editSetCallbacks=editSetCallbacks,
                                       editGetCallbacks=editGetCallbacks,
                                       editWidgets=editWidgets,
                                       headingList=headingList,
                                       callback=self.selectExpSeries,
                                       deleteFunc=self.deleteExpSeries,
                                       grid=(0,0), gridSpan=(None, 3))

    tipTexts = ['Make a new, blank NMR series specification in the CCPN project',
                'Delete the selected NMR series from the project, although any component experiments remain. Note you cannot delete pseudo-nD series; delete the actual experiment instead',
                'Colour the spectrum contours for each experiment in the selected series (not pseudo-nD) using a specified scheme']
    texts    = ['Add Series','Delete Series',
                'Auto Colour Spectra']
    commands = [self.addExpSeries,self.deleteExpSeries,
                self.autoColorSpectra]
                
    self.seriesButtons = ButtonList(frame0, texts=texts, commands=commands,
                                    grid=(1,0), tipTexts=tipTexts)

    label = Label(frame0, text='Scheme:', grid=(1,1))
    
    tipText = 'Selects which colour scheme to apply to the contours of (separate) experiments within an NMR series'
    self.colorSchemePulldown = PulldownList(frame0, grid=(1,2), tipText=tipText)

    row += 1
    div = LabelDivider(guiFrame, text='Experimental Parameters & Conditions', grid=(row, 0))

    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    frame1 = Frame(guiFrame, grid=(row, 0))
    frame1.expandGrid(0,0)
    tipTexts = ['The kind of experimental parameter that is being used to define the NMR series',
                'The experiment that corresponds to the specified parameter value; can be edited from an arbitrary initial experiment',
                'The numeric value of the parameter (condition) that relates to the experiment or point in the NMR series',
                'The estimated error in value of the condition',
                'The measurement unit in which the value of the condition is represented']
    headingList      = ['Parameter','Experiment','Value','Error','Unit']
    editWidgets      = [None,self.experimentPulldown,self.valueEntry,self.errorEntry, self.unitPulldown]
    editGetCallbacks = [None,self.getExperiment,     self.getValue,  self.getError,   self.getUnit]
    editSetCallbacks = [None,self.setExperiment,     self.setValue,  self.setError,   self.setUnit]
    self.conditionPointsMatrix = ScrolledMatrix(frame1, grid=(0,0), tipTexts=tipTexts,
                                                editSetCallbacks=editSetCallbacks,
                                                editGetCallbacks=editGetCallbacks,
                                                editWidgets=editWidgets,
                                                headingList=headingList,
                                                callback=self.selectConditionPoint,
                                                deleteFunc=self.deleteConditionPoint)
    
    self.conditionPointsMatrix.doEditMarkExtraRules = self.conditionTableShow 
    tipTexts = ['Add a new point to the NMR series with an associated parameter value and experiment',
                'Remove the selected point from the series, including any associated parameter value',
                'For appropriate kinds of NMR series, set or unset a point as representing the plane to use as a reference']
    texts    = ['Add Series Point','Delete Series Point','Set/Unset Ref Plane']
    commands = [self.addConditionPoint,self.deleteConditionPoint,self.setSampledReferencePlane]
    self.conditionPointsButtons = ButtonList(frame1, texts=texts, commands=commands,
                                             tipTexts=tipTexts, grid=(1,0))
    
    self.updateAfter()
    self.updateColorSchemes()

    self.administerNotifiers(self.registerNotify)
class editResidueTypePopup(BasePopup):
    '''
    The main popup that is shown when the macro is loaded.
    '''

    def __init__(self, parent, *args, **kw):

        self.font = 'Helvetica 10'
        self.sFont = 'Helvetica %d'
        self.project = parent.project
        self.guiParent = parent
        self.chemCompDict = {}
        self.createChemCompDict()
        self.waiting = False
        BasePopup.__init__(self, parent,
                           title="Residue Type Probabilities", **kw)

    def open(self):

        self.updateAfter()
        BasePopup.open(self)

    def body(self, guiFrame):
        '''Describes where all the GUI element are.'''

        self.geometry('400x500')
        guiFrame.expandGrid(0, 0)
        tableFrame = Frame(guiFrame)
        tableFrame.grid(row=0, column=0, sticky='nsew', )
        tableFrame.expandGrid(0, 0)
        buttonFrame = Frame(guiFrame)
        buttonFrame.grid(row=1, column=0, sticky='nsew', )
        headingList = ['Spinsystem Number', 'Assignment', 'Residue Type Probs']
        self.table = ScrolledMatrix(tableFrame, headingList=headingList,
                                    callback=self.updateSpinSystemSelection,
                                    multiSelect=True)
        self.table.grid(row=0, column=0, sticky='nsew')
        texts = ['Add Prob']
        commands = [self.addProb]
        self.AddProbButton = ButtonList(buttonFrame, commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=0, sticky='nsew')
        texts = ['Remove Prob']
        commands = [self.removeProb]
        self.AddProbButton = ButtonList(buttonFrame, commands=commands,
                                        texts=texts)
        self.AddProbButton.grid(row=0, column=2, sticky='nsew')
        selectCcpCodes = sorted(self.chemCompDict.keys())
        tipText = 'select ccpCode'
        self.selectCcpCodePulldown = PulldownList(buttonFrame,
                                                  texts=selectCcpCodes,
                                                  grid=(0, 1),
                                                  tipText=tipText)

        selectCcpCodes = ['All Residue Types']

        tipText = 'select ccpCode'
        self.selectCcpCodeRemovePulldown = PulldownList(buttonFrame,
                                                        texts=selectCcpCodes,
                                                        index=0,
                                                        grid=(0, 3),
                                                        tipText=tipText)
        self.updateTable()

    def updateSpinSystemSelection(self, obj, row, col):
        '''Called after selectin a row in the table.'''
        self.updateRemoveCcpCodePullDown()

    def updateRemoveCcpCodePullDown(self):
        '''Updates the pulldown showing all current residueTypeProbs
           for a resonanceGroup that can be removed.

        '''

        removeCcpCodes = []
        for spinSystem in self.table.currentObjects:
            removeCcpCodes.extend([typeProp.possibility.ccpCode for typeProp in spinSystem.getResidueTypeProbs()])
        removeCcpCodes = ['All Residue Types'] + list(set(removeCcpCodes))
        self.selectCcpCodeRemovePulldown.setup(texts=removeCcpCodes,
                                               objects=removeCcpCodes,
                                               index=0)

    def getSpinSystems(self):
        '''Get resonanceGroups (spin systems) in the project.'''
        return self.nmrProject.resonanceGroups

    def addProb(self):
        '''Add the residue type selected in the selectCcpCodePulldown
           as an residueTypeProb.

        '''
        ccpCode = self.selectCcpCodePulldown.object
        for spinSystem in self.table.currentObjects:
            if ccpCode not in [typeProp.possibility.ccpCode for typeProp in spinSystem.getResidueTypeProbs()]:
                chemComp = self.chemCompDict.get(ccpCode)
                spinSystem.newResidueTypeProb(possibility=chemComp)
        self.updateTable()
        self.updateRemoveCcpCodePullDown()

    def removeProb(self):
        '''Removes the residueTypeProb selected in the
           selectCcpCodeRemovePulldown from the selected resonanceGroup.

        '''
        ccpCode = self.selectCcpCodeRemovePulldown.object
        for spinSystem in self.table.currentObjects:
            residueTypeProbs = spinSystem.getResidueTypeProbs()
            for typeProb in residueTypeProbs:
                if ccpCode == 'All Residue Types' or ccpCode == typeProb.possibility.ccpCode:
                    typeProb.delete()
        self.updateTable()
        self.updateRemoveCcpCodePullDown()

    def createChemCompDict(self):
        '''Make a list of all amino acid types present in any of the
           molecular chains present in the project.

        '''
        chains = self.getChains()
        for chain in chains:
            for residue in chain.sortedResidues():
                if residue.ccpCode not in self.chemCompDict:
                    self.chemCompDict[residue.ccpCode] = residue.chemCompVar.chemComp

    def getChains(self):
        '''Get all molecular chains stored in the project.'''
        chains = []
        if self.project:
            for molSystem in self.project.sortedMolSystems():
                for chain in molSystem.sortedChains():
                    if chain.residues:
                        chains.append(chain)
        return chains

    def updateTable(self):
        '''Update the whole table.'''
        objectList = []
        data = []
        for spinSystem in self.getSpinSystems():
            objectList.append(spinSystem)
            residueTypeProbs = spinSystem.getResidueTypeProbs()
            spinSystemInfo = self.getStringDescriptionOfSpinSystem(spinSystem)
            probString = ''
            for typeProp in residueTypeProbs:
                probString += typeProp.possibility.ccpCode + ' '
            data.append([spinSystem.serial, spinSystemInfo, probString])
        self.table.update(objectList=objectList, textMatrix=data)

    def getStringDescriptionOfSpinSystem(self, spinsys):
        '''Get a simple identifier for the assignment status of a
           resonanceGroup.

        '''

        spinSystemInfo = ''
        if spinsys.residue:
            spinSystemInfo += str(spinsys.residue.seqCode) + ' ' + spinsys.residue.ccpCode
        elif spinsys.residueProbs:
            for residueProb in spinsys.residueProbs:
                res = residueProb.possibility
                spinSystemInfo += '{} {}? /'.format(res.seqCode, res.ccpCode)
            spinSystemInfo = spinSystemInfo[:-1]
        elif spinsys.ccpCode:
            spinSystemInfo += spinsys.ccpCode
        return spinSystemInfo
Beispiel #32
0
    def body(self, guiFrame):

        row = 0
        col =0
#    frame = Frame( guiFrame )
#    frame.grid(row=row, column=col, sticky='news')
        self.menuBar = Menu( guiFrame)
        self.menuBar.grid( row=row, column=col, sticky='ew')

        #----------------------------------------------------------------------------------
        # Project frame
        #----------------------------------------------------------------------------------

#    guiFrame.grid_columnconfigure(row, weight=1)
#    frame = LabelFrame(guiFrame, text='Project', font=medFont)
        row = +1
        col =0
        frame = LabelFrame(guiFrame, text='Project', **labelFrameAttributes )
        print '>', frame.keys()
        frame.grid(row=row, column=col, sticky='nsew' )
        frame.grid_columnconfigure(2, weight=1)
#    frame.grid_rowconfigure(0, weight=1)

        srow = 0
        self.projectOptions = ['old','new from PDB','new from CCPN','new from CYANA']
        self.projOptionsSelect = RadioButtons(frame, selected_index=0, entries=self.projectOptions, direction='vertical',
                                              select_callback=self.updateGui
                                             )
        self.projOptionsSelect.grid(row=srow,column=0,rowspan=len(self.projectOptions),columnspan=2, sticky='w')

        if self.options.name: 
            text = self.options.name
        else: 
            text=''
        # end if
        self.projEntry = Entry(frame, bd=1, text=text, returnCallback=self.updateGui)
        self.projEntry.grid(row=srow,column=2,columnspan=2,sticky='ew')
#    self.projEntry.bind('<Key>', self.updateGui)
        self.projEntry.bind('<Leave>', self.updateGui)

        projButton = Button(frame, bd=1,command=self.chooseOldProjectFile, text='browse')
        projButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.pdbEntry = Entry(frame, bd=1, text='')
        self.pdbEntry.grid(row=srow,column=2,sticky='ew')
        self.pdbEntry.bind('<Leave>', self.updateGui)

        pdbButton = Button(frame, bd=1,command=self.choosePdbFile, text='browse')
        pdbButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.ccpnEntry = Entry(frame, bd=1, text='')
        self.ccpnEntry.grid(row=srow,column=2,sticky='ew')
        self.ccpnEntry.bind('<Leave>', self.updateGui)

        ccpnButton = Button(frame, bd=1,command=self.chooseCcpnFile, text='browse')
        ccpnButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.cyanaEntry = Entry(frame, bd=1, text='')
        self.cyanaEntry.grid(row=srow,column=2,sticky='ew')
        self.cyanaEntry.bind('<Leave>', self.updateGui)

        cyanaButton = Button(frame, bd=1,command=self.chooseCyanaFile, text='browse')
        cyanaButton.grid(row=srow,column=3,sticky='ew')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        label = Label(frame, text='Project name:')
        label.grid(row=srow,column=0,sticky='nw')
        self.nameEntry = Entry(frame, bd=1, text='')
        self.nameEntry.grid(row=srow,column=2,sticky='w')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        self.openProjectButton = Button(frame, command=self.openProject, text='Open Project', **actionButtonAttributes )
        self.openProjectButton.grid(row=srow,column=0, columnspan=4, sticky='ew')


        #----------------------------------------------------------------------------------
        # status
        #----------------------------------------------------------------------------------
#    guiFrame.grid_columnconfigure(1, weight=0)
        srow = 0
        frame = LabelFrame(guiFrame, text='Status', **labelFrameAttributes)
        frame.grid( row=srow, column=1, sticky='wnes')
        self.projectStatus = Text(frame, height=11, width=70, borderwidth=0, relief='flat')
        self.projectStatus.grid(row=0, column=0, sticky='wen')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        self.closeProjectButton = Button(frame, command=self.closeProject, text='Close Project', **actionButtonAttributes)
        self.closeProjectButton.grid(row=srow,column=0, columnspan=4, sticky='ew')

        #----------------------------------------------------------------------------------
        # Validate frame
        #----------------------------------------------------------------------------------

        row +=1
        col=0
        frame = LabelFrame(guiFrame, text='Validate', **labelFrameAttributes)
#    frame = LabelFrame(guiFrame, text='Validate', font=medFont)
        frame.grid(row=row, column=col, sticky='nsew')
#    frame.grid_columnconfigure(2, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        srow = 0
#    label = Label(frame, text='validation')
#    label.grid(row=srow,column=0,sticky='nw')
#
#    self.selectDoValidation = CheckButton(frame)
#    self.selectDoValidation.grid(row=srow, column=1,sticky='nw' )
#    self.selectDoValidation.set(True)
#
#    srow += 1
#    label = Label(frame, text='')
#    label.grid(row=srow,column=0,sticky='nw')
#
#    srow += 1
        label = Label(frame, text='checks')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectCheckAssign = CheckButton(frame)
        self.selectCheckAssign.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckAssign.set(True)
        label = Label(frame, text='assignments and shifts')
        label.grid(row=srow,column=2,sticky='nw')


#    srow += 1
#    self.selectCheckQueen = CheckButton(frame)
#    self.selectCheckQueen.grid(row=srow, column=4,sticky='nw' )
#    self.selectCheckQueen.set(False)
#    label = Label(frame, text='QUEEN')
#    label.grid(row=srow,column=5,sticky='nw')
#
#    queenButton = Button(frame, bd=1,command=None, text='setup')
#    queenButton.grid(row=srow,column=6,sticky='ew')


        srow += 1
        self.selectCheckResraint = CheckButton(frame)
        self.selectCheckResraint.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckResraint.set(True)
        label = Label(frame, text='restraints')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectCheckStructure = CheckButton(frame)
        self.selectCheckStructure.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckStructure.set(True)
        label = Label(frame, text='structural')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectMakeHtml = CheckButton(frame)
        self.selectMakeHtml.grid(row=srow, column=1,sticky='nw' )
        self.selectMakeHtml.set(True)
        label = Label(frame, text='generate HTML')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectCheckScript = CheckButton(frame)
        self.selectCheckScript.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckScript.set(False)
        label = Label(frame, text='user script')
        label.grid(row=srow,column=0,sticky='nw')

        self.validScriptEntry = Entry(frame, bd=1, text='')
        self.validScriptEntry.grid(row=srow,column=2,columnspan=3, sticky='ew')

        scriptButton = Button(frame, bd=1,command=self.chooseValidScript, text='browse')
        scriptButton.grid(row=srow,column=5,sticky='ew')

        srow += 1
        label = Label(frame, text='ranges')
        label.grid(row=srow,column=0,sticky='nw')
        self.rangesEntry = Entry( frame, text='' )
        self.rangesEntry.grid( row=srow, column=2, columnspan=3, sticky='ew')

#    self.validScriptEntry = Entry(frame, bd=1, text='')
#    self.validScriptEntry.grid(row=srow,column=3,sticky='ew')
#
#    scriptButton = Button(frame, bd=1,command=self.chooseValidScript, text='browse')
#    scriptButton.grid(row=srow,column=4,sticky='ew')


        srow += 1
        texts    = ['Run Validation','View Results','Setup QUEEN']
        commands = [self.runCing, None, None]
        buttonBar = ButtonList(frame, texts=texts, commands=commands,expands=True)
        buttonBar.grid(row=srow, column=0, columnspan=6, sticky='ew')
        for button in buttonBar.buttons:
            button.config(**actionButtonAttributes)
        # end for
        self.runButton = buttonBar.buttons[0]
        self.viewResultButton = buttonBar.buttons[1]
        self.queenButton = buttonBar.buttons[2]

        #----------------------------------------------------------------------------------
        # Miscellaneous frame
        #----------------------------------------------------------------------------------

        row +=0
        col=1
#    frame = LabelFrame(guiFrame, text='Miscellaneous', font=medFont)
        frame = LabelFrame(guiFrame, text='Miscellaneous', **labelFrameAttributes)
        frame.grid(row=row, column=col, sticky='news')
        frame.grid_columnconfigure(2, weight=1)
        frame.grid_columnconfigure(4, weight=1,minsize=30)
        frame.grid_rowconfigure(0, weight=1)

        # Exports

        srow = 0
        label = Label(frame, text='export to')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectExportXeasy = CheckButton(frame)
        self.selectExportXeasy.grid(row=srow, column=1,sticky='nw' )
        self.selectExportXeasy.set(True)
        label = Label(frame, text='Xeasy, Sparky, TALOS, ...')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportCcpn = CheckButton(frame)
        self.selectExportCcpn.grid(row=srow, column=1,sticky='nw' )
        self.selectExportCcpn.set(True)
        label = Label(frame, text='CCPN')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportQueen = CheckButton(frame)
        self.selectExportQueen.grid(row=srow, column=1,sticky='nw' )
        self.selectExportQueen.set(True)
        label = Label(frame, text='QUEEN')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportRefine = CheckButton(frame)
        self.selectExportRefine.grid(row=srow, column=1,sticky='nw' )
        self.selectExportRefine.set(True)
        label = Label(frame, text='refine')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        # User script

        srow += 1
        label = Label(frame, text='user script')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectMiscScript = CheckButton(frame)
        self.selectMiscScript.grid(row=srow, column=1,sticky='nw' )
        self.selectMiscScript.set(False)

        self.miscScriptEntry = Entry(frame, bd=1, text='')
        self.miscScriptEntry.grid(row=srow,column=3,sticky='ew')

        script2Button = Button(frame, bd=1,command=self.chooseMiscScript, text='browse')
        script2Button.grid(row=srow,column=4,sticky='ew')

        srow += 1
        texts    = ['Export','Run Script']
        commands = [None, None]
        buttonBar = ButtonList(frame, texts=texts, commands=commands,expands=True)
        buttonBar.grid(row=srow, column=0, columnspan=5, sticky='ew')
        for button in buttonBar.buttons:
            button.config(**actionButtonAttributes)
        # end for
        self.exportButton = buttonBar.buttons[0]
        self.scriptButton = buttonBar.buttons[1]

        #----------------------------------------------------------------------------------
        # Textarea
        #----------------------------------------------------------------------------------
        row +=1
        guiFrame.grid_rowconfigure(row, weight=1)
        self.outputTextBox = ScrolledText(guiFrame)
        self.outputTextBox.grid(row=row, column=0, columnspan=2, sticky='nsew')

        self.redirectConsole()

        #----------------------------------------------------------------------------------
        # Buttons
        #----------------------------------------------------------------------------------
        row +=1
        col=0
        texts    = ['Quit', 'Help']
        commands = [self.close, None]
        self.buttonBar = ButtonList(guiFrame, texts=texts, commands=commands,expands=True)
        self.buttonBar.grid(row=row, column=col, columnspan=2, sticky='ew')

#    self.openProjectButton = self.buttonBar.buttons[0]
#    self.closeProjectButton = self.buttonBar.buttons[1]
#    self.runButton = self.buttonBar.buttons[0]
#    self.viewResultButton = self.buttonBar.buttons[1]

        for button in self.buttonBar.buttons:
            button.config(**actionButtonAttributes)
Beispiel #33
0
    def __init__(self,
                 parent,
                 initial_list=None,
                 width=60,
                 height=5,
                 xscroll=True,
                 yscroll=True,
                 addDeleteButtons=False,
                 selectmode=Tkinter.BROWSE,
                 exportselection=0,
                 select_callback=None,
                 double_callback=None,
                 list_background='white',
                 *args,
                 **kw):

        if (initial_list is None):
            initial_list = []

        apply(Frame.__init__, (self, parent) + args, kw)

        self.selectmode = selectmode

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        listbox = Tkinter.Listbox(self,
                                  width=width,
                                  height=height,
                                  background=list_background,
                                  selectmode=selectmode,
                                  exportselection=exportselection)
        listbox.grid(row=0, column=0, sticky=Tkinter.NSEW)

        if (xscroll):
            xscrollbar = Tkinter.Scrollbar(self, orient=Tkinter.HORIZONTAL)
            xscrollbar.config(command=listbox.xview)
            listbox.config(xscrollcommand=xscrollbar.set)
            xscrollbar.grid(row=1, column=0, sticky=Tkinter.EW)

        if (yscroll):
            yscrollbar = Tkinter.Scrollbar(self, orient=Tkinter.VERTICAL)
            yscrollbar.config(command=listbox.yview)
            listbox.config(yscrollcommand=yscrollbar.set)
            yscrollbar.grid(row=0, column=1, sticky=Tkinter.NS)

        if addDeleteButtons:
            texts = ['Add item', 'Delete selected']
            commands = [self.addItem, self.deleteItems]
            buttons = ButtonList(self, texts=texts, commands=commands)
            buttons.grid(row=1, columnspan=2, sticky=Tkinter.EW)

        # bind frame, not listbox, because listbox with focus has
        # activation which means in particular that get underlining
        self.bind('<Enter>', self.enterCallback)
        self.bind('<KeyPress>', self.keypressCallback)

        self.listbox = listbox

        self.setItems(initial_list)

        self.setSelectCallback(select_callback)
        self.setDoubleCallback(double_callback)

        self.size = self.listbox.size  # otherwise get Frame size called
Beispiel #34
0
class HelpFrame(Frame):
    def __init__(self,
                 parent,
                 width=70,
                 height=20,
                 xscroll=False,
                 yscroll=True,
                 *args,
                 **kw):

        apply(Frame.__init__, (self, parent) + args, kw)

        self.grid_columnconfigure(1, weight=1)

        row = 0
        texts = ('back', 'forward', 'load')
        commands = (self.prevUrl, self.nextUrl, self.loadUrl)
        self.buttons = ButtonList(self, texts=texts, commands=commands)
        self.buttons.grid(row=row, column=0)
        self.url_entry = Entry(self, returnCallback=self.loadUrl)
        self.url_entry.grid(row=row, column=1, columnspan=2, sticky=Tkinter.EW)
        row = row + 1

        frame = Frame(self)
        frame.grid(row=row, column=0, columnspan=3, sticky=Tkinter.W)
        self.createFindFrame(frame)
        row = row + 1

        self.grid_rowconfigure(row, weight=1)
        self.help_text = ScrolledHtml(self,
                                      width=width,
                                      height=height,
                                      xscroll=xscroll,
                                      yscroll=yscroll,
                                      startUrlCallback=self.startOpenUrl,
                                      endUrlCallback=self.endOpenUrl,
                                      enterLinkCallback=self.setLinkLabel,
                                      leaveLinkCallback=self.setLinkLabel)
        self.help_text.grid(row=row,
                            column=0,
                            columnspan=3,
                            sticky=Tkinter.NSEW)
        row = row + 1

        self.link_label = Label(self)
        self.link_label.grid(row=row, column=0, columnspan=2, sticky=Tkinter.W)
        button = memops.gui.Util.createDismissButton(self,
                                                     dismiss_cmd=self.close)
        button.grid(row=row, column=2)

        self.urls = []
        self.current = -1
        self.updateUrlList = True

        self.setButtonState()

    def close(self):

        if (self.popup):
            if (self.popup.modal):
                self.popup.do_grab()

        popup = self.parent
        while (not hasattr(popup, 'top')):
            popup = popup.parent
        popup.close()

    def createFindFrame(self, master):

        frame = Frame(master)
        frame.grid(row=0, column=0, sticky=Tkinter.W)

        arrow = ToggleArrow(frame, callback=self.toggleFindFrame)
        arrow.grid(row=0, column=0)
        button = Button(frame, text='find:', command=self.findPhrase)
        button.grid(row=0, column=1)
        self.find_entry = Entry(frame,
                                width=20,
                                returnCallback=self.findPhrase)
        self.find_entry.grid(row=0, column=2)

        self.find_frame = frame = Frame(master)

        entries = ('search forwards', 'search backwards')
        self.direction_buttons = PulldownMenu(frame, entries=entries)
        self.direction_buttons.grid(row=0, column=0, sticky=Tkinter.W, padx=5)

        self.forwards_entries = entries = ('wrap search', 'stop at end')
        self.backwards_entries = ('wrap search', 'stop at beginning')
        self.wrap_buttons = PulldownMenu(frame, entries=entries)
        self.wrap_buttons.grid(row=0, column=1, sticky=Tkinter.W, padx=5)

        self.direction_buttons.callback = self.setWrapText

        entries = ('case insensitive', 'case sensitive')
        self.case_buttons = PulldownMenu(frame, entries=entries)
        self.case_buttons.grid(row=0, column=2, sticky=Tkinter.W, padx=5)

        entries = ('literal search', 'regex search')
        self.pattern_buttons = PulldownMenu(frame, entries=entries)
        self.pattern_buttons.grid(row=0, column=3, sticky=Tkinter.W, padx=5)

        self.countVar = Tkinter.IntVar()

    def setWrapText(self, entry_ind, entry):

        if (entry_ind == 0):
            entries = self.forwards_entries
        else:
            entries = self.backwards_entries

        self.wrap_buttons.replace(
            entries, selected_index=self.wrap_buttons.getSelectedIndex())

    def findPhrase(self, *extra):

        phrase = self.find_entry.get()
        if (not phrase):
            showError('No find phrase', 'Enter phrase in entry box.')
            return

        if (self.direction_buttons.getSelectedIndex() == 0):
            forwards = 1
            backwards = 0
        else:
            forwards = 0
            backwards = 1

        if (self.case_buttons.getSelectedIndex() == 0):
            nocase = 1
        else:
            nocase = 0

        if (self.pattern_buttons.getSelectedIndex() == 0):
            exact = 1
            regexp = 0
        else:
            exact = 0
            regexp = 1

        start = self.help_text.tag_nextrange(Tkinter.SEL, '1.0')
        if (start):
            start = start[0]
            if (forwards):
                start = '%s+1c' % start
            else:
                start = '%s-1c' % start
        else:
            start = Tkinter.CURRENT

        if (self.wrap_buttons.getSelectedIndex() == 0):
            match = self.help_text.search(phrase,
                                          start,
                                          count=self.countVar,
                                          forwards=forwards,
                                          backwards=backwards,
                                          nocase=nocase,
                                          exact=exact,
                                          regexp=regexp)
        elif (forwards):
            match = self.help_text.search(phrase,
                                          start,
                                          count=self.countVar,
                                          forwards=forwards,
                                          backwards=backwards,
                                          nocase=nocase,
                                          exact=exact,
                                          regexp=regexp,
                                          stopindex=Tkinter.END)
        else:
            match = self.help_text.search(phrase,
                                          start,
                                          count=self.countVar,
                                          forwards=forwards,
                                          backwards=backwards,
                                          nocase=nocase,
                                          exact=exact,
                                          regexp=regexp,
                                          stopindex='1.0')

        if (match):
            self.help_text.see(match)
            self.help_text.setSelection(
                match, '%s+%dc' % (match, self.countVar.get()))
            self.help_text.tag_config(Tkinter.SEL, background='gray70')
        else:
            showInfo('No match', 'No match found for phrase.')

    def toggleFindFrame(self, isClosed):

        if (isClosed):
            self.find_frame.grid_forget()
        else:
            self.find_frame.grid(row=1, column=0, sticky=Tkinter.W)

    def setButtonState(self):

        n = len(self.urls)

        if ((n >= 2) and (self.current > 0)):
            state = Tkinter.NORMAL
        else:
            state = Tkinter.DISABLED
        self.buttons.buttons[0].config(state=state)

        if ((n >= 2) and (self.current < (n - 1))):
            state = Tkinter.NORMAL
        else:
            state = Tkinter.DISABLED
        self.buttons.buttons[1].config(state=state)

    def setLinkLabel(self, url=''):

        self.link_label.set(url)

    def loadUrl(self, *extra):

        url = self.url_entry.get()
        if (url):
            if (url.find(':') == -1):
                if (url[:2] != '//'):
                    url = '//' + url
                url = 'http:' + url
            self.showUrl(url, forceLoad=True)

    def newUrl(self, url):

        self.current = self.current + 1
        self.urls[self.current:] = [[url, 0.0]]
        self.setButtonState()
        #print 'newUrl', self.current, self.urls

    def prevUrl(self):

        if (self.current > 0):  # True if called via button
            (url, offset) = self.urls[self.current - 1]
            self.updateUrlList = False
            self.showUrl(url, offset=offset, allowModifyPath=False)
            self.updateUrlList = True
            self.current = self.current - 1
            self.setButtonState()
        #print 'prevUrl', self.current, self.urls

    def nextUrl(self):

        if (self.current < (len(self.urls) - 1)):  # True if called via button
            (url, offset) = self.urls[self.current + 1]
            self.updateUrlList = False
            self.showUrl(url, offset=offset, allowModifyPath=False)
            self.updateUrlList = True
            self.current = self.current + 1
            self.setButtonState()
        #print 'nextUrl', self.current, self.urls

    def showText(self, message, popup=None):

        self.popup = popup
        if (popup):
            self.parent.modal = popup.modal
        self.help_text.setState(Tkinter.NORMAL)  # so that can add text
        self.help_text.clear()  # clear existing text
        self.help_text.append(message)
        self.help_text.setState(Tkinter.DISABLED)  # make text read-only
        self.open()

    def startOpenUrl(self, yview):

        if (self.urls):
            self.urls[self.current][1] = yview[0]

    def endOpenUrl(self, url):

        #print 'endOpenUrl', url, self.updateUrlList
        self.url_entry.set(url)
        if (self.updateUrlList):
            self.newUrl(url)
        self.setLinkLabel()
        self.open()

    def showUrl(self,
                url,
                offset=None,
                forceLoad=False,
                allowModifyPath=True,
                popup=None):

        self.popup = popup
        if (popup):
            self.parent.modal = popup.modal
        self.help_text.openUrl(url,
                               forceLoad=forceLoad,
                               allowModifyPath=allowModifyPath)
        if (offset is not None):
            self.help_text.yview(Tkinter.MOVETO, str(offset))
Beispiel #35
0
class CalcHeteroNoePopup(BasePopup):
  """
  **Calculate Heteronuclear NOE Values From Peak Intensities**
  
  The purpose of this popup window is to calculate the heteronuclear NOE for
  amide resonances based upon a comparison of the peak intensities in spectra
  that derive from an NOE saturated experiment and an unsaturated (reference)
  experiment. The basic idea of this tool is that three peak lists are chosen,
  two of which are for heteronuclear NOE experiments (H,N axes); unsaturated
  reference and saturated, and one which is the source of assignments and peak
  locations. This last "Assignment" peak list may be the same as one of the NOE
  peak lists, but may also be entirely separate.

  The "Assignment" peak list is used to specify which peak assignments and
  locations should be used for the calculation of the heteronuclear NOE values,
  and thus can be used to specify only a subset of the resonances for
  measurement. For example, it is common to copy an HQSC peak list for use as
  the "Assignment" peak list but remove overlapped and NH2 peaks so that the NOE
  values are only calculated for separated backbone amides. The calculation
  process involves taking each of these assigned peaks and finding peaks with
  the same assignment in the NOE peak lists, or if that fails finding peaks with
  a similar position (within the stated tolerances); new peaks may be picked if
  the "Pick new peaks?" option is set.

  The first "Peak Lists & Settings" tab allows the user to choose the peak lists
  and various options that will be used in the peak-finding and NOE calculation.
  The "Peaks" table allows the peaks from each of the three peak list selections
  to be displayed when one of the "Show" buttons is clicked. The [Separate Peak
  Table] function allows these peaks to be displayed in the main, separate `Peak
  Lists`_ table, which has many more peak manipulation options. The options
  below the table may be used to locate selected peaks within the spectrum
  window displays.

  The second "Peak Intensity Comparison" tab is where the heteronuclear NOE
  values are actually calculated. Assuming that two NOE experiment peak lists
  have been chosen and that some of their peaks match the assigned peak
  positions then the peak intensities are extracted and NOE values automatically
  calculated when the tab is opened. Although, a refresh of the table can be
  forced with [Find Matching Peaks] at the bottom

  If pairs of NOE saturated and reference peaks are found then the actual
  heteronuclear NOE value is displayed as the "Intensity Ratio" in the last,
  rightmost, column of the table. To store these values as a NOE measurement
  list; so that the data can be saved in the CCPN project without need for
  recalculation, the [Create Hetero NOE List] function can be used. The results
  are then available to view at any time via the `Measurement Lists`_ table.

  **Caveats & Tips**

  Erroneous peak intensity comparisons may be removed with the [Remove Pairs]
  function, but its is common to curate the "Assign" peak list first and
  avoid tidying afterwards.

  The "Closeness score" can be used to find peak positions where the compared
  NOE peaks are unexpectedly far from one another.

  .. _`Peak Lists`: EditPeakListsPopup.html
  .. _`Measurement Lists`: EditMeasurementListsPopup.html
  
  """

  def __init__(self, parent, *args, **kw):

    self.guiParent      = parent
    self.peakPairs      = []
    self.intensityType  = 'height'
    self.selectedPair   = None
    self.assignPeakList = None
    self.refPeakList    = None
    self.satPeakList    = None
    self.displayPeakList = None
    self.waiting        = 0
  
    BasePopup.__init__(self, parent, title="Data Analysis : Heteronuclear NOE", **kw)

  def body(self, guiFrame):

    self.geometry('700x700')
   
    guiFrame.expandGrid(0,0)
    
    options = ['Peak Lists & Settings','Peak Intensity Comparison']
    tabbedFrame = TabbedFrame(guiFrame, options=options, callback=self.changeTab)
    tabbedFrame.grid(row=0, column=0, sticky='nsew')
    self.tabbedFrame = tabbedFrame
    frameA, frameB = tabbedFrame.frames

    row = 0
    frameA.grid_columnconfigure(1, weight=1)
    frameA.grid_columnconfigure(3, weight=1)
    frameA.grid_columnconfigure(5, weight=1)
    frameA.grid_rowconfigure(5, weight=1)

    tipText = 'Number of reference peaks (no saturation)'
    self.peaksALabel = Label(frameA, text='Number of Ref Peaks: ', tipText=tipText)
    self.peaksALabel.grid(row=1,column=0,columnspan=2,sticky='w')

    tipText = 'Number of NOE saturation peaks'
    self.peaksBLabel = Label(frameA, text='Number of Sat Peaks: ', tipText=tipText)
    self.peaksBLabel.grid(row=1,column=2,columnspan=2,sticky='w')

    tipText = 'Number of peaks in assigned list'
    self.peaksCLabel = Label(frameA, text='Number of Assign Peaks: ', tipText=tipText)
    self.peaksCLabel.grid(row=1,column=4,columnspan=2,sticky='w')
    
    tipText = 'Selects which peak list is considered the NOE intensity reference (no saturation)'
    specALabel = Label(frameA, text='Ref Peak List: ')
    specALabel.grid(row=0,column=0,sticky='w')
    self.specAPulldown = PulldownList(frameA, callback=self.setRefPeakList, tipText=tipText)
    self.specAPulldown.grid(row=0,column=1,sticky='w')

    tipText = 'Selects which peak list is considered as NOE saturated.'
    specBLabel = Label(frameA, text='Sat Peak List: ')
    specBLabel.grid(row=0,column=2,sticky='w')
    self.specBPulldown = PulldownList(frameA, callback=self.setSatPeakList, tipText=tipText)
    self.specBPulldown.grid(row=0,column=3,sticky='w')

    tipText = 'Selects a peak list with assignments to use as a positional reference'
    specCLabel = Label(frameA, text='Assignment Peak List: ')
    specCLabel.grid(row=0,column=4,sticky='w')
    self.specCPulldown = PulldownList(frameA, callback=self.setAssignPeakList, tipText=tipText)
    self.specCPulldown.grid(row=0,column=5,sticky='w')

    frame0a = Frame(frameA)
    frame0a.grid(row=2,column=0,columnspan=6,sticky='nsew')
    frame0a.grid_columnconfigure(9, weight=1)
    
    tipText = '1H ppm tolerance for matching assigned peaks to reference & NOE saturation peaks'
    tolHLabel   = Label(frame0a, text='Tolerances: 1H')
    tolHLabel.grid(row=0,column=0,sticky='w')
    self.tolHEntry = FloatEntry(frame0a,text='0.02', width=6, tipText=tipText)
    self.tolHEntry .grid(row=0,column=1,sticky='w')  

    tipText = '15N ppm tolerance for matching assigned peaks to reference & NOE saturation peaks'
    tolNLabel   = Label(frame0a, text=' 15N')
    tolNLabel .grid(row=0,column=2,sticky='w')   
    self.tolNEntry = FloatEntry(frame0a,text='0.1', width=6, tipText=tipText)
    self.tolNEntry .grid(row=0,column=3,sticky='w')   

    tipText = 'Whether to peak new peaks in reference & NOE saturated lists (at assignment locations)'
    label = Label(frame0a, text=' Pick new peaks?', grid=(0,4)) 
    self.pickPeaksSelect = CheckButton(frame0a, tipText=tipText,
                                       grid=(0,5), selected=True)

    tipText = 'Whether to assign peaks in the peaks in the reference & NOE saturation lists, if not already assigned'
    label = Label(frame0a, text=' Assign peaks?')
    label.grid(row=0,column=6,sticky='w')   
    self.assignSelect = CheckButton(frame0a, tipText=tipText)
    self.assignSelect.set(1)
    self.assignSelect.grid(row=0,column=7,sticky='w')    

    tipText = 'Whether to consider peak height or volume in the heteronuclear NOE calculation'
    intensLabel = Label(frame0a, text=' Intensity Type:')
    intensLabel .grid(row=0,column=8,sticky='w')   
    self.intensPulldown = PulldownList(frame0a, texts=['height','volume'],
                                       callback=self.setIntensityType,
                                       tipText=tipText)
    self.intensPulldown.grid(row=0,column=9,sticky='w')    

    divider = LabelDivider(frameA, text='Peaks', grid=(3,0),
                           gridSpan=(1,6))

    tipTexts = ['Show the selected intensity reference peaks in the below table',
                'Show the selected NOE saturation peaks in the below table',
                'Show the selected assigned peak list in the below table',
                'Show the displayed peaks in a separate peak table, where assignments etc. may be adjusted']
    texts    = ['Show Ref Peaks','Show Sat Peaks',
                'Show Assign Peaks', 'Separate Peak Table']
    commands = [self.viewRefPeakList, self.viewSatPeakList,
                self.viewAssignPeakList, self.viewSeparatePeakTable]
    self.viewPeaksButtons = ButtonList(frameA, expands=True, tipTexts=tipTexts,
                                       texts=texts, commands=commands)
    self.viewPeaksButtons.grid(row=4,column=0,columnspan=6,sticky='nsew')

    self.peakTable = PeakTableFrame(frameA, self.guiParent, grid=(5,0),
                                    gridSpan=(1,6))
    self.peakTable.bottomButtons1.grid_forget()
    self.peakTable.bottomButtons2.grid_forget()
    #self.peakTable.topFrame.grid_forget()
    self.peakTable.topFrame.grid(row=2, column=0, sticky='ew')
    # Next tab

    frameB.expandGrid(0,0)
    
    tipTexts = ['Row number',
                'Assignment annotation for NOE saturation peak',
                'Assignment annotation for reference peak (no saturation)',
                '1H chemical shift of NOE saturation peak',
                '1H chemical shift of reference peak',
                '15N chemical shift of NOE saturation peak',
                '15N chemical shift of reference peak',
                'The separation between compared peaks: square root of the sum of ppm differences squared',
                'The intensity if the NOE saturation peak',
                'The intensity of the reference peak (no saturation)',
                'Ratio of peak intensities: saturated over reference',
                'Residue(s) for reference peak']
    colHeadings      = ['#','Sat Peak','Ref Peak','1H shift A',
                        '1H shift B','15N shift A','15N shift B',
                        'Closeness\nScore','Intensity A','Intensity B',
                        'Intensity\nRatio','Residue']
    self.scrolledMatrix = ScrolledMatrix(frameB, multiSelect=True, 
                                         headingList=colHeadings,
                                         callback=self.selectCell,
                                         tipTexts=tipTexts,
                                         grid=(0,0),
                                         deleteFunc=self.removePair)

    tipTexts = ['Force a manual update of the table; pair-up NOE saturation and reference peaks according to assigned peak positions',
                'Remove the selected rows of peak pairs',
                'Show peaks corresponding to the selected row in a table',
                'Save the Heteronuclear NOE values in the CCPN project as a data list']
    texts    = ['Refresh Table','Remove Pairs',
                'Show Peak Pair','Create Hetero NOE List']
    commands = [self.matchPeaks,self.removePair,
                self.showPeakPair,self.makeNoeList]
    self.pairButtons = ButtonList(frameB, tipTexts=tipTexts, grid=(1,0),
                                  texts=texts, commands=commands)


    bottomButtons = UtilityButtonList(tabbedFrame.sideFrame, helpUrl=self.help_url)
    bottomButtons.grid(row=0, column=0, sticky='e')
    
    self.updatePulldowns()
    self.updateAfter()

    self.administerNotifiers(self.registerNotify)

  def administerNotifiers(self, notifyFunc):

    for func in ('__init__', 'delete','setName'):
      for clazz in ('ccp.nmr.Nmr.DataSource', 'ccp.nmr.Nmr.Experiment',):
        notifyFunc(self.updatePulldowns, clazz, func)
        
    for func in ('__init__', 'delete'):
      notifyFunc(self.updatePulldowns,'ccp.nmr.Nmr.PeakList', func)

    for func in ('__init__', 'delete','setAnnotation','setFigOfMerit'):
      notifyFunc(self.updatePeaks, 'ccp.nmr.Nmr.Peak', func)
    for func in ('setAnnotation','setPosition','setNumAliasing'):
      notifyFunc(self.updatePeakChild, 'ccp.nmr.Nmr.PeakDim', func)
    for func in ('__init__', 'delete', 'setValue'):
      notifyFunc(self.updatePeakChild, 'ccp.nmr.Nmr.PeakIntensity', func)

  def changeTab(self, index):
  
    if index == 1:
      self.matchPeaks()

  def open(self):
  
    self.updatePulldowns()
    self.updateAfter()
    BasePopup.open(self)
    
    
  def destroy(self):
  
    self.administerNotifiers(self.unregisterNotify)

    BasePopup.destroy(self)
 
  def updatePulldowns(self, *obj):

    index0 = 0
    index1 = 0
    index2 = 0
    names, peakLists = self.getPeakLists()
    
    if names:

      if self.refPeakList not in peakLists:
        self.refPeakList = peakLists[0]

      if  self.satPeakList not in peakLists:
        self.satPeakList = peakLists[0]

      if self.assignPeakList not in peakLists:
        self.assignPeakList = peakLists[0]

      index0 = peakLists.index(self.refPeakList)
      index1 = peakLists.index(self.satPeakList)
      index2 = peakLists.index(self.assignPeakList)
    
    self.specAPulldown.setup(names, peakLists, index0)
    self.specBPulldown.setup(names, peakLists, index1)
    self.specCPulldown.setup(names, peakLists, index2)

  def updatePeakChild(self,peakChild):
  
    if self.waiting:
      return
    
    self.updatePeaks(peakChild.peak)
  
  def updatePeaks(self, peak):
  
    if self.waiting:
      return
    
    if peak.peakList in (self.refPeakList,self.satPeakList,self.assignPeakList):
      if peak.isDeleted and (peak.peakList in (self.refPeakList,self.satPeakList) ):
        for peaks in self.peakPairs:
          if peak in peaks:
            self.peakPairs.remove(peaks)
            if self.selectedPair is peaks:
              self.selectedPair = None
            self.updateAfter()
            return
            
      self.updateAfter()
 
  def setIntensityType(self, intensityType):
    
    self.intensityType = intensityType
    self.updateAfter()
  
  def viewRefPeakList(self):
  
    if self.refPeakList:
      self.updatePeakTable(self.refPeakList)
   
  def viewSatPeakList(self):
  
    if self.satPeakList:
      self.updatePeakTable(self.satPeakList)
  
  def viewAssignPeakList(self):
  
    if self.assignPeakList:
      self.updatePeakTable(self.assignPeakList)
  
  def viewSeparatePeakTable(self):
  
    if self.displayPeakList:
      self.guiParent.editPeakList(peakList=self.displayPeakList)
  
  def setRefPeakList(self, refPeakList):
  
    if self.displayPeakList is self.refPeakList:
      self.updatePeakTable(refPeakList)

    self.refPeakList = refPeakList
    self.updateViewButtons()
    self.updateAfter()
  
  def setSatPeakList(self, satPeakList):
  
    if self.displayPeakList is self.satPeakList:
      self.updatePeakTable(satPeakList)
      
    self.satPeakList = satPeakList
    self.updateViewButtons()
    self.updateAfter()
  
  def setAssignPeakList(self, assignPeakList):
  
    if self.displayPeakList is self.assignPeakList:
      self.updatePeakTable(assignPeakList)
      
    self.assignPeakList = assignPeakList
    self.updateViewButtons()
    self.updateAfter()
  
  def getPeakListName(self, peakList):
  
    if peakList:
      spectrum = peakList.dataSource
      experiment = spectrum.experiment
      name = '%s:%s:%d' % (experiment.name, spectrum.name, peakList.serial)
    else:
      name = '<None>'
  
    return name
  
  def getPeakLists(self):
  
    names = []
    peakLists = []
    
    for experiment in self.nmrProject.sortedExperiments():
      for dataSource in experiment.sortedDataSources():
        if dataSource.numDim == 2:
          dimsN = findSpectrumDimsByIsotope(dataSource,'15N')
          dimsH = findSpectrumDimsByIsotope(dataSource,'1H')
          if len(dimsN) == 1 and len(dimsH) == 1:
            for peakList in dataSource.sortedPeakLists():
              name = self.getPeakListName(peakList)
              names.append( name )
              peakLists.append(peakList)
    
    return names, peakLists
  
  def showPeakPair(self):
  
    if self.selectedPair:
      self.guiParent.viewPeaks(self.selectedPair)
          
  def selectCell(self, object, row, col):
  
    self.selectedPair = object

    if self.selectedPair:
      self.pairButtons.buttons[1].enable()
      self.pairButtons.buttons[2].enable()
    else:
      self.pairButtons.buttons[1].disable()
      self.pairButtons.buttons[2].disable()
  
  def removePair(self, *event):
  
    pairs = self.scrolledMatrix.currentObjects
    
    if pairs:
      for pair in pairs:
        self.peakPairs.remove(pair)
        
      self.selectedPair = None
      self.updateAfter()
  
  def matchPeaks(self):
  
    # assign relative to reference
    
    if self.assignPeakList and self.assignPeakList.peaks and self.refPeakList and self.satPeakList:
 
      tolH = float( self.tolHEntry.get() )
      tolN = float( self.tolNEntry.get() )
      pickNewPeaks = self.pickPeaksSelect.get()
      doAssign     = self.assignSelect.get()
 
      dimH  = findSpectrumDimsByIsotope(self.assignPeakList.dataSource,'1H' )[0]
      dimHA = findSpectrumDimsByIsotope(self.refPeakList.dataSource,'1H' )[0]
      dimHB = findSpectrumDimsByIsotope(self.satPeakList.dataSource,'1H' )[0]
      dimN  = 1-dimH
      dimNA = 1-dimHA
      dimNB = 1-dimHB
 
      tolerancesA = [0,0]
      tolerancesA[dimHA] = tolH
      tolerancesA[dimNA] = tolN

      tolerancesB = [0,0]
      tolerancesB[dimHB] = tolH
      tolerancesB[dimNB] = tolN
 
      self.peakPairs = matchHnoePeaks(self.assignPeakList,self.refPeakList,
                                      self.satPeakList,tolerancesA,tolerancesB,
                                      pickNewPeaks,doAssign)
 
      self.updateAfter()
 
  def makeNoeList(self):

    if self.refPeakList is self.satPeakList:
      showWarning('Same Peak List',
                  'Ref Peak List and Sat Peak List cannot be the same',
                  parent=self)
      return

    if self.peakPairs:
      s1 = self.refPeakList.dataSource
      s2 = self.satPeakList.dataSource
      noiseRef = getSpectrumNoise(s1)
      noiseSat = getSpectrumNoise(s2)
      
      es = '%s-%s' % (s1.experiment.name,s2.experiment.name)
      if len(es) > 50:
        es = 'Expt(%d)-Expt(%d)' % (s1.experiment.serial,s2.experiment.serial)

      noeList = self.nmrProject.newNoeList(unit='None',name='Hetero NOE list for %s' % es)
      noeList.setExperiments([s1.experiment,])
      if s1.experiment is not s2.experiment:
        noeList.addExperiment( s2.experiment )
      # TBD: sf, noeValueType, refValue, refDescription
    
      resonancePairsSeen = set()
      for (peakA,peakB) in self.peakPairs: # peakA is sat
        intensA    = getPeakIntensity(peakA,self.intensityType)
        intensB    = getPeakIntensity(peakB,self.intensityType)
        value      = float(intensA)/intensB
        error      = abs(value) * sqrt((noiseSat/intensA)**2 + (noiseRef/intensB)**2)
        resonances = tuple(self.getPeakResonances(peakA))
        frozenResonances = frozenset(resonances)
        if len(resonances) < 2:
          pl = peakA.peakList
          sp = pl.dataSource
          msg = 'Skipping %s:%s:%d peak %d it has too few resonances assigned'
          data = (sp.experiment.name, sp.name, pl.serial, peakA.serial)
          showWarning('Warning',msg % data, parent=self)
        
        elif len(resonances) > 2:
          pl = peakA.peakList
          sp = pl.dataSource
          resonanceText = ' '.join([makeResonanceGuiName(r) for r in resonances])
          msg = 'Skipping %s:%s:%d peak %d it has too many resonances assigned (%s)'
          data = (sp.experiment.name, sp.name, pl.serial, peakA.serial, resonanceText)
          showWarning('Warning', msg % data, parent=self)
        
        elif frozenResonances not in resonancePairsSeen:
          resonancePairsSeen.add(frozenResonances)
          noeList.newNoe(value=value,resonances=resonances,peaks=[peakA,peakB],error=error)
          
        else:
          resonanceText = ' '.join([makeResonanceGuiName(r) for r in resonances])
          msg = 'Skipping duplicate entry for resonances %s' % resonanceText
          showWarning('Warning', msg, parent=self)

      self.parent.editMeasurements(measurementList=noeList)

  def getPeakResonances(self,peak):
  
    resonances = []
    for peakDim in peak.sortedPeakDims():
      for contrib in peakDim.sortedPeakDimContribs():
        resonances.append(contrib.resonance)
    
    return resonances

  def updateAfter(self, *opt):

    if self.waiting:
      return
    else:
      self.waiting = True
      self.after_idle(self.update)
 
  def updateViewButtons(self):
  
    if self.refPeakList:
      self.viewPeaksButtons.buttons[0].enable()
    else:
      self.viewPeaksButtons.buttons[0].disable()
  
    if self.satPeakList:
      self.viewPeaksButtons.buttons[1].enable()
    else:
      self.viewPeaksButtons.buttons[1].disable()
  
    if self.assignPeakList:
      self.viewPeaksButtons.buttons[2].enable()
    else:
      self.viewPeaksButtons.buttons[2].disable()
  
  def updatePeakTable(self, peakList):
    
    if peakList is not self.displayPeakList:
      self.displayPeakList = peakList
      self.peakTable.update(peaks=peakList.sortedPeaks())

  
  def update(self):

    if self.refPeakList:
      self.peaksALabel.set( 'Number of Ref Peaks: %d' % len(self.refPeakList.peaks) )
    else:
      self.peaksALabel.set( 'Number of Ref Peaks: %d' % 0 )
    if self.satPeakList:
      self.peaksBLabel.set( 'Number of Sat Peaks: %d' % len(self.satPeakList.peaks) )
    else:
      self.peaksBLabel.set( 'Number of Sat Peaks: %d' % 0 )
    if self.assignPeakList:
      self.peaksCLabel.set( 'Number of Assign Peaks: %d' % len(self.assignPeakList.peaks) )
    else:
      self.peaksCLabel.set( 'Number of Assign Peaks: %d' % 0 )

    if self.refPeakList and self.satPeakList and self.assignPeakList:
      if self.refPeakList is self.satPeakList:
        self.pairButtons.buttons[0].disable()
      else:
        self.pairButtons.buttons[0].enable()
    else:
      self.pairButtons.buttons[0].disable()
 
    if self.selectedPair:
      self.pairButtons.buttons[1].enable()
      self.pairButtons.buttons[2].enable()
    else:
      self.pairButtons.buttons[1].disable()
      self.pairButtons.buttons[2].disable()

    if self.peakPairs:
      self.pairButtons.buttons[3].enable()
      dsA = self.peakPairs[0][0].peakList.dataSource
      dsB = self.peakPairs[0][1].peakList.dataSource
      dimHA = findSpectrumDimsByIsotope(dsA,'1H')[0]
      dimHB = findSpectrumDimsByIsotope(dsB,'1H')[0]
      dimNA = findSpectrumDimsByIsotope(dsA,'15N')[0]
      dimNB = findSpectrumDimsByIsotope(dsB,'15N')[0]
    else:
      self.pairButtons.buttons[3].disable()
    
    objectList  = []
    textMatrix  = []

    i = 0
    for (peakA,peakB) in self.peakPairs:
      i += 1

      peakDimsA = peakA.sortedPeakDims()
      peakDimsB = peakB.sortedPeakDims()

      ppm0 = peakDimsA[dimHA].value
      ppm1 = peakDimsB[dimHB].value
      ppm2 = peakDimsA[dimNA].value
      ppm3 = peakDimsB[dimNB].value
      d0 = abs(ppm0-ppm1)
      d1 = abs(ppm2-ppm3)
      intensA = getPeakIntensity(peakA,self.intensityType)
      intensB = getPeakIntensity(peakB,self.intensityType)
      datum = []
      datum.append( i )
      datum.append( getPeakAnnotation(peakA, doPeakDims=False) )
      datum.append( getPeakAnnotation(peakB, doPeakDims=False) )
      datum.append( ppm0 )
      datum.append( ppm1 )
      datum.append( ppm2 )
      datum.append( ppm3 )
      datum.append( sqrt((d0*d0)+(d1*d1)) )
      datum.append( intensA )
      datum.append( intensB )
      if intensB:
        datum.append( float(intensA)/intensB )
      else:
        datum.append( None )
      seqCodes = ','.join(['%s' % seqCode for seqCode in getPeakSeqCodes(peakB)])
      datum.append(seqCodes)
      
      objectList.append( (peakA,peakB) )
      textMatrix.append( datum )
      
    if not objectList:
      textMatrix.append([])

    self.scrolledMatrix.update(objectList=objectList, textMatrix=textMatrix)

    self.waiting = False
Beispiel #36
0
  def __init__(self, guiParent, ccpnProject=None, **kw):

    self.guiParent = guiParent
    self.project = ccpnProject
    self.spectrum = None
    self.peakMode = 0
    
    if ccpnProject:
      self.nmrProject = ccpnProject.currentNmrProject
    else:
      self.nmrProject = None
    
    Frame.__init__(self, guiParent, **kw)
  
    self.expandGrid(0,0)

    options = ['Peak Picking',] #,'About Auremol' 'NOE assignment','Homology Modelling',]
    self.tabbedFrame = TabbedFrame(self, options=options)
    self.tabbedFrame.grid(row=0,column=0,sticky='nsew')
    frameA = self.tabbedFrame.frames[0]
    
    #frameC.grid_columnconfigure(0, weight=1)
    #frameC.grid_rowconfigure(0, weight=1)
    #frameD.grid_columnconfigure(0, weight=1)
    #frameD.grid_rowconfigure(0, weight=1)
    
    #
    # Frame A
    #
    frameA.expandGrid(2,0)
    frameA.expandGrid(3,0)
    frameA.expandGrid(4,0)
    frameA.expandGrid(5,0)
    
    
    frame = Frame(frameA, grid=(0,0))
    frame.expandGrid(0,4)
    
    label = Label(frame, text='Spectrum:', grid=(0,0))
    self.spectrumPulldown = PulldownList(frame, self.changeSpectrum, grid=(0,1))
    
    label = Label(frame, text='  Use Peak Sign:', grid=(0,2))
    self.peakModePulldown = PulldownList(frame, self.changePeakMode, texts=PEAK_MODES,
                                         objects=[0,1,2], grid=(0,3))
    
    
    frame = Frame(frameA, grid=(1,0))
    frame.expandGrid(0,4)
    
    label = Label(frame, text='Integration Depth (Relative to max):', grid=(1,0))
    self.segLevelEntry = FloatEntry(frame, text=0.1, grid=(1,1), width=8)
    
    label = Label(frame, text='Threshold (Threshold only):', grid=(1,3))
    self.thresholdEntry = IntEntry(frame, text=100000, grid=(1,4), width=8)
    
    label = Label(frame, text='Keep Peaks (Adaptive only):', grid=(1,5))
    self.keepPeakEntry = IntEntry(frame, text=4000, grid=(1,6), width=8)
    
    texts = ['Threshold\nPeak Pick','Adaptive\nPeak Pick']
    commands = [self.pickThreshold, self.pickAdaptive]
    self.buttons = ButtonList(frameA, texts=texts, commands=commands,
                              grid=(2,0),  sticky='NSEW')
    
    frame = Frame(frameA, grid=(3,0))
    frame.expandGrid(0,0)
    frame = Frame(frameA, grid=(4,0))
    frame.expandGrid(0,0)
    frame = Frame(frameA, grid=(5,0))
    frame.expandGrid(0,0)
     
    #
    # About
    """
    frameB.expandGrid(4,0)

    label = Label(frameB, text='References', font='Helvetica 12 bold')
    label.grid(row=0, column=0, sticky='w')
    
    text = 
    * Gronwald W, Brunner K, Kirchhofer R, Nasser A, Trenner J, Ganslmeier B,
    Riepl H, Ried A, Scheiber J, Elsner R, Neidig K-P, Kalbitzer HR
    AUREMOL, a New Program for the Automated Structure Elucidation of Biological Macromolecules
    Bruker Reports 2004; 154/155: 11-14

    * Ried A, Gronwald W, Trenner JM, Brunner K, Neidig KP, Kalbitzer HR
    Improved simulation of NOESY spectra by RELAX-JT2 including effects of J-coupling,
    transverse relaxation and chemical shift anisotrophy
    J Biomol NMR. 2004 Oct;30(2):121-31

    * Gronwald W, Moussa S, Elsner R, Jung A, Ganslmeier B, Trenner J, Kremer W, Neidig KP, Kalbitzer HR
    Automated assignment of NOESY NMR spectra using a knowledge based method (KNOWNOE)
    J Biomol NMR. 2002 Aug;23(4):271-87

    * Gronwald W, Kirchhofer R, Gorler A, Kremer W, Ganslmeier B, Neidig KP, Kalbitzer HR
    RFAC, a program for automated NMR R-factor estimation
    J Biomol NMR. 2000 Jun;17(2):137-51
    
    label = Label(frameB, text=text)
    label.grid(row=1, column=0, sticky='w')
    """
   
    #
    # Frame C
    #

    
    #
    # Frame D
    #

  
    self.updateAll()
Beispiel #37
0
class ObjectTablePopup(BasePopup):
    def __init__(self, parent, root, metaclass, onlyShow=False, *args, **kw):

        self.root = root
        self.metaclass = metaclass
        self.onlyShow = onlyShow

        BasePopup.__init__(self,
                           parent,
                           title='Browser for %s objects' % metaclass.name,
                           location='+50+50',
                           *args,
                           **kw)

    def body(self, master):

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self.table = ObjectTable(master, self.metaclass)
        self.table.grid(row=0, column=0, sticky=Tkinter.NSEW)

        if (self.onlyShow):
            texts = ['Close']
            commands = [self.close]
        else:
            texts = ['Ok', 'Cancel']
            commands = [self.ok, self.close]

        self.buttons = ButtonList(master,
                                  texts=texts,
                                  commands=commands,
                                  direction=Tkinter.HORIZONTAL,
                                  expands=True)
        self.buttons.grid(row=1, column=0, sticky=Tkinter.EW)

        self.selected = None

        self.setObjects()

        self.doRegisters()

    def doRegisters(self):

        # do not need '' since dealing with keys
        #for func in ('', '__init__', 'delete'):
        for func in ('__init__', 'delete'):
            self.registerNotify(self.setObjects,
                                self.metaclass.qualifiedName(), func)

    # unregisters dealt with by BasePopup

    def apply(self):

        selected = self.table.currentObject

        if (not selected):
            showError('No selection', "No object selected", parent=self)
            return False

        self.selected = selected

        return True

    def setObjects(self, *extra):

        objects = getAllObjects(self.root, self.metaclass)

        self.table.setObjects(objects)
Beispiel #38
0
class CingGui(BasePopup):

    def __init__(self, parent, options, *args, **kw):


        # Fill in below variable once run generates some results
        self.haveResults = None
        # store the options
        self.options = options

        BasePopup.__init__(self, parent=parent, title='CING Setup', **kw)

#    self.setGeometry(850, 750, 50, 50)

        self.project = None

#    self.tk_strictMotif( True)

        self.updateGui()
    # end def __init__

    def body(self, guiFrame):

        row = 0
        col =0
#    frame = Frame( guiFrame )
#    frame.grid(row=row, column=col, sticky='news')
        self.menuBar = Menu( guiFrame)
        self.menuBar.grid( row=row, column=col, sticky='ew')

        #----------------------------------------------------------------------------------
        # Project frame
        #----------------------------------------------------------------------------------

#    guiFrame.grid_columnconfigure(row, weight=1)
#    frame = LabelFrame(guiFrame, text='Project', font=medFont)
        row = +1
        col =0
        frame = LabelFrame(guiFrame, text='Project', **labelFrameAttributes )
        print '>', frame.keys()
        frame.grid(row=row, column=col, sticky='nsew' )
        frame.grid_columnconfigure(2, weight=1)
#    frame.grid_rowconfigure(0, weight=1)

        srow = 0
        self.projectOptions = ['old','new from PDB','new from CCPN','new from CYANA']
        self.projOptionsSelect = RadioButtons(frame, selected_index=0, entries=self.projectOptions, direction='vertical',
                                              select_callback=self.updateGui
                                             )
        self.projOptionsSelect.grid(row=srow,column=0,rowspan=len(self.projectOptions),columnspan=2, sticky='w')

        if self.options.name: 
            text = self.options.name
        else: 
            text=''
        # end if
        self.projEntry = Entry(frame, bd=1, text=text, returnCallback=self.updateGui)
        self.projEntry.grid(row=srow,column=2,columnspan=2,sticky='ew')
#    self.projEntry.bind('<Key>', self.updateGui)
        self.projEntry.bind('<Leave>', self.updateGui)

        projButton = Button(frame, bd=1,command=self.chooseOldProjectFile, text='browse')
        projButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.pdbEntry = Entry(frame, bd=1, text='')
        self.pdbEntry.grid(row=srow,column=2,sticky='ew')
        self.pdbEntry.bind('<Leave>', self.updateGui)

        pdbButton = Button(frame, bd=1,command=self.choosePdbFile, text='browse')
        pdbButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.ccpnEntry = Entry(frame, bd=1, text='')
        self.ccpnEntry.grid(row=srow,column=2,sticky='ew')
        self.ccpnEntry.bind('<Leave>', self.updateGui)

        ccpnButton = Button(frame, bd=1,command=self.chooseCcpnFile, text='browse')
        ccpnButton.grid(row=srow,column=3,sticky='ew')

        srow += 1
        self.cyanaEntry = Entry(frame, bd=1, text='')
        self.cyanaEntry.grid(row=srow,column=2,sticky='ew')
        self.cyanaEntry.bind('<Leave>', self.updateGui)

        cyanaButton = Button(frame, bd=1,command=self.chooseCyanaFile, text='browse')
        cyanaButton.grid(row=srow,column=3,sticky='ew')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        label = Label(frame, text='Project name:')
        label.grid(row=srow,column=0,sticky='nw')
        self.nameEntry = Entry(frame, bd=1, text='')
        self.nameEntry.grid(row=srow,column=2,sticky='w')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        self.openProjectButton = Button(frame, command=self.openProject, text='Open Project', **actionButtonAttributes )
        self.openProjectButton.grid(row=srow,column=0, columnspan=4, sticky='ew')


        #----------------------------------------------------------------------------------
        # status
        #----------------------------------------------------------------------------------
#    guiFrame.grid_columnconfigure(1, weight=0)
        srow = 0
        frame = LabelFrame(guiFrame, text='Status', **labelFrameAttributes)
        frame.grid( row=srow, column=1, sticky='wnes')
        self.projectStatus = Text(frame, height=11, width=70, borderwidth=0, relief='flat')
        self.projectStatus.grid(row=0, column=0, sticky='wen')

        #Empty row
        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        srow += 1
        self.closeProjectButton = Button(frame, command=self.closeProject, text='Close Project', **actionButtonAttributes)
        self.closeProjectButton.grid(row=srow,column=0, columnspan=4, sticky='ew')

        #----------------------------------------------------------------------------------
        # Validate frame
        #----------------------------------------------------------------------------------

        row +=1
        col=0
        frame = LabelFrame(guiFrame, text='Validate', **labelFrameAttributes)
#    frame = LabelFrame(guiFrame, text='Validate', font=medFont)
        frame.grid(row=row, column=col, sticky='nsew')
#    frame.grid_columnconfigure(2, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        srow = 0
#    label = Label(frame, text='validation')
#    label.grid(row=srow,column=0,sticky='nw')
#
#    self.selectDoValidation = CheckButton(frame)
#    self.selectDoValidation.grid(row=srow, column=1,sticky='nw' )
#    self.selectDoValidation.set(True)
#
#    srow += 1
#    label = Label(frame, text='')
#    label.grid(row=srow,column=0,sticky='nw')
#
#    srow += 1
        label = Label(frame, text='checks')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectCheckAssign = CheckButton(frame)
        self.selectCheckAssign.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckAssign.set(True)
        label = Label(frame, text='assignments and shifts')
        label.grid(row=srow,column=2,sticky='nw')


#    srow += 1
#    self.selectCheckQueen = CheckButton(frame)
#    self.selectCheckQueen.grid(row=srow, column=4,sticky='nw' )
#    self.selectCheckQueen.set(False)
#    label = Label(frame, text='QUEEN')
#    label.grid(row=srow,column=5,sticky='nw')
#
#    queenButton = Button(frame, bd=1,command=None, text='setup')
#    queenButton.grid(row=srow,column=6,sticky='ew')


        srow += 1
        self.selectCheckResraint = CheckButton(frame)
        self.selectCheckResraint.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckResraint.set(True)
        label = Label(frame, text='restraints')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectCheckStructure = CheckButton(frame)
        self.selectCheckStructure.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckStructure.set(True)
        label = Label(frame, text='structural')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectMakeHtml = CheckButton(frame)
        self.selectMakeHtml.grid(row=srow, column=1,sticky='nw' )
        self.selectMakeHtml.set(True)
        label = Label(frame, text='generate HTML')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectCheckScript = CheckButton(frame)
        self.selectCheckScript.grid(row=srow, column=1,sticky='nw' )
        self.selectCheckScript.set(False)
        label = Label(frame, text='user script')
        label.grid(row=srow,column=0,sticky='nw')

        self.validScriptEntry = Entry(frame, bd=1, text='')
        self.validScriptEntry.grid(row=srow,column=2,columnspan=3, sticky='ew')

        scriptButton = Button(frame, bd=1,command=self.chooseValidScript, text='browse')
        scriptButton.grid(row=srow,column=5,sticky='ew')

        srow += 1
        label = Label(frame, text='ranges')
        label.grid(row=srow,column=0,sticky='nw')
        self.rangesEntry = Entry( frame, text='' )
        self.rangesEntry.grid( row=srow, column=2, columnspan=3, sticky='ew')

#    self.validScriptEntry = Entry(frame, bd=1, text='')
#    self.validScriptEntry.grid(row=srow,column=3,sticky='ew')
#
#    scriptButton = Button(frame, bd=1,command=self.chooseValidScript, text='browse')
#    scriptButton.grid(row=srow,column=4,sticky='ew')


        srow += 1
        texts    = ['Run Validation','View Results','Setup QUEEN']
        commands = [self.runCing, None, None]
        buttonBar = ButtonList(frame, texts=texts, commands=commands,expands=True)
        buttonBar.grid(row=srow, column=0, columnspan=6, sticky='ew')
        for button in buttonBar.buttons:
            button.config(**actionButtonAttributes)
        # end for
        self.runButton = buttonBar.buttons[0]
        self.viewResultButton = buttonBar.buttons[1]
        self.queenButton = buttonBar.buttons[2]

        #----------------------------------------------------------------------------------
        # Miscellaneous frame
        #----------------------------------------------------------------------------------

        row +=0
        col=1
#    frame = LabelFrame(guiFrame, text='Miscellaneous', font=medFont)
        frame = LabelFrame(guiFrame, text='Miscellaneous', **labelFrameAttributes)
        frame.grid(row=row, column=col, sticky='news')
        frame.grid_columnconfigure(2, weight=1)
        frame.grid_columnconfigure(4, weight=1,minsize=30)
        frame.grid_rowconfigure(0, weight=1)

        # Exports

        srow = 0
        label = Label(frame, text='export to')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectExportXeasy = CheckButton(frame)
        self.selectExportXeasy.grid(row=srow, column=1,sticky='nw' )
        self.selectExportXeasy.set(True)
        label = Label(frame, text='Xeasy, Sparky, TALOS, ...')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportCcpn = CheckButton(frame)
        self.selectExportCcpn.grid(row=srow, column=1,sticky='nw' )
        self.selectExportCcpn.set(True)
        label = Label(frame, text='CCPN')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportQueen = CheckButton(frame)
        self.selectExportQueen.grid(row=srow, column=1,sticky='nw' )
        self.selectExportQueen.set(True)
        label = Label(frame, text='QUEEN')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        self.selectExportRefine = CheckButton(frame)
        self.selectExportRefine.grid(row=srow, column=1,sticky='nw' )
        self.selectExportRefine.set(True)
        label = Label(frame, text='refine')
        label.grid(row=srow,column=2,sticky='nw')

        srow += 1
        label = Label(frame, text='')
        label.grid(row=srow,column=0,sticky='nw')

        # User script

        srow += 1
        label = Label(frame, text='user script')
        label.grid(row=srow,column=0,sticky='nw')

        self.selectMiscScript = CheckButton(frame)
        self.selectMiscScript.grid(row=srow, column=1,sticky='nw' )
        self.selectMiscScript.set(False)

        self.miscScriptEntry = Entry(frame, bd=1, text='')
        self.miscScriptEntry.grid(row=srow,column=3,sticky='ew')

        script2Button = Button(frame, bd=1,command=self.chooseMiscScript, text='browse')
        script2Button.grid(row=srow,column=4,sticky='ew')

        srow += 1
        texts    = ['Export','Run Script']
        commands = [None, None]
        buttonBar = ButtonList(frame, texts=texts, commands=commands,expands=True)
        buttonBar.grid(row=srow, column=0, columnspan=5, sticky='ew')
        for button in buttonBar.buttons:
            button.config(**actionButtonAttributes)
        # end for
        self.exportButton = buttonBar.buttons[0]
        self.scriptButton = buttonBar.buttons[1]

        #----------------------------------------------------------------------------------
        # Textarea
        #----------------------------------------------------------------------------------
        row +=1
        guiFrame.grid_rowconfigure(row, weight=1)
        self.outputTextBox = ScrolledText(guiFrame)
        self.outputTextBox.grid(row=row, column=0, columnspan=2, sticky='nsew')

        self.redirectConsole()

        #----------------------------------------------------------------------------------
        # Buttons
        #----------------------------------------------------------------------------------
        row +=1
        col=0
        texts    = ['Quit', 'Help']
        commands = [self.close, None]
        self.buttonBar = ButtonList(guiFrame, texts=texts, commands=commands,expands=True)
        self.buttonBar.grid(row=row, column=col, columnspan=2, sticky='ew')

#    self.openProjectButton = self.buttonBar.buttons[0]
#    self.closeProjectButton = self.buttonBar.buttons[1]
#    self.runButton = self.buttonBar.buttons[0]
#    self.viewResultButton = self.buttonBar.buttons[1]

        for button in self.buttonBar.buttons:
            button.config(**actionButtonAttributes)
        # end for
    # end def body


    def getGuiOptions(self):

        projectName = self.projEntry.get()

        index = self.projOptionsSelect.getIndex()

        if index > 0:
            makeNewProject = True
            projectImport  = None

            if index > 1:
                i = index-2
                format = ['PDB','CCPN','CYANA'][i]
                file   = [self.pdbEntry, self.ccpnEntry, self.cyanaEntry][i].get()

                if not file:
                    showWarning('Failure','No %s file selected' % format)
                    return
                # end if

                projectImport  = (format, file)
            # end if

        else:
            # Chould also check that any old project file exists

            makeNewProject = False
            projectImport  = None
        # end if

        doValidation = self.selectDoValidation.get()
        checks = []

        if doValidation:
            if self.selectCheckAssign.get():
                checks.append('assignments')
            # end if

            if self.selectCheckResraint.get():
                checks.append('restraints')
            # end if

            if self.selectCheckStructure.get():
                checks.append('structural')
            # end if

            if self.selectMakeHtml.get():
                checks.append('HTML')
            # end if

            if self.selectCheckScript.get():
                script = self.validScriptEntry.get()

                if script:
                    checks.append( ('script',script) )
                # end if
            # end if

            if self.selectCheckQueen.get():
                checks.append('queen')
            # end if
        # end if

        exports = []

        if self.selectExportXeasy.get():
            exports.append('Xeasy')
        # end if

        if self.selectExportCcpn.get():
            exports.append('CCPN')
        # end if

        if self.selectExportQueen.get():
            exports.append('QUEEN')
        # end if

        if self.selectExportRefine.get():
            exports.append('refine')
        # end if

        miscScript = None

        if self.selectMiscScript.get():
            script = self.miscScriptEntry.get()

            if script:
                miscScript = script
            # end if
        # end if

        return projectName, makeNewProject, projectImport, doValidation, checks, exports, miscScript
    # end def getGuiOptions


    def runCing(self):

        options = self.getGuiOptions()

        if options:

            projectName, makeNewProject, projectImport, doValidation, checks, exports, miscScript = options

            print 'Project name:', projectName
            print 'Make new project?', makeNewProject
            print 'Import source:', projectImport
            print 'Do vailidation?', doValidation
            print 'Validation checks:', ','.join(checks)
            print 'Export to:', ','.join(exports)
            print 'User script:', miscScript
        # end if
    # end def runCing

        # else there was already an error message

    def chooseOldProjectFile(self):

        fileTypes = [  FileType('CING', ['project.xml']),
                       FileType('All',  ['*'])
                    ]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'Select CING project file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
#    dirName  = popup.getDirectory()

        if len(fileName) > 0:
                # Put text into entry,name widgets
            dummy,name = cing.Project.rootPath(fileName)
            self.projEntry.configure(state='normal')
            self.projEntry.set(fileName)

            self.nameEntry.configure(state='normal')
            self.nameEntry.set(name)
            self.nameEntry.configure(state='disabled')
            # choose the correct radiobutton
            self.projOptionsSelect.setIndex(0)
            self.updateGui()
        # end if
        #nd if

        popup.destroy()
    # end def chooseOldProjectFile

    def choosePdbFile(self):

        fileTypes = [ FileType('PDB', ['*.pdb']),  FileType('All', ['*'])]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'PDB file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
        if len(fileName)>0:
            # Put text into entry widget
            self.pdbEntry.configure(state='normal')
            self.pdbEntry.set(fileName)
            # Put text into name widget
            _dir,name,dummy = nTpath( fileName )
            self.nameEntry.configure(state='normal')
            self.nameEntry.set(name)
            # choose the correct radiobutton
            self.projOptionsSelect.setIndex(1)
            self.updateGui()
        #end if

        popup.destroy()
    # end def choosePdbFile


    def chooseCcpnFile(self):

        fileTypes = [  FileType('XML', ['*.xml']), FileType('All', ['*'])]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'CCPN project XML file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
        if len(fileName)>0:
            self.pdbEntry.configure(state='normal')
            self.pdbEntry.set(fileName)
            self.projOptionsSelect.setIndex(1)

            _dir,name,dummy = nTpath( fileName )
            self.nameEntry.set(name)
        #end if
        self.ccpnEntry.set(fileName)
        self.projOptionsSelect.setIndex(2)

        popup.destroy()
    # end def chooseCcpnFile


    def chooseCyanaFile(self):

        # Prepend default Cyana file extension below
        fileTypes = [  FileType('All', ['*']), ]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'CYANA fproject file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
        self.cyanaEntry.set(fileName)
        self.projOptionsSelect.setIndex(3)

        popup.destroy()
    # end def chooseCyanaFile

    def chooseValidScript(self):

        # Prepend default Cyana file extension below
        fileTypes = [  FileType('All', ['*']), ]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'Script file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
        self.validScriptEntry.set(fileName)
        popup.destroy()
    # end def chooseValidScript

    def chooseMiscScript(self):

        # Prepend default Cyana file extension below
        fileTypes = [  FileType('All', ['*']), ]
        popup = FileSelectPopup(self, file_types = fileTypes,
                                title = 'Script file', dismiss_text = 'Cancel',
                                selected_file_must_exist = True)

        fileName = popup.getFile()
        self.miscScriptEntry.set(fileName)
        popup.destroy()
    # end def chooseMiscScript

    def openProject(self ):
        projOption = self.projOptionsSelect.get()
        if projOption == self.projectOptions[0]: 
            self.openOldProject()
        elif projOption == self.projectOptions[1]: 
            self.initPdb()
        # end if

        if self.project: 
            self.project.gui = self
        # end if
        self.updateGui()
    #end def

    def openOldProject(self ):
        fName = self.projEntry.get()
        if not os.path.exists( fName ):
            nTerror('Error: file "%s" does not exist\n', fName)
        #end if

        if self.project: 
            self.closeProject()
        # end if
        self.project = cing.Project.open( name=fName, status='old', verbose=False )
    #end def

    def initPdb(self ):
        fName = self.pdbEntry.get()
        if not os.path.exists( fName ):
            nTerror('Error: file "%s" does not exist\n', fName)
        #end if
        self.project = cing.Project.open( self.nameEntry.get(), status='new' )
        self.project.initPDB( pdbFile=fName, convention = 'PDB' )
    #end def

    def closeProject(self):
        if self.project: 
            self.project.close()
        # end if
        self.project = None
        self.updateGui()
    #end def

    def updateGui(self, event=None):

        projOption = self.projOptionsSelect.get()
        buttons = self.buttonBar.buttons

        # Disable entries
        for e in [self.projEntry, self.pdbEntry, self.ccpnEntry, self.cyanaEntry, self.nameEntry]:
            e.configure(state='disabled')
        #end for

        if projOption == self.projectOptions[0]:
            # Enable entries
            self.projEntry.configure(state='normal')

            if (len(self.projEntry.get()) > 0):
                self.openProjectButton.enable()
                self.runButton.enable()
            else:
                self.openProjectButton.disable()
                self.runButton.disable()
            #end if

        elif projOption == self.projectOptions[1]:
            # Enable entries
            self.pdbEntry.configure(state='normal')
            self.nameEntry.configure(state='normal')

            if (len(self.pdbEntry.get()) > 0 and len(self.nameEntry.get())  > 0):
                buttons[0].enable()
                buttons[1].enable()
            else:
                buttons[0].disable()
                buttons[1].disable()
            #end if
        #end if

        elif projOption == self.projectOptions[2]:
            # Enable entries
            self.ccpnEntry.configure(state='normal')
            self.nameEntry.configure(state='normal')

            if (len(self.ccpnEntry.get()) > 0 and len(self.nameEntry.get())  > 0):
                buttons[0].enable()
                buttons[1].enable()
            else:
                buttons[0].disable()
                buttons[1].disable()
            #end if
        #end if

        elif projOption == self.projectOptions[3]:
            # Enable entries
            self.cyanaEntry.configure(state='normal')
            self.nameEntry.configure(state='normal')

            if (len(self.cyanaEntry.get()) > 0 and len(self.nameEntry.get())  > 0):
                buttons[0].enable()
                buttons[1].enable()
            else:
                buttons[0].disable()
                buttons[1].disable()
            #end if
        #end if

        self.projectStatus.clear()
        if not self.project:
            self.projectStatus.setText('No open project')
            self.closeProjectButton.setText('Close Project')
            self.closeProjectButton.disable()
        else:
            self.projectStatus.setText(self.project.format())
            self.closeProjectButton.enable()
            self.closeProjectButton.setText(sprintf('Close Project "%s"', self.project.name))
        #end if
    #end def

    def redirectConsole(self):

        #pipe = TextPipe(self.inputTextBox.text_area)
        #sys.stdin = pipe

        pipe = TextPipe(self.outputTextBox.text_area)
        sys.stdout = pipe
        nTmessage.stream = pipe
    # end def redirectConsole
#    sys.stderr = pipe

    def resetConsole(self):
        #sys.stdin   = stdin
        nTmessage.stream = stdout
        sys.stdout  = stdout
        sys.stderr  = stderr
    # end def resetConsole

    def open(self):

        self.redirectConsole()
        BasePopup.open(self)
    # end def open

    def close(self):

        geometry = self.getGeometry()
        self.resetConsole()
        BasePopup.close(self)

        print 'close:',geometry
        sys.exit(0) # remove later
    # end def close

    def destroy(self):

        geometry = self.getGeometry()
        self.resetConsole()
        BasePopup.destroy(self)

        print 'destroy:',geometry
        sys.exit(0) # remove later
Beispiel #39
0
class WorkflowFrame(Frame):

  def __init__(self, guiParent, basePopup):
    # Base popup required to handle notification of data model changes
    # e.g. new peak lists, so that the GUI can update to the latest
    # state
    self.basePopup = basePopup
    self.guiParent = guiParent

    self.basePopup.frameShortcuts['Workflow'] = self

    #self.registerNotify=basePopup.registerNotify
    #self.unregisterNotify=basePopup.unregisterNotify

    Frame.__init__(self, guiParent)
  
    self.grid_rowconfigure(0, weight=0)
    self.grid_rowconfigure(1, weight=0, minsize=100)
    self.grid_rowconfigure(2, weight=1)
    self.grid_rowconfigure(3, weight=0, minsize=30)
    
    self.grid_columnconfigure(0, weight=0)
    self.grid_columnconfigure(1, weight=1)
    self.grid_columnconfigure(2, weight=0)

    # build up the body.

    self.lcA = LinkChart(self, background='#8080B0', height=110)
    self.lcB = LinkChart(self, background='#8080B0')

    lcButtonOpts=['Load','Save','Clear','New Protocol']
    lcButtonCmds=[self.tmpCall,self.tmpCall,self.tmpCall,self.tmpCall]
    self.lcButtons = ButtonList(self, lcButtonOpts, lcButtonCmds)

    # hack for now. This should come from db of meta-tasks
    self.expts=['Test1','Test2','ARIA','CING','ISD']

    # needs custom version
    self.filter = FilterFrame(self, self.basePopup, text='Filter')

    # no bean udnerneath for now so mock up nodes    
    self.wfTree = Tree(self, width=35)

    wfButtonOpts=['Load','Save']
    wfButtonCmds=[self.tmpCall,self.tmpCall]
    self.wfButtons = ButtonList(self, wfButtonOpts, wfButtonCmds)
    

    self.drawFrame()

  def drawFrame(self):

    # hack the WF Tree for now. just get is looking OK
    texts=['JMCI WF 1','JMCI WF 2']
    icons=[]
    parents=[]
    callbacks=[]
    objects=['JMCI WF 1','JMCI WF 2']

    for text in texts:
      icons.append('list-add')
      callbacks.append(None)
      parents.append(None)

    self.wfTree.update(parents, objects, texts, icons, callbacks)  

    self.lcA.grid(row=1, column=1, padx=5, pady=5, sticky='new')
    self.lcB.grid(row=2, column=1, padx=5, pady=5, sticky='nsew')
    self.lcButtons.grid(row=3, column=1, padx=5, pady=5, sticky='ew')

    self.filter.grid(row=1, column=2, sticky='new')
    self.wfTree.grid(row=2, column=2, padx=5, pady=5, sticky='nsew')
    self.wfButtons.grid(row=3, column=2, padx=5, pady=5, sticky='ew')

    self.nodes = []
    x = 0
    for expt in self.expts:

      node = PrototypeNode(self.lcA, title=expt, width=38,
                           updateFunc=None, resizeable=False, shape='SQUARE',
                           coords=(50+x*90, 50), object=None)

      x += 1
    
      
    self.lcA.draw()
    self.lcB.draw()

    

  def tmpCall(self):

    pass
    
  def administerNotifiers(self, notifyFunc):

      for func in ('__init__','delete','setName'):
        notifyFunc(self.updateAllAfter, 'ccp.nmr.Nmr.Experiment', func)
        notifyFunc(self.updateAllAfter, 'ccp.nmr.Nmr.DataSource', func)

  def updateAllAfter(self, obj):

    self.after_idle(self.updateAll)

  def updateAll(self, project=None):

    if project:
      self.project = project
      self.nmrProject = project.currentNmrProject

      if not self.nmrProject:
        self.nmrProject = project.newNmrProject(name=project.name)

    if not self.project:
      return


  def quit(self):
  
    self.guiParent.parent.destroy()
    
  def destroy(self):
  
    self.administerNotifiers(self.basePopup.unregisterNotify)
    Frame.destroy(self)
Beispiel #40
0
  def body(self, guiFrame):

    self.geometry('600x350')

    project = self.project
    analysisProject = self.analysisProject

    guiFrame.grid_columnconfigure(1, weight=1)

    row = 0
    frame = Frame(guiFrame, grid=(0,0))
    label = Label(frame, text=' Window:', grid=(0,0))
    self.windowPulldown = PulldownList(frame, grid=(0,1),
                                      tipText='The window that will be printed out',
                                      callback=self.selectWindow)
                                      
    tipTexts = ['For the window pulldown, show all of the spectrum windows in the current project, irrespective of the active group',
                'For the window pulldown, show only spectrum windows that are in the currently active window group']
    self.whichWindows = RadioButtons(frame, grid=(0,2),
                                     entries=ACTIVE_OPTIONS, tipTexts=tipTexts,
                                     select_callback=self.updateWindows)
    
    texts = [ 'Save Print File' ]
    tipTexts = [ 'Save the printout to the specified file' ]
    commands = [ self.saveFile ]
    buttons = UtilityButtonList(guiFrame, helpUrl=self.help_url, grid=(row,2),
                                commands=commands, texts=texts, tipTexts=tipTexts)
    self.buttons = buttons
    buttons.buttons[0].config(bg='#B0FFB0')
    
    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    options = ['Options', 'Spectra', 'Peak Lists', 'Region']
    tipTexts = ['Optional settings for spectra', 'Optional settings for peak lists', 'Optional settings for the region']
    tabbedFrame = TabbedFrame(guiFrame, options=options, tipTexts=tipTexts)
    tabbedFrame.grid(row=row, column=0, columnspan=3, sticky='nsew')
    self.tabbedFrame = tabbedFrame

    optionFrame, spectrumFrame, peakListFrame, regionFrame = tabbedFrame.frames

    optionFrame.expandGrid(0, 0)
    getOption = lambda key, defaultValue: PrintBasic.getPrintOption(analysisProject, key, defaultValue)
    setOption = lambda key, value: PrintBasic.setPrintOption(analysisProject, key, value)
    self.printFrame = PrintFrame(optionFrame, getOption=getOption,
                                 grid=(0,0), gridSpan=(1,1),
                                 setOption=setOption, haveTicks=True,
                                 doOutlineBox=False)

    spectrumFrame.expandGrid(0, 0)
    frame = Frame(spectrumFrame, grid=(0,0), gridSpan=(1,1))
    frame.expandGrid(1,0)

    self.overrideSpectrum = CheckButton(frame,
       text='Use below settings when printing',
       tipText='Use below settings when printing instead of the window values',
       grid=(0,0), sticky='w')

    tipText = 'Change the settings of the selected spectra back to their window values'
    button = Button(frame, text='Reset Selected', tipText=tipText,
                    command=self.resetSelected, grid=(0,1), sticky='e')

    self.posColorPulldown = PulldownList(self, callback=self.setPosColor)
    self.negColorPulldown = PulldownList(self, callback=self.setNegColor)
    headings = ['Spectrum', 'Pos. Contours\nDrawn', 'Neg. Contours\nDrawn', 'Positive\nColours', 'Negative\nColours']
    tipTexts = ['Spectrum in window', 'Whether the positive contours should be drawn', 'Whether the negative contours should be drawn',
      'Colour scheme for positive contours (can be a single colour)', 'Colour scheme for negative contours (can be a single colour)']

    editWidgets      = [ None, None, None, self.posColorPulldown, self.negColorPulldown]
    editGetCallbacks = [ None, self.togglePos, self.toggleNeg, self.getPosColor, self.getNegColor]
    editSetCallbacks = [ None, None, None, self.setPosColor, self.setNegColor]
    self.spectrumTable = ScrolledMatrix(frame, headingList=headings,
                                        tipTexts=tipTexts,
                                        multiSelect=True,
                                        editWidgets=editWidgets,
                                        editGetCallbacks=editGetCallbacks,
                                        editSetCallbacks=editSetCallbacks,
                                        grid=(1,0), gridSpan=(1,2))

    peakListFrame.expandGrid(0, 0)
    frame = Frame(peakListFrame, grid=(0,0), gridSpan=(1,3))
    frame.expandGrid(1,0)

    self.overridePeakList = CheckButton(frame,
       text='Use below settings when printing',
       tipText='Use below settings when printing instead of the window values',
       grid=(0,0))

    tipText = 'Change the settings of the selected peak lists back to their window values'
    button = Button(frame, text='Reset Selected', tipText=tipText,
                    command=self.resetSelected, grid=(0,1), sticky='e')

    colors = Color.standardColors
    self.peakColorPulldown = PulldownList(self, callback=self.setPeakColor,
                                        texts=[c.name for c in colors],
                                        objects=[c.hex for c in colors],
                                        colors=[c.hex for c in colors])
    headings = [ 'Peak List', 'Symbols Drawn', 'Peak Font', 'Peak Colour']
    self.fontMenu = FontList(self, mode='Print', extraTexts=[no_peak_text])
    editWidgets      = [ None, None, self.fontMenu, self.peakColorPulldown]
    editGetCallbacks = [ None, self.togglePeaks, self.getPeakFont, self.getPeakColor ]
    editSetCallbacks = [ None, None, self.setPeakFont, self.setPeakColor ]
    self.peakListTable = ScrolledMatrix(frame, headingList=headings,
                                        multiSelect=True,
                                        editWidgets=editWidgets,
                                        editGetCallbacks=editGetCallbacks,
                                        editSetCallbacks=editSetCallbacks,
                                        grid=(1,0), gridSpan=(1,2))

    regionFrame.expandGrid(0, 0)
    frame = Frame(regionFrame, grid=(0,0), gridSpan=(1,3))
    frame.expandGrid(3,0)
    tipText = 'Use the specified override region when printing rather than the window values'
    self.overrideButton = CheckButton(frame, text='Use override region when printing',
                                      tipText=tipText,
                                      callback=self.toggledOverride, grid=(0,0))

    tipTexts = ('Use min and max to specify override region', 'Use center and width to specify override region')
    self.use_entry = USE_ENTRIES[0]
    self.useButtons = RadioButtons(frame, entries=USE_ENTRIES,
                                      tipTexts=tipTexts,
                                      select_callback=self.changedUseEntry,
                                      grid=(1,0))

    texts = ('Set Region from Window', 'Set Center from Window', 'Set Width from Window')
    tipTexts = ('Set the override region to be the current window region',
                'Set the center of the override region to be the center of the current window region',
                'Set the width of the override region to be the width of the current window region')
    commands = (self.setRegionFromWindow, self.setCenterFromWindow, self.setWidthFromWindow)
    self.setRegionButton = ButtonList(frame, texts=texts,
                                      tipTexts=tipTexts,
                                      commands=commands, grid=(2,0))

    self.minRegionWidget = FloatEntry(self, returnCallback=self.setMinRegion, width=10)
    self.maxRegionWidget = FloatEntry(self, returnCallback=self.setMaxRegion, width=10)
    headings = MIN_MAX_HEADINGS
    editWidgets      = [ None, None, self.minRegionWidget, self.maxRegionWidget ]
    editGetCallbacks = [ None, None, self.getMinRegion,    self.getMaxRegion ]
    editSetCallbacks = [ None, None, self.setMinRegion,    self.setMaxRegion ]
    self.regionTable = RegionScrolledMatrix(frame, headingList=headings,
                                            editWidgets=editWidgets,
                                            editGetCallbacks=editGetCallbacks,
                                            editSetCallbacks=editSetCallbacks,
                                            grid=(3,0))

    self.updateWindows()
    self.updateAfter()
    
    self.administerNotifiers(self.registerNotify)