Example #1
0
    def __init__(self, title, message, texts, objects=None, parent=None):

        if parent is None:
            parent = Tkinter.Tk()
            #parent.withdraw()
            self.root = parent
            parent.protocol('WM_DELETE_WINDOW', self.destroy)

        else:
            self.root = None

        Tkinter.Toplevel.__init__(self, parent)

        self.resizable(0, 0)
        self.parent = parent
        self.title(title)
        self.var = Tkinter.IntVar()
        self.objects = objects or range(len(texts))

        assert len(self.objects) == len(texts)

        x = parent.winfo_rootx() + parent.winfo_width() / 2
        y = parent.winfo_rooty() + parent.winfo_height() / 2
        location = '+%d+%d' % (x, y)

        if hasattr(parent, 'font'):
            self.font = parent.font
        else:
            self.font = None

        Tkinter.Toplevel.geometry(self, location)
        Tkinter.Toplevel.lift(self, parent)
        self.update_idletasks()
        self.transient(parent)

        self.protocol('WM_DELETE_WINDOW', self._null)
        self.focus_force()
        self.grab_set()

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

        label = Label(self, text=message, grid=(0, 0))
        self.config(bg=label.cget('bg'))

        frame = Frame(self, grid=(1, 0))

        _buttons = []
        for i, text in enumerate(texts):
            button = Button(frame,
                            text=text,
                            command=lambda j=i: self._click(j))
            button.grid(row=i + 1, column=0, padx=2, pady=2, sticky='ew')
            if objects[i] is None:
                button.config(bg='#B0FFB0')
            _buttons.append(button)

        self._wait()
Example #2
0
    def body(self, master):

        self.geometry('600x130')
        master.grid_columnconfigure(1, weight=1)
        for n in range(5):
            master.grid_rowconfigure(n, weight=1)

        row = 0
        label = Label(master, text='Spectrum: ')
        label.grid(row=row, column=0, sticky='e')
        tipText = 'The spectrum for which the contour file is being added'
        self.expt_spectrum = PulldownList(master,
                                          callback=self.updateContourDir,
                                          tipText=tipText)
        self.expt_spectrum.grid(row=row, column=1, sticky='w')

        row = row + 1
        tipText = 'The location of the directory where contour files are stored on disk'
        label = Label(master, text='Contour dir: ')
        label.grid(row=row, column=0, sticky='e')
        self.dir_label = Label(master, text='', tipText=tipText)
        self.dir_label.grid(row=row, column=1, sticky='w')

        row = row + 1
        label = Label(
            master,
            text=
            '(file will be copied into Contour dir if it is not already in there)'
        )
        label.grid(row=row, column=1, sticky='w')

        row = row + 1
        tipText = 'Browse for a file store contour data'
        button = Button(master,
                        text='File name: ',
                        command=self.selectFile,
                        tipText=tipText)
        button.grid(row=row, column=0, sticky='e')
        tipText = 'Enter the name of the file to store contour data'
        self.file_entry = Entry(master, tipText=tipText)
        self.file_entry.grid(row=row, column=1, sticky='ew')

        row = row + 1
        texts = ['Add File']
        commands = [self.addFile]
        tipTexts = [
            'Use the selected contour file in the current project, copying it to the contour directory if required',
        ]
        self.buttons = UtilityButtonList(master,
                                         texts=texts,
                                         doClone=False,
                                         tipTexts=tipTexts,
                                         commands=commands,
                                         helpUrl=self.help_url)
        self.buttons.grid(row=row, column=0, columnspan=2, sticky='ew')

        self.curateNotifiers(self.registerNotify)
        self.updateSpectrum()
Example #3
0
 def body(self, master):
     label = Tkinter.Label(master, text='label 1')
     label.grid(row=0, column=0, sticky=Tkinter.EW)
     label = Tkinter.Label(master, text='label 2')
     label.grid(row=1, column=0, sticky=Tkinter.EW)
     button = Button(master, text='ok', command=self.ok)
     button.grid(row=2, column=0, sticky=Tkinter.EW)
     button = Button(master, text='cancel', command=self.close)
     button.grid(row=2, column=1, sticky=Tkinter.EW)
Example #4
0
    def body(self, master):

        master.grid_columnconfigure(2, weight=1)

        row = 0
        label = Label(master, text='Data to export:')
        label.grid(row=row, column=0, columnspan=3, sticky=Tkinter.W)

        self.check_buttons = {}
        i = 0
        for heading in self.headings:
            row = row + 1
            isSelected = self.exportSelection.get(row, True)
            self.check_buttons[i] = c = CheckButton(
                master, selected=isSelected, callback=self.toggleCheckButton)
            c.grid(row=row, column=1)
            label = Label(master, text=heading)
            label.grid(row=row, column=2, sticky=Tkinter.W)
            i += 1

        row = row + 1
        button = Button(master, text='File:', command=self.findFile)
        button.grid(row=row, column=0, sticky=Tkinter.W)
        self.file_entry = Entry(master, text=self.file, width=30)
        self.file_entry.grid(row=row,
                             column=1,
                             columnspan=2,
                             sticky=Tkinter.EW)

        row = row + 1
        label = Label(master, text='Format:')
        label.grid(row=row, column=0, sticky=Tkinter.W)
        self.format_menu = PulldownMenu(master, entries=exportFormats)
        self.format_menu.grid(row=row,
                              column=1,
                              columnspan=2,
                              sticky=Tkinter.W)

        row = row + 1
        master.grid_rowconfigure(row, weight=1)
        texts = ['Save']
        commands = [self.ok]
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands,
                                              dismiss_text='Cancel')
        buttons.grid(row=row, column=0, columnspan=3, sticky=Tkinter.EW)
Example #5
0
class ToggleLabel(Frame):
 
  def __init__(self, parent, arrowSize = 12, outline='#5050b0', fill='#a0a0ff', font=None,
               isArrowClosed = True, callback = None, text = '', *args, **kw):

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

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

    self.arrow = ToggleArrow(self, arrowSize=arrowSize, outline=outline, fill=fill,
                             isArrowClosed=isArrowClosed, callback=callback)
    self.arrow.grid(row=0, column=0, sticky=Tkinter.W)
    if font:
      self.label = Button(self, relief='flat',borderwidth=0, padx=1, pady=1, text=text, font=font, command=self.arrow.flipState)
    else:
      self.label = Button(self, relief='flat',borderwidth=0, padx=1, pady=1, text=text, command=self.arrow.flipState)
    self.label.grid(row=0, column=1, sticky=Tkinter.W)

  def arrowOn(self):
  
    if self.arrow.isArrowClosed:
      self.arrow.isArrowClosed = 0
      self.arrow.drawArrow()
  
  def arrowOff(self):
  
    if not self.arrow.isArrowClosed:
      self.arrow.isArrowClosed = 1
      self.arrow.drawArrow()

  def __getattr__(self, name):
 
    # dispatch everything not defined by ToggleLabel to arrow widget
 
    try:
      return getattr(self.__dict__['arrow'], name)
    except:
      raise AttributeError, "%s instance has no attribute '%s'" % (self.__class__.__name__, name)
Example #6
0
    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()
Example #7
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)
Example #8
0
class DataFileImportFrame(Frame):
    """
  TODO: should I also ask for sample conditions info with chemical shifts? Or do in ECI - possible? Check!
  """

    # TODO should go where?
    email = '*****@*****.**'

    defaultSelectText = "Select file."
    fontOkColor = 'green3'
    fontCheckColor = 'orange3'
    fontBadColor = 'red3'
    fontDefaultColor = 'black'

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

        #
        # Variable initialisation
        #

        self.fcWrapper = basePopup.fcWrapper
        self.project = basePopup.project
        self.basePopup = basePopup

        # TODO necessary?
        if self.project:
            self.nmrProject = self.project.currentNmrProject
            self.entry = self.project.currentNmrEntryStore.findFirstEntry()
            if not self.entry:
                self.entry = self.project.currentNmrEntryStore.newEntry(
                    name=self.project.name)
        else:
            self.nmrProject = None

        self.sequenceCoordinatesLoaded = False
        self.shiftsLoaded = False
        self.linkResDone = False

        self.currentShiftList = None
        self.shiftListChainPairs = []

        self.moleculeList = []
        self.moleculeDict = {}

        #
        # Frame setup
        #

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

        self.grid_columnconfigure(1, weight=1)
        self.grid_rowconfigure(1, weight=1)

        options = ['Import', 'Deposition']

        tabbedFrame = TabbedFrame(self,
                                  options=options,
                                  callback=self.selectTab)
        tabbedFrame.grid(row=1, column=0, columnspan=2, sticky='nsew')

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

        #
        # Main
        #

        frameA.grid_columnconfigure(0, weight=1)
        #frameA.grid_columnconfigure(1, weight=1) # Change to 2 if want 2 columns
        frameA.grid_rowconfigure(12, weight=1)
        #frameA.grid_rowconfigure(12, weight=1)

        row = 0

        div = LabelDivider(
            frameA,
            text=
            'Select the full coordinate file or a sequence file (with info for a single molecule).',
            justify='center',
            grid=(row, 0),
            gridSpan=(1, 1))

        row += 1

        self.sequenceCoordinatesImport = Button(
            frameA,
            text=self.defaultSelectText,
            command=self.importSequenceOrCoords,
            foreground=self.fontDefaultColor)
        self.sequenceCoordinatesImport.grid(row=row, column=0, sticky='ew')

        row += 1

        label = Label(frameA, text="")
        label.grid(row=row, column=0, sticky='ew')

        row += 1

        div = LabelDivider(
            frameA,
            text='Select the molecule relevant for your chemical shift file.',
            justify='center',
            grid=(row, 0),
            gridSpan=(1, 1))

        row += 1

        self.moleculeSelect = Label(
            frameA,
            text="None available yet - import valid file first",
            foreground=self.fontBadColor)
        self.moleculeSelect.grid(row=row, column=0, sticky='ew')
        self.moleculeSelectRow = row

        row += 1

        label = Label(frameA, text="")
        label.grid(row=row, column=0, sticky='ew')

        row += 1

        div = LabelDivider(
            frameA,
            text=
            'Select a chemical shift file with values only for the above molecule.',
            justify='center',
            grid=(row, 0),
            gridSpan=(1, 1))

        row += 1

        self.shiftImport = Button(frameA,
                                  text=self.defaultSelectText,
                                  command=self.importShifts,
                                  foreground=self.fontDefaultColor)
        self.shiftImport.grid(row=row, column=0, sticky='ew')

        row += 1

        label = Label(frameA, text="")
        label.grid(row=row, column=0, sticky='ew')

        row += 1

        div = LabelDivider(
            frameA,
            text='Consistency check between molecule and shift information.',
            justify='center',
            grid=(row, 0),
            gridSpan=(2, 1))

        row += 1

        self.linkResCheckInfo = Label(frameA, text='')
        self.linkResCheckInfo.grid(row=row, column=0, sticky='ew')

        row += 1

        div = Separator(frameA, grid=(row, 0), gridSpan=(1, 1))

        row += 1

        texts = ['Import new sequence', 'Import new set of shifts']
        commands = [self.resetSequenceImport, self.resetShiftImport]

        self.mainButtons = ButtonList(frameA, texts=texts, commands=commands)
        self.mainButtons.grid(row=row, column=0, columnspan=2, sticky='ew')
        self.mainButtons.buttons[0].config(foreground=self.fontDefaultColor)

        #print row

        self.frameA = frameA

        #
        # Not in use...
        #

        #frameX.grid_columnconfigure(0, weight=1)
        #frameX.grid_columnconfigure(1, weight=1)
        #frameX.grid_rowconfigure(1, weight=1)
        #frameX.grid_rowconfigure(3, weight=1)

        #
        # Deposition, is updated after each successful import run.
        #

        frameD.grid_columnconfigure(0, weight=1)
        frameD.grid_rowconfigure(5, weight=1)

        self.frameD = frameD

        row = 0

        div = LabelDivider(frameD,
                           text='Imported data.',
                           justify='center',
                           grid=(row, 0),
                           gridSpan=(1, 2))

        row += 1

        self.depositionImportText = "\nImported %d shift list(s) for a total of %d shifts.\n\nImported %d molecule(s) and %d chain(s).\n\nImported %d model(s) for a total of %d atom coordinates.\n\nLinked %.2f%% of imported NMR information to %d chain(s)."
        self.depositionImportLoc = (row, 0)

        # These used for setting text above...
        self.depositionImportNums = [0, 0, 0, 0, 0, 0, 0.0, 0]
        self.importedShiftLists = []
        self.connectedChains = []

        self.depositionImportLabel = Label(frameD,
                                           text=self.depositionImportText %
                                           tuple(self.depositionImportNums),
                                           foreground=self.fontBadColor)
        self.depositionImportLabel.grid(row=row, column=0, sticky='ew')

        row += 1

        label = Label(frameD, text="")
        label.grid(row=row, column=0, sticky='ew')

        #
        # Finalize the import part, proceed to ECI.
        #

        row += 1

        div = LabelDivider(
            frameD,
            text=
            'Import completed, save project and start Entry Completion Interface.',
            justify='center',
            grid=(row, 0),
            gridSpan=(1, 1))

        row += 1

        self.eciStart = Button(frameD,
                               text="Finalise import",
                               command=self.finaliseImport,
                               foreground=self.fontBadColor)
        self.eciStart.grid(row=row, column=0, sticky='ew')

    def finaliseImport(self):

        if not self.depositionImportNums[6]:
            showWarning('Failure',
                        'Need connected molecule and shift information first')
            return

        if showYesNo(
                "Save project and continue annotation",
                "Are you sure you want to save this project and continue?",
                parent=self):

            if self.depositionImportNums[5] or showYesNo(
                    "No coordinates",
                    "No coordinates are available - are you sure you want to continue?",
                    parent=self):

                showInfo("Project name",
                         "Your project will be saved in the %s directory." %
                         self.project.name,
                         parent=self)

                self.project.saveModified()

                #userData = self.project.findFirstRepository(name='userData')
                #currentPath = userData.url.path
                #currentProjectName = self.project.name

                #projectDir = os.path.join(currentPath,currentProjectName)

                eci = EntryCompletionGui(self.basePopup.root)
                eci.initProject(self.project)

    #
    # File type determination and import
    #

    def createFileTypes(self, dataTypes):

        fileTypes = [FileType('all', ['*'])]

        for dataType in dataTypes:
            formatNames = fileTypeDict[dataType].keys()
            formatNames.sort()
            for formatName in formatNames:
                if formatName in self.fcWrapper.formatNameLists[dataType]:
                    fileTypes.append(
                        FileType(formatName,
                                 fileTypeDict[dataType][formatName]))

        return fileTypes

    def getFileName(self, title, fileTypes):

        fileSelectPopup = FileSelectPopup(
            self,
            file_types=fileTypes,
            title=title,
            dismiss_text='Cancel',
            selected_file_must_exist=True,
            multiSelect=False,
        )

        self.fileName = fileSelectPopup.getFile()

        if not self.fileName:
            showWarning('Failure',
                        'Please select an existing file.',
                        parent=self)
            return False

        return True

    def importSequenceOrCoords(self):

        dataTypes = ['sequence', 'coordinates']
        fileTypes = self.createFileTypes(dataTypes)

        if self.getFileName('Import sequence or coordinate file', fileTypes):

            formatNameSuggestions = {}

            for dataType in dataTypes:

                tmpList = self.fcWrapper.determineFormatNamesForFile(
                    dataType, self.fileName)

                if tmpList:
                    formatNameSuggestions[dataType] = tmpList

            if not formatNameSuggestions:
                showWarning(
                    'Failure',
                    'This file cannot be read by this software.\nPlease send the file with an explanation to %s.'
                    % self.email,
                    parent=self)
                return False

            #
            # Let user select if multiple options, otherwise take default
            #

            if len(formatNameSuggestions) == 1 and len(formatNameSuggestions[
                    formatNameSuggestions.keys()[0]]) == 1:

                dataType = formatNameSuggestions.keys()[0]
                formatName = formatNameSuggestions[dataType][0]

                if not showYesNo(
                        'File type detected',
                        'Reading as %s file in %s format. Is this correct?' %
                    (dataType, formatName),
                        parent=self):
                    showWarning(
                        'Failure',
                        'This file cannot be read by this software.\nPlease send the file with an explanation to %s.'
                        % self.email,
                        parent=self)
                    return False

            else:

                #
                # Create a selection (hopefully user-understandable)
                #

                selectionList = []
                selectionDict = {}

                for dataType in dataTypes:

                    dataTypeString = dataType

                    if formatNameSuggestions.has_key(dataType):
                        formatNames = formatNameSuggestions[dataType]
                        formatNames.sort()

                        for formatName in formatNames:
                            selectionString = "%s file in %s format." % (
                                dataTypeString, formatName)
                            selectionList.append(selectionString)
                            selectionDict[selectionString] = (dataType,
                                                              formatName)

                interaction = SelectionListPopup(self,
                                                 selectionList,
                                                 title='File format selection',
                                                 text='This is a:',
                                                 selectionDict=selectionDict,
                                                 dismissButton=True,
                                                 modal=True)

                #
                # Check if anything was selected...
                #

                dataType = formatName = None

                if interaction.isSelected:
                    (dataType, formatName) = interaction.selection
                else:
                    showWarning(
                        'Failure',
                        'This file cannot by read without a format selection.\nIf the correct format is not available, please send the file with an explanation to %s'
                        % self.email,
                        parent=self)
                    return False

            #
            # Now read the file, need to do some field updates!
            #

            (fileRead, fileInformation) = self.fcWrapper.readFile(
                dataType, formatName, self.fileName)

            if not fileRead:
                showWarning(
                    'Failure',
                    'This file cannot be read by this software:%s\nPlease send the file with an explanation to %s.'
                    % (fileInformation, self.email),
                    parent=self)
                return False

            (conversionInfo, conversionSuccess) = (
                self.fcWrapper.formatConversion.conversionInfo,
                self.fcWrapper.formatConversion.conversionSuccess)

            if not conversionSuccess:
                showWarning(
                    'Failure',
                    'This file was read by the software but contains invalid information.\nPlease send the file with an explanation to %s.'
                    % self.email,
                    parent=self)
                return False

            #
            # Set info if import worked OK
            #

            conversionLines = conversionInfo.split(": ")

            showInfo("Import coordinate and/or sequence information",
                     ":\n".join(conversionLines),
                     parent=self)

            if dataType == 'sequence':
                chains = self.fcWrapper.importReturns[dataType]
                models = []
            elif dataType == 'coordinates':
                models = self.fcWrapper.importReturns[dataType]
                chains = [
                    cChain.chain
                    for cChain in models[0].structureEnsemble.coordChains
                ]

            self.sequenceCoordinatesImport.setText(
                self.fileName)  # TODO change color or something?
            self.sequenceCoordinatesImport.configure(
                foreground=self.fontOkColor)

            self.sequenceCoordinatesLoaded = True

            #
            # Reset to list selector for further use
            #

            moleculeName = None

            for chain in chains:

                if chain in self.moleculeDict.values():
                    continue

                numResidues = len(chain.residues)
                if numResidues == 1:
                    residueText = "%s residue" % chain.findFirstResidue(
                    ).ccpCode
                else:
                    residueText = "%d residues" % numResidues

                moleculeName = "%s (chain '%s', %s)" % (
                    chain.molecule.name, chain.code, residueText)

                self.moleculeList.append(moleculeName)
                self.moleculeDict[moleculeName] = chain

            self.moleculeList.sort()

            self.moleculeSelect.destroy()

            if len(chains) == 1 and moleculeName:
                selectedIndex = self.moleculeList.index(moleculeName)
            else:
                selectedIndex = 0

            self.moleculeSelect = PulldownList(self.frameA,
                                               texts=self.moleculeList,
                                               index=selectedIndex,
                                               sticky='ew')
            self.moleculeSelect.grid(row=self.moleculeSelectRow, column=0)

            #
            # Now update Deposition tab
            #

            molecules = []
            for chain in chains:
                if not chain.molecule in molecules:
                    molecules.append(chain.molecule)

            numCoords = 0
            for model in models:
                numCoords += len(model.coords)

            self.updateDepositionImportLabel(molecules=len(molecules),
                                             chains=len(chains),
                                             models=len(models),
                                             coordinates=numCoords)

            # Add the molSystem to the entry!
            if chains and not chains[0].molSystem == self.entry.molSystem:
                self.entry.molSystem = chains[0].molSystem

        self.updateAll()

    def importShifts(self):

        currentChain = self.getCurrentChain()

        if not currentChain:
            showWarning(
                'Failure',
                'Please first read in a sequence or coordinate file and select the molecule relevant for this shift list.',
                parent=self)
            return

        elif self.currentShiftList:
            shiftListChainPair = (self.currentShiftList, currentChain)

            if shiftListChainPair in self.shiftListChainPairs:
                showWarning(
                    'Failure',
                    "You already read in chemical shifts for this chain.\nPlease read in related shifts for the other chain(s), if present, or press the 'Import new set of shifts' button to read in a new set of shifts.",
                    parent=self)
                return

        dataType = 'shifts'

        fileTypes = self.createFileTypes([dataType])

        if self.getFileName('Import chemical shift file', fileTypes):

            formatNameSuggestions = self.fcWrapper.determineFormatNamesForFile(
                dataType, self.fileName)

            if not formatNameSuggestions:
                showWarning(
                    'Failure',
                    'This file cannot be read by this software.\nPlease send the file with an explanation to %s.'
                    % self.email,
                    parent=self)
                return False

            #
            # Let user select if multiple options, otherwise take default
            #

            if len(formatNameSuggestions) == 1:

                formatName = formatNameSuggestions[0]

                if not showYesNo(
                        'File type detected',
                        'Reading as a chemical shift file in %s format. Is this correct?'
                        % formatName,
                        parent=self):
                    showWarning(
                        'Failure',
                        'This file cannot be read by this software.\nPlease send the file with an explanation to %s.'
                        % self.email,
                        parent=self)
                    return False

            else:

                #
                # Create a selection (hopefully user-understandable)
                #

                selectionList = []
                selectionDict = {}

                formatNameSuggestions.sort()

                for formatName in formatNameSuggestions:
                    selectionString = "chemical shift file in %s format." % (
                        formatName)
                    selectionList.append(selectionString)
                    selectionDict[selectionString] = formatName

                interaction = SelectionListPopup(self,
                                                 selectionList,
                                                 title='File format selection',
                                                 text='This is a:',
                                                 selectionDict=selectionDict,
                                                 dismissButton=True,
                                                 modal=True)

                #
                # Check if anything was selected...
                #

                formatName = None

                if interaction.isSelected:
                    formatName = interaction.selection
                else:
                    showWarning(
                        'Failure',
                        'This file cannot by read without a format selection.\nIf the correct format is not available, please send the file with an explanation to %s'
                        % self.email,
                        parent=self)
                    return False

            #
            # Now read the file, need to do some field updates! Also make sure to re-use shift list for other molecules...
            #

            (fileRead, fileInformation) = self.fcWrapper.readFile(
                dataType,
                formatName,
                self.fileName,
                addKeywords={'measurementList': self.currentShiftList})

            if not fileRead:
                showWarning(
                    'Failure',
                    'This file cannot be read by this software:%s\nPlease send the file with an explanation to %s.'
                    % (fileInformation, self.email),
                    parent=self)
                return False

            (conversionInfo, conversionSuccess) = (
                self.fcWrapper.formatConversion.conversionInfo,
                self.fcWrapper.formatConversion.conversionSuccess)

            if not conversionSuccess:
                showWarning(
                    'Failure',
                    'This file was read by the software but contains invalid information.\nPlease send the file with an explanation to %s.'
                    % self.email,
                    parent=self)
                return False

            #
            # Set info if import worked OK
            #

            conversionLines = conversionInfo.split(": ")

            showInfo("Import chemical shift information",
                     ":\n".join(conversionLines),
                     parent=self)

            self.shiftImport.setText(
                self.fileName)  # TODO change color or something?
            self.shiftImport.configure(foreground=self.fontOkColor)
            self.shiftsLoaded = True
            self.shiftsFormatName = formatName

            shiftList = self.fcWrapper.importReturns[dataType]

            if not self.currentShiftList:
                self.currentShiftList = shiftList

            self.shiftListChainPairs.append(
                (self.currentShiftList, currentChain))

            self.updateDepositionImportLabel(shiftList=shiftList)

            if not shiftList in self.entry.measurementLists:
                print shiftList
                self.entry.addMeasurementList(shiftList)
                print self.entry.measurementLists

        self.updateAll()

    #
    # Updaters
    #

    def selectTab(self, index):

        funcsDict = {
            0: (self.updateMain, ),
            1: (self.updateCoordinates, ),
            2: (self.updateDeposition, )
        }

        for func in funcsDict[index]:
            func()

    def updateMain(self):

        pass

    def updateCoordinates(self):

        pass

    def updateDeposition(self):

        pass

    def updateAll(self):

        self.selectTab(self.tabbedFrame.selected)

        if self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Connect shifts to sequence',
                    'You have to check whether the chemical shift information matches the sequence. Do you want to this now?',
                    parent=self):
                self.connectShiftsSequence()

        self.waiting = False

    def getCurrentChain(self):

        if len(self.moleculeList) == 1:
            chain = self.moleculeDict.values()[0]
        else:
            try:
                moleculeSelected = self.moleculeSelect.getText()
                chain = self.moleculeDict[moleculeSelected]
            except:
                chain = None

        return chain

    def connectShiftsSequence(self):

        if not self.linkResDone:

            changeResetColor = False

            #
            # Get chain mapping and run linkResonances
            #

            chain = self.getCurrentChain()

            forceChainMappings = self.fcWrapper.linkResonancesToSequence(
                chain=chain)
            self.fcWrapper.formatConversion.linkResonances(
                forceChainMappings=forceChainMappings, guiParent=self)

            #
            # Get information about the linking process
            #
            # TODO Should only have an nmrProject (no restraint import, should be included?)
            # In any case, is always the LAST info in numResonancesLinked info

            numResonancesLinked = self.fcWrapper.formatConversion.numResonancesLinked
            (origLinked, origUnlinked, linked,
             unlinked) = (numResonancesLinked['origLinked'][-1],
                          numResonancesLinked['origUnlinked'][-1],
                          numResonancesLinked['linked'][-1],
                          numResonancesLinked['unlinked'][-1])

            #
            # Track number of new resonances, and reset for new import
            #

            if self.fcWrapper.formatConversion.allResonancesLinked:
                status = 'All information matches (for all imports).'
                foreground = self.fontOkColor
                changeResetColor = True
            else:
                if origUnlinked - unlinked == self.fcWrapper.numNewResonances:
                    status = 'All information matches (for this import)'
                    foreground = self.fontOkColor
                    changeResetColor = True
                else:
                    if origUnlinked != unlinked:
                        status = 'Not all information matches (for this and/or another import).'
                        foreground = self.fontCheckColor
                        changeResetColor = True
                    else:
                        status = 'No information matches (for this import).'
                        foreground = self.fontBadColor

                    otherUnlinked = (origUnlinked -
                                     self.fcWrapper.numNewResonances)
                    notLinked = unlinked - otherUnlinked

                    status += "\nUnable to link %d out of %d imported shifts (%.2f%%)." % (
                        notLinked, self.fcWrapper.numNewResonances,
                        (notLinked * 100.0) / self.fcWrapper.numNewResonances)

            self.linkResCheckInfo.set("Status: %s" % status)
            self.linkResCheckInfo.config(foreground=foreground)

            self.linkResDone = True

            #
            # Change the color of the reset button to indicate OK to do next one
            #

            if changeResetColor:

                self.mainButtons.buttons[0].config(foreground=self.fontOkColor)

                self.updateDepositionImportLabel(
                    shiftList=None,
                    percentageLinked=(linked * 100.0 / (unlinked + linked)),
                    connectedChain=chain)

    def updateDepositionImportLabel(self,
                                    shiftList=None,
                                    molecules=0,
                                    chains=0,
                                    models=0,
                                    coordinates=0,
                                    percentageLinked=None,
                                    connectedChain=None):

        if shiftList and shiftList not in self.importedShiftLists:
            self.importedShiftLists.append(shiftList)
            self.depositionImportNums[0] += 1

        shifts = 0
        for shiftList in self.importedShiftLists:
            shifts += len(shiftList.measurements)

        self.depositionImportNums[1] += shifts
        self.depositionImportNums[2] += molecules
        self.depositionImportNums[3] += chains
        self.depositionImportNums[4] += models
        self.depositionImportNums[5] += coordinates

        if percentageLinked != None:
            self.depositionImportNums[6] = percentageLinked

        if connectedChain and connectedChain not in self.connectedChains:
            self.depositionImportNums[7] += 1
            self.connectedChains.append(connectedChain)

        self.depositionImportLabel.destroy()

        finalForeground = self.fontBadColor
        if self.depositionImportNums[0] == 0 and self.depositionImportNums[
                2] == 0:
            # Nothing imported
            foreground = self.fontBadColor

        elif self.depositionImportNums[6]:
            # Linked shifts available - TODO base this on % of shifts linked?
            foreground = self.fontOkColor
            if self.depositionImportNums[5]:
                finalForeground = self.fontOkColor
            else:
                finalForeground = self.fontCheckColor

        else:
            # Intermediate state
            foreground = self.fontCheckColor

        self.depositionImportLabel = Label(self.frameD,
                                           text=self.depositionImportText %
                                           tuple(self.depositionImportNums),
                                           foreground=foreground)
        self.depositionImportLabel.grid(row=self.depositionImportLoc[0],
                                        column=self.depositionImportLoc[1],
                                        sticky='ew')

        self.eciStart.configure(foreground=finalForeground)

    def resetSequenceImport(self):

        doReset = True

        if not self.linkResDone and self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Shifts not connected to sequence',
                    'You have not checked whether the imported chemical shift information matches the imported sequence. Do you want to this first? If not, the last imported data will be invalid.',
                    parent=self):
                self.connectShiftsSequence()
                doReset = False

        if doReset:

            self.mainButtons.buttons[0].config(
                foreground=self.fontDefaultColor)

            self.sequenceCoordinatesLoaded = self.shiftsLoaded = self.linkResDone = False

            self.sequenceCoordinatesImport.setText(self.defaultSelectText)
            self.sequenceCoordinatesImport.configure(
                foreground=self.fontDefaultColor)

            self.moleculeSelect.destroy()
            self.moleculeSelect = Label(
                self.frameA,
                text="None available yet - import valid file first",
                foreground=self.fontBadColor)
            self.moleculeSelect.grid(row=self.moleculeSelectRow,
                                     column=0,
                                     sticky='ew')

            self.shiftImport.setText(self.defaultSelectText)
            self.shiftImport.configure(foreground=self.fontDefaultColor)

            self.linkResCheckInfo.set("")

    def resetShiftImport(self):

        doReset = True

        if not self.linkResDone and self.sequenceCoordinatesLoaded and self.shiftsLoaded:
            if showYesNo(
                    'Shifts not connected to sequence',
                    'You have not checked whether the imported chemical shift information matches the imported sequence. Do you want to this first? If not, the last imported data will be invalid.',
                    parent=self):
                self.connectShiftsSequence()
                doReset = False

        if doReset:

            self.mainButtons.buttons[1].config(
                foreground=self.fontDefaultColor)

            self.shiftsLoaded = self.linkResDone = False

            self.currentShiftList = None

            self.shiftImport.setText(self.defaultSelectText)
            self.shiftImport.configure(foreground=self.fontDefaultColor)

            self.linkResCheckInfo.set("")

    def destroy(self):

        Frame.destroy(self)

    #
    # Instructions
    #

    def showMainInstructions(self):

        popup = getPopup(self)

        message = """Use this tab to import the chemical shifts and the coordinate and/or sequence information for your molecular chains.
    
The imported chemical shift file should contain information for only *one* molecular chain to make it easier to connect the molecule information to the chemical shift information. You therefore have to select a single chain for each shift list from the dropdown menu that will appear after you imported a coordinate or sequence file.
    
For example, when using sequence files for a dimer, import the information for the chemical shifts for each chain separately:
    
  1. Import the sequence for the first molecular chain.
  2. Import a chemical shift file with shifts only for this molecular chain.  
  3. Reset using the 'Import new sequence' button
  4. Import the sequence for the second molecular chain
  5. Import a chemical shift file with shifts only for this second chain
  
Alternatively, it is possible to read in the molecule information from a full coordinate file:

  1. Import a coordinate file with all molecular information, including coordinates.
  2. Select a molecular chain.
  3. Import a chemical shift file with shifts only for the selected molecular chain.
  4. Go back to step 2. if necessary.
  
You can also import multiple sets of chemical shifts (e.g. for the sample in different conditions). In this case, you have to import all chemical shift information that belongs together for all molecular chains, then press the 'Import new set of shifts' button.

Notes:

1. This application always creates a new CCPN project. It is not possible to import files into existing projects.
2. If your chemical shift file contains information for multiple chains, you have to edit it manually to split up the information per chain.
    """

        showHelpText(self, message, popup=popup)

    def showFormats(self):

        popup = getPopup(self)

        message = """For chemical shifts, the following formats are recognised:

*** Auremol ***

section_sequenzdefinition
_Residue_seq_code
_Atom_num_code
_Residue_label
_Atom_name
_Atom_type
_Atom_alias
_Atom_equivalent
_Atom_CSA
  1   1 MET   HN H   -      -            8.95
  1   2 MET    N N   -      -          157.00
  1   3 MET   CA C   -      -           40.00


*** Autoassign ***

AA        HN    N15    CO-1   CA-1   CB-1   HA-1          CO     CA     CB     HA

A31      8.14  121.4                                            51.3   19.6                 (GS178 115.HSQC)
D32      8.88  122.9          51.3   19.5                       55.4   39.6                 (GS271 22.HSQC)


*** CNS ***

do ( store1 = 53.13218 ) ( resid 78 and name CA )
do ( store1 = 0.7356673 ) ( resid 15 and name HD1# )
do ( store1 = 120.5381 ) ( resid 8 and name N )
do ( store1 = 121.1414 ) ( resid 78 and name N )


*** Cosmos ***

CS_VALUES 3
C_ALA 176.6
CA_ALA 51.66
CB_ALA 17.26
END


*** CSI ***

#     A       HA       CA       CO       CB       Consensus
#
1     MET       0 C      0 C      NA       0 C         0 C 
2     GLY       0 C      0 C      NA       0 C         0 C 


*** MARS ***

            H         N         CO-1      CA        CA-1   
PR_2        8.900   123.220   170.540    55.080    54.450  
PR_4        8.320   115.340   175.920      -       55.080  


*** MONTE ***

         1            102.544      8.211     45.853     54.925      0.000     18.069    180.112 
         2            103.276      8.580     45.334     54.154      0.000     35.650    175.087 
         3            103.997      7.407     45.165      0.000      0.000      0.000      0.000 


*** NMR-STAR ***

data_test

save_shifts1
   _Saveframe_category               assigned_chemical_shifts

   loop_
      _Atom_shift_assign_ID
      _Residue_seq_code
      _Residue_label
      _Atom_name
      _Atom_type
      _Chem_shift_value
      _Chem_shift_value_error
      _Chem_shift_ambiguity_code

          1     1   ASP  CA    C   52.000  0.02  1  
          2     1   ASP  HA    H    4.220  0.02  1  

   stop_

save_


*** NMRVIEW ***

  2.CG1     18.549 0
  2.CG2     18.844 0
  2.HG1#     0.800 0
  2.HG2#     0.723 0
  3.HG2      2.298 0
  3.HG1      2.298 0


*** PIPP ***

RES_ID          1
RES_TYPE        MET
SPIN_SYSTEM_ID  1
    CA        55.9920
    CB        33.1470
    HA         4.1141
    HB#        2.0492
    HG#        2.4250
END_RES_DEF


*** PISTACHIO ***

   1    1  GLY    C     C  172.621  1.000  0 
   2    1  GLY   CA     C   44.308  1.000  0 
   3    2  SER    N     N  122.241  1.000  0 


*** PRONTO ***

Spin system   HN          HA      Other:

1: Val-1                  3.76    HB: 1.945, HG1: 0.770, HG2: 0.608
2: Ile-2      8.80        4.26    HB: 1.526, HG1: 1.278, HG2: 0.728, HD: 0.918


*** SHIFTX ***

  NUM RES   HA     H       N        CA      CB       C
--- --- ------ ------ -------- ------- ------- --------
 2     T  4.4161 8.1749 111.0443 61.8324 70.3867 172.5362
 3     Y  4.9022 9.0239 120.2106 56.0493 41.4218 173.0761

 NUM RES  H    HA   HB   HB2  HB3  HD1  HD2  HD21 HD22 HD3  HE   HE1 HE2  HE21 HE22 HE3  HG   HG1  HG12 HG13 HG2  HG3  HZ
 2     T  8.17 4.42 4.24 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.21 0.00 0.00
 3     Y  9.02 4.90 0.00 2.22 2.20 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00


*** SPARKY ***

 Group   Atom  Nuc    Shift   SDev  Assignments

     R2     CA  13C   56.539  0.003      3
     R2     CB  13C   30.808  0.009      3


*** TALOS ***

VARS   RESID RESNAME PHI PSI DPHI DPSI DIST COUNT CLASS
FORMAT %4d %s %8.3f %8.3f %8.3f %8.3f %8.3f %2d %s

   1 Q 9999.000 9999.000    0.000    0.000    0.000  0 None
   2 N  -85.000  124.000   23.000   28.000   85.920 10 Good


***XEASY/CYANA:

   1 117.803 0.000 N       1
   2   8.208 0.002 HN      1
   3  56.508 0.055 CA      1
   4 999.000 0.000 HA      1
   5  29.451 0.004 CB      1
    
    """

        showHelpText(self, message, popup=popup)
Example #9
0
class ResultsTab(object):
    def __init__(self, parent, frame):

        self.guiParent = parent

        self.frame = frame

        self.project = parent.project

        self.nmrProject = parent.nmrProject

        self.selectedLinkA = None
        self.selectedLinkB = None
        self.selectedResidueA = None
        self.selectedResidueB = None
        self.selectedLink = None

        self.dataModel = self.guiParent.connector.results

        self.body()

    def body(self):

        frame = self.frame

        self.resultsResidueNumber = 1

        frame.expandGrid(5, 0)

        resultTopFrame = LabelFrame(frame, text='Which results to show')
        resultTopFrame.grid(row=0, column=0, sticky='ew')

        self.resultsResidueNumber = 3

        texts = [' < ']
        commands = [self.resultsPrevResidue]
        self.resultsPreviousButton = ButtonList(resultTopFrame,
                                                commands=commands,
                                                texts=texts)
        self.resultsPreviousButton.grid(row=0, column=1, sticky='nsew')

        tipText = 'The Number of the residue in the sequence to display results for'
        self.resultsResidueNumberEntry = IntEntry(
            resultTopFrame,
            grid=(0, 2),
            width=7,
            text=3,
            returnCallback=self.resultsUpdateAfterEntry,
            tipText=tipText)
        #self.resultsResidueNumberEntry.bind('<Leave>', self.resultsUpdateAfterEntry, '+')

        texts = [' > ']
        commands = [self.resultsNextResidue]
        self.resultsNextButton = ButtonList(resultTopFrame,
                                            commands=commands,
                                            texts=texts)
        self.resultsNextButton.grid(row=0, column=3, sticky='nsew')

        selectCcpCodes = ['residue'] + AMINO_ACIDS
        self.resultsSelectedCcpCode = 'residue'

        tipText = 'Instead of going through the sequence residue by residue, jump directly to next amino acid of a specific type.'
        resultsSelectCcpCodeLabel = Label(
            resultTopFrame,
            text='Directly jump to previous/next:',
            grid=(0, 4))
        self.resultsSelectCcpCodePulldown = PulldownList(
            resultTopFrame,
            callback=self.resultsChangeSelectedCcpCode,
            texts=selectCcpCodes,
            index=selectCcpCodes.index(self.resultsSelectedCcpCode),
            grid=(0, 5),
            tipText=tipText)

        self.selectedSolution = 1

        runLabel = Label(resultTopFrame, text='run:')
        runLabel.grid(row=0, column=6)

        texts = [' < ']
        commands = [self.resultsPrevSolution]
        self.resultsPreviousSolutionButton = ButtonList(resultTopFrame,
                                                        commands=commands,
                                                        texts=texts)
        self.resultsPreviousSolutionButton.grid(row=0, column=7, sticky='nsew')

        tipText = 'If you ran the algorithm more than once, you can select the solution given by the different runs.'
        self.resultsSolutionNumberEntry = IntEntry(
            resultTopFrame,
            grid=(0, 8),
            width=7,
            text=1,
            returnCallback=self.solutionUpdateAfterEntry,
            tipText=tipText)
        #self.resultsSolutionNumberEntry.bind('<Leave>', self.solutionUpdateAfterEntry, '+')

        texts = [' > ']
        commands = [self.resultsNextSolution]
        self.resultsNextSolutionButton = ButtonList(resultTopFrame,
                                                    commands=commands,
                                                    texts=texts)
        self.resultsNextSolutionButton.grid(row=0, column=9, sticky='nsew')

        self.energyLabel = Label(resultTopFrame, text='energy:')
        self.energyLabel.grid(row=0, column=10)

        texts = ['template for puzzling']
        commands = [self.adoptSolution]
        self.adoptButton = ButtonList(resultTopFrame,
                                      commands=commands,
                                      texts=texts)
        self.adoptButton.grid(row=0, column=11, sticky='nsew')

        # LabelFrame(frame, text='Spin Systems')
        resultsSecondFrame = Frame(frame)
        resultsSecondFrame.grid(row=2, column=0, sticky='nsew')

        resultsSecondFrame.grid_columnconfigure(0, weight=1)
        resultsSecondFrame.grid_columnconfigure(1, weight=1)
        resultsSecondFrame.grid_columnconfigure(2, weight=1)
        resultsSecondFrame.grid_columnconfigure(3, weight=1)
        resultsSecondFrame.grid_columnconfigure(4, weight=1)

        headingList = ['#', '%']

        tipTexts = [
            'Spinsystem number {} indicates serial of the spinsystem. If the spinsystem was already assigned to a residue, the residue number is shown aswell',
            'percentage of the solutions that connected this spinsystem to this residue'
        ]

        editWidgets = [None, None, None]

        self.displayResultsTables = []
        self.residueLabels = []

        for i in range(5):

            label = Label(resultsSecondFrame, text='residue')
            label.grid(row=0, column=i)

            #editGetCallbacks = [createCallbackFunction(i)]*3

            displayResultsTable = ScrolledMatrix(
                resultsSecondFrame,
                headingList=headingList,
                multiSelect=False,
                tipTexts=tipTexts,
                callback=self.selectSpinSystemForTable,
                passSelfToCallback=True)

            displayResultsTable.grid(row=2, column=i, sticky='nsew')
            displayResultsTable.sortDown = False

            self.residueLabels.append(label)
            self.displayResultsTables.append(displayResultsTable)

        # LabelFrame(frame, text='Sequence Fragment')
        resultsFirstFrame = Frame(resultsSecondFrame)
        resultsFirstFrame.grid(row=1, column=0, sticky='ew', columnspan=5)

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

        texts = [
            ' res 1 ', ' links ', ' res 2 ', ' links ', ' res 3 ', ' links ',
            ' res 4 ', ' links ', ' res 5 '
        ]
        commands = [
            lambda: self.selectRelativeResidue(1, True),
            lambda: self.selectLink(1, True),
            lambda: self.selectRelativeResidue(2, True),
            lambda: self.selectLink(2, True),
            lambda: self.selectRelativeResidue(3, True),
            lambda: self.selectLink(3, True),
            lambda: self.selectRelativeResidue(4, True),
            lambda: self.selectLink(4, True),
            lambda: self.selectRelativeResidue(5, True)
        ]
        self.sequenceButtons = ButtonList(resultsFirstFrame,
                                          commands=commands,
                                          texts=texts)
        self.sequenceButtons.grid(row=0, column=0, sticky='nsew')

        for n, button in enumerate(self.sequenceButtons.buttons):

            if n % 2:

                button.grid(column=n, sticky='ns')

                self.sequenceButtons.grid_columnconfigure(n, weight=0)

            else:

                self.sequenceButtons.grid_columnconfigure(n, uniform=2)

        spacer = Spacer(resultsFirstFrame)
        spacer.grid(row=1, column=0, sticky='nsew')

        texts = [
            ' res 1 ', ' links ', ' res 2 ', ' links ', ' res 3 ', ' links ',
            ' res 4 ', ' links ', ' res 5 '
        ]
        commands = commands = [
            lambda: self.selectRelativeResidue(1, False),
            lambda: self.selectLink(1, False),
            lambda: self.selectRelativeResidue(2, False),
            lambda: self.selectLink(2, False),
            lambda: self.selectRelativeResidue(3, False),
            lambda: self.selectLink(3, False),
            lambda: self.selectRelativeResidue(4, False),
            lambda: self.selectLink(4, False),
            lambda: self.selectRelativeResidue(5, False)
        ]
        self.sequenceButtonsB = ButtonList(resultsFirstFrame,
                                           commands=commands,
                                           texts=texts)
        self.sequenceButtonsB.grid(row=2, column=0, sticky='nsew')

        for n, button in enumerate(self.sequenceButtonsB.buttons):

            if n % 2:

                button.grid(column=n, sticky='ns')

                self.sequenceButtonsB.grid_columnconfigure(n, weight=0)

            else:

                self.sequenceButtonsB.grid_columnconfigure(n, uniform=2)

        frame.grid_rowconfigure(3, weight=2)

        resultsThirdFrame = Frame(frame)
        resultsThirdFrame.grid(row=3, column=0, sticky='nsew')

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

        tabbedFrameB = TabbedFrame(resultsThirdFrame,
                                   options=['Peaks', 'Spin System'],
                                   callback=self.toggleTab,
                                   grid=(0, 0))
        #self.tabbedFrameB = tabbedFrame

        PeakFrame, SpinSystemFrame = tabbedFrameB.frames

        SpinSystemFrame.grid_rowconfigure(0, weight=1)
        PeakFrame.grid_rowconfigure(1, weight=1)

        SpinSystemFrame.grid_columnconfigure(0, weight=1)
        PeakFrame.grid_columnconfigure(0, weight=1)

        headingList = [
            'residue', 'assigned to in project', 'user defined sequence',
            'selected annealing result', '%'
        ]

        tipTexts = [None, None, None, None, None]

        editWidgets = [None, None, None, None, None]

        editGetCallbacks = [None, None, None, None, None]

        editSetCallbacks = [None, None, None, None, None]

        self.spinSysTable = ScrolledMatrix(SpinSystemFrame,
                                           headingList=headingList,
                                           editWidgets=editWidgets,
                                           multiSelect=False,
                                           editGetCallbacks=editGetCallbacks,
                                           editSetCallbacks=editSetCallbacks,
                                           tipTexts=tipTexts)
        self.spinSysTable.grid(row=0, column=0, sticky='nsew')

        buttonFrameinPeakFrame = Frame(PeakFrame)
        buttonFrameinPeakFrame.grid(sticky='ew')

        self.findButton = Button(
            buttonFrameinPeakFrame,
            text=' Go to Peak ',
            borderwidth=1,
            padx=2,
            pady=1,
            command=self.findPeak,
            tipText='Locate the currently selected peak in the specified window'
        )

        self.findButton.grid(row=0, column=0, sticky='e')

        label = Label(buttonFrameinPeakFrame, text='in window:')

        label.grid(row=0, column=1, sticky='w')

        self.windowPulldown = PulldownList(
            buttonFrameinPeakFrame,
            callback=self.selectWindowPane,
            tipText='Choose the spectrum window for locating peaks or strips')

        self.windowPulldown.grid(row=0, column=2, sticky='w')

        self.assignSelectedPeaksButton = Button(
            buttonFrameinPeakFrame,
            text='Assign Resonances to Peak(s)',
            borderwidth=1,
            padx=2,
            pady=1,
            command=self.assignSelectedPeaks,
            tipText=
            'Assign resonances to peak dimensions, this of course only works when the peak is found in the spectrum.'
        )

        self.assignSelectedPeaksButton.grid(row=0, column=3, sticky='ew')

        self.assignSelectedSpinSystemsToResiduesButton = Button(
            buttonFrameinPeakFrame,
            text='Assign Spinsystems to Residues',
            borderwidth=1,
            padx=2,
            pady=1,
            command=self.assignSelectedSpinSystemsToResidues,
            tipText='Assign spinsystems to residues')

        self.assignSelectedSpinSystemsToResiduesButton.grid(row=0,
                                                            column=4,
                                                            sticky='ew')

        headingList = [
            '#', 'spectrum', 'Dim1', 'Dim2', 'Dim3', 'c.s. dim1', 'c.s. dim2',
            'c.s. dim3', 'colabelling'
        ]

        tipTexts = [
            'Peak number, only present when the peak was actually found in the spectrum.',
            'Name of the spectrum',
            'Name of atomSet measured in this dimension. Dimension number corresponds to Ref Exp Dim as indicated by going in the main menu to Experiment-->Experiments-->Experiment Type',
            'Name of atomSet measured in this dimension. Dimension number corresponds to Ref Exp Dim as indicated by going in the main menu to Experiment-->Experiments-->Experiment Type',
            'Name of atomSet measured in this dimension. Dimension number corresponds to Ref Exp Dim as indicated by going in the main menu to Experiment-->Experiments-->Experiment Type',
            'Chemical Shift', 'Chemical Shift', 'Chemical Shift',
            'Colabbeling fraction over all nuclei that are on the magnetization transfer pathway during the experiment that gave rise to the peak, including visited nuclei that were not measured in any of the peak dimensions'
        ]

        #editWidgets = [None, None, None, None, None, None, None, None, None]

        editGetCallbacks = [
            None, None, None, None, None, None, None, None, None
        ]

        #editGetCallbacks = [self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak, self.selectPeak]

        editSetCallbacks = [
            None, None, None, None, None, None, None, None, None
        ]

        self.displayPeakTable = ScrolledMatrix(PeakFrame,
                                               headingList=headingList,
                                               multiSelect=True,
                                               tipTexts=tipTexts)
        #editWidgets=editWidgets, multiSelect=True,
        # editGetCallbacks=editGetCallbacks,
        # editSetCallbacks=editSetCallbacks,
        # tipTexts=tipTexts)
        self.displayPeakTable.grid(row=1, column=0, sticky='nsew')

        self.windowPane = None
        self.updateWindows()

    def selectSpinSystemForTable(self, spinSystem, row, column, table):

        table_number = self.displayResultsTables.index(table)
        self.selectSpinSystem(table_number, spinSystem)

    @lockUntillResults
    def showResults(self):

        self.updateResultsTable()

    @lockUntillResults
    def selectLink(self, number, topRow):

        if topRow:

            self.selectedResidueA = None
            self.selectedResidueB = None
            self.selectedLinkA = number
            self.selectedLinkB = None

        else:

            self.selectedResidueA = None
            self.selectedResidueB = None
            self.selectedLinkA = None
            self.selectedLinkB = number

        self.updateButtons()
        self.updateLink()

    @lockUntillResults
    def selectRelativeResidue(self, number, topRow):

        if topRow:

            self.selectedResidueA = number
            self.selectedResidueB = None
            self.selectedLinkA = None
            self.selectedLinkB = None

        else:

            self.selectedResidueA = None
            self.selectedResidueB = number
            self.selectedLinkA = None
            self.selectedLinkB = None

        self.updateButtons()
        self.updateLink()

    def updateLink(self):
        '''
        Checks for any selected link (self.selectedLinkA or self.selectedLinkB) and calls
        updatePeakTable with the correct residue Object and spinsystem Objects.
        '''

        number = self.selectedLinkA or self.selectedLinkB or self.selectedResidueA or self.selectedResidueB

        if not number:

            self.emptyPeakTable()
            return

        dataModel = self.dataModel
        resNumber = self.resultsResidueNumber
        chain = dataModel.chain
        residues = chain.residues
        solutionNumber = self.selectedSolution - 1

        if self.selectedResidueA:

            res = residues[resNumber - 4 + number]
            spinSystem = res.solutions[solutionNumber]

            self.selectedLink = None
            if res and spinSystem:
                self.selectedLink = res.getIntraLink(spinSystem)

            #self.updatePeakTableIntra(res, spinSystem)
            self.updateSpinSystemTable(spinSystem)

        elif self.selectedResidueB:

            res = residues[resNumber - 4 + number]
            spinSystem = res.userDefinedSolution

            self.selectedLink = None
            if res and spinSystem:
                self.selectedLink = res.getIntraLink(spinSystem)

            #self.updatePeakTableIntra(res, spinSystem)
            self.updateSpinSystemTable(spinSystem)

        elif self.selectedLinkA:

            resA = residues[resNumber - 4 + number]
            resB = residues[resNumber - 3 + number]

            spinSystemA = resA.solutions[solutionNumber]
            spinSystemB = resB.solutions[solutionNumber]

            self.selectedLink = None
            if resA and spinSystemA and spinSystemB:
                self.selectedLink = resA.getLink(spinSystemA, spinSystemB)

            #self.updatePeakTable(resA, spinSystemA, spinSystemB)

        # and resA.userDefinedSolution and resB.userDefinedSolution:
        elif self.selectedLinkB:

            resA = residues[resNumber - 4 + number]
            resB = residues[resNumber - 3 + number]

            spinSystemA = resA.userDefinedSolution
            spinSystemB = resB.userDefinedSolution

            self.selectedLink = None
            if resA and spinSystemA and spinSystemB:
                self.selectedLink = resA.getLink(spinSystemA, spinSystemB)

            #self.updatePeakTable(resA, spinSystemA, spinSystemB)

        self.updatePeakTable()

    def emptyPeakTable(self):

        self.displayPeakTable.update(objectList=[],
                                     textMatrix=[],
                                     colorMatrix=[])

    def updatePeakTable(self):
        '''
        Updates the peak table to show the peaks that are found for a sequencial pair of
        spinsystems A and B. If there is not a linkobject found for spinsystems A and B the
        table is emptied. Also sets the selected peak to None.
        '''

        link = self.selectedLink

        if not link:
            self.emptyPeakTable()

        else:

            resA, resB = link.getResidues()
            spinSystemA, spinSystemB = link.getSpinSystems()
            data = []
            objectList = []
            peakLinks = link.getAllPeakLinks()

            if not peakLinks:
                self.emptyPeakTable()
                return

            maxDimenionality = max([
                len(peakLink.getSimulatedPeak().getContribs())
                for peakLink in peakLinks
            ])

            for peakLink in peakLinks:

                serial = None
                realPeak = peakLink.getPeak()
                simPeak = peakLink.getSimulatedPeak()
                atomTexts = [None] * maxDimenionality
                chemicalShifts = [None] * maxDimenionality

                for simulatedPeakContrib in simPeak.getContribs():

                    atomName = simulatedPeakContrib.getAtomName()

                    #ccpCode = simulatedPeakContrib.getCcpCode()

                    dimNumber = simulatedPeakContrib.getDimNumber()

                    if resA is simulatedPeakContrib.getResidue():

                        spinSystemDescription = spinSystemA.getDescription(
                            noSerialWhenSeqCodeIsPresent=True)

                    else:

                        spinSystemDescription = spinSystemB.getDescription(
                            noSerialWhenSeqCodeIsPresent=True)

                    atomTexts[dimNumber -
                              1] = '%s %s' % (spinSystemDescription, atomName)

                if realPeak:

                    serial = realPeak.getSerial()
                    for dim in realPeak.getDimensions():
                        chemicalShifts[dim.getDimNumber() -
                                       1] = dim.getChemicalShift()

                else:
                    shiftListSerial = simPeak.getSpectrum().getShiftListSerial(
                    )
                    for resonance, simulatedPeakContrib in zip(
                            peakLink.getResonances(), simPeak.getContribs()):

                        if resonance:

                            chemicalShifts[simulatedPeakContrib.getDimNumber()
                                           - 1] = resonance.getChemicalShift(
                                               shiftListSerial)

                        else:

                            chemicalShifts[simulatedPeakContrib.getDimNumber()
                                           - 1] = '?'

                data.append([serial, simPeak.getSpectrum().name] + atomTexts +
                            chemicalShifts + [simPeak.colabelling])
                objectList.append(peakLink)
            headingList = ['#', 'spectrum'] + [
                'dim%s' % a for a in range(1, maxDimenionality + 1)
            ] + ['c.s. dim%s' % a
                 for a in range(1, maxDimenionality + 1)] + ['colabbeling']
            self.displayPeakTable.update(objectList=objectList,
                                         textMatrix=data,
                                         headingList=headingList)

    def findPeak(self):

        if not self.windowPane:

            return

        selectedPeakLinks = self.displayPeakTable.currentObjects

        if not selectedPeakLinks:

            self.guiParent.updateInfoText('Please select a peak first.')
            return

        if len(selectedPeakLinks) > 1:

            self.guiParent.updateInfoText('Can only go to one peak at a time.')
            return

        selectedPeakLink = selectedPeakLinks[0]
        selectedPeak = selectedPeakLink.getPeak()

        if selectedPeak:

            ccpnPeak = selectedPeak.getCcpnPeak()
            createPeakMark(ccpnPeak, lineWidth=2.0)

            windowFrame = self.windowPane.getWindowFrame()
            windowFrame.gotoPeak(ccpnPeak)

        else:

            simPeak = selectedPeakLink.getSimulatedPeak()
            spectrum = simPeak.getSpectrum()
            ccpnSpectrum = spectrum.getCcpnSpectrum()
            view = getSpectrumWindowView(self.windowPane, ccpnSpectrum)

            if not view:

                self.guiParent.updateInfoText(
                    'This peak cannot be displayed in the window you chose.')

            axisMappingByRefExpDimNumber = {}

            for axisMapping in view.axisMappings:

                refExpDimNumber = axisMapping.analysisDataDim.dataDim.expDim.refExpDim.dim

                axisMappingByRefExpDimNumber[refExpDimNumber] = axisMapping

            positionToGoTo = {}
            markPosition = []
            axisTypes = []

            for resonance, contrib in zip(selectedPeakLink.getResonances(),
                                          simPeak.getContribs()):

                dimNumber = contrib.getDimNumber()

                axisMapping = axisMappingByRefExpDimNumber.get(dimNumber)

                label = axisMapping.label

                if resonance:

                    axisType = axisMapping.axisPanel.axisType
                    chemicalShift = resonance.getChemicalShift()

                    positionToGoTo[label] = chemicalShift
                    markPosition.append(chemicalShift)
                    axisTypes.append(axisType)

                # Not drawing a mark at this chemical shift, just hoovering to
                # the good region in the spectrum
                else:

                    ccpCode = contrib.getResidue().getCcpCode()
                    atomName = contrib.getAtomName()

                    medianChemicalShift = self.getMedianChemicalShift(
                        ccpCode, atomName)

                    if medianChemicalShift:

                        positionToGoTo[label] = medianChemicalShift

            if positionToGoTo:

                windowFrame = self.windowPane.getWindowFrame()
                windowFrame.gotoPosition(positionToGoTo)

            if markPosition:

                createNonPeakMark(markPosition, axisTypes)

    def assignSelectedPeaks(self):

        selectedPeakLinks = self.displayPeakTable.currentObjects

        for pl in selectedPeakLinks:

            peak = pl.getPeak()

            if peak:

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

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

                    if ccpnResonance and ccpnDimension:

                        assignResToDim(ccpnDimension, ccpnResonance)

    def assignSelectedSpinSystemsToResidues(self):

        link = self.selectedLink

        if link:

            residues = link.getResidues()
            spinSystems = link.getSpinSystems()

            ccpnSpinSystems = []
            ccpnResidues = []

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

                if spinSys and res:

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

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

            self.updateButtons()
            self.updateButtons()
            self.updateResultsTable()
            self.updatePeakTable()

    def getMedianChemicalShift(self, ccpCode, atomName):

        nmrRefStore = self.project.findFirstNmrReferenceStore(
            molType='protein', ccpCode=ccpCode)

        chemCompNmrRef = nmrRefStore.findFirstChemCompNmrRef(
            sourceName='RefDB')

        chemCompVarNmrRef = chemCompNmrRef.findFirstChemCompVarNmrRef(
            linking='any', descriptor='any')

        if chemCompVarNmrRef:

            chemAtomNmrRef = chemCompVarNmrRef.findFirstChemAtomNmrRef(
                name=atomName)

            if chemAtomNmrRef:

                distribution = chemAtomNmrRef.distribution

                maxIndex = max([
                    (value, index) for index, value in enumerate(distribution)
                ])[1]

                return chemAtomNmrRef.refValue + chemAtomNmrRef.valuePerPoint * (
                    maxIndex - chemAtomNmrRef.refPoint)

        return None

    def selectWindowPane(self, windowPane):

        if windowPane is not self.windowPane:
            self.windowPane = windowPane

    def updateWindows(self):

        index = 0
        windowPane = None
        windowPanes = []
        names = []
        peakList = None
        tryWindows = WindowBasic.getActiveWindows(self.project)

        windowData = []
        getName = WindowBasic.getWindowPaneName

        for window in tryWindows:
            for windowPane0 in window.spectrumWindowPanes:
                # if WindowBasic.isSpectrumInWindowPane(windowPane0, spectrum):
                windowData.append((getName(windowPane0), windowPane0))

            windowData.sort()
            names = [x[0] for x in windowData]
            windowPanes = [x[1] for x in windowData]

        if windowPanes:
            if windowPane not in windowPanes:
                windowPane = windowPanes[0]

            index = windowPanes.index(windowPane)

        else:
            windowPane = None

        self.selectWindowPane(windowPane)

        self.windowPulldown.setup(names, windowPanes, index)

    def selectSpinSystem(self, number, spinSystem):

        res = self.dataModel.chain.residues[self.resultsResidueNumber - 3 +
                                            number]

        oldSpinSystemForResidue = res.userDefinedSolution

        if oldSpinSystemForResidue and res.getSeqCode(
        ) in oldSpinSystemForResidue.userDefinedSolutions:

            oldSpinSystemForResidue.userDefinedSolutions.remove(
                res.getSeqCode())

        res.userDefinedSolution = spinSystem

        spinSystem.userDefinedSolutions.append(res.getSeqCode())

        # self.updateSpinSystemTable(spinSystem)
        self.updateLink()
        self.updateButtons()

    def updateSpinSystemTable(self, spinSystem):

        if not spinSystem:

            self.emptySpinSystemTable()
            return

        dataModel = self.dataModel

        residues = dataModel.chain.residues

        data = []
        colorMatrix = []

        for residue in spinSystem.allowedResidues:

            oneRow = []
            oneRowColor = []
            string = str(residue.getSeqCode()) + ' ' + residue.getCcpCode()

            oneRow.append(string)

            resonanceGroup = spinSystem.getCcpnResonanceGroup()
            ccpnResidue = residue.ccpnResidue

            # Assigned in the project to this residue
            if resonanceGroup and resonanceGroup.residue and resonanceGroup.residue is ccpnResidue:
                oneRow.append('x')
            else:
                oneRow.append(None)

            # The user selected this res for this spinsystem (could be more
            # than one res for which this happens)
            if residue.getSeqCode() in spinSystem.userDefinedSolutions:
                oneRow.append('x')
            else:
                oneRow.append(None)

            if residue.solutions[self.selectedSolution - 1] == spinSystem:
                oneRow.append('x')
            else:
                oneRow.append(None)

            if spinSystem.solutions:

                percentage = spinSystem.solutions.count(
                    residue.getSeqCode()) / float(len(
                        spinSystem.solutions)) * 100.0

            else:

                percentage = 0

            oneRow.append(int(percentage + 0.5))
            color = pick_color_by_percentage(percentage)
            oneRowColor = [color] * 5

            data.append(oneRow)
            colorMatrix.append(oneRowColor)

        self.spinSysTable.update(objectList=data,
                                 textMatrix=data,
                                 colorMatrix=colorMatrix)

        self.spinSysTable.sortDown = False
        self.spinSysTable.sortLine(-1, noUpdate=True)

    def emptySpinSystemTable(self):

        self.spinSysTable.update(objectList=[], textMatrix=[], colorMatrix=[])

    @lockUntillResults
    def adoptSolution(self):

        dataModel = self.dataModel
        selectedSolution = self.selectedSolution

        for res in dataModel.chain.residues:

            spinSystem = res.solutions[selectedSolution - 1]
            res.userDefinedSolution = spinSystem
            spinSystem.userDefinedSolutions = [res.getSeqCode()]

        self.updateLink()
        self.updateButtons()

    @lockUntillResults
    def resultsPrevSolution(self):

        if self.selectedSolution != 1:
            self.selectedSolution = self.selectedSolution - 1
            self.resultsSolutionNumberEntry.set(self.selectedSolution)

            self.updateLink()
            self.updateButtons()
            self.updateEnergy()

    @lockUntillResults
    def resultsNextSolution(self):

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

        if self.selectedSolution < amountOfRepeats:
            self.selectedSolution = self.selectedSolution + 1
            self.resultsSolutionNumberEntry.set(self.selectedSolution)

            self.updateLink()
            self.updateButtons()
            self.updateEnergy()

    @lockUntillResults
    def resultsPrevResidue(self):

        residues = self.dataModel.chain.residues
        #chainLength = len(residues)

        new_value = self.resultsResidueNumber
        if self.resultsSelectedCcpCode == 'residue':
            if self.resultsResidueNumber != 3:
                new_value = self.resultsResidueNumber - 1
        else:
            for res in residues:
                if res.getSeqCode() == self.resultsResidueNumber:
                    break
                elif res.getCcpCode() == self.resultsSelectedCcpCode:
                    new_value = res.getSeqCode()
                    if new_value < 3:
                        new_value = 3
        if self.resultsResidueNumber != new_value:
            self.resultsResidueNumber = new_value

            self.resultsResidueNumberEntry.set(self.resultsResidueNumber)

            self.updateLink()
            self.updateButtons()
            self.updateButtons()
            self.updateResultsTable()
            self.updateResidueLabels()

    @lockUntillResults
    def resultsNextResidue(self):

        residues = self.dataModel.chain.residues
        chainLength = len(residues)

        new_value = self.resultsResidueNumber
        if self.resultsSelectedCcpCode == 'residue':
            if self.resultsResidueNumber != chainLength - 2:
                new_value = self.resultsResidueNumber + 1
        else:
            for res in residues[(self.resultsResidueNumber):]:
                if res.getCcpCode() == self.resultsSelectedCcpCode:
                    new_value = res.getSeqCode()
                    if new_value > chainLength - 2:
                        new_value = chainLength - 2
                    break
        if self.resultsResidueNumber != new_value:
            self.resultsResidueNumber = new_value
            self.resultsResidueNumberEntry.set(self.resultsResidueNumber)

            self.updateLink()
            self.updateButtons()
            self.updateButtons()
            self.updateResultsTable()
            self.updateResidueLabels()

    def resultsChangeSelectedCcpCode(self, ccpCode):

        self.resultsSelectedCcpCode = ccpCode

    @lockUntillResults
    def resultsUpdateAfterEntry(self, event=None):
        '''
        Update for entry of residue number in strip plots
        '''

        residues = self.dataModel.chain.residues

        value = self.resultsResidueNumberEntry.get()
        if value == self.resultsResidueNumber:
            return
        else:
            self.resultsResidueNumber = value
        if value < 3:
            self.resultsResidueNumberEntry.set(3)
            self.resultsResidueNumber = 3

        elif value > len(residues) - 2:
            self.resultsResidueNumber = len(residues) - 2
            self.resultsResidueNumberEntry.set(self.resultsResidueNumber)

        else:
            self.resultsResidueNumberEntry.set(self.resultsResidueNumber)

        self.updateLink()
        self.updateButtons()
        self.updateButtons()
        self.updateResultsTable()
        self.updateResidueLabels()

    @lockUntillResults
    def solutionUpdateAfterEntry(self, event=None):
        '''
        Update for entry of residue number in strip plots
        '''

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

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

        self.updateLink()
        self.updateButtons()

    def update(self):

        self.updateLink()
        self.updateResidueLabels()
        self.updateResultsTable()
        self.updateButtons()
        self.updateButtons()
        self.updateEnergy()

    def updateResultsTable(self):

        resNumber = self.resultsResidueNumber

        dataModel = self.dataModel

        chain = dataModel.chain

        residues = chain.residues

        resA = residues[resNumber - 3]
        resB = residues[resNumber - 2]
        resC = residues[resNumber - 1]
        resD = residues[resNumber]
        resE = residues[resNumber + 1]

        resList = [resA, resB, resC, resD, resE]
        tableList = self.displayResultsTables

        for res, table in zip(resList, tableList):

            ccpCode = res.ccpCode

            spinSystemsWithThisCcpCode = dataModel.getSpinSystems()[ccpCode]

            data = []
            colorMatrix = []
            objectList = []

            jokers = []
            realSpinSystems = []

            for spinSys in spinSystemsWithThisCcpCode:

                if spinSys.getIsJoker():

                    jokers.append(spinSys)

                else:

                    realSpinSystems.append(spinSys)

            for spinsys in realSpinSystems:

                oneRow = []
                oneRowColor = []

                # self.getStringDescriptionOfSpinSystem(spinsys)
                spinSystemInfo = spinsys.getDescription()

                oneRow.append(spinSystemInfo)

                assignmentPercentage = int(
                    float(res.solutions.count(spinsys)) / len(res.solutions) *
                    100.0)

                oneRow.append(assignmentPercentage)

                objectList.append(spinsys)

                color = pick_color_by_percentage(assignmentPercentage)

                oneRowColor = [color, color]

                data.append(oneRow)
                colorMatrix.append(oneRowColor)

            if jokers:

                oneRow = ['Joker']

                NumberOfAssignmentsToJoker = 0

                for spinSys in jokers:

                    NumberOfAssignmentsToJoker += res.solutions.count(spinSys)

                assignmentPercentage = int(
                    float(NumberOfAssignmentsToJoker) / len(res.solutions) *
                    100.0)

                oneRow.append(assignmentPercentage)

                color = pick_color_by_percentage(assignmentPercentage)

                oneRowColor = [color, color]

                data.append(oneRow)
                colorMatrix.append(oneRowColor)
                objectList.append(jokers[0])

            percentages = [datapoint[1] for datapoint in data]

            tableData = sorted(zip(percentages, data, objectList, colorMatrix),
                               reverse=True)

            percentage, data, objectList, colorMatrix = zip(*tableData)

            table.update(objectList=objectList,
                         textMatrix=data,
                         colorMatrix=colorMatrix)

    def updateResidueLabels(self):

        resList = self.getCurrentlyDisplayedResidues()
        labels = self.residueLabels

        for residue, label in zip(resList, labels):

            text = str(residue.getSeqCode()) + ' ' + residue.getCcpCode()

            label.set(text)

    def updateButtons(self):

        self.updateButtonHighLights()
        self.updateResultsTopRowButtons()
        self.updateResultsBottomRowButtons()

    def updateResultsTopRowButtons(self):

        resList = self.getCurrentlyDisplayedResidues()

        buttons = self.sequenceButtons.buttons[::2]

        for button, res in zip(buttons, resList):

            spinsys = res.solutions[self.selectedSolution - 1]

            # str(res.getSeqCode()) + ' ' + res.getCcpCode() + ': ' +
            # spinsys.getDescription()
            # self.getStringDescriptionOfSpinSystem(spinsys)
            text = spinsys.getDescription(noSerialWhenSeqCodeIsPresent=False)

            button.config(text=text)

    def updateResultsBottomRowButtons(self):

        resList = self.getCurrentlyDisplayedResidues()

        buttons = self.sequenceButtonsB.buttons[::2]

        for button, res in zip(buttons, resList):

            if res.userDefinedSolution:

                selectedSpinSystem = res.userDefinedSolution
                text = selectedSpinSystem.getDescription(
                    noSerialWhenSeqCodeIsPresent=False)

                if len(selectedSpinSystem.userDefinedSolutions) > 1:

                    # The red color signals that the spinssystem is used in
                    # more than 1 place in the sequence
                    button.config(text=text, bg=highLightRed)

                else:

                    button.config(text=text)

            else:

                # str(res.getSeqCode()) + ' ' + res.getCcpCode() + ': -'
                text = '-'

                button.config(text=text)

    def updateButtonHighLights(self):

        self.setAllButtonsToGrey()

        if self.selectedResidueA:

            buttons = [
                self.sequenceButtons.buttons[0],
                self.sequenceButtons.buttons[2],
                self.sequenceButtons.buttons[4],
                self.sequenceButtons.buttons[6],
                self.sequenceButtons.buttons[8]
            ]
            buttons[self.selectedResidueA - 1].config(bg=highLightYellow)

        elif self.selectedResidueB:

            buttons = [
                self.sequenceButtonsB.buttons[0],
                self.sequenceButtonsB.buttons[2],
                self.sequenceButtonsB.buttons[4],
                self.sequenceButtonsB.buttons[6],
                self.sequenceButtonsB.buttons[8]
            ]
            buttons[self.selectedResidueB - 1].config(bg=highLightYellow)

        elif self.selectedLinkA:

            buttons = [
                self.sequenceButtons.buttons[1],
                self.sequenceButtons.buttons[3],
                self.sequenceButtons.buttons[5],
                self.sequenceButtons.buttons[7]
            ]
            buttons[self.selectedLinkA - 1].config(bg=highLightYellow)

        elif self.selectedLinkB:

            buttons = [
                self.sequenceButtonsB.buttons[1],
                self.sequenceButtonsB.buttons[3],
                self.sequenceButtonsB.buttons[5],
                self.sequenceButtonsB.buttons[7]
            ]
            buttons[self.selectedLinkB - 1].config(bg=highLightYellow)

    def updateEnergy(self):

        text = 'energy: %s' % int(
            self.dataModel.getEnergy(self.selectedSolution - 1) + 0.5)
        self.energyLabel.set(text)
        self.energyLabel.update()

    def setAllButtonsToGrey(self):

        for button in self.sequenceButtons.buttons + self.sequenceButtonsB.buttons:

            button.config(bg='grey83')

    def setAllRedButtonsToGrey(self):

        for button in self.sequenceButtons.buttons + self.sequenceButtonsB.buttons:

            if button.enableFg == highLightRed:

                button.config(bg='grey83')

    def getCurrentlyDisplayedResidues(self):

        resNumber = self.resultsResidueNumber

        residues = self.dataModel.chain.residues[resNumber - 3:resNumber + 2]

        return residues

    def toggleTab(self, index):

        pass
Example #10
0
class FilterFrame(LabelFrame):
    def __init__(self,
                 guiParent,
                 basePopup,
                 borderRelief='raised',
                 text=' ',
                 justify='left',
                 width=None,
                 font=None,
                 height=None,
                 *args,
                 **kw):

        # 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.borderRelief = borderRelief
        self.text = text
        self.justify = justify
        self.width = width
        self.font = font
        self.height = height

        # get a port proxy instance
        # this should probably belong to the repository directly

        loc = SharedBeanServiceLocator()
        self.port = loc.getSharedBean()

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

        LabelFrame.__init__(self, guiParent, borderRelief, text, justify,
                            width, font, height, *args, **kw)

        # set up the grid

        self.grid_columnconfigure(0, weight=0, minsize=20)

        self.grid_rowconfigure(0, weight=0, minsize=5)
        self.grid_rowconfigure(1, weight=0, minsize=10)
        self.grid_rowconfigure(2, weight=0, minsize=10)
        self.grid_rowconfigure(3, weight=0, minsize=10)

        # build up the body.

        self.nameLabel = Label(self, text='Name:')
        self.nameLabel.grid(row=1, column=0, padx=2, sticky='nw')

        self.nameText = Text(self, width=20, height=1)
        self.nameText.grid(row=1, column=1, sticky='nw')

        self.dateLabel = Label(self, text='Date:')
        self.dateLabel.grid(row=2, column=0, padx=2, sticky='nw')

        self.dateText = Text(self, width=20, height=1)
        self.dateText.grid(row=2, column=1, sticky='nw')

        self.userLabel = Label(self, text='User:'******'nw')

        self.userText = Text(self, width=20, height=1)
        self.userText.grid(row=3, column=1, sticky='nw')

        self.clearButton = Button(self,
                                  text='Clear',
                                  command=self.clear_filter,
                                  width=10,
                                  height=1)
        self.clearButton.grid(row=4, column=0, columnspan=2, sticky='nw')

        self.filterButton = Button(self,
                                   text='Go',
                                   command=self.tmpCall,
                                   width=10,
                                   height=1)
        self.filterButton.grid(row=4, column=1, columnspan=2, sticky='ne')

    def clear_filter(self):

        self.nameText.xlear()
        self.dateText.clear()
        self.userText.clear()

    def tmpCall(self, event=None):

        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):

        return

    def quit(self):

        self.guiParent.parent.destroy()

    def destroy(self):

        self.administerNotifiers(self.basePopup.unregisterNotify)
        Frame.destroy(self)
Example #11
0
    return self.var.get()

  def set(self, text = ''):

    self.var.set(text)

if (__name__ == '__main__'):

  from memops.gui.Button import Button

  msg = 'hello world'
  count = 0

  def func():

    global count

    count = count + 1
    label.set(msg + ' ' + str(count))
    print label.get()

  root = Tkinter.Tk()
 
  label = Label(root, text='hello world')
  label.grid()
  button = Button(root, text='hit me', command=func)
  button.grid()

  root.mainloop()

class RepositoryPropertiesFrame(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.registerNotify = basePopup.registerNotify
        self.unregisterNotify = basePopup.unregisterNotify

        Frame.__init__(self, guiParent)

        # set up the grid

        self.grid_columnconfigure(0, weight=1, minsize=10)
        self.grid_columnconfigure(1, weight=0, minsize=10)
        self.grid_columnconfigure(2, weight=0, minsize=20)
        self.grid_columnconfigure(3, weight=1, minsize=10)

        self.grid_rowconfigure(0, weight=1, minsize=5)
        self.grid_rowconfigure(1, weight=0, minsize=10)
        self.grid_rowconfigure(2, weight=0, minsize=10)
        self.grid_rowconfigure(3, weight=0, minsize=10)
        self.grid_rowconfigure(4, weight=0, minsize=10)
        self.grid_rowconfigure(5, weight=0, minsize=10)
        self.grid_rowconfigure(6, weight=1, minsize=5)

        # build up the body.

        # Column headers

        self.name_label = Label(self, text='Repository Name:')
        self.name_label.grid(row=1, column=1, padx=5, pady=5, sticky='w')

        self.name_value = Text(self, width=20, height=1, text="")
        self.name_value.grid(row=1, column=2, padx=5, pady=5, sticky='w')

        self.rep_label = Label(self, text='Repository Url:')
        self.rep_label.grid(row=2, column=1, padx=5, pady=5, sticky='w')

        self.rep_value = Text(self, width=20, height=1, text="")
        self.rep_value.grid(row=2, column=2, padx=5, pady=5, sticky='w')

        self.user_label = Label(self, text='Username:'******'w')

        self.user_value = Text(self, width=20, height=1, text="")
        self.user_value.grid(row=3, column=2, padx=5, pady=5, sticky='w')

        self.pswd_label = Label(self, text='Password:'******'w')

        self.pswd_value = Text(self, width=20, height=1, text="")
        self.pswd_value.grid(row=4, column=2, padx=5, pady=5, sticky='w')

        self.cancel_button = Button(self,
                                    width=10,
                                    height=1,
                                    text="Cancel",
                                    command=self.quit)
        self.cancel_button.grid(row=5, column=1, padx=5, pady=5, sticky='e')

        self.login_botton = Button(self,
                                   width=10,
                                   height=1,
                                   text="Connect",
                                   command=self.connectRepository)
        self.login_botton.grid(row=5, column=2, padx=5, pady=5, sticky='w')

    def connectRepository(self):

        # need to check that all values are input

        # trim off the end

        name = self.name_value.getText()[:-1]
        connect = self.rep_value.getText()[:-1]
        username = self.user_value.getText()[:-1]
        passwd = self.pswd_value.getText()[:-1]

        # need to test the connection and store the set of connections
        # locally (in rep?)

        self.basePopup.parent.repList.newRepository(name, connect, username)

        # there must be a better way of finding this!

        for ff in self.basePopup.parent.tabbedFrame.frames[0].children.values(
        ):
            ff.draw()

        self.basePopup.destroy()

    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):

        return

    def quit(self):

        self.guiParent.parent.destroy()

    def destroy(self):

        self.administerNotifiers(self.basePopup.unregisterNotify)
        Frame.destroy(self)
Example #13
0
class MultiWidget(Frame):
    def __init__(self,
                 parent,
                 widgetClass,
                 options=None,
                 values=None,
                 callback=None,
                 minRows=3,
                 maxRows=None,
                 useImages=True,
                 *args,
                 **kw):

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

        if not values:
            values = []
        if not options:
            options = []

        # Widget types currently: Entries, Pulldown, Checkbutton

        if useImages:
            gfxDir = path.join(getTopDirectory(), 'python', 'memops', 'gui',
                               'graphics')
            self.crossImage = Tkinter.PhotoImage(
                file=path.join(gfxDir, 'cross.gif'))
            self.tickImage = Tkinter.PhotoImage(
                file=path.join(gfxDir, 'tick.gif'))
            self.plusImage = Tkinter.PhotoImage(
                file=path.join(gfxDir, 'plus.gif'))
            self.minusImage = Tkinter.PhotoImage(
                file=path.join(gfxDir, 'minus.gif'))
        else:
            self.crossImage = None
            self.tickImage = None
            self.plusImage = None
            self.minusImage = None

        module = widgetClass.__module__
        self.widgetType = module.split('.')[-1]
        self.widgetClass = widgetClass
        self.callback = callback

        self.numRows = 0
        self.values = values
        self.options = options
        self.minRows = minRows
        self.maxRows = maxRows
        self.widgets = []
        self.labels = []
        self.grid_columnconfigure(1, weight=1)

        self.topFrame = Frame(self)
        self.topFrame.grid(row=0, column=0, columnspan=4, sticky=Tkinter.NSEW)
        self.topFrame.grid_columnconfigure(1, weight=1)
        self.topFrame.grid_rowconfigure(0, weight=1)

        self.addButton = None
        self.removeButton = None
        self.commitButton = None
        self.cancelButton = None

        self.set(self.values, self.options)

        self.updateButtons()

        self.bind('<KeyPress-Return>', self.commit)
        self.bind('<KeyPress-Escape>', self.cancel)

    def get(self):

        values = []

        if self.widgetType == 'PulldownMenu':
            for i in range(self.numRows):
                value = self.widgets[i].getSelected()
                if value is not None:
                    values.append(value)

        elif self.widgetType == 'PulldownList':
            for i in range(self.numRows):
                value = self.widgets[i].getObject()
                if value is not None:
                    values.append(value)

        else:
            for i in range(self.numRows):
                value = self.widgets[i].get()
                if (value is not None) and (value != ''):
                    values.append(value)

        return values

    def set(self, values=None, options=None):

        if values is not None:
            self.values = values
        if options is not None:
            self.options = options

        N = max(len(self.values), self.minRows)
        if self.maxRows is not None:
            N = min(N, self.maxRows)

        #N = max( min(len(self.values), self.maxRows), self.minRows)
        #N = len(self.values)
        if self.numRows < N:
            for i in range(self.numRows, N):
                self.addRow()

        elif self.numRows > N:
            for i in range(N, self.numRows):
                self.removeRow(doClear=1)

        for i in range(self.numRows):
            if i < len(self.values):
                value = self.values[i]
            else:
                value = None

            if i < len(self.options):
                option = self.options[i]
            else:
                option = None

            self.updateWidget(i, value, option)

    def setOptions(self, options):

        self.set(self.values, options)

    def setValues(self, values):

        self.set(values, self.options)

    def updateWidget(self, row, value, option):

        if self.labels:
            font = self.labels[0].cget('font')
        else:
            font = None

        widget = self.widgets[row]
        if self.widgetType in ('Entry', 'IntEntry', 'FloatEntry'):
            widget.set(value)
            label = self.labels[row]
            label.set(option or '')
            if font:
                label.config(font=font)

        elif self.widgetType == 'PulldownMenu':
            index = -1
            if value in self.options:
                index = self.options.index(value or self.options[0])
            widget.setup(self.options, index)

        elif self.widgetType == 'PulldownList':
            index = 0
            if value in self.options:
                index = self.options.index(value or self.options[0])
            widget.setup(self.options, self.options, index)

        elif self.widgetType == 'CheckButton':
            widget.set(value)
            label = self.labels[row]
            label.set(option or '')
            if font:
                label.config(font=font)

        else:
            raise 'Widget type %s not supported in MultiWidget' % self.widgetType

    def updateButtons(self):

        row = 1
        col = 0
        if self.widgetType != 'CheckButton':
            if (self.maxRows is None) or (self.numRows < self.maxRows):
                if not self.addButton:
                    if self.plusImage:
                        self.addButton = Button(self,
                                                image=self.plusImage,
                                                command=self.addRow,
                                                borderwidth=1)
                    else:
                        self.addButton = Button(self,
                                                text='+',
                                                command=self.addRow,
                                                borderwidth=1,
                                                bg=blueColor)

                self.addButton.grid(row=row, column=col, sticky=Tkinter.EW)
                col += 1

            elif self.addButton:
                self.addButton.grid_forget()

            if self.numRows > self.minRows:
                if not self.removeButton:
                    if self.minusImage:
                        self.removeButton = Button(self,
                                                   image=self.minusImage,
                                                   command=self.removeRow,
                                                   borderwidth=1)
                    else:
                        self.removeButton = Button(self,
                                                   text='-',
                                                   command=self.removeRow,
                                                   borderwidth=1,
                                                   bg=blueColor)
                self.removeButton.grid(row=row, column=col, sticky=Tkinter.EW)
                col += 1

            elif self.removeButton:
                self.removeButton.grid_forget()

        if self.callback:
            if not self.commitButton:
                if self.tickImage:
                    self.commitButton = Button(self,
                                               image=self.tickImage,
                                               command=self.commit,
                                               borderwidth=1)
                else:
                    self.commitButton = Button(self,
                                               text='OK',
                                               command=self.commit,
                                               borderwidth=1,
                                               bg=blueColor)

            self.commitButton.grid(row=row, column=col, sticky=Tkinter.EW)
            self.grid_columnconfigure(col, weight=1)
            col += 1

            if not self.cancelButton:
                if self.crossImage:
                    self.cancelButton = Button(self,
                                               image=self.crossImage,
                                               command=self.cancel,
                                               borderwidth=1)
                else:
                    self.cancelButton = Button(self,
                                               text='Cancel',
                                               command=self.cancel,
                                               borderwidth=1,
                                               bg=blueColor)

            self.cancelButton.grid(row=row, column=col, sticky=Tkinter.EW)
            self.grid_columnconfigure(col, weight=1)

    def addWidget(self, row, value=None):

        if self.widgetType in ('Entry', 'IntEntry', 'FloatEntry'):
            option = ''
            if row < len(self.options):
                option = self.options[row]

            label = Label(self.topFrame, text=option or '', anchor='w')
            label.grid(row=row, column=0, sticky=Tkinter.E)
            self.labels.append(label)

            widget = self.widgetClass(self.topFrame, text=value, width=12)
            widget.grid(row=row, column=1, sticky=Tkinter.EW)

            widget.bind('<KeyPress-Return>', self.commit)
            widget.bind('<KeyPress-Escape>', self.cancel)

        elif self.widgetType == 'PulldownList':
            index = -1
            if value in self.options:
                index = self.options.index(value or self.options[0])
            widget = self.widgetClass(self.topFrame)
            widget.setup(self.options, self.options, index)
            widget.grid(row=row, column=0, columnspan=2, sticky=Tkinter.W)

        elif self.widgetType == 'PulldownMenu':
            index = -1
            if value in self.options:
                index = self.options.index(value or self.options[0])
            widget = self.widgetClass(self.topFrame)
            widget.setup(self.options, index)
            widget.grid(row=row, column=0, columnspan=2, sticky=Tkinter.W)

        elif self.widgetType == 'CheckButton':
            widget = self.widgetClass(self.topFrame)
            widget.set(value)
            widget.grid(row=row, column=0, sticky=Tkinter.W)

            option = ''
            if row < len(self.options):
                option = self.options[row]

            label = Label(self.topFrame, text=option or '', anchor='w')
            label.grid(row=row, column=1, sticky=Tkinter.W)
            self.labels.append(label)

        else:
            raise 'Widget type %s not supported in MultiWidget' % self.widgetType

        return widget

    def commit(self, event=None):

        values = self.get()

        if self.callback:
            self.callback(values)

    def cancel(self, event=None):

        if self.callback:
            self.callback(None)

    def addRow(self):

        if (self.maxRows is None) or (self.numRows < self.maxRows):
            row = self.numRows
            self.numRows += 1

            if self.numRows > len(self.widgets):
                widget = self.addWidget(row)
                self.widgets.append(widget)

            else:
                widget = self.widgets[row]
                if self.widgetType in ('Entry', 'IntEntry', 'FloatEntry'):
                    label = self.labels[row]
                    label.grid(row=row, column=0, sticky=Tkinter.E)
                    widget.grid(row=row, column=1, sticky=Tkinter.EW)

                elif self.widgetType == 'CheckButton':
                    widget.grid(row=row, column=0, sticky=Tkinter.W)
                    label = self.labels[row]
                    label.grid(row=row, column=1, sticky=Tkinter.W)

                else:
                    widget.grid(row=row,
                                column=0,
                                columnspan=2,
                                sticky=Tkinter.W)

            if row == 0:
                self.topFrame.grid(row=0,
                                   column=0,
                                   columnspan=4,
                                   sticky=Tkinter.NSEW)

            self.updateButtons()

    def removeRow(self, doClear=0):

        if self.numRows > self.minRows:
            self.numRows -= 1
            row = self.numRows
            widget = self.widgets[row]
            widget.grid_forget()

            if self.widgetType == 'CheckButton':
                label = self.labels[row]
                label.grid_forget()

            elif self.widgetType in ('Entry', 'IntEntry', 'FloatEntry'):
                label = self.labels[row]
                label.grid_forget()

            if doClear:
                self.updateWidget(row, None, '')

            if self.numRows == 0:
                self.topFrame.grid_forget()

            self.updateButtons()
Example #14
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
Example #15
0
class TaskFilterFrame(LabelFrame):

  def __init__(self, guiParent, basePopup, borderRelief='raised', text=' ', justify='left',
               width=None, font=None, height=None, *args, **kw):

    # 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.borderRelief = borderRelief
    self.text = text
    self.justify = justify
    self.width = width
    self.font = font
    self.height = height

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


    LabelFrame.__init__(self, guiParent, borderRelief, text, justify,
                        width, font, height, *args, **kw)
  

    # set up the grid

    self.grid_columnconfigure(0, weight=0, minsize=20)

    self.grid_rowconfigure(0, weight=0, minsize=5)
    self.grid_rowconfigure(1, weight=0, minsize=10)
    self.grid_rowconfigure(2, weight=0, minsize=10)
    self.grid_rowconfigure(3, weight=0, minsize=10)


    # FIXME
    # should be an enumerated list
    self.statusLabel = Label(self,text='Type:')
    self.statusText = Text(self, width=20, height=1)

    # FIXME
    # should be an enumerated list
    self.typeLabel = Label(self,text='Type:')
    self.typeText = Text(self, width=20, height=1)

    # FIXME
    # should be an enumerated list
    self.projLabel = Label(self,text='Project:')
    self.projText = Text(self, width=20, height=1)

    # FIXME
    # should be an enumerated list
    self.userLabel = Label(self,text='User:'******'Clear', command=self.clear_filter, width=10, height=1)
    self.filterButton = Button(self, text='Go', command=self.refresh_filter, width=10, height=1)


    self.statusLabel.grid(row=2, column=0, padx=2, sticky='nw')
    self.statusText.grid(row=2, column=1, sticky='nw')
    self.typeLabel.grid(row=3, column=0, padx=2, sticky='nw')
    self.typeText.grid(row=3, column=1, sticky='nw')
    self.projLabel.grid(row=4, column=0, padx=2, sticky='nw')
    self.projText.grid(row=4, column=1, sticky='nw')
    self.userLabel.grid(row=5, column=0, padx=2, sticky='nw')
    self.userText.grid(row=5, column=1, sticky='nw')
    
    self.clearButton.grid(row=6, column=0, columnspan=2, sticky='nw')
    self.filterButton.grid(row=6, column=1, columnspan=2, sticky='ne')

  def clear_filter(self):

    self.statusText.clear()
    self.typeText.clear()
    self.projText.clear()
    self.userText.clear()

  def refresh_filter(self):

    status = self.statusText.getText()[:-1]
    type = self.typeText.getText()[:-1]
    proj = self.projText.getText()[:-1]
    user = self.userText.getText()[:-1]

    print 'status ',status,'.'
    print 'type ', type,'.'
    print 'proj ', proj,'.'
    print 'user ', user,'.'

    select = {}
    if status not in ["", None]:
      select['status'] = status.__str__()
    # this is going to be a little harder to work in to the Bean
    # if type not in ["", None]:
    #   select['type'] = type

    # really we need to be able to put in text here that allows more
    # than one project etc to be included. But what should the syntax be?
    if proj not in ["", None]:
      select['proj'] = proj
    if user not in ["", None]:
      select['user'] = user.__str__()

    print 'set select hash ', select

    self.guiParent.select = select
    self.guiParent.drawFrame()
Example #16
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
Example #17
0
class ProjectFrame(Frame):

  def __init__(self, guiParent, basePopup):

    self.basePopup = basePopup
    self.guiParent = guiParent

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

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

    Frame.__init__(self, guiParent)
  
    # set up the grid

    self.grid_columnconfigure(0, weight=0, minsize=10)
    self.grid_columnconfigure(1, weight=0, minsize=50)
    self.grid_columnconfigure(2, weight=1, minsize=20)
    self.grid_columnconfigure(3, weight=0, minsize=40)


    self.grid_rowconfigure(0, weight=0, minsize=5)
    self.grid_rowconfigure(1, weight=0, minsize=10)
    self.grid_rowconfigure(2, weight=0, minsize=10)
    self.grid_rowconfigure(3, weight=0, minsize=10)

    # we could in theory choose to store the last visited
    # project in the user config file and load this on log in

    # if we then decide that login is mandatory then this
    # would give as a project from the start
    
    self.repository = None
    self.projectName = None
    self.versionTag = None


    # we define as much as possible once on startup and use the
    # grid manager to control the display thereafter

    # when no data
    
    self.noData_widgets = []
    
    self.null_proj_label = Label(self, text='No Project selected')
    self.noData_widgets.append(self.null_proj_label)

    # when data

    self.data_widgets = []
    
    self.proj_rep_title = Label(self, text='Project:', font='Helvetica16')
    self.data_widgets.append(self.proj_rep_title)

    self.proj_rep_label = Label(self, text='Repository:')
    self.data_widgets.append(self.proj_rep_label)
    self.proj_rep_value = Label(self, text='')
    self.data_widgets.append(self.proj_rep_value)
        
    # This is more complex than it seems. We need to have some
    # user information accoisated with this too (who has the lock)
    self.proj_status_label = Label(self, text = 'Status:')
    self.data_widgets.append(self.proj_status_label)
    self.proj_status_value = Label(self, text='')
    self.data_widgets.append(self.proj_status_value)

    self.proj_details_label = Label(self, text='Description:')
    self.proj_details = Text(self, width=75, height=6, text='')
    self.data_widgets.append(self.proj_details)

    info_modes = ['versions','tasks','raw data']
    self.info_mode_select = PulldownList(self, self.tmpCall, info_modes)
    self.data_widgets.append(self.info_mode_select)
    
    initial_cols = ['Project','Version','Created by Task', 'Created from Project version']
    self.proj_history_matrix = ScrolledMatrix(self, headingList=initial_cols, initialRows=7,
                                      doubleCallback=self.history_callback)
    self.data_widgets.append(self.proj_history_matrix)

    initial_cols = ['ID','Task','User','Status', 'Date']
    self.proj_tasks_matrix = ScrolledMatrix(self, headingList=initial_cols, initialRows=7,
                                            doubleCallback=self.history_callback)
    self.data_widgets.append(self.proj_tasks_matrix)

    initial_cols = ['name','type','size','details']
    self.proj_files_matrix = ScrolledMatrix(self, headingList=initial_cols, initialRows=7,
                                            doubleCallback=self.history_callback)
    self.data_widgets.append(self.proj_files_matrix)

    
    self.proj_export_button = Button(self, 
                                     height=1, width=14,text='Export',
                                     command=self.export_project)
    self.data_widgets.append(self.proj_export_button)

    self.proj_import_button = Button(self, 
                                     height=1, width=14,text='Import',
                                     command=self.export_project)
    self.data_widgets.append(self.proj_import_button)
   
    self.run_testtask1_button = Button(self, 
                                       height=1, width=14,text='Run TestTask1',
                                       command=self.goto_task1_tab)
    self.data_widgets.append(self.run_testtask1_button)

    # FIXME JMCI

    # insert this inside this Frame directly: not worth abstracting out

    self.filter_frame = FilterFrame(self, self.basePopup, text='Filter')
    self.data_widgets.append(self.filter_frame)


    self.drawFrame()



  # Refreshing of the Frame is meaningless without setting the full
  # connection parameters


  def drawFrame(self):

    if self.basePopup.repList:
      self.repository = self.basePopup.repList.currentRepository
      if self.repository:      
        self.projectName = self.repository.currentProjectName
        self.versionTag = self.repository.currentVersionTag
    
    print 'in drawFrame ', self.repository, self.projectName, self.versionTag

    
    if self.projectName == None:

      for widget in self.data_widgets:
        widget.grid_remove()
      
      self.null_proj_label.grid(row=1, column=1, columnspan=4, sticky='nswe')
     
    else:

    # build up the body.

      for widget in self.noData_widgets:
        widget.grid_remove()

      # OK, so we need to determine the project that we are showing
      # in this frame. To uniquely describe a project we need to
      # know the repository, the project name, and the project version
      # so all these need to be set somehow. Maybe the best approach is
      # so have a public method that takes these arguments and to force
      # every refresh to operate through this. Then the drawFrame() method
      # would be private.

      loc = SharedBeanServiceLocator()
      port = loc.getSharedBean()

      # need two calls, one for the Project and one for the version
      hm1 = {'name': self.projectName }
      wsstr_in1 = WSString(hm1)

      request1 = getFields();
      request1._arg0 = 'org.pimslims.applet.server.ProjectBean';
      request1._arg1 = 'getFields';
      request1._arg2 = wsstr_in1.str

      response1 = port.getFields(request1)

      wsstr_out1 = WSString(response1._return)
      hm_proj = wsstr_out1.getStructHM()

      # now the version
  
      hm2 = {'project' : { 'name': self.projectName },
            'versionTag': self.versionTag }

      wsstr_in2 = WSString(hm2)

      request2 = getFields();
      request2._arg0 = 'org.pimslims.applet.server.ProjectVersionBean';
      request2._arg1 = 'getFields';
      request2._arg2 = wsstr_in2.str

      response2 = port.getFields(request2)

      wsstr_out2 = WSString(response2._return)
      hm_pv = wsstr_out2.getStructHM()


      self.proj_rep_title.set('Project: ' + self.projectName + ' v ' + self.versionTag)
      self.proj_rep_title.grid(row=1, column=1, sticky='w')

      self.proj_rep_label.grid(row=2, column=1, sticky='w')
      self.proj_rep_value.set(self.repository.name)
      self.proj_rep_value.grid(row=2, column=2, sticky='w')

      status = 'N/A'
      if hm_pv['status'] != 'valIsNullPointer':
        status = hm_pv['status']
        
      self.proj_status_label.grid(row=3, column=1, sticky='w')
      self.proj_status_value.set(status)
      self.proj_status_value.grid(row=3, column=2, sticky='w')

      # also want to know:
      # * how this file was created
      # * what external file (e.g. spectrum files) it uses
      # * the log history
      # * what processes it has been used in
      # * if locked, what process, user is responsible for this

      details = 'N/A'
      if hm_proj['details'] != 'valIsNullPointer':
        details = hm_proj['details']
      
      self.proj_details_label.grid(row=4, column=1, columnspan=2, sticky='nw')
      self.proj_details.setText(details)
      self.proj_details.grid(row=4, column=2, pady=10, sticky='nw')

      self.info_mode_select.grid(row=5, column=1, sticky='w')

      # this needs to go into a separate subroutine

      # get al the version
  
      hm3 = {'project' : { 'name': self.projectName }}
      wsstr_in3 = WSString(hm3)

      request3 = getList()
      request3._arg0 = 'org.pimslims.applet.server.ProjectVersionBean';
      request3._arg1 = 'getListWithFields';
      request3._arg2 =  wsstr_in3.str

      response3 = port.getList(request3)

      wsstr_out3 = WSString(response3._return)
      vers = wsstr_out3.getStruct()

      matrix = [];
      objs = [];

      print 'PROJECT: ', vers

      for ver in vers:

        taskSerial = 'unknown'
        if (ver.has_key('createdByTask')):
          task = ver['createdByTask']
          taskSerial = task['serial']

        # FIXME JMCI

        # Really should get this from the task, of it exists

        parentVersionTag = 'unknown'
        if (ver.has_key('sourceVersion')):
          pv = ver['sourceVersion']
          pvp = pv['project']
          parentName = pvp['name']
          parentVersionTag = pvp['name'] + ' ' + pv['versionTag']

        new_row = (self.projectName, ver['versionTag'], taskSerial, parentVersionTag )
        matrix.append(new_row)
        objs.append(ver)

      self.proj_history_matrix.update(objectList=objs, textMatrix=matrix)
      self.proj_history_matrix.grid(row=6, column=1, columnspan=2, pady=10, sticky='nsew')

      self.filter_frame.grid(row=6, column=3, pady=10, sticky='n')
      

      # have a button to export. It should now be clear which version
      # of which project in which repository should be exported

      self.proj_import_button.grid(row=1, column=3, padx=3,pady=3, sticky='ew')
      self.proj_export_button.grid(row=2, column=3, padx=3,pady=3, sticky='ew')
        
      self.run_testtask1_button.grid(row=4, column=3, padx=3,pady=3, sticky='ew')

      # It is not clear precisely how methods should be triggered from
      # the project frame, as there may be >1 input to a given task with
      # a specific role. It maybe that we need to parse out a metadescription
      # of the task and use this to produce the correct buttons (maybe
      # even depending on the contents of the file ?)

      #self.task_button_texts=['Test1Task','Test2Task']
      #self.task_button_cmds=[self.runTest1Task, self.runTest2Task]
      #self.task_button_list = ButtonList(self, self.task_button_texts, self.task_button_cmds,
      #                                    None, 1, 1, True, None, Tkinter.VERTICAL)
      # 
      #self.task_button_list.grid(row=1, rowspan=3, column=4, padx=3, sticky='w')

  def history_callback (self, obj, row, col):

    if (col == 1):
      pv = obj['versionTag']
      print 'PROJECT -> PROJECT (DIRECT) ', pv
      self.repository.currentVersionTag = pv.__str__()

      self.drawFrame()
      
    elif (col == 2):
      task = obj['createdByTask']
      taskSerial = task['serial']
      
      print 'PROJECT -> TASK ', taskSerial

      self.basePopup.currentTask = taskSerial.__str__()    

      # FIXME

      # This is more complex. Need to navigate to the correct
      # panel within the Task submenu

      if self.basePopup.frameShortcuts.has_key('Task'):
        taskFrame = self.basePopup.frameShortcuts['Task']
        # really need to check on the type of task
        if taskFrame.frameShortcuts.has_key('Test1'):
          taskFrame.frameShortcuts['Test1'].drawFrame()
      # also need to select the current tabbed frame
      self.basePopup.tabbedFrame.select(2)
      

    # FIXME JMCI

    # need to look into this. Really we need both the project and
    # the version for this (in theory this could be based on a different
    # project although it is highly unlikely!)

    elif (col == 3):
      pv = obj['sourceVersion']
      parentVersion = pv['versionTag']
      
      pvp = pv['project']
      parentName = pvp['name']
      
      print 'PROJECT -> PROJECT (SOURCE) ', parentVersion

      self.repository.currentVersionTag = parentVersion.__str__()
      self.repository.currentProjectName = parentName.__str__()

      self.drawFrame()
 

  # create a new task with this project as an input

  # it is not clear how we should do this:- construct data locally
  # and then save, or save a first cut and then ammend. On the basis
  # that the serial has to be generated by the DB, we will go for the
  # former for now

  # it would be better to pass this to a processor layer that
  # determines parameters and then builds the stub.

  def goto_task1_tab(self):

    # create a new task (provisional status)

    loc = SharedBeanServiceLocator()
    port = loc.getSharedBean()

    #hm0 = { 'project': { 'name': self.projectName},
    #        'versionTag' : self.versionTag,
    #        '_handle' : 'findOrFail' }

    # FIXME

    # We have an error here (it seems to be a problem between the CCPN
    # and hibernate layers that is not picking objects as the same for
    # some reason. Therefore do not set the inputVersion for now

    hm0 = { 'project': { 'name': self.projectName},
            'versionTag' : self.versionTag}
    hm2 = { 'inputVersion' : hm0,
            'status' : 'PROVISIONAL' }

    #hm2 = { 'status' : 'PROVISIONAL' }

    wsstr_in1 = WSString(hm2)
            
    req1 = recordAndLoad();

    req1._arg0 = 'org.pimslims.applet.server.TaskBean';
    req1._arg1 = 'recordTest1';
    req1._arg2 =  wsstr_in1.str
    
    resp1 = port.recordAndLoad(req1)
    wsstr_out1 = WSString(resp1._return)
    v = wsstr_out1.getStructHM()

    self.basePopup.currentTask =   v['serial'].__str__()

    # FIXME

    # This is more complex. Need to navigate to the correct
    # panel within the Task submenu

    if self.basePopup.frameShortcuts.has_key('Task'):
      taskFrame = self.basePopup.frameShortcuts['Task']
      # really need to check on the type of task
      if taskFrame.frameShortcuts.has_key('Test1'):
        taskFrame.frameShortcuts['Test1'].drawFrame()
    # also need to select the current tabbed frame
    self.basePopup.tabbedFrame.select(2)

    
  # method for exporting repository directory to local file
  # system. This is a very basic approach, essentially first
  # listing all the files required for transfer and then
  # copying them over one by one. Note that due to limitations
  # in ZSI we cannot do much better than base64 encoding each
  # file. We could consider storing a tgz on the server and
  # exporting that. It might be a considerable improvement as
  # the compression leads to a file < 10% of the original size
  # which would cut down on traffic enormously

  def export_project(self):

    versionTag = self.versionTag
    name = self.projectName

    # need to preserve the current status. Take a default from the
    # Wms layer 
    rootDir = self.basePopup.repList.current_export_dir

    # This should be obtained from a query box. Hard code for now
    fileSelectPopup = FileSelectPopup(self, None, rootDir)

    exp_project_dir = fileSelectPopup.getDirectory()
    self.basePopup.repList.current_export_dir = exp_project_dir

    # These should come from the repository object
    loc = SharedBeanServiceLocator()
    port = loc.getSharedBean()

    req1 = getList()

    hm1 = {'projectName': name,
           'versionTag': versionTag,
           'segment': 'jionides' }
    wsstr1 = WSString(hm1)

    # these are actually static
    req1._arg0 = 'org.pimslims.applet.server.CcpnFileBean';
    req1._arg1 = 'getList';
    req1._arg2 = wsstr1.str

    # get the response
    resp1 = port.getList(req1)

    # this is a hack at present. It needs to be written properly
    wsstr = WSString(resp1._return)
    ss = wsstr.getStruct()

    print 'got array ', ss

    for strg in ss:

      print 'trying to handle file ', strg

      hm2 = {'projectName': name,
             'versionTag': versionTag,
             'segment': 'jionides',
             'fileName' : '/' + strg.__str__(),
             'random' : 'test',
             'raw' : False}
      
      print 'trying to handle file 2 ', strg
      print 'trying to handle file 2 ', hm2

      req2 = getDocWithParams()
      
      wsstr2 = WSString(hm2)

      # these are actually static
      req2._arg0 = 'org.pimslims.applet.server.CcpnFileBean';
      req2._arg1 = wsstr2.str

      # get the response
      resp2 = port.getDocWithParams(req2)

      local_file_path = exp_project_dir + '/' + name + '/' + strg

      idx = local_file_path.rfind('/')
      local_dir = local_file_path[:idx]
      print 'trying to create ', local_dir
      os.makedirs(local_dir)

      print 'writing to local area; ', local_file_path

      f = open(local_file_path, 'w')
      f.write(resp2._return)
          

  # it is likely that these methods are going to have to be highly specialised
  # as some tasks are going to have many input files and we need to know which
  # role the project we are in takes in the task.

  def runTest1Task(self):

    pass

  def runTest2Task(self):

    pass

  def view_project(self, project):

    self.project = project

    self.drawFrame()


  def tmpCall(self):

    return


  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):

      return

  def quit(self):
  
    self.guiParent.parent.destroy()
    
  def destroy(self):
  
    self.administerNotifiers(self.basePopup.unregisterNotify)
    Frame.destroy(self)
Example #18
0
  def __init__(self, parent, getOption = None, setOption = None,
               haveTicks = False, doOutlineBox = True, *args, **kw):

    self.getOption = getOption
    self.setOption = setOption
    self.haveTicks = haveTicks
    self.doOutlineBox = doOutlineBox

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

    self.file_select_popup = None

    self.getOptionValues()

    try:
      size_index = paper_types.index(self.paper_type)
    except:
      size_index = 0

    try:
      other_unit_index = paper_units.index(self.other_unit)
    except:
      other_unit_index = 0

    try:
      orientation_index = paper_orientations.index(self.paper_orientation)
    except:
      orientation_index = 0

    try:
      style_index = style_choices.index(self.output_style)
    except:
      style_index = 0

    try:
      format_index = format_choices.index(self.output_format)
    except:
      format_index = 0

    if haveTicks:
      try:
        tick_location_index = tick_locations.index(self.tick_location)
      except:
        tick_location_index = 0

    self.grid_columnconfigure(1, weight=1)

    row = 0
    button = Button(self, text='File:', command=self.findFile,
                    tipText='Select location to save print file')
    button.grid(row=row, column=0, sticky='e')
    self.file_entry = Entry(self, width=40, text=self.file_name,
                tipText='Location where file is saved on disk')
    self.file_entry.grid(row=row, column=1, sticky='ew')

    row += 1
    label = Label(self, text='Title:')
    label.grid(row=row, column=0, sticky='e')
    self.title_entry = Entry(self, width=40, text=self.title,
                    tipText='Title of the printout, displayed at top')
    self.title_entry.grid(row=row, column=1, sticky='ew')

    row += 1
    label = Label(self, text='X axis label:')
    label.grid(row=row, column=0, sticky='e')
    self.x_axis_entry = Entry(self, width=40, text=self.x_axis_label,
                    tipText='X axis label for the printout')
    self.x_axis_entry.grid(row=row, column=1, sticky='ew')

    row += 1
    label = Label(self, text='Y axis label:')
    label.grid(row=row, column=0, sticky='e')
    self.y_axis_entry = Entry(self, width=40, text=self.y_axis_label,
                    tipText='Y axis label for the printout')
    self.y_axis_entry.grid(row=row, column=1, sticky='ew')

    row += 1
    frame = Frame(self)
    frame.grid(row=row, column=0, columnspan=2, sticky='ew')
    frame.grid_columnconfigure(4, weight=1)
    
    label = Label(frame, text='Paper size:')
    label.grid(row=0, column=0, sticky='e')
    entries = []
    for t in paper_types:
      if t == Output.other_paper_type:
        entry = t
      else:
        (w, h, u) = paper_sizes[t]
        entry = t + ' (%2.1f %s x %2.1f %s)' % (w, u, h, u)
      entries.append(entry)
    self.size_menu = PulldownList(frame, callback=self.changedSize,
                                  texts=entries, index=size_index,
                                  tipText='The paper size for the printout')
    self.size_menu.grid(row=0, column=1, sticky='w')

    self.other_frame = Frame(frame)

    self.other_frame.grid_columnconfigure(0, weight=1)
    self.other_entry = FloatEntry(self.other_frame, text=self.other_size,
                                  isArray=True,
                                  tipText='The size of the Other paper in both dimensions; this requires two values, space or comma separated')
    self.other_entry.grid(row=0, column=0, sticky='ew')
    self.other_unit_menu= PulldownList(self.other_frame, texts=paper_units,
                                       index=other_unit_index,
                                       tipText='The unit for the Other paper size')
    self.other_unit_menu.grid(row=0, column=1, sticky='ew')

    row += 1
    frame = Frame(self)
    frame.grid(row=row, column=0, columnspan=4, sticky='ew')
    frame.grid_columnconfigure(1, weight=1)
    frame.grid_columnconfigure(3, weight=1)
    frame.grid_columnconfigure(5, weight=1)

    label = Label(frame, text='Orientation:')
    label.grid(row=0, column=0, sticky='e')
    self.orientation_menu = PulldownList(frame, texts=paper_orientations,
                                         index=orientation_index,
                                         tipText='Whether the paper should be set in Portrait or Landscape mode')
    self.orientation_menu.grid(row=0, column=1, sticky='w')

    label = Label(frame, text='  Style:')
    label.grid(row=0, column=2, sticky='e')
    self.style_menu = PulldownList(frame, texts=style_choices,
                                   index=style_index,
                                   tipText='Whether the printout should be in colour or black and white')
    self.style_menu.grid(row=0, column=3, sticky='w')

    label = Label(frame, text='  Format:')
    label.grid(row=0, column=4, sticky='e')
    self.format_menu = PulldownList(frame, callback=self.changedFormat,
                                    texts=format_choices, index=format_index,
                                    tipText='Whether to save as PS, EPS or PDF')

    self.format_menu.grid(row=0, column=5, sticky='w')

    if haveTicks:

      row += 1
      frame = Frame(self)
      frame.grid(row=row, column=0, columnspan=4, sticky='ew')
      frame.grid_columnconfigure(1, weight=1)
      frame.grid_columnconfigure(3, weight=1)
      
      label = Label(frame, text='Tick Location:')
      label.grid(row=0, column=0, sticky='e')
      self.tick_menu = PulldownList(frame, texts=tick_locations,
                                    index=tick_location_index,
                                    tipText='Whether the tick marks appear on the inside or outside of the frame')
      self.tick_menu.grid(row=0, column=1, sticky='w')

      label = Label(frame, text='  Tick Placement:')
      label.grid(row=0, column=2, sticky='e')
      if self.tick_placement is None:
        selected = None
      else:
        selected = [(x in self.tick_placement) for x in tick_placements]
      self.tick_buttons = CheckButtons(frame, entries=tick_placements,
                                       selected=selected,
                                       tipTexts=('Whether the tick marks appear on the top and/or bottom and/or left and/or right',))
      self.tick_buttons.grid(row=0, column=3, sticky='w')

      row += 1
      frame = Frame(self)
      frame.grid(row=row, column=0, columnspan=4, sticky='ew')
      frame.grid_columnconfigure(1, weight=1)
      frame.grid_columnconfigure(3, weight=1)
      
      label = Label(frame, text='Tick Font:')
      label.grid(row=0, column=0, sticky='e')
      self.tick_font_list = FontList(frame, mode='Print',
                            selected=self.tick_font,
                            extraTexts=[PrintTicks.no_tick_text],
                            tipText='The font used for the tick mark labels')
      self.tick_font_list.grid(row=0, column=1, sticky='w')

      label = Label(frame, text='Tick Spacing:')
      label.grid(row=0, column=2, sticky='e')
      # TBD: put preferred choice in data model
      self.spacing_menu = PulldownList(frame, texts=spacing_choices, index=0,
                                       callback=self.changedSpacing,
                                       tipText='Whether the program should automatically calculate the major/minor tick spacings and how many decimal places are used for the ticks, or whether the these are specified manually')
      self.spacing_menu.grid(row=0, column=3, sticky='w')

      ff = self.spacing_frame = Frame(frame)
      ff.grid_columnconfigure(1, weight=1)
      ff.grid_columnconfigure(2, weight=1)
      label = Label(ff, text='Tick Spacing')
      label.grid(row=0, column=0, sticky='w')
      label = Label(ff, text='Major')
      label.grid(row=0, column=1, sticky='ew')
      label = Label(ff, text='Minor')
      label.grid(row=0, column=2, sticky='ew')
      label = Label(ff, text='Decimals')
      label.grid(row=0, column=3, sticky='ew')
      label = Label(ff, text='X:')
      label.grid(row=1, column=0, sticky='w')
      self.x_major_entry = FloatEntry(ff, tipText='The spacing in display units of the major tick marks in the X dimension')
      self.x_major_entry.grid(row=1, column=1, sticky='ew')
      self.x_minor_entry = FloatEntry(ff, tipText='The spacing in display units of the minor tick marks in the X dimension (not printed if left blank)')
      self.x_minor_entry.grid(row=1, column=2, sticky='ew')
      self.x_decimal_entry = IntEntry(ff, tipText='The number of decimal places for the tick numbers in the X dimension')
      self.x_decimal_entry.grid(row=1, column=3, sticky='ew')
      label = Label(ff, text='Y:')
      label.grid(row=2, column=0, sticky='w')
      self.y_major_entry = FloatEntry(ff, tipText='The spacing in display units of the major tick marks in the Y dimension')
      self.y_major_entry.grid(row=2, column=1, sticky='ew')
      self.y_minor_entry = FloatEntry(ff, tipText='The spacing in display units of the minor tick marks in the Y dimension (not printed if left blank)')
      self.y_minor_entry.grid(row=2, column=2, sticky='ew')
      self.y_decimal_entry = IntEntry(ff, tipText='The number of decimal places for the tick numbers in the Y dimension')
      self.y_decimal_entry.grid(row=2, column=3, sticky='ew')

      row += 1
      frame = Frame(self)
      frame.grid(row=row, column=0, columnspan=4, sticky='ew')
      frame.grid_columnconfigure(1, weight=1)
      
      label = Label(frame, text='Tick Length:')
      label.grid(row=0, column=0, sticky='e')
      # TBD: put preferred choice in data model
      self.tick_length_menu = PulldownList(frame, texts=tick_length_choices, index=0,
                                       callback=self.changedLength,
                                       tipText='Whether the program should automatically calculate the major/minor tick lengths, or whether the these are specified manually')
      self.tick_length_menu.grid(row=0, column=1, sticky='w')

      ff = self.length_frame = Frame(frame)
      ff.grid_columnconfigure(1, weight=1)
      label = Label(ff, text='  Major length:')
      label.grid(row=0, column=0, sticky='w')
      self.length_major_entry = FloatEntry(ff, tipText='The length in points of the major tick marks')
      self.length_major_entry.grid(row=0, column=1, sticky='w')
      label = Label(ff, text='Minor length:')
      label.grid(row=0, column=2, sticky='w')
      self.length_minor_entry = FloatEntry(ff, tipText='The length in points of the minor tick marks')
      self.length_minor_entry.grid(row=0, column=3, sticky='w')

    row += 1
    frame = Frame(self)
    frame.grid(row=row, column=0, columnspan=4, sticky='ew')
    frame.grid_columnconfigure(3, weight=1)
    frame.grid_columnconfigure(4, weight=1)

    label = Label(frame, text='Scaling:')
    label.grid(row=0, column=0, sticky='e')
    # TBD: put preferred choice in data model
    self.scaling_menu = PulldownList(frame, texts=scaling_choices, index=0,
                                     callback=self.changedScaling,
                                     tipText='Whether the plot should be scaled as a percentage of the maximum size that would fit on the paper, or instead should be specified by the number of cms or inches per unit')
    self.scaling_menu.grid(row=0, column=1, sticky='ew')

    self.scaling_scale = Scale(frame, orient=Tkinter.HORIZONTAL, value=self.scaling, tipText='The percentage of the maximum size that would fit on the paper that the plot is scaled by')
    self.scaling_scale.grid(row=0, column=2, columnspan=3, sticky='ew')

    self.x_scaling_label = Label(frame, text='X:')
    self.x_scaling_entry = FloatEntry(frame, tipText='The scaling that should be used in the X dimension as cms or inches per unit')
    self.y_scaling_label = Label(frame, text='Y:')
    self.y_scaling_entry = FloatEntry(frame, tipText='The scaling that should be used in the Y dimension as cms or inches per unit')

    row += 1
    frame = Frame(self)
    frame.grid(row=row, column=0, columnspan=4, sticky='w')
    frame.grid_columnconfigure(2, weight=1)
  
    label = Label(frame, text='Include:')
    label.grid(row=0, column=0, sticky='e')
    tipTexts = ('Whether the time and date should be included in the printout',
                'Whether the file name should be included in the printout')
    if self.border_decoration is None:
      selected = None
    else:
      selected = [(x in self.border_decoration) for x in border_decorations]
    self.border_buttons = CheckButtons(frame, entries=border_decorations,
                                       selected=selected,
                                       tipTexts=tipTexts)
    self.border_buttons.grid(row=0, column=1, sticky='w')

    label = Label(frame, text='    Using Font:')
    label.grid(row=0, column=2, sticky='e')
    self.border_font_list = FontList(frame, mode='Print',
                          selected=self.border_font,
                          tipText='The font used for the border texts')
    self.border_font_list.grid(row=0, column=3, sticky='w')

    row += 1
    label = Label(self, text='Line width:')
    label.grid(row=row, column=0, sticky='w')
    self.linewidth_entry = FloatEntry(self, width=10,
                                  text=self.linewidth,
                                  tipText='Line width for drawing')
    self.linewidth_entry.grid(row=row, column=1, sticky='w')
class AnnealingSettingsTab(object):
    '''This class describes the tab in the GUI where the user
       can change setting that govern the monte carlo / annleaing
       procedure. This also includes which information from the ccpn
       analysis project is used and which information is
       ignored. This includes:
           * present sequential assignments
           * tentative assignments
           * amino acid type information
           * whether to include untyped spin systems
           * assignments to peak dimensions
       ALso the chain can be selected here.
       Furthermore the user can set the temperature
       regime of the annealing, the amount of times the procedure
       is repeated to obtain statistics. The fraction of peaks
       that is left out in each run to diversify the results,
       the treshhold score for amino acid typing and the treshhold
       collabelling for a peak to be expected.
    '''

    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.minIsoFrac = 0.1
        self.leavePeaksOutFraction = 0.0
        self.minTypeScore = 1.0
        self.chain = None
        self.amountOfRepeats = 10
        self.amountOfSteps = 10000
        self.acceptanceConstantList = [0.0, 0.01, 0.015, 0.022,
                                       0.033, 0.050, 0.075, 0.113,
                                       0.170, 0.256, 0.384, 0.576,
                                       0.864, 1.297, 1.946, 2.919,
                                       4.378, 6.568, 9.852, 14.77,
                                       22.16, 33.25]
        self.energyDataSets = [[]]
        self.residues = []
        self.body()

    def body(self):
        '''describes the body of this tab. It bascically consists
           of some field to fill out for the user at the top and
           a ScrolledGraph that shows the progess of the annealing
           procedure a the bottom.
        '''

        frame = self.frame

        # frame.expandGrid(13,0)
        frame.expandGrid(15, 1)
        row = 0

        text = 'Calculate Assignment Suggestions'
        command = self.runCalculations
        self.startButton = Button(frame, command=command, text=text)
        self.startButton.grid(row=row, column=0, sticky='nsew', columnspan=2)

        row += 1

        Label(frame, text='Amount of runs: ', grid=(row, 0))
        tipText = 'The amount of times the whole optimization procedure is performed, each result is safed'
        self.repeatEntry = IntEntry(frame, grid=(row, 1), width=7, text=10,
                                    returnCallback=self.updateRepeatEntry,
                                    tipText=tipText, sticky='nsew')
        self.repeatEntry.bind('<Leave>', self.updateRepeatEntry, '+')

        row += 1

        Label(frame, text='Temperature regime: ', grid=(row, 0))
        tipText = 'This list of numbers govern the temperature steps during the annealing, every number represents 1/(kb*t), where kb is the Boltzmann constant and t the temperature of one step.'
        self.tempEntry = Entry(frame, text=map(str, self.acceptanceConstantList), width=64,
                               grid=(row, 1), isArray=True, returnCallback=self.updateAcceptanceConstantList,
                               tipText=tipText, sticky='nsew')

        row += 1

        Label(frame, text='Amount of attempts per temperature:', grid=(row, 0))
        tipText = 'The amount of attempts to switch the position of two spinsystems in the sequence are performed for each temperature point'
        self.NAStepEntry = IntEntry(frame, grid=(row, 1), width=7, text=10000,
                                    returnCallback=self.updateStepEntry,
                                    tipText=tipText, sticky='nsew')
        self.NAStepEntry.bind('<Leave>', self.updateStepEntry, '+')

        row += 1

        Label(frame, text='Fraction of peaks to leave out:', grid=(row, 0))
        tipText = 'In each run a fraction of the peaks can be left out of the optimization, thereby increasing the variability in the outcome and reducing false negatives. In each run this will be different randomly chosen sub-set of all peaks. 0.1 (10%) can be a good value.'
        self.leaveOutPeaksEntry = FloatEntry(frame, grid=(row, 1), width=7, text=0.0,
                                             returnCallback=self.updateLeavePeaksOutEntry,
                                             tipText=tipText, sticky='nsew')
        self.leaveOutPeaksEntry.bind(
            '<Leave>', self.updateLeavePeaksOutEntry, '+')

        row += 1

        Label(frame, text='Minmal amino acid typing score:', grid=(row, 0))
        tipText = 'If automatic amino acid typing is selected, a cut-off value has to set. Every amino acid type that scores higher than the cut-off is taken as a possible type. This is the same score as can be found under resonance --> spin systems --> predict type. Value should be between 0 and 100'
        self.minTypeScoreEntry = FloatEntry(frame, grid=(row, 1), width=7, text=1.0,
                                            returnCallback=self.updateMinTypeScoreEntry,
                                            tipText=tipText, sticky='nsew')
        self.minTypeScoreEntry.bind(
            '<Leave>', self.updateMinTypeScoreEntry, '+')

        row += 1

        Label(frame, text='Minimal colabelling fraction:', grid=(row, 0))
        tipText = 'The minimal amount of colabelling the different nuclei should have in order to still give rise to a peak.'
        self.minLabelEntry = FloatEntry(frame, grid=(row, 1), width=7, text=0.1,
                                        returnCallback=self.updateMinLabelEntry,
                                        tipText=tipText, sticky='nsew')
        self.minLabelEntry.bind('<Leave>', self.updateMinLabelEntry, '+')

        row += 1

        Label(frame, text='Use sequential assignments:', grid=(row, 0))
        tipText = 'When this option is select the present sequential assignments will be kept in place'
        self.useAssignmentsCheck = CheckButton(
            frame, selected=True, tipText=tipText, grid=(row, 1))

        row += 1

        Label(frame, text='Use tentative assignments:', grid=(row, 0))
        tipText = 'If a spin system has tentative assignments this can be used to narrow down the amount of possible sequential assignments.'
        self.useTentativeCheck = CheckButton(
            frame, selected=True, tipText=tipText, grid=(row, 1))

        row += 1

        Label(frame, text='Use amino acid types:', grid=(row, 0))
        tipText = 'Use amino acid types of the spin systems. If this option is not checked the spin systems are re-typed, only resonance names and frequencies are used'
        self.useTypeCheck = CheckButton(
            frame, selected=True, tipText=tipText, grid=(row, 1))

        row += 1

        Label(frame, text='Include untyped spin systems:', grid=(row, 0))
        tipText = 'Also include spin system that have no type information. Amino acid typing will be done on the fly.'
        self.useAlsoUntypedSpinSystemsCheck = CheckButton(
            frame, selected=True, tipText=tipText, grid=(row, 1))

        row += 1

        Label(frame, text='Use dimensional assignments:', grid=(row, 0))
        tipText = 'If one or more dimensions of a peak is already assigned, assume that this assignment is the only option. If not the check the program will consider all possibilities for the assignment of the dimension.'
        self.useDimensionalAssignmentsCheck = CheckButton(
            frame, selected=True, tipText=tipText, grid=(row, 1))

        row += 1

        Label(frame, text='Chain:', grid=(row, 0))
        self.molPulldown = PulldownList(
            frame, callback=self.changeMolecule, grid=(row, 1))
        self.updateChains()

        row += 1

        Label(frame, text='Residue ranges: ', grid=(row, 0))
        tipText = 'Which residues should be included. Example: "10-35, 62-100, 130".'
        self.residueRangeEntry = Entry(frame, text=None, width=64,
                                       grid=(row, 1), isArray=True, returnCallback=self.updateResidueRanges,
                                       tipText=tipText, sticky='nsew')
        self.updateResidueRanges(fromChain=True)

        row += 1

        self.energyPlot = ScrolledGraph(frame, symbolSize=2, width=600,
                                        height=200, title='Annealing',
                                        xLabel='temperature step', yLabel='energy')
        self.energyPlot.grid(row=row, column=0, columnspan=2, sticky='nsew')

    def runCalculations(self):
        '''Run all calculations. Also triggers the disabling of
           some buttons and fields.
        '''

        self.startButton.disable()
        self.disableIllegalButtonsAfterPrecalculations()
        self.guiParent.connector.runAllCalculations()
        self.startButton.configure(text='More runs')
        self.startButton.enable()

    def disableIllegalButtonsAfterPrecalculations(self):
        '''Disable buttons and field the user can not alter
           any longer after the model is set up and the
           'pre-calculations' have finished.
           This is done because this part of the calculation
           should only be run once. All settings that would
           be changed after this point will not have any influence.
        '''

        illegalButtons = [self.minTypeScoreEntry, self.minLabelEntry,
                          self.useAlsoUntypedSpinSystemsCheck, self.useAssignmentsCheck,
                          self.useTypeCheck, self.useDimensionalAssignmentsCheck,
                          self.useTentativeCheck]

        for illegalButton in illegalButtons:
            illegalButton.configure(state='disabled')

        self.molPulldown.disable()

    def getChainName(self, chain):
        '''Get the name for a chain.
               args: chain: ccpn analysis
                            chain object
               returns: chain name
        '''

        return '%s:%s (%s)' % (chain.molSystem.code, chain.code, chain.molecule.molType)

    def getChains(self):
        '''Get all chains present in the project.
               returns: list of ccpn analysis chain objects
        '''
        chains = []
        if self.project:
            for molSystem in self.project.sortedMolSystems():
                for chain in molSystem.sortedChains():
                    if chain.residues:
                        chains.append(chain)

        return chains

    def updateChains(self, *opt):
        '''Updates the list of chains if a new one is added
           to or deleted from the project. Updates the
           pull down list where a chain can be selected.
        '''

        index = 0
        texts = []
        chains = self.getChains()
        chain = self.chain

        if chains:
            if chain not in chains:
                chain = chains[0]

            texts = [self.getChainName(c) for c in chains]
            index = chains.index(chain)

        else:
            chain = None

        self.molPulldown.setup(texts, chains, index)

        if chain is not self.chain:
            self.chain = chain

    def changeMolecule(self, chain):
        '''Select a molecular chain.'''

        if chain is not self.chain:
            self.chain = chain
            self.updateResidueRanges(fromChain=True)

    def updateStepEntry(self, event=None):
        '''Update the value and entry that sets the amount of
           steps per temperature point.
        '''

        value = self.NAStepEntry.get()
        if value == self.amountOfSteps:
            return
        if value < 1:
            self.NAStepEntry.set(1)
            self.amountOfSteps = 1
        else:
            self.amountOfSteps = value
            self.NAStepEntry.set(value)

    def updateRepeatEntry(self, event=None):
        '''Update the value and entry of that sets
           the amount of times the whole annealing
           procedure is repeated in order
           to obtain statistics.
        '''

        value = self.repeatEntry.get()

        if value == self.amountOfRepeats:
            return
        if value < 1:
            self.repeatEntry.set(1)
            self.amountOfRepeats = 1
        else:
            self.amountOfRepeats = value
            self.repeatEntry.set(value)

    def updateMinTypeScoreEntry(self, event=None):
        '''Updates the value and the entry for the
           treshhold value for amino acid typing.
        '''

        value = self.minTypeScoreEntry.get()

        if value == self.minTypeScore:
            return
        if value < 0:
            self.minTypeScoreEntry.set(0.0)
            self.minTypeScore = 0.0
        elif value > 100:
            self.minTypeScoreEntry.set(100.0)
            self.minTypeScore = 100.0
        else:
            self.minTypeScoreEntry.set(value)
            self.minTypeScore = value

    def updateMinLabelEntry(self, event=None):
        '''Updates the minimum colabelling fraction
           for which a peak is expected to be present
           in the spectra.
        '''

        value = self.minLabelEntry.get()

        if value == self.minIsoFrac:
            return
        if value < 0:
            self.minIsoFrac = 0.0
            self.minLabelEntry.set(0.0)
        elif value > 1:
            self.minIsoFrac = 1.0
            self.minLabelEntry.set(1.0)
        else:
            self.minIsoFrac = value
            self.minLabelEntry.set(value)

    def updateLeavePeaksOutEntry(self, event=None):
        '''Updates the value and entry of the fraction
           of peaks that should be left out in each
           run in order to diversify the results.
        '''

        value = self.leaveOutPeaksEntry.get()

        if value == self.leavePeaksOutFraction:
            return
        if value < 0:
            self.leavePeaksOutFraction = 0.0
            self.leaveOutPeaksEntry.set(0.0)
        elif value > 1:
            self.leavePeaksOutFraction = 1.0
            self.leaveOutPeaksEntry.set(1.0)
        else:
            self.leavePeaksOutFraction = value
            self.leaveOutPeaksEntry.set(value)

    def updateAcceptanceConstantList(self, event=None):
        '''Updates the list with constants that are used
           during the monte carlo procedure to decide whether
           a changed is accepted or not.
        '''

        acList = self.tempEntry.get()
        newList = []

        for constant in acList:

            try:

                number = float(constant)
                newList.append(number)

            except ValueError:

                string = constant + \
                    ' in temperature constants is not a number.'

                showWarning('Not A Number', string, parent=self.guiParent)

                return False

        self.acceptanceConstantList = newList

        return True

    def updateResidueRanges(self, event=None, fromChain=False):

        self.residues = set()

        subRanges = self.residueRangeEntry.get()
        if not subRanges or fromChain:
            self.residues = set(self.chain.residues)
            residues = self.chain.sortedResidues()
            text = '{}-{}'.format(residues[0].seqCode, residues[-1].seqCode)
            self.residueRangeEntry.set(text=text)
            return

        for subRange in subRanges:
            indeces = subRange.split('-')
            start = int(indeces[0])
            stop = int(indeces[-1]) + 1
            for seqCode in range(start, stop):
                residue = self.chain.findFirstResidue(seqCode=seqCode)
                if not residue:
                    showWarning('Residue out of range.',
                                'There is no residue at position {}'.format(seqCode),
                                parent=self.guiParent)
                    self.residues = set()
                    return
                self.residues.add(residue)

    def addEnergyPoint(self, energy, time):
        '''Adds a point to the graph that shows the progress
           of the annealling procedure.
               args: energy: the y-value
                     time:   the x-value
        '''

        point = (time, energy * -1)

        # This means one run has finished
        if len(self.energyDataSets[-1]) / (len(self.acceptanceConstantList) + 1):

            self.energyDataSets.append([point])

        else:

            self.energyDataSets[-1].append(point)

        colors = colorSeries
        Ncolors = len(colors)
        NdataSets = len(self.energyDataSets)
        colorList = (NdataSets / Ncolors) * colors + \
            colors[:NdataSets % Ncolors]
        self.energyPlot.update(dataSets=self.energyDataSets,
                               dataColors=colorList)

        # Forcing the graph to draw, eventhough calculations
        # are still running. Only do this with high numbers of
        # steps, otherwise drawing takes longer than annealling.
        if self.amountOfSteps >= 100000:

            self.energyPlot.draw()
Example #20
0
    def __init__(self,
                 parent,
                 getOption=None,
                 setOption=None,
                 text='Print Options',
                 haveTicks=False,
                 doOutlineBox=True,
                 *args,
                 **kw):

        self.getOption = getOption
        self.setOption = setOption
        self.haveTicks = haveTicks
        self.doOutlineBox = doOutlineBox

        LabelFrame.__init__(self, parent=parent, text=text, *args, **kw)

        self.file_select_popup = None

        self.getOptionValues()

        try:
            size_index = self.paper_types.index(self.paper_type)
        except:
            size_index = 0

        try:
            other_unit_index = self.paper_units.index(self.other_unit)
        except:
            other_unit_index = 0

        try:
            orientation_index = self.paper_orientations.index(self.orientation)
        except:
            orientation_index = 0

        try:
            style_index = self.style_choices.index(self.output_style)
        except:
            style_index = 0

        try:
            format_index = self.format_choices.index(self.output_format)
        except:
            format_index = 0

        if haveTicks:
            try:
                tick_location_index = self.tick_locations.index(
                    self.tick_location)
            except:
                tick_location_index = 0

        self.grid_columnconfigure(2, weight=1)

        row = 0
        label = Label(self, text='File:')
        label.grid(row=row, column=0, sticky='e')
        self.file_entry = Entry(self, width=40, text=self.file_name)
        self.file_entry.grid(row=row, column=1, columnspan=2, sticky='ew')
        button = Button(self, text='Choose File', command=self.findFile)
        button.grid(row=row, column=3, rowspan=2, sticky='nsew')

        row += 1
        label = Label(self, text='Title:')
        label.grid(row=row, column=0, sticky='e')
        self.title_entry = Entry(self, width=40, text=self.title)
        self.title_entry.grid(row=row, column=1, columnspan=2, sticky='ew')

        row += 1
        frame = Frame(self)
        frame.grid(row=row, column=0, columnspan=4, sticky='ew')
        frame.grid_columnconfigure(4, weight=1)

        label = Label(frame, text='Paper size:')
        label.grid(row=0, column=0, sticky='e')
        entries = []
        for t in paper_types:
            if t == Output.other_paper_type:
                entry = t
            else:
                (w, h, u) = paper_sizes[t]
                entry = t + ' (%2.1f %s x %2.1f %s)' % (w, u, h, u)
            entries.append(entry)
        self.size_menu = PulldownList(frame,
                                      callback=self.changedSize,
                                      texts=entries,
                                      index=size_index)
        self.size_menu.grid(row=0, column=1, sticky='w')

        self.other_frame = Frame(frame)

        self.other_frame.grid_columnconfigure(0, weight=1)
        self.other_entry = FloatEntry(self.other_frame,
                                      text=self.other_size,
                                      isArray=True)
        self.other_entry.grid(row=0, column=0, sticky='ew')
        self.other_unit_menu = PulldownList(self.other_frame,
                                            texts=paper_units,
                                            index=other_unit_index)
        self.other_unit_menu.grid(row=0, column=1, sticky='ew')

        row += 1
        frame = Frame(self)
        frame.grid(row=row, column=0, columnspan=4, sticky='ew')
        frame.grid_columnconfigure(1, weight=1)
        frame.grid_columnconfigure(3, weight=1)
        frame.grid_columnconfigure(5, weight=1)

        label = Label(frame, text='Orientation:')
        label.grid(row=0, column=0, sticky='e')
        self.orientation_menu = PulldownList(frame,
                                             texts=paper_orientations,
                                             index=orientation_index)
        self.orientation_menu.grid(row=0, column=1, sticky='w')

        label = Label(frame, text='  Style:')
        label.grid(row=0, column=2, sticky='e')
        self.style_menu = PulldownList(frame,
                                       texts=style_choices,
                                       index=style_index)
        self.style_menu.grid(row=0, column=3, sticky='w')

        label = Label(frame, text='  Format:')
        label.grid(row=0, column=4, sticky='e')
        self.format_menu = PulldownList(frame,
                                        callback=self.changedFormat,
                                        texts=format_choices,
                                        index=format_index)

        self.format_menu.grid(row=0, column=5, sticky='w')

        if haveTicks:

            row += 1
            frame = Frame(self)
            frame.grid(row=row, column=0, columnspan=4, sticky='ew')
            frame.grid_columnconfigure(1, weight=1)
            frame.grid_columnconfigure(3, weight=1)

            label = Label(frame, text='Tick Location:')
            label.grid(row=0, column=0, sticky='e')
            self.tick_menu = PulldownList(frame,
                                          texts=tick_locations,
                                          index=tick_location_index)
            self.tick_menu.grid(row=0, column=1, sticky='w')

            label = Label(frame, text='  Tick Placement:')
            label.grid(row=0, column=2, sticky='e')
            self.tick_buttons = CheckButtons(frame,
                                             entries=tick_placements,
                                             selected=self.tick_placement)
            self.tick_buttons.grid(row=0, column=3, sticky='w')

        row += 1
        frame = Frame(self)
        frame.grid(row=row, column=0, columnspan=4, sticky='ew')
        frame.grid_columnconfigure(3, weight=1)

        label = Label(frame, text='Include:')
        label.grid(row=0, column=0, sticky='e')
        self.border_buttons = CheckButtons(frame,
                                           entries=border_decorations,
                                           selected=self.border_decoration)
        self.border_buttons.grid(row=0, column=1, sticky='w')

        label = Label(frame, text='  Scaling:')
        label.grid(row=0, column=2, sticky='e')
        self.scaling_scale = Scale(frame,
                                   orient=Tkinter.HORIZONTAL,
                                   value=self.scaling)
        self.scaling_scale.grid(row=0, column=3, sticky='ew')
Example #21
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)
Example #22
0
    def body(self, master):

        fileName = self.fileName
        directory = os.path.dirname(fileName)
        if not directory:
            directory = os.getcwd()
        fileName = os.path.basename(fileName)

        m = template_re.match(fileName)
        if m:
            n = len(m.groups(2))
            ss = '%%0%dd' % n
            template = re.sub(template_re, r'\1%s\3' % ss, fileName)
        else:
            template = fileName

        master.rowconfigure(0, weight=1)
        master.rowconfigure(1, weight=1)
        master.columnconfigure(1, weight=1)

        tipTexts = [
            'The experiment is pseudo-N dimensional, with a sampled axis',
            'The experiment is the regular kind with only NMR frequency axes'
        ]
        self.pseudoButton = RadioButtons(
            master,
            entries=self.pseudoEntries,
            select_callback=self.changedPseudoMode,
            grid=(0, 0),
            sticky='nw',
            tipTexts=tipTexts)

        frame = self.pseudoFrame = Frame(master)
        self.pseudoFrame.grid(row=1, column=0, sticky='nsew')

        row = 0
        npts = self.params.npts[self.dim]
        tipText = 'Number of data points (planes) along sampled axis'
        label = Label(frame, text='Number of points: ')
        label.grid(row=row, column=0, sticky='e')
        self.nptsEntry = IntEntry(frame,
                                  text=npts,
                                  tipText=tipText,
                                  width=8,
                                  grid=(row, 1))

        tipText = 'Load the values for the sampled axis from a text file containing a list of numeric values'
        Button(frame,
               text='Load values from text file',
               command=self.loadValues,
               tipText=tipText,
               grid=(row, 2),
               sticky='ew')

        row = row + 1
        tipText = 'The values (e.g. T1, T2) corresponding to each data point (plane) along sampled axis'
        label = Label(frame, text='Point values: ')
        label.grid(row=row, column=0, sticky='e')
        self.valueEntry = FloatEntry(frame, isArray=True, tipText=tipText)
        self.valueEntry.grid(row=row, column=1, columnspan=2, sticky='ew')

        row = row + 1
        tipText = 'Fetch the Point values from the files given by the NMRPipe template'
        button = Button(
            frame,
            text='Fetch values from file(s) specified by template below',
            command=self.fetchValues,
            tipText=tipText)
        button.grid(row=row, column=1, columnspan=2, sticky='w')

        row = row + 1
        tipText = 'The directory where the data files reside'
        button = Button(frame,
                        text='Data directory: ',
                        command=self.chooseDirectory)
        button.grid(row=row, column=0, sticky='e')
        self.directoryEntry = Entry(frame,
                                    text=directory,
                                    width=40,
                                    tipText=tipText)
        self.directoryEntry.grid(row=row, column=1, columnspan=2, sticky='ew')

        row = row + 1
        tipText = 'The NMRPipe template for the data files, if you want to use these to fetch the point values from'
        button = Button(frame,
                        text='NMRPipe template: ',
                        command=self.chooseFile)
        button.grid(row=row, column=0, sticky='e')
        self.templateEntry = Entry(frame, text=template, tipText=tipText)
        self.templateEntry.grid(row=row, column=1, columnspan=2, sticky='ew')

        for n in range(row):
            frame.rowconfigure(n, weight=1)
        frame.columnconfigure(1, weight=1)

        buttons = UtilityButtonList(master,
                                    closeText='Ok',
                                    doClone=False,
                                    closeCmd=self.updateParams,
                                    helpUrl=self.help_url)
        buttons.grid(row=2, column=0, sticky='ew')
Example #23
0
    import sys
    import Tkinter
    from memops.gui.Button import Button

    popup_select = None

    def callback(text):
        global popup_select
        if (popup_select):
            print 'callback: selected =', popup_select.getSelected()

    def toggle():
        global popup_select
        if (popup_select.getSelected()):
            popup_select.setSelected(False)
        else:
            popup_select.setSelected(True)

    root = Tkinter.Tk()

    popup_select = BooleanPulldownMenu(root, callback=callback, selected=False)
    popup_select.grid(row=0, column=0, columnspan=2)

    button = Button(root, text='toggle extra state', command=toggle)
    button.grid(row=1, column=0)

    button = Button(root, text='quit', command=sys.exit)
    button.grid(row=1, column=1)

    root.mainloop()
Example #24
0
    def drawFrame(self):

        # build up the body.

        # what are the rules governing when this tab should show something and
        # when it should not? In fact, there is the whole question of how the
        # two different sections (file management and task management) should
        # interract sensibly.

        # This needs to be composed. We know the task type (from the tab) so what
        # we need to know is how to handle ids. should we generate a placeholder
        # id, or would it be better not to assign an id to begin with or else
        # just use id(new)

        self.task_id = self.basePopup.currentTask

        print 'trying to render task with serial ', self.task_id

        if self.task_id == None:

            for widget in self.data_widgets:
                widget.grid_remove()

            self.null_task_label.grid(row=1,
                                      column=1,
                                      columnspan=4,
                                      sticky='nswe')

        else:

            for widget in self.noData_widgets:
                widget.grid_remove()

            loc = SharedBeanServiceLocator()
            port = loc.getSharedBean()

            # need two calls, one for the Project and one for the version
            hm1 = {'serial': int(self.task_id)}
            wsstr_in1 = WSString(hm1)

            request1 = getFieldsWithMethod()
            request1._arg0 = 'org.pimslims.applet.server.TaskBean'
            request1._arg1 = 'getTest1Fields'
            request1._arg2 = wsstr_in1.str

            response1 = port.getFieldsWithMethod(request1)

            wsstr_out1 = WSString(response1._return)
            hm_tv = wsstr_out1.getStructHM()

            print 'RESULT ', hm_tv

            self.task_rep_title.set('Task: ' + self.task_id)
            self.task_rep_title.grid(row=1, column=1, columnspan=2, sticky='w')

            self.repository = self.basePopup.repList.currentRepository
            self.task_rep_label.grid(row=2, column=1, sticky='w')
            self.task_rep_value.set(self.repository.user + '@' +
                                    self.repository.name + '  ( ' +
                                    self.repository.connect + ' )')
            self.task_rep_value.grid(row=2, column=2, columnspan=2, sticky='w')

            # FIXME JMCI

            # This actually needs to be editable

            self.task_status_label.grid(row=3,
                                        column=1,
                                        columnspan=2,
                                        sticky='w')
            self.task_status_value.set(hm_tv['status'])
            #self.task_status_value.set('PENDING')
            self.task_status_value.grid(row=3,
                                        column=2,
                                        columnspan=2,
                                        sticky='w')

            par1 = 'N/A'
            if hm_tv['par1'] != 'valIsNullPointer':
                par1 = hm_tv['par1']

            self.task_par1_label.grid(row=4,
                                      column=1,
                                      columnspan=2,
                                      sticky='w')
            self.task_par1_value.set(par1)
            self.task_par1_value.grid(row=4,
                                      column=2,
                                      columnspan=2,
                                      sticky='w')

            par2 = 'N/A'
            if hm_tv['par1'] != 'valIsNullPointer':
                par2 = hm_tv['par2']

            self.task_par2_label.grid(row=5,
                                      column=1,
                                      columnspan=2,
                                      sticky='w')
            self.task_par2_value.set(par2)
            self.task_par2_value.grid(row=5,
                                      column=2,
                                      columnspan=2,
                                      sticky='w')

            # this will depend on the status
            #self.task_date_label.grid(row=4, column=1, columnspan=2, sticky='w')
            #self.task_date_value.set('11 FEB 2009:11:36')
            #self.task_date_value.grid(row=4, column=2, columnspan=2, sticky='w')

            # FIXME JMCI

            # This is not in the current model
            #self.task_details_label.grid(row=4, column=1, columnspan=2, sticky='w')
            #self.task_details_value.set(hm_pv['details'])
            #self.task_details_value.grid(row=4, column=2, columnspan=2, sticky='w')

            inputProject = 'N/A'
            # This needs to be populated from the fields hash
            # It is also going to be dependent on the precise task
            if hm_tv.has_key('inputVersion'):
                inputProjectName = hm_tv['inputVersion']['project']['name']
                inputVersionTag = hm_tv['inputVersion']['versionTag']
                inputProject = inputProjectName + '::' + inputVersionTag

            self.task_input_label.grid(row=6, column=1, sticky='w')
            self.task_input_value.set(inputProject)
            self.task_input_value.grid(row=6, column=2, sticky='w')

            self.button_file_in_browse.grid(row=6, column=3, sticky='e')

            outputProject = 'N/A'
            # This needs to be populated from the fields hash
            # It is also going to be dependent on the precise task
            if hm_tv.has_key('generatedVersion'):
                outputProjectName = hm_tv['generatedVersion']['project'][
                    'name']
                outputVersionTag = hm_tv['generatedVersion']['versionTag']
                outputProject = outputProjectName + '::' + outputVersionTag

            self.task_output_label.grid(row=7, column=1, sticky='w')
            self.task_output_value.set(outputProject)
            self.task_output_value.grid(row=7, column=2, sticky='w')

            # it not clear when we would want to allow the project to be
            # set, but allow it anyway for now

            self.button_file_out_browse.grid(row=7, column=3, sticky='e')

            # FIXME JMCI

            # again, this really depends on what the status is. Need to decide
            # the transitions
            button_submit = Button(self, text='Submit', command=self.submit)
            button_submit.grid(row=8, column=2, sticky='w')
Example #25
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)
Example #26
0
class Test1Frame(Frame):
    def __init__(self, guiParent, basePopup):

        self.guiParent = guiParent
        self.basePopup = basePopup

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

        self.task_id = None

        # should be set in parent initMethod() call now
        #self.basePopup.frameShortcuts['Task'].frameShortcuts['Test1'] = self

        # NOTE: JMCI

        # We can reasonably set the repository from the current repository. It is
        # harder to know how project/projectVersion and task interract

        # TODO
        # decide whether we really need this
        self.repository = self.basePopup.repList.currentRepository

        Frame.__init__(self, guiParent)

        # set up the grid

        self.grid_columnconfigure(0, weight=0, minsize=20)
        self.grid_columnconfigure(1, weight=0, minsize=30)
        self.grid_columnconfigure(2, weight=1, minsize=20)
        self.grid_columnconfigure(3, weight=0, minsize=20)
        self.grid_columnconfigure(4, weight=1, minsize=20)

        self.grid_rowconfigure(0, weight=0, minsize=20)
        self.grid_rowconfigure(1, weight=0, minsize=10)
        self.grid_rowconfigure(2, weight=0, minsize=10)
        self.grid_rowconfigure(3, weight=0, minsize=10)
        self.grid_rowconfigure(4, weight=0, minsize=20)

        # we define as much as possible once on startup and use the
        # grid manager to control the display thereafter

        # when no data

        self.noData_widgets = []

        self.null_task_label = Label(self, text='No Task selected')
        self.noData_widgets.append(self.null_task_label)

        # when data

        self.data_widgets = []

        self.task_rep_title = Label(self, text='Task:', font='Helvetica16')
        self.data_widgets.append(self.task_rep_title)

        self.task_rep_label = Label(self, text='Repository:')
        self.data_widgets.append(self.task_rep_label)
        self.task_rep_value = Label(self, text='')
        self.data_widgets.append(self.task_rep_value)

        self.task_status_label = Label(self, text='Status:')
        self.data_widgets.append(self.task_status_label)
        self.task_status_value = Label(self, text='')
        self.data_widgets.append(self.task_status_value)

        self.task_details_label = Label(self, text='Details:')
        self.data_widgets.append(self.task_details_label)
        self.task_details_value = Label(self, text='')
        self.data_widgets.append(self.task_details_value)

        self.task_date_label = Label(self, text='Date:')
        self.data_widgets.append(self.task_date_label)
        self.task_date_value = Label(self, text='')
        self.data_widgets.append(self.task_date_value)

        self.task_par1_label = Label(self, text='Par1:')
        self.data_widgets.append(self.task_par1_label)
        self.task_par1_value = Label(self, text='')
        self.data_widgets.append(self.task_par1_value)

        self.task_par2_label = Label(self, text='Par2:')
        self.data_widgets.append(self.task_par2_label)
        self.task_par2_value = Label(self, text='')
        self.data_widgets.append(self.task_par2_value)

        self.task_input_label = Label(self, text='Input Data:')
        self.data_widgets.append(self.task_input_label)
        self.task_input_value = Label(self, text='')
        self.data_widgets.append(self.task_input_value)

        self.button_file_in_browse = Button(self,
                                            text='Browse',
                                            command=self.tmpCall)
        self.data_widgets.append(self.button_file_in_browse)
        self.button_file_out_browse = Button(self,
                                             text='Browse',
                                             command=self.tmpCall)
        self.data_widgets.append(self.button_file_out_browse)

        self.task_output_label = Label(self, text='Output Data:')
        self.data_widgets.append(self.task_output_label)
        self.task_output_value = Label(self, text='')
        self.data_widgets.append(self.task_output_value)

        self.drawFrame()

    def drawFrame(self):

        # build up the body.

        # what are the rules governing when this tab should show something and
        # when it should not? In fact, there is the whole question of how the
        # two different sections (file management and task management) should
        # interract sensibly.

        # This needs to be composed. We know the task type (from the tab) so what
        # we need to know is how to handle ids. should we generate a placeholder
        # id, or would it be better not to assign an id to begin with or else
        # just use id(new)

        self.task_id = self.basePopup.currentTask

        print 'trying to render task with serial ', self.task_id

        if self.task_id == None:

            for widget in self.data_widgets:
                widget.grid_remove()

            self.null_task_label.grid(row=1,
                                      column=1,
                                      columnspan=4,
                                      sticky='nswe')

        else:

            for widget in self.noData_widgets:
                widget.grid_remove()

            loc = SharedBeanServiceLocator()
            port = loc.getSharedBean()

            # need two calls, one for the Project and one for the version
            hm1 = {'serial': int(self.task_id)}
            wsstr_in1 = WSString(hm1)

            request1 = getFieldsWithMethod()
            request1._arg0 = 'org.pimslims.applet.server.TaskBean'
            request1._arg1 = 'getTest1Fields'
            request1._arg2 = wsstr_in1.str

            response1 = port.getFieldsWithMethod(request1)

            wsstr_out1 = WSString(response1._return)
            hm_tv = wsstr_out1.getStructHM()

            print 'RESULT ', hm_tv

            self.task_rep_title.set('Task: ' + self.task_id)
            self.task_rep_title.grid(row=1, column=1, columnspan=2, sticky='w')

            self.repository = self.basePopup.repList.currentRepository
            self.task_rep_label.grid(row=2, column=1, sticky='w')
            self.task_rep_value.set(self.repository.user + '@' +
                                    self.repository.name + '  ( ' +
                                    self.repository.connect + ' )')
            self.task_rep_value.grid(row=2, column=2, columnspan=2, sticky='w')

            # FIXME JMCI

            # This actually needs to be editable

            self.task_status_label.grid(row=3,
                                        column=1,
                                        columnspan=2,
                                        sticky='w')
            self.task_status_value.set(hm_tv['status'])
            #self.task_status_value.set('PENDING')
            self.task_status_value.grid(row=3,
                                        column=2,
                                        columnspan=2,
                                        sticky='w')

            par1 = 'N/A'
            if hm_tv['par1'] != 'valIsNullPointer':
                par1 = hm_tv['par1']

            self.task_par1_label.grid(row=4,
                                      column=1,
                                      columnspan=2,
                                      sticky='w')
            self.task_par1_value.set(par1)
            self.task_par1_value.grid(row=4,
                                      column=2,
                                      columnspan=2,
                                      sticky='w')

            par2 = 'N/A'
            if hm_tv['par1'] != 'valIsNullPointer':
                par2 = hm_tv['par2']

            self.task_par2_label.grid(row=5,
                                      column=1,
                                      columnspan=2,
                                      sticky='w')
            self.task_par2_value.set(par2)
            self.task_par2_value.grid(row=5,
                                      column=2,
                                      columnspan=2,
                                      sticky='w')

            # this will depend on the status
            #self.task_date_label.grid(row=4, column=1, columnspan=2, sticky='w')
            #self.task_date_value.set('11 FEB 2009:11:36')
            #self.task_date_value.grid(row=4, column=2, columnspan=2, sticky='w')

            # FIXME JMCI

            # This is not in the current model
            #self.task_details_label.grid(row=4, column=1, columnspan=2, sticky='w')
            #self.task_details_value.set(hm_pv['details'])
            #self.task_details_value.grid(row=4, column=2, columnspan=2, sticky='w')

            inputProject = 'N/A'
            # This needs to be populated from the fields hash
            # It is also going to be dependent on the precise task
            if hm_tv.has_key('inputVersion'):
                inputProjectName = hm_tv['inputVersion']['project']['name']
                inputVersionTag = hm_tv['inputVersion']['versionTag']
                inputProject = inputProjectName + '::' + inputVersionTag

            self.task_input_label.grid(row=6, column=1, sticky='w')
            self.task_input_value.set(inputProject)
            self.task_input_value.grid(row=6, column=2, sticky='w')

            self.button_file_in_browse.grid(row=6, column=3, sticky='e')

            outputProject = 'N/A'
            # This needs to be populated from the fields hash
            # It is also going to be dependent on the precise task
            if hm_tv.has_key('generatedVersion'):
                outputProjectName = hm_tv['generatedVersion']['project'][
                    'name']
                outputVersionTag = hm_tv['generatedVersion']['versionTag']
                outputProject = outputProjectName + '::' + outputVersionTag

            self.task_output_label.grid(row=7, column=1, sticky='w')
            self.task_output_value.set(outputProject)
            self.task_output_value.grid(row=7, column=2, sticky='w')

            # it not clear when we would want to allow the project to be
            # set, but allow it anyway for now

            self.button_file_out_browse.grid(row=7, column=3, sticky='e')

            # FIXME JMCI

            # again, this really depends on what the status is. Need to decide
            # the transitions
            button_submit = Button(self, text='Submit', command=self.submit)
            button_submit.grid(row=8, column=2, sticky='w')

    def submit(self):

        print 'submitting a process (set status to pending)'

        # get a port proxy instance
        # this should probably belong to the repository directly

        h2 = {'serial': int(self.task_id), 'status': 'PENDING'}

        loc = SharedBeanServiceLocator()
        self.port = loc.getSharedBean()

        request2 = record()

        request2._arg0 = 'org.pimslims.applet.server.TaskBean'
        request2._arg1 = 'updateStatus'

        wsstr_in = WSString(h2)

        print 'trying to update status with ', h2, ', ', wsstr_in.str
        request2._arg2 = wsstr_in.str

        response2 = self.port.record(request2)

        # now need to redraw task-related frames
        self.drawFrame()
        if self.basePopup.frameShortcuts.has_key('Tasks'):
            self.basePopup.frameShortcuts['Tasks'].drawFrame()

    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):

        return

    def quit(self):

        self.guiParent.parent.destroy()

    def destroy(self):

        #self.administerNotifiers(self.basePopup.unregisterNotify)
        Frame.destroy(self)
Example #27
0
    else:
      self.var.set(0)

  def toggle(self):

    self.setSelected(not self.getSelected())

if __name__ == '__main__':

  from memops.gui.Button import Button

  def get_me():
    print 'get_me:', c.getSelected()

  def toggle_me():
    c.toggle()

  def my_callback(selected):
    print 'my_callback:', selected

  root = Tkinter.Tk()

  c = CheckButton(root, 'check button', callback=my_callback)
  c.grid()
  b = Button(root, text='get me', command=get_me)
  b.grid()
  b = Button(root, text='toggle me', command=toggle_me)
  b.grid()

  root.mainloop()
Example #28
0
class BacusPopup(BasePopup):

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

  
    self.project    = parent.project
    self.hNoesy    = None
    self.nNoesy     = None
    self.cNoesy     = None
    self.shiftList  = None

    BasePopup.__init__(self, parent, title="BACUS control module", **kw)
  
  def body(self, guiParent):
    
    guiParent.grid_columnconfigure(0, weight=1)

    row = 0
    guiParent.grid_rowconfigure(row, weight=1)
    inputFrame = LabelFrame(guiParent, text='Inputs:')
    inputFrame.grid(row=row, column=0, sticky=Tkinter.NSEW)
 
    label = Label(inputFrame, text='NOESY:')
    label.grid(row=0, column=0, sticky=Tkinter.NW)
    
    self.hNoesyPulldown = PulldownMenu(inputFrame,callback=self.setHNoesy)
    self.hNoesyPulldown.grid(row=0, column=1, sticky=Tkinter.NW)

    label = Label(inputFrame, text='15N NOESY:')
    label.grid(row=1, column=0, sticky=Tkinter.NW)
    
    self.nNoesyPulldown = PulldownMenu(inputFrame,callback=self.setNNoesy)
    self.nNoesyPulldown.grid(row=1, column=1, sticky=Tkinter.NW)
    
    label = Label(inputFrame, text='13C NOESY:')
    label.grid(row=2, column=0, sticky=Tkinter.NW)
 
    self.cNoesyPulldown = PulldownMenu(inputFrame,callback=self.setCNoesy)
    self.cNoesyPulldown.grid(row=2, column=1, sticky=Tkinter.NW)
    
    label = Label(inputFrame, text='Shift List:')
    label.grid(row=3, column=0, sticky=Tkinter.NW)
 
    self.shiftListPulldown = PulldownMenu(inputFrame,callback=self.setShiftList)
    self.shiftListPulldown.grid(row=3, column=1, sticky=Tkinter.NW)
    
    label = Label(inputFrame, text='2d BACUS executable:')
    label.grid(row=4, column=0, sticky=Tkinter.NW)
    
    self.executableEntry = Entry(inputFrame, text='/home/tjs23/clouds/justin/SpiBacusMidge/bacus/bacus_tjs.exe')
    self.executableEntry.grid(row=4, column=1, sticky=Tkinter.NW)

    self.executableButton = Button(inputFrame, text='Choose file', command=self.chooseExecutable)
    self.executableButton.grid(row=5, column=1, sticky=Tkinter.EW)
    
    row += 1
    outputFrame = LabelFrame(guiParent, text='Output:')
    outputFrame.grid(row=row, column=0, sticky=Tkinter.NSEW)
 
    row += 1
    texts    = ['Run BACUS 2d','Run BACUS 3d']
    commands = [self.runBacus,self.runBacus3d]
    self.bottomButtons = createDismissHelpButtonList(guiParent,texts=texts,commands=commands,expands=0,help_url=None)
    self.bottomButtons.grid(row=row, column=0, sticky=Tkinter.EW)
    
    self.update()    
  
  
  def chooseExecutable(self):
  
    fileTypes = [FileType('Table', ['*.exe']), FileType('All', ['*'])]
    fileSelectPopup = FileSelectPopup(self, file_types = fileTypes,
                                      title = 'Choose 2d BACUS executable', dismiss_text = 'Cancel',
                                      selected_file_must_exist = False)

    fileName = fileSelectPopup.getFile() 
    if fileName:
      self.executableEntry.set(fileName)
  
  
  def update(self):
 
    # set defaults via pulldown callbacks

    names = [self.getPeakListlabel(x) for x in self.gethNoesys()]
    if names:
      self.hNoesyPulldown.setup(names,0)
    else:
      self.hNoesyPulldown.setup([],-1)

    names = [self.getPeakListlabel(x) for x in self.getNNoesys()]
    if names:
      self.nNoesyPulldown.setup(names,0)
    else:
      self.nNoesyPulldown.setup([],-1)

    names = [self.getPeakListlabel(x) for x in self.getCNoesys()]
    if names:
      self.cNoesyPulldown.setup(names,0)
    else:
      self.cNoesyPulldown.setup([],-1)
  
    names = ['Shift List %d' % x.serial for x in self.getShiftLists()]
    if names:
      self.shiftListPulldown.setup(names,0)
    else:
      self.shiftListPulldown.setup([],-1)
  
    self.updateButtons()
  
  
  def updateButtons(self):
    
    if ( self.cNoesy or self.nNoesy ) and self.shiftList:
      self.bottomButtons.buttons[1].enable()
    else:
      self.bottomButtons.buttons[1].disable()
      
      
    if self.hNoesy and self.executableEntry.get() and self.shiftList:
      self.bottomButtons.buttons[0].enable()
    else:
      self.bottomButtons.buttons[0].disable()
    
  
  def runBacus3d(self, fileRoot='CCPN1'):
  
    if ( self.cNoesy or self.nNoesy ) and self.shiftList:
      run3dBacus(fileRoot,self.shiftList,self.cNoesy,self.nNoesy)
 
  def runBacus(self, fileRoot='CCPN1'):
     
    executable = self.executableEntry.get()
    if self.hNoesy and self.shiftList and executable:
      run2dBacus(fileRoot, executable, self.hNoesy,  self.shiftList)


  def getPeakListlabel(self, peakList):
  
    return '%s:%s:%d' % (peakList.dataSource.experiment.name, peakList.dataSource.name, peakList.serial)
  
  
  def getShiftLists(self):
  
    shiftLists = []
    if self.project:
      nmrProject = self.project.currentNmrProject
      shiftLists = nmrProject.findAllMeasurementLists(className='ShiftList')
    
    return list(shiftLists)
  
  
  def setShiftList(self, index, name=None):
  
    shiftLists = self.getShiftLists()
    if shiftLists:
      self.shiftList = shiftLists[index]
    else:
      self.shiftList = None
    
  def gethNoesys(self):
  
    peakLists = []
    if self.project:
      for experiment in self.project.currentNmrProject.experiments:
        for spectrum in experiment.dataSources:
          isotopes = getSpectrumIsotopes(spectrum)
          if isotopes == ['1H', '1H']:
            for peakList in spectrum.peakLists:
              #if 'NOE' in experiment.name.upper():
              #  peakLists.insert(0, peakList)
              #else:
              peakLists.append(peakList)
    
    return peakLists
  
  def getNNoesys(self):
  
    peakLists = []
    if self.project:
      for experiment in self.project.currentNmrProject.experiments:
        for spectrum in experiment.dataSources:
          isotopes = getSpectrumIsotopes(spectrum)
          isotopes.sort()
          if isotopes == ['15N', '1H', '1H']:
            for peakList in spectrum.peakLists:
              #if 'NOE' in experiment.name.upper():
              #  peakLists.insert(0, peakList)
              #else:
              peakLists.append(peakList)
    
    return peakLists
  
  
  def getCNoesys(self):
  
    peakLists = []
    if self.project:
      for experiment in self.project.currentNmrProject.experiments:
        for spectrum in experiment.dataSources:
          isotopes = getSpectrumIsotopes(spectrum)
          isotopes.sort()
          if isotopes == ['13C', '1H', '1H']:
            for peakList in spectrum.peakLists:
              if 'NOE' in experiment.name.upper():
                peakLists.insert(0, peakList)
              else:
                peakLists.append(peakList)
    
    return peakLists
        
        
  def setHNoesy(self, index, name=None):
 
    peakLists = self.gethNoesys()
    if peakLists:
      self.hNoesy = peakLists[index]
    else:
      self.hNoesy = None
        
        
  def setNNoesy(self, index, name=None):
 
    peakLists = self.getNNoesys()
    if peakLists:
      self.nNoesy = peakLists[index]
    else:
      self.nNoesy = None

 
  def setCNoesy(self, index, name=None):
  
    peakLists = self.getCNoesys()
    if peakLists:
      self.cNoesy = peakLists[index]
    else:
      self.cNoesy = None
 

  def destroy(self):

    BasePopup.destroy(self)
Example #29
0
            '#000040', '#000080', '#0000A0', '#0000FF', '#0040FF', '#0080FF',
            '#00A0FF', '#00C0FF', '#00E0FF', '#00FFFF', '#40FFFF', '#80FFFF',
            '#A0FFFF', '#D0FFFF', '#FFFFFF'
        ], None
    ]
    selected_index = 2

    popup_select = PulldownMenu(root,
                                callback=callback,
                                entries=entries,
                                colors=colors,
                                selected_index=selected_index)
    popup_select.grid(row=0, column=0, columnspan=3)

    button = Button(root, text='add', command=add)
    button.grid(row=1, column=0)

    button = Button(root, text='remove', command=remove)
    button.grid(row=1, column=1)

    button = Button(root, text='getSelected', command=getSelected)
    button.grid(row=1, column=2)

    button = Button(root, text='getSelectedInd', command=getSelectedInd)
    button.grid(row=1, column=3)

    button = Button(root, text='quit', command=sys.exit)
    button.grid(row=1, column=4)

    root.mainloop()
Example #30
0
class FileBrowserFrame(Frame):
    def __init__(self, guiParent, basePopup, callback=None):

        # 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

        # we need to be able to define a callback before exit
        self.callback = callback

        Frame.__init__(self, guiParent)

        # Basic principle is that we want to supply a root directory
        # and we will get a tree that will allow us to browse anything
        # below the directory. We will also have a button for going
        # up a directory.

        self.rootDir = '/home/jionides/work/CCPN/test_WMS_archive'

        self.icon_dict = {
            'none': 'text-x-generic-template',
            'text': 'text-x-generic',
            'text/plain': 'text-x-generic',
            'text/html': 'text-html',
            'text/script': 'text-x-script',
            'text/x-python': 'text-x-script',
            'text/x-perl': 'text-x-script',
            'image': 'image-x-generic',
            'application': 'applications-other',
            'video': 'video-x-generic',
            'message': 'internet-mail',
            'audio': 'audio-x-generic',
            'chemical': 'applications-internet',
            'application/x-tar': 'package-x-generic',
            'application/msword': 'x-office-document',
            'application/postscript': 'x-office-drawing',
            'application/pdf': 'x-office-drawing',
            'application/xml': 'text-x-script',
            'application/x-python-code': 'application-x-executable',
        }

        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

        self.fileTree = Tree(self)
        self.fileTree.grid(row=1, column=1, padx=10, pady=10, sticky='nsew')

        self.ok_button = Button(self, width=10, text='OK', command=self.isOk)
        #self.ok_button = Button(self, text='OK', command=self.isOk)
        self.ok_button.grid(row=2, column=1, padx=10, pady=10, sticky='e')

        self.cancel_button = Button(self,
                                    width=10,
                                    text='Cancel',
                                    command=self.isCancel)
        #self.cancel_button = Button(self,text='Cancel', command=self.isCancel)
        self.cancel_button.grid(row=2, column=1, padx=10, pady=10, sticky='w')

        files = listdir(self.rootDir)
        parents = [None] * len(files)
        icons = []
        objects = []
        texts = []
        callbacks = []
        for file in files:
            file = path.join(self.rootDir, file)

            text, icon, isDir = self.getData(file)
            icons.append(icon)
            texts.append(text)
            objects.append(file)

            if isDir:
                callbacks.append(self.openDir)
            else:
                callbacks.append(None)

        print 'updating', texts

        self.fileTree.update(parents, objects, texts, icons, callbacks)

    def getData(self, file):

        dirr, text = path.split(file)

        readable = access(file, R_OK)

        isDir = False
        if path.isdir(file):

            if not readable:
                icon = 'emblem-unreadable'
            elif path.islink(file):
                isDir = True
                icon = 'folder-remote'
            else:
                isDir = True
                icon = 'folder'
            text += '/'

        elif path.isfile(file):

            if not readable:
                icon = 'emblem-unreadable'
            #elif path.islink(file):
            #  icon = 'text-html'
            else:
                mimeType = mimetypes.guess_type(file)[0]

                if mimeType:
                    if not self.icon_dict.get(mimeType):
                        print mimeType

                    icon = self.icon_dict.get(mimeType) \
                            or self.icon_dict.get(mimeType.split('/')[0]) \
                            or self.icon_dict['none']
                else:
                    icon = self.icon_dict['none']

        elif not readable:
            icon = 'emblem-unreadable'

        else:
            icon = 'emblem-system'

        return text, icon, isDir

    def openDir(self, node):

        tree = node.tree
        filePath = node.object
        files = listdir(filePath)

        for file in files:

            file = path.join(filePath, file)
            text, icon, isDir = self.getData(file)
            parent, null = path.split(file)

            if isDir and access(file, R_OK):
                callback = self.openDir
            else:
                callback = None

            tree.add(node, file, text, icon, callback)

    def isCancel(self):

        print 'should be exiting'
        self.quit()

    def isOk(self):

        print 'setting selected ', self.fileTree.getSelected()

    def destroy(self):

        print 'in main destroy method'
        Frame.destroy(self)

    def quit(self):

        print 'in main quit method'
        self.guiParent.parent.destroy()
Example #31
0
    def __init__(self,
                 parent,
                 texts,
                 commands,
                 images=None,
                 buttonBorderwidth=1,
                 spacers=1,
                 expands=True,
                 font=None,
                 direction=HORIZONTAL,
                 sticky='ew',
                 *args,
                 **kw):

        assert direction in (HORIZONTAL,
                             VERTICAL), 'direction = %s' % direction

        if (type(commands) is types.DictType):
            have_dict = True
            for key in commands.keys():
                assert key in texts, 'key = %s' % key
        else:
            have_dict = False
            assert len(texts) == len(
                commands), 'len(texts) = %s, len(commands) = %s' % (
                    len(texts), len(commands))

        if not kw.has_key('bg'):
            kw['bg'] = 'grey82'

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

        if (direction == Tkinter.HORIZONTAL):
            self.grid_rowconfigure(0, weight=1)
        else:
            self.grid_columnconfigure(0, weight=1)

        if images is None:
            images = [None] * len(texts)

        self.font = font
        self.spacers = spacers
        r = 0
        c = 0

        if expands:
            self.spacers = spacers = 0
            for i in range(len(texts)):
                if texts[i]:
                    if (direction == Tkinter.HORIZONTAL):
                        self.grid_columnconfigure(i, weight=1)
                    else:
                        self.grid_rowconfigure(i, weight=1)

        else:
            if spacers and (direction == Tkinter.HORIZONTAL):
                self.grid_columnconfigure(c, weight=1)
                self.grid_columnconfigure(len(texts) + 1, weight=1)
                spacer1 = Spacer(self)
                spacer2 = Spacer(self)
                spacer1.grid(row=r, column=c, sticky=Tkinter.NSEW)
                spacer2.grid(row=r, column=len(texts) + 1, sticky=Tkinter.NSEW)
                c += 1

        self.buttons = []
        bg = kw['bg']

        for n, text in enumerate(texts):

            if n < len(images):
                image = images[n]
            else:
                image = None

            if type(text) not in (STRING_TYPE, UNICODE_TYPE):
                text = str(text)

            if (have_dict):
                try:
                    command = commands[text]
                except:
                    command = lambda x=text: notYetImplemented(x)
            else:
                command = commands[n]
                if not command:
                    command = lambda x=text: notYetImplemented(x)

            button = Button(self,
                            text=text,
                            command=command,
                            bg=bg,
                            image=image,
                            borderwidth=buttonBorderwidth,
                            font=self.font)
            button.grid(row=r, column=c, sticky=Tkinter.NSEW)
            self.buttons.append(button)

            if direction == Tkinter.HORIZONTAL:
                c = c + 1
            else:
                r = r + 1
Example #32
0
class LoginFrame(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.registerNotify=basePopup.registerNotify
    self.unregisterNotify=basePopup.unregisterNotify


    Frame.__init__(self, guiParent)
  
    # set up the grid

    self.grid_columnconfigure(0, weight=1, minsize=10)
    self.grid_columnconfigure(1, weight=0, minsize=10)
    self.grid_columnconfigure(2, weight=0, minsize=20)
    self.grid_columnconfigure(3, weight=1, minsize=10)

    self.grid_rowconfigure(0, weight=1, minsize=5)
    self.grid_rowconfigure(1, weight=0, minsize=10)
    self.grid_rowconfigure(2, weight=0, minsize=10)
    self.grid_rowconfigure(3, weight=0, minsize=10)
    self.grid_rowconfigure(4, weight=1, minsize=5)

    # build up the body.

    # Column headers

    self.user_label = Label(self,text='Username:'******'w')

    self.user_value = Text(self, width=20, height=1, text="")
    self.user_value.grid(row=1, column=2,  padx=5, pady=5, sticky='w')


    self.pswd_label = Label(self,text='Password:'******'w')

    self.pswd_value = Text(self, width=20, height=1, text="")
    self.pswd_value.grid(row=2, column=2,  padx=5, pady=5, sticky='w')

    
    self.cancel_button = Button(self, width=10, height=1,
                               text="Cancel",
                               command=self.quit )
    self.cancel_button.grid(row=3, column=1,  padx=5, pady=5, sticky='e')

    
    self.login_botton = Button(self, width=10, height=1,
                               text="Login",
                               command=self.login )
    self.login_botton.grid(row=3, column=2,  padx=5, pady=5, sticky='w')


  def login(self):

    username = self.user_value.getText()

    # obviously need an authentication check here!

    self.basePopup.parent.setUsername(username)
    self.basePopup.parent.readConfig(username)
    self.basePopup.destroy()

    
  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):

      return

  def quit(self):
  
    self.guiParent.parent.destroy()
    
  def destroy(self):
  
    self.administerNotifiers(self.basePopup.unregisterNotify)
    Frame.destroy(self)