Example #1
0
    def body(self, guiFrame):

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

        frame = LabelFrame(guiFrame, text='Options')
        frame.grid(row=0,column=0,sticky='ew')
        frame.grid_columnconfigure(5, weight=1)

        # Choose type of symmetry set to define or change (if allready present in the model)
        self.molLabel = Label(frame, text='Symmetry Operator:')
        self.molLabel.grid(row=0,column=2,sticky='w')
        self.symmCodePulldown = PulldownMenu(frame, callback=self.setSymmCode, entries=['NCS','C2','C3','C5'], do_initial_callback=False)
        self.symmCodePulldown.grid(row=0,column=3,sticky='w')

        frame = LabelFrame(guiFrame, text='Symmetry Operations')
        frame.grid(row=1,column=0,sticky='nsew')
        frame.grid_columnconfigure(0, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        self.molSysPulldown   = PulldownMenu(self, callback=self.setMolSystem, do_initial_callback=False)
        self.chainSelect      = MultiWidget(self, CheckButton, callback=self.setChains, minRows=0, useImages=False)
        self.segStartEntry    = IntEntry(self, returnCallback=self.setSegStart, width=6)
        self.segLengthEntry   = IntEntry(self, returnCallback=self.setSegLength, width=6)

        headings = ['#','Symmetry\noperator','Mol System','Chains','Start\nresidue','Segment\nlength']  
        editWidgets      = [None, None, self.molSysPulldown, self.chainSelect, self.segStartEntry, self.segLengthEntry] 
        editGetCallbacks = [None, None, self.getMolSystem, self.getChains, self.getSegStart, self.getSegLength]
        editSetCallbacks = [None, self.setSymmCode, self.setMolSystem, self.setChains, self.setSegStart, self.setSegLength]
        
        self.symmetryMatrix = ScrolledMatrix(frame,headingList=headings,
                                             callback=self.selectSymmetry,
                                             editWidgets=editWidgets,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)
        self.symmetryMatrix.grid(row=0,column=0,sticky='nsew')

        texts = ['Add Symmetry Set','Remove Symmetry Set']
        commands = [self.addSymmetrySet,self.removeSymmetrySet]
        self.buttonList = createDismissHelpButtonList(guiFrame, texts=texts, commands=commands, expands=True)
        self.buttonList.grid(row=2,column=0,sticky='ew')
        
        self.updateMolPartners()
        self.notify(self.registerNotify)

        #Temporary report of parameters
        print self.molSystem
        print self.molecules
        print self.symmetrySet
        print self.symmetryOp
        print self.symmetryCode
Example #2
0
    def body(self, master):

        self.alarm_id = None
        self.root_widget = getRoot(self)

        row = 0
        label = Label(master, text='Widget count:')
        label.grid(row=row, column=0, sticky=Tkinter.W)
        self.count_label = Label(master,
                                 text='',
                                 tipText='Number of Tkinter widget objects')
        self.count_label.grid(row=row, column=1, sticky=Tkinter.W)

        row = row + 1
        ind = 1
        label = Label(master, text='Auto count:')
        label.grid(row=row, column=0, sticky=Tkinter.W)
        self.on_off_buttons = RadioButtons(master,
                                           entries=self.on_off_entries,
                                           select_callback=self.applyAuto,
                                           selected_index=ind)
        self.on_off_buttons.grid(row=row, column=1, sticky=Tkinter.EW)

        row = row + 1
        label = Label(master, text='Auto frequency:')
        label.grid(row=row, column=0, sticky=Tkinter.W)
        self.freq_entry = IntEntry(master,
                                   text=60,
                                   returnCallback=self.applyAuto)
        self.freq_entry.grid(row=row, column=1, sticky=Tkinter.EW)
        label = Label(master, text='seconds')
        label.grid(row=row, column=2, sticky=Tkinter.W)

        row = row + 1
        texts = ['Do Immediate Count']
        commands = [self.applyManual]
        buttons = createDismissHelpButtonList(master,
                                              texts=texts,
                                              commands=commands,
                                              help_msg=self.help_msg,
                                              help_url=self.help_url)
        buttons.grid(row=row, column=0, columnspan=3, sticky=Tkinter.EW)

        self.doCount()
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 #4
0
class PopupTemplate(BasePopup):

  def __init__(self, parent, project=None, *args, **kw):

    self.project = project
    self.parent  = parent
    self.objects = self.getObjects()
    self.object  = None
    
    BasePopup.__init__(self, parent=parent, title='Popup Template', **kw)
                       
    self.updateObjects()

  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)

  def floatEntryReturn(self, event):
  
    value = self.floatEntry.get()
    self.textWindow.setText('%s\n' % value)

  def selectObject(self, object, row, col):
  
    self.object = object

  def getKeywords(self, object):
  
    if object :
      values = object.keywords
      self.multiWidget.set(values)
  
  def setKeywords(self, event):
  
    values = self.multiWidget.get()
    self.object.keywords = values
    self.updateObjects()

  def getNumber(self, object):

    if object :
      self.intEntry.set(object.quantity)

  def setNumber(self, event):

    value = self.intEntry.get()
    self.object.quantity = value
    self.updateObjects()

  def toggleFrame1(self, isHidden):
 
    if isHidden:
      self.scrolledMatrix.grid_forget()
      self.toggleFrame.grid_forget()
    else:
      self.scrolledGraph.grid_forget()
      self.scrolledCanvas.grid_forget()
      self.scrolledMatrix.grid(row=0, column=0, sticky=Tkinter.NSEW)
      self.toggleFrame.grid(row=self.toggleRow, column=1,sticky=Tkinter.NSEW)
      self.toggleLabel2.arrowOff()
      self.toggleLabel3.arrowOff()


  def toggleFrame2(self, isHidden):
 
    if isHidden:
      self.scrolledGraph.grid_forget()
      self.toggleFrame.grid_forget()
    else:
      self.scrolledMatrix.grid_forget()
      self.scrolledCanvas.grid_forget()
      self.scrolledGraph.grid(row=0, column=0, sticky=Tkinter.NSEW)
      self.toggleFrame.grid(row=self.toggleRow, column=1,sticky=Tkinter.NSEW)
      self.toggleLabel1.arrowOff()
      self.toggleLabel3.arrowOff()

  def toggleFrame3(self, isHidden):
 
    if isHidden:
      self.scrolledCanvas.grid_forget()
      self.toggleFrame.grid_forget()
    else:
      self.scrolledMatrix.grid_forget()
      self.scrolledGraph.grid_forget()
      self.scrolledCanvas.grid(row=0, column=0, sticky=Tkinter.NSEW)
      self.toggleFrame.grid(row=self.toggleRow, column=1,sticky=Tkinter.NSEW)
      self.toggleLabel1.arrowOff()
      self.toggleLabel2.arrowOff()

 
  def valueRampCallback(self, value):
  
    self.textWindow.setText('%s\n' % value)

  def checkRadioButtons(self, value):
  
    self.textWindow.setText('%s\n' % value)

  def selectPulldown(self, index, name):
  
    self.textWindow.setText('%d, %s\n' % (index, name))

  def toggleSelector(self, value):
  
    self.textWindow.setText('%s\n' % value)

  def changedCheckButtons(self, values):
  
    self.textWindow.setText(','.join(values) + '\n')

  def getObjects(self):
  
    objects = []
    
    objects.append( Fruit('Lemon',   '#FFFF00',1,keywords=['Bitter','Tangy'] ) )
    objects.append( Fruit('Orange',  '#FF8000',4 ) )
    objects.append( Fruit('Banana',  '#FFF000',5 ) )
    objects.append( Fruit('Pinapple','#FFD000',9 ) )
    objects.append( Fruit('Kiwi',    '#008000',12) )
    objects.append( Fruit('Lime',    '#00FF00',2 ) )
    objects.append( Fruit('Apple',   '#800000',5,keywords=['Crunchy'] ) )
    objects.append( Fruit('Pear',    '#408000',6 ) )
    objects.append( Fruit('Peach',   '#FFE0C0',2,keywords=['Sweet','Furry'] ) )
    objects.append( Fruit('Plumb',   '#800080',7 ) )
    
    return objects

  def updateObjects(self, event=None):

    textMatrix = []
    objectList = []
    colorMatrix = []
    
    for object in self.objects:
      datum = []
      datum.append( object.name )
      datum.append( None )
      datum.append( object.quantity )
      datum.append( ','.join(object.keywords) )
    
      colors = [None, object.color, None, None]
    
      textMatrix.append(datum)
      objectList.append(object)
      colorMatrix.append(colors)

    if self.check.get():
      self.scrolledMatrix.update(textMatrix=textMatrix, objectList=objectList)
    else:
      self.scrolledMatrix.update(textMatrix=textMatrix, objectList=objectList, colorMatrix=colorMatrix)

  def selectFile(self):

    fileSelectPopup = FileSelectPopup(self, title = 'Choose file', dismiss_text = 'Cancel',
                                      selected_file_must_exist = True)

    fileName = fileSelectPopup.getFile()

    self.textWindow.setText('File Selected: %s\n' % fileName)

  def showWarning(self, eventObject):
  
    self.textWindow.setText('Text Entry Return Pressed\n')
    showWarning('Warning Title','Warning Message')
    return

  def pressButton(self):
  
    self.textWindow.setText('Button Pressed\n')
    if showYesNo('Title','Prompt: Clear text window?'):
       self.textWindow.clear()
       
    return

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

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

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

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

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

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

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

        row = 0

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

        row += 1

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

        row = 0

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

        row += 1

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

        row += 1

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

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

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

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

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

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

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

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

        texts = ['Transfer Assignments']
        commands = [self.transferAssignments]
        self.transferButton = ButtonList(
            self.frame, commands=commands, texts=texts)
        self.transferButton.grid(row=5, column=0, sticky='nsew', columnspan=2)
Example #6
0
  def body(self, guiFrame):
  
    guiFrame.grid_columnconfigure(0, weight=1)
    guiFrame.grid_rowconfigure(0, weight=1)

    options = ['Parameters','Restraints','Alignment Media & Tensors','About Meccano']
    tabbedFrame = TabbedFrame(guiFrame, options=options)
    tabbedFrame.grid(row=0, column=0, sticky='nsew')
    
    frameA, frameB, frameC, frameD = tabbedFrame.frames
    frameA.grid_columnconfigure(1, weight=1)
    frameA.grid_rowconfigure(13, weight=1)
    frameB.grid_columnconfigure(1, weight=1)
    frameB.grid_rowconfigure(1, weight=1)
    frameC.grid_columnconfigure(0, weight=1)
    frameC.grid_rowconfigure(1, weight=1)
    frameD.grid_columnconfigure(0, weight=1)
    frameD.grid_rowconfigure(0, weight=1)
    
    texts = ['Run MECCANO!']
    commands = [self.runMeccano]
    bottomButtons = createDismissHelpButtonList(guiFrame, texts=texts,
                                                commands=commands, expands=True)
    bottomButtons.grid(row=1, column=0, sticky='ew')

    if not Meccano:
      bottomButtons.buttons[0].disable()
  
    # Parameters
        
    row = 0
    label = Label(frameA, text='Calculation Run:')
    label.grid(row=row,column=0,sticky='w')
    self.runPulldown = PulldownList(frameA, callback=self.selectRun)
    self.runPulldown.grid(row=row,column=1,sticky='w')
    
    row += 1    
    label = Label(frameA, text='Shift List (for CO):')
    label.grid(row=row,column=0,sticky='w')
    self.shiftListPulldown = PulldownList(frameA, callback=self.selectShiftList)
    self.shiftListPulldown.grid(row=row,column=1,sticky='w')
           
    row += 1    
    label = Label(frameA, text='Keep Copy of Used Shifts:')
    label.grid(row=row,column=0,sticky='w')
    self.toggleCopyShifts = CheckButton(frameA)
    self.toggleCopyShifts.grid(row=row,column=1,sticky='w')
    self.toggleCopyShifts.set(True)
        
    row += 1    
    label = Label(frameA, text='Molecular System:')
    label.grid(row=row,column=0,sticky='w')
    self.molSystemPulldown = PulldownList(frameA, callback=self.selectMolSystem)
    self.molSystemPulldown.grid(row=row,column=1,sticky='w')
        
    row += 1    
    label = Label(frameA, text='Chain:')
    label.grid(row=row,column=0,sticky='w')
    self.chainPulldown = PulldownList(frameA, callback=self.selectChain)
    self.chainPulldown.grid(row=row,column=1,sticky='w')
    self.chainPulldown.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='First Peptide Plane:')
    label.grid(row=row,column=0,sticky='w')
    self.firstResEntry = IntEntry(frameA, text=None, width=8)
    self.firstResEntry.grid(row=row,column=1,sticky='w')
    self.firstResEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Last Peptide Plane:')
    label.grid(row=row,column=0,sticky='w')
    self.lastResEntry = IntEntry(frameA, text=None, width=8)
    self.lastResEntry.grid(row=row,column=1,sticky='w')
    self.lastResEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Max Num Optimisation Steps:')
    label.grid(row=row,column=0,sticky='w')
    self.maxOptStepEntry = IntEntry(frameA, text=500, width=8)
    self.maxOptStepEntry.grid(row=row,column=1,sticky='w')
    self.maxOptStepEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Num Optimisation Peptide Planes:')
    label.grid(row=row,column=0,sticky='w')
    self.numOptPlaneEntry = IntEntry(frameA, text=2, width=8)
    self.numOptPlaneEntry.grid(row=row,column=1,sticky='w')
    self.numOptPlaneEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Min Num Optimisation Hits:')
    label.grid(row=row,column=0,sticky='w')
    self.numOptHitsEntry = IntEntry(frameA, text=5, width=8)
    self.numOptHitsEntry.grid(row=row,column=1,sticky='w')
    self.numOptHitsEntry.bind('<Leave>', self.updateRunParams) 

    row += 1    
    label = Label(frameA, text='File Name Prefix:')
    label.grid(row=row,column=0,sticky='w')
    self.pdbFileEntry = Entry(frameA, text='Meccano', width=8)
    self.pdbFileEntry.grid(row=row,column=1,sticky='w')
    self.pdbFileEntry.bind('<Leave>', self.updateRunParams) 
           
    row += 1    
    label = Label(frameA, text='Write Output File (.out):')
    label.grid(row=row,column=0,sticky='w')
    self.toggleWriteOutFile = CheckButton(frameA)
    self.toggleWriteOutFile.grid(row=row,column=1,sticky='w')
    self.toggleWriteOutFile.set(False)
    self.toggleWriteOutFile.bind('<Leave>', self.updateRunParams) 
           
    row += 1    
    label = Label(frameA, text='Write PDB File (.pdb):')
    label.grid(row=row,column=0,sticky='w')
    self.toggleWritePdbFile = CheckButton(frameA)
    self.toggleWritePdbFile.grid(row=row,column=1,sticky='w')
    self.toggleWritePdbFile.set(True)
    self.toggleWritePdbFile.bind('<Leave>', self.updateRunParams) 
    
    if not Meccano:
      row += 1    
      label = Label(frameA, text='The Meccano executable is not available (it needs to be compiled)', fg='red')
      label.grid(row=row,column=0,columnspan=2,sticky='w')

    # Restraints
    
    label = Label(frameB, text='Constraint Set:')
    label.grid(row=0,column=0,sticky='w')
    
    self.constraintSetPulldown = PulldownList(frameB, callback=self.selectConstraintSet)
    self.constraintSetPulldown.grid(row=0,column=1,sticky='w')
    
    self.alignMediumPulldown= PulldownList(self, callback=self.setAlignMedium)
    
    headingList = ['#','List Type','Use?','Alignment\nMedium','Num\nRestraints']
    editWidgets      = [None,None,None,self.alignMediumPulldown,None]
    editGetCallbacks = [None,None,self.toggleUseRestraints,self.getAlignMedium,None]
    editSetCallbacks = [None,None,None,self.setAlignMedium,None]
    self.restraintMatrix = ScrolledMatrix(frameB,
                                          headingList=headingList,
                                          editSetCallbacks=editSetCallbacks,
                                          editGetCallbacks=editGetCallbacks, 
                                          editWidgets=editWidgets,
                                          callback=None,
                                          multiSelect=True)
    self.restraintMatrix.grid(row=1,column=0,columnspan=2,sticky='nsew')
    
    
    # Alignment Media
    
    div = LabelDivider(frameC,text='Alignment Media')
    div.grid(row=0,column=0,sticky='ew')
    
    self.mediumNameEntry = Entry(self, returnCallback=self.setMediumName)
    self.mediumDetailsEntry = Entry(self, returnCallback=self.setMediumDetails)
    
    headingList = ['#','Name','Details','Static Tensor','Dynamic Tensor']
    editWidgets      = [None, self.mediumNameEntry, self.mediumDetailsEntry, None, None]
    editGetCallbacks = [None, self.getMediumName, self.getMediumDetails, None, None]
    editSetCallbacks = [None, self.setMediumName, self.setMediumDetails, None, None]
    self.mediaMatrix = ScrolledMatrix(frameC,
                                      headingList=headingList,
                                      editSetCallbacks=editSetCallbacks,
                                      editGetCallbacks=editGetCallbacks, 
                                      editWidgets=editWidgets,
                                      callback=self.selectAlignMedium,
                                      multiSelect=True)
                                 
    self.mediaMatrix.grid(row=1,column=0,sticky='nsew')
     
    
    texts = ['Add Alignment medium','Remove Alignment Medium']
    commands = [self.addAlignMedium,self.removeAlignMedium]
    buttonList = ButtonList(frameC, texts=texts, commands=commands, expands=True)
    buttonList.grid(row=2,column=0,sticky='nsew')
    
    self.editAxialEntry = FloatEntry(self, returnCallback=self.setAxial)
    self.editRhombicEntry = FloatEntry(self, returnCallback=self.setRhombic)
    self.editAlphaEulerEntry = FloatEntry(self, returnCallback=self.setEulerAlpha)
    self.editBetaEulerEntry = FloatEntry(self, returnCallback=self.setEulerBeta)
    self.editGammaEulerEntry = FloatEntry(self, returnCallback=self.setEulerGamma)
    
    
    div = LabelDivider(frameC,text='Alignment Tensors')
    div.grid(row=3,column=0,sticky='ew')
    
    headingList = ['Type', u'Axial (\u03B6)',u'Rhombic (\u03B7)',
                   u'Euler \u03B1',u'Euler \u03B2',u'Euler \u03B3']
    editWidgets      = [None,self.editAxialEntry,
                        self.editRhombicEntry,self.editAlphaEulerEntry,
                        self.editBetaEulerEntry,self.editGammaEulerEntry]
    editSetCallbacks = [None,self.setAxial,self.setRhombic,
                        self.setEulerAlpha,self.setEulerBeta,self.setEulerGamma]
    editGetCallbacks = [None,self.getAxial,self.getRhombic,
                        self.getEulerAlpha,self.getEulerBeta,self.getEulerGamma]
                   
    self.tensorMatrix = ScrolledMatrix(frameC, maxRows=2,
                                       headingList=headingList,
                                       editSetCallbacks=editSetCallbacks,
                                       editGetCallbacks=editGetCallbacks, 
                                       editWidgets=editWidgets,
                                       callback=self.selectTensor,
                                       multiSelect=True)
                                          
    self.tensorMatrix.grid(row=4,column=0,sticky='nsew')
    
    texts = ['Add Static Tensor','Add Dynamic Tensor','Remove Tensor']
    commands = [self.addStaticTensor,self.addDynamicTensor,self.removeTensor]
    buttonList = ButtonList(frameC,texts=texts, commands=commands, expands=True)
    buttonList.grid(row=5,column=0,sticky='ew')
       
    # About
    
    label = Label(frameD, text='About Meccano...')
    label.grid(row=0,column=0,sticky='w')
  
    #
  
    self.geometry('500x400')

    self.updateShiftLists()
    self.updateMolSystems()
    self.updateResidueRanges()
    self.updateConstraintSets()
    self.updateAlignMedia()
    self.updateRuns()
Example #7
0
    def body(self, guiFrame):

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

        frame = LabelFrame(guiFrame, text='Options')
        frame.grid(row=0, column=0, sticky='ew')
        frame.grid_columnconfigure(5, weight=1)

        label = Label(frame, text='MolSystem:')
        label.grid(row=0, column=0, sticky='w')
        self.molSystemPulldown = PulldownMenu(frame,
                                              callback=self.selectMolSystem)
        self.molSystemPulldown.grid(row=0, column=1, sticky='w')

        self.molLabel = Label(frame, text='Molecule:')
        self.molLabel.grid(row=0, column=2, sticky='w')
        self.moleculePulldown = PulldownMenu(frame,
                                             callback=self.selectMolecule)
        self.moleculePulldown.grid(row=0, column=3, sticky='w')

        label = Label(frame, text='Same Molecule Symmetry:')
        label.grid(row=0, column=4, sticky='w')
        self.molSelect = CheckButton(frame, callback=self.toggleSingleMolecule)
        self.molSelect.grid(row=0, column=5, sticky='w')
        self.molSelect.set(self.singleMolecule)

        frame = LabelFrame(guiFrame, text='Symmetry Operations')
        frame.grid(row=1, column=0, sticky='nsew')
        frame.grid_columnconfigure(0, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        self.symmCodePulldown = PulldownMenu(self,
                                             callback=self.setSymmCode,
                                             do_initial_callback=False)
        self.segLengthEntry = IntEntry(self,
                                       returnCallback=self.setSegLength,
                                       width=6)
        self.setChainMulti = MultiWidget(self,
                                         CheckButton,
                                         callback=self.setChains,
                                         minRows=0,
                                         useImages=False)
        self.setSegmentMulti = MultiWidget(self,
                                           IntEntry,
                                           callback=self.setSegments,
                                           minRows=0,
                                           useImages=False)

        editWidgets = [
            None, self.symmCodePulldown, self.segLengthEntry,
            self.setChainMulti, self.setSegmentMulti
        ]
        editGetCallbacks = [
            None, self.getSymmCode, self.getSegLength, self.getChains,
            self.getSegments
        ]
        editSetCallbacks = [
            None, self.setSymmCode, self.setSegLength, self.setChains,
            self.setSegments
        ]

        headings = [
            '#', 'Symmetry\nType', 'Segment\nLength', 'Chains',
            'Segment\nPositions'
        ]
        self.symmetryMatrix = ScrolledMatrix(frame,
                                             headingList=headings,
                                             callback=self.selectSymmetry,
                                             editWidgets=editWidgets,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)
        self.symmetryMatrix.grid(row=0, column=0, sticky='nsew')

        texts = ['Add Symmetry Op', 'Remove Symmetrey Op']
        commands = [self.addSymmOp, self.removeSymmOp]
        buttonList = createDismissHelpButtonList(guiFrame,
                                                 texts=texts,
                                                 commands=commands,
                                                 expands=True)
        buttonList.grid(row=2, column=0, sticky='ew')

        self.updateMolSystems()
        self.updateMolecules()
        self.updateSymmetriesAfter()

        self.notify(self.registerNotify)
Example #8
0
    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()
Example #9
0
class CloudsPopup(BasePopup):
    def __init__(self, parent, *args, **kw):

        self.guiParent = parent
        self.project = parent.getProject()
        self.waiting = 0
        self.specFreq = 800.13
        self.maxIter = 50
        self.mixTime = 60
        self.corrTime = 11.5
        self.leakRate = 2.0
        self.peakListDict = {}
        self.noesyPeakList = None
        self.tocsyPeakList = None
        self.noesy3dPeakList = None
        self.hsqcPeakList = None
        self.maxIntens = 37000000

        self.resonances = None
        self.origResonances = None
        self.noesyPeaks = None
        self.distanceConstraintList = None
        self.antiDistConstraintList = None
        self.numClouds = 100
        self.filePrefix = 'cloud_'
        self.cloudsFiles = []
        self.adcAtomTypes = 'HN'
        self.structure = None

        # step num, initial temp, final temp, cooling steps, MD steps, MD tau, rep scale
        self.coolingScheme = []
        self.coolingScheme.append([1, 1, 1, 3, 500, 0.001, 0])
        self.coolingScheme.append([2, 80000, 4000, 19, 1000, 0.001, 0])
        self.coolingScheme.append([3, 4000, 1, 5, 500, 0.001, 0])
        self.coolingScheme.append([4, 15000, 1, 3, 1000, 0.001, 0])
        self.coolingScheme.append([5, 1, 1, 5, 500, 0.001, 0])
        self.coolingScheme.append([6, 8000, 1, 3, 1000, 0.001, 0])
        self.coolingScheme.append([7, 1, 1, 5, 500, 0.001, 0])
        self.coolingScheme.append([8, 3000, 25, 60, 2500, 0.001, 1])
        self.coolingScheme.append([9, 25, 25, 1, 7500, 0.001, 1])
        self.coolingScheme.append([10, 10, 10, 1, 7500, 0.001, 1])
        self.coolingScheme.append([11, 0.01, 0.01, 1, 7500, 0.0005, 1])

        self.coolingStep = None

        BasePopup.__init__(self,
                           parent,
                           title="Resonance Clouds Analysis",
                           **kw)

    def body(self, guiFrame):

        self.specFreqEntry = IntEntry(self,
                                      text=self.specFreq,
                                      width=8,
                                      returnCallback=self.setSpecFreq)
        self.maxIterEntry = IntEntry(self,
                                     text=self.maxIter,
                                     width=8,
                                     returnCallback=self.setMaxIter)
        self.mixTimeEntry = FloatEntry(self,
                                       text=self.mixTime,
                                       width=8,
                                       returnCallback=self.setMixTime)
        self.corrTimeEntry = FloatEntry(self,
                                        text=self.corrTime,
                                        width=8,
                                        returnCallback=self.setCorrTime)
        self.leakRateEntry = FloatEntry(self,
                                        text=self.leakRate,
                                        width=8,
                                        returnCallback=self.setLeakRate)
        self.maxIntensEntry = IntEntry(self,
                                       text=self.maxIntens,
                                       width=8,
                                       returnCallback=self.setMaxIntens)

        self.mdInitTempEntry = FloatEntry(self,
                                          text='',
                                          returnCallback=self.setMdInitTemp)
        self.mdFinTempEntry = FloatEntry(self,
                                         text='',
                                         returnCallback=self.setMdFinTemp)
        self.mdCoolStepsEntry = IntEntry(self,
                                         text='',
                                         returnCallback=self.setMdCoolSteps)
        self.mdSimStepsEntry = IntEntry(self,
                                        text='',
                                        returnCallback=self.setMdSimSteps)
        self.mdTauEntry = FloatEntry(self,
                                     text='',
                                     returnCallback=self.setMdTau)
        self.mdRepScaleEntry = FloatEntry(self,
                                          text='',
                                          returnCallback=self.setMdRepScale)

        guiFrame.grid_columnconfigure(0, weight=1)

        row = 0
        frame0 = LabelFrame(guiFrame, text='Setup peak lists')
        frame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame0.grid_columnconfigure(1, weight=1)

        f0row = 0
        label00 = Label(frame0, text='1H-1H NOESY spectrum')
        label00.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.noesyPulldown = PulldownMenu(frame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.noesyPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label01 = Label(frame0, text='15N HSQC spectrum')
        label01.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.hsqcPulldown = PulldownMenu(frame0,
                                         entries=self.getHsqcs(),
                                         callback=self.setHsqc,
                                         selected_index=0,
                                         do_initial_callback=0)
        self.hsqcPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label02 = Label(frame0, text='15N HSQC TOCSY spectrum')
        label02.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.tocsyPulldown = PulldownMenu(frame0,
                                          entries=self.getTocsys(),
                                          callback=self.setTocsy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tocsyPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label02 = Label(frame0, text='15N HSQC NOESY spectrum')
        label02.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.noesy3dPulldown = PulldownMenu(frame0,
                                            entries=self.getNoesy3ds(),
                                            callback=self.setNoesy3d,
                                            selected_index=0,
                                            do_initial_callback=0)
        self.noesy3dPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        texts = ['Setup resonances & peaks', 'Show Peaks', 'Show resonances']
        commands = [self.setupResonances, self.showPeaks, self.showResonances]
        self.setupButtons = ButtonList(frame0,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.setupButtons.grid(row=f0row,
                               column=0,
                               columnspan=2,
                               sticky=Tkinter.NSEW)

        f0row += 1
        self.label03a = Label(frame0, text='Resonances found: 0')
        self.label03a.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.label03b = Label(frame0, text='NOESY peaks found: 0')
        self.label03b.grid(row=f0row, column=1, sticky=Tkinter.NW)

        row += 1
        frame1 = LabelFrame(guiFrame, text='Calculate distance constraints')
        frame1.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame1.grid_columnconfigure(3, weight=1)

        f1row = 0
        frame1.grid_rowconfigure(f1row, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate, self.maxIntens
        ]
        colHeadings = [
            'Spectrometer\nfrequency', 'Max\niterations', 'Mixing\ntime (ms)',
            'Correl.\ntime (ns)', 'Leak\nrate', 'Max\nintensity'
        ]
        editWidgets = [
            self.specFreqEntry,
            self.maxIterEntry,
            self.mixTimeEntry,
            self.corrTimeEntry,
            self.leakRateEntry,
            self.maxIntensEntry,
        ]
        editGetCallbacks = [
            self.getSpecFreq,
            self.getMaxIter,
            self.getMixTime,
            self.getCorrTime,
            self.getLeakRate,
            self.getMaxIntens,
        ]
        editSetCallbacks = [
            self.setSpecFreq,
            self.setMaxIter,
            self.setMixTime,
            self.setCorrTime,
            self.setLeakRate,
            self.setMaxIntens,
        ]
        self.midgeParamsMatrix = ScrolledMatrix(
            frame1,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=1,
            initialCols=5,
            headingList=colHeadings,
            callback=None,
            objectList=[
                'None',
            ],
            textMatrix=[
                data,
            ])
        self.midgeParamsMatrix.grid(row=f1row,
                                    column=0,
                                    columnspan=4,
                                    sticky=Tkinter.NSEW)

        f1row += 1
        label10 = Label(frame1, text='Benchmark structure')
        label10.grid(row=f1row, column=0, sticky=Tkinter.NW)
        self.structurePulldown = PulldownMenu(frame1,
                                              entries=self.getStructures(),
                                              callback=self.setStructure,
                                              selected_index=0,
                                              do_initial_callback=0)
        self.structurePulldown.grid(row=f1row, column=1, sticky=Tkinter.NW)

        label11 = Label(frame1, text='ADC atom types:')
        label11.grid(row=f1row, column=2, sticky=Tkinter.NW)
        self.adcAtomsPulldown = PulldownMenu(frame1,
                                             entries=self.getAdcAtomTypes(),
                                             callback=self.setAdcAtomTypes,
                                             selected_index=0,
                                             do_initial_callback=0)
        self.adcAtomsPulldown.grid(row=f1row, column=3, sticky=Tkinter.NW)

        f1row += 1
        texts = [
            'Calculate distances', 'Show distance\nconstraints',
            'Show anti-distance\nconstraints'
        ]
        commands = [
            self.calculateDistances, self.showConstraints,
            self.showAntiConstraints
        ]
        self.midgeButtons = ButtonList(frame1,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.midgeButtons.grid(row=f1row,
                               column=0,
                               columnspan=4,
                               sticky=Tkinter.NSEW)

        f1row += 1
        self.distConstrLabel = Label(frame1, text='Distance constraints:')
        self.distConstrLabel.grid(row=f1row,
                                  column=0,
                                  columnspan=2,
                                  sticky=Tkinter.NW)
        self.antiConstrLabel = Label(frame1, text='Anti-distance constraints:')
        self.antiConstrLabel.grid(row=f1row,
                                  column=2,
                                  columnspan=2,
                                  sticky=Tkinter.NW)

        row += 1
        guiFrame.grid_rowconfigure(row, weight=1)
        frame2 = LabelFrame(guiFrame, text='Proton cloud molecular dynamics')
        frame2.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame2.grid_columnconfigure(1, weight=1)

        f2row = 0
        frame2.grid_rowconfigure(f2row, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate
        ]
        colHeadings = [
            'Step', 'Initial temp.', 'Final temp.', 'Cooling steps',
            'MD steps', 'MD tau', 'Rep. scale'
        ]
        editWidgets = [
            None, self.mdInitTempEntry, self.mdFinTempEntry,
            self.mdCoolStepsEntry, self.mdSimStepsEntry, self.mdTauEntry,
            self.mdRepScaleEntry
        ]
        editGetCallbacks = [
            None, self.getMdInitTemp, self.getMdFinTemp, self.getMdCoolSteps,
            self.getMdSimSteps, self.getMdTau, self.getMdRepScale
        ]
        editSetCallbacks = [
            None, self.setMdInitTemp, self.setMdFinTemp, self.setMdCoolSteps,
            self.setMdSimSteps, self.setMdTau, self.setMdRepScale
        ]
        self.coolingSchemeMatrix = ScrolledMatrix(
            frame2,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=9,
            initialRows=12,
            headingList=colHeadings,
            callback=self.selectCoolingStep,
            objectList=self.coolingScheme,
            textMatrix=self.coolingScheme)
        self.coolingSchemeMatrix.grid(row=f2row,
                                      column=0,
                                      columnspan=4,
                                      sticky=Tkinter.NSEW)

        f2row += 1
        texts = ['Move earlier', 'Move later', 'Add step', 'Remove step']
        commands = [
            self.moveStepEarlier, self.moveStepLater, self.addCoolingStep,
            self.removeCoolingStep
        ]
        self.coolingSchemeButtons = ButtonList(frame2,
                                               expands=1,
                                               commands=commands,
                                               texts=texts)
        self.coolingSchemeButtons.grid(row=f2row,
                                       column=0,
                                       columnspan=4,
                                       sticky=Tkinter.EW)

        f2row += 1
        label20 = Label(frame2, text='Number of clouds:')
        label20.grid(row=f2row, column=0, sticky=Tkinter.NW)
        self.numCloudsEntry = FloatEntry(frame2,
                                         text=100,
                                         returnCallback=self.setNumClouds,
                                         width=10)
        self.numCloudsEntry.grid(row=f2row, column=1, sticky=Tkinter.NW)
        label21 = Label(frame2, text='Cloud file prefix:')
        label21.grid(row=f2row, column=2, sticky=Tkinter.NW)
        self.filePrefixEntry = Entry(frame2,
                                     text='cloud_',
                                     returnCallback=self.setFilePrefix,
                                     width=10)
        self.filePrefixEntry.grid(row=f2row, column=3, sticky=Tkinter.NW)

        f2row += 1
        texts = ['Start molecular dynamics', 'Show dynamics progress']
        commands = [self.startMd, self.showMdProgress]
        self.mdButtons = ButtonList(frame2,
                                    expands=1,
                                    commands=commands,
                                    texts=texts)
        self.mdButtons.grid(row=f2row,
                            column=0,
                            columnspan=4,
                            sticky=Tkinter.NSEW)

        row += 1
        self.bottomButtons = createDismissHelpButtonList(guiFrame,
                                                         expands=0,
                                                         help_url=None)
        self.bottomButtons.grid(row=row, column=0, sticky=Tkinter.EW)

        self.setButtonStates()

    def getStructures(self):

        names = [
            '<None>',
        ]
        for molSystem in self.project.sortedMolSystems():
            for structure in molSystem.sortedStructureEnsembles():
                names.append('%s:%d' % (molSystem.name, structure.ensembleId))

        return names

    def setStructure(self, index, name=None):

        if index < 1:
            self.structure = None
        else:
            structures = []
            for molSystem in self.project.molSystems:
                for structure in molSystem.structureEnsembles:
                    structures.append(structure)

            self.structure = structures[index - 1]

    def getAdcAtomTypes(self):

        return ['HN', 'HN HA', 'HN HA HB']

    def setAdcAtomTypes(self, index, name=None):

        if name is None:
            name = self.adcAtomsPulldown.getSelected()

        self.adcAtomTypes = name

    def startMd(self):

        self.setNumClouds()
        self.setFilePrefix()
        if (self.distanceConstraintList and self.antiDistConstraintList
                and (self.numClouds > 0) and self.filePrefix):

            resDict = {}
            for resonance in self.guiParent.project.currentNmrProject.resonances:
                resDict[resonance.serial] = resonance

            resonances = []
            for constraint in self.distanceConstraintList.constraints:
                for item in constraint.items:
                    for fixedResonance in item.resonances:
                        if resDict.get(
                                fixedResonance.resonanceSerial) is not None:
                            resonances.append(
                                resDict[fixedResonance.resonanceSerial])
                            resDict[fixedResonance.resonanceSerial] = None

            startMdProcess(self.numClouds, self.distanceConstraintList,
                           resonances, self.coolingScheme, self.filePrefix)

            #structGen = self.distanceConstraintList.structureGeneration

            serials = []
            for resonance in resonances:
                serials.append(resonance.serial)
            clouds = []
            for i in range(self.numClouds):
                clouds.append('%s%3.3d.pdb' % (self.filePrefix, i))
            self.guiParent.application.setValues(
                self.distanceConstraintList.nmrConstraintStore,
                'clouds',
                values=clouds)
            self.guiParent.application.setValues(
                self.distanceConstraintList.nmrConstraintStore,
                'cloudsResonances',
                values=serials)

            # do better than this check for creation

    def showMdProgress(self):

        n = 0
        m = self.numClouds
        for i in range(m):
            pdbFileName = '%s%3.3d.pdb' % (self.filePrefix, i)
            if os.path.exists(pdbFileName):
                n += 1

        p = n * 100 / float(m)
        text = 'Done %d of %d clouds (%1.2f)%%' % (n, m, p)
        showInfo('MD Progress', text)

    def setFilePrefix(self, text=None):

        if not text:
            text = self.filePrefixEntry.get()

        if text:
            self.filePrefix = text

    def setNumClouds(self, n=None, *event):

        if not n:
            n = self.numCloudsEntry.get()

        if n:
            self.numClouds = int(n)

    def calculateDistances(self):

        # setup normalisation factor intensityMax

        # self.maxIter
        # what if failure ?

        resDict = {}
        for resonance in self.project.currentNmrProject.resonances:
            resDict[resonance.serial] = resonance

        self.resonances = self.origResonances
        intensityFactors = [1.0 for x in range(len(self.resonances))]

        # optimiseRelaxation will remove unconstrained resonances
        self.distanceConstraintList = optimiseRelaxation(
            self.resonances,
            self.noesyPeaks,
            intensityMax=self.maxIntens,
            intensityFactors=intensityFactors,
            tmix=self.mixTime,
            sf=self.specFreq,
            tcor=self.corrTime,
            rleak=self.leakRate)

        constrainSpinSystems(self.distanceConstraintList)
        # for testing calculate distances from structure overrides any resonances: uses assigned ones
        #(self.distanceConstraintList, self.resonances) = self.cheatForTesting()
        #self.antiDistConstraintList = self.distanceConstraintList
        protonNumbs = {'CH3': 3, 'Haro': 2, 'HN': 1, 'H': 1}

        PI = 3.1415926535897931
        GH = 2.6752e4
        HB = 1.05459e-27
        CONST = GH * GH * GH * GH * HB * HB
        tc = 1.0e-9 * self.corrTime
        wh = 2.0 * PI * self.specFreq * 1.0e6
        j0 = CONST * tc
        j1 = CONST * tc / (1.0 + wh * wh * tc * tc)
        j2 = CONST * tc / (1.0 + 4.0 * wh * wh * tc * tc)
        #jself = 6.0*j2 + 3.0*j1 + j0
        jcross = 6.0 * j2 - j0

        if self.distanceConstraintList:
            constraintStore = self.distanceConstraintList.nmrConstraintStore

            dict = {
                'HN': ['H'],
                'HN HA': ['H', 'HA', 'HA1', 'HA2'],
                'HN HA HB': ['H', 'HA', 'HA1', 'HA2', 'HB', 'HB2', 'HB3']
            }

            self.antiDistConstraintList = makeNoeAdcs(
                self.resonances,
                self.noesyPeakList.dataSource,
                constraintStore,
                allowedAtomTypes=dict[self.adcAtomTypes])

            if self.structure:

                N = len(self.resonances)
                sigmas = [[] for i in range(N)]
                for i in range(N):
                    sigmas[i] = [0.0 for j in range(N)]

                for constraint in self.distanceConstraintList.constraints:
                    resonances = list(constraint, findFirstItem().resonances)

                    ri = resDict[resonances[0].resonanceSerial]
                    rj = resDict[resonances[1].resonanceSerial]
                    i = self.resonances.index(ri)
                    j = self.resonances.index(rj)
                    atomSets1 = list(ri.resonanceSet.atomSets)
                    atomSets2 = list(rj.resonanceSet.atomSets)
                    if atomSets1 == atomSets2:
                        ass = list(atomSets1)
                        atomSets1 = [
                            ass[0],
                        ]
                        atomSets2 = [
                            ass[-1],
                        ]

                    distance = getAtomSetsDistance(atomSets1, atomSets2,
                                                   self.structure)
                    r = distance * 1e-8
                    nhs = protonNumbs[rj.name]
                    sigma = 0.1 * jcross * nhs / (r**6)
                    sigmas[i][j] = sigma

                    constraint.setDetails('Known Dist: %4.3f' % (distance))
                    #for constraint in self.antiDistConstraintList.constraints:
                    #  atomSets1 = list(resonances[0].resonanceSet.atomSets)
                    #  atomSets2 = list(resonances[1].resonanceSet.atomSets)
                    #  distance = getAtomSetsDistance(atomSets1, atomSets2, self.structure)
                    #  constraint.setDetails('Known Dist: %4.3f' % (distance))

                fp = open('sigmas.out', 'w')
                for i in range(N - 1):
                    for j in range(i + 1, N):
                        if sigmas[i][j] != 0.0:
                            fp.write('%3.1d  %3.1d   %9.2e\n' %
                                     (i, j, sigmas[i][j]))
                    #fp.write('\n')
                fp.close()

        self.setButtonStates()

    def cheatForTesting(self, atomSelection='H'):
        """ Makes a perfect cloud from a structure. """

        project = self.project
        structure = self.guiParent.argumentServer.getStructure()

        constraintStore = makeNmrConstraintStore(project)
        distConstraintList = NmrConstraint.DistanceConstraintList(
            constraintStore)

        chain = structure.findFirstCoodChain()
        structureGeneration.hydrogenResonances = []

        molSystem = structure.molSystem
        atomSets = []
        resonances = []
        i = 0
        for resonance in project.currentNmrProject.resonances:

            if resonance.isotopeCode == '1H':

                if resonance.resonanceSet:

                    atomSet = resonance.resonanceSet.findFirstAtomSet()
                    atom = atomSet.findFirstAtom()
                    seqId = atom.residue.seqId
                    if (seqId < 9) or (seqId > 78):
                        continue

                    if atom.residue.chain.molSystem is molSystem:

                        if atomSelection == 'methyl':
                            if len(atomSet.atoms) == 3:
                                if atom.residue.ccpCode not in ('Ala', 'Val',
                                                                'Ile', 'Leu',
                                                                'Thr', 'Met'):
                                    continue
                            elif atom.name != 'H':
                                continue

                        elif atomSelection == 'amide':
                            if atom.name != 'H':
                                continue

                        if atom.name == 'H':
                            resonance.name = 'HN'
                        else:
                            resonance.name = 'H'

                        resonances.append(resonance)
                        atomSets.append(list(resonance.resonanceSet.atomSets))
                        i += 1

        print "Found %d atomSets" % (len(atomSets))
        weight = 1
        adcWeight = 1
        constrDict = {}
        N = len(atomSets)
        for i in range(N - 1):
            atomSets0 = atomSets[i]
            residue0 = atomSets0[0].findFirstAtom().residue.seqId
            print "R", residue0

            for j in range(i + 1, N):
                if j == i:
                    continue
                atomSets1 = atomSets[j]

                dist = getAtomSetsDistance(atomSets0, atomSets1, structure)
                if not dist:
                    continue

                if dist < 5.5:
                    fixedResonance0 = getFixedResonance(
                        constraintStore, resonances[i])
                    fixedResonance1 = getFixedResonance(
                        constraintStore, resonances[j])
                    constrDict[i] = 1
                    constrDict[j] = 1
                    constraint = NmrConstraint.DistanceConstraint(
                        distConstraintList,
                        weight=weight,
                        targetValue=dist,
                        upperLimit=dist + (dist / 10),
                        lowerLimit=dist - (dist / 10),
                        error=dist / 5)
                    item = NmrConstraint.DistanceConstraintItem(
                        constraint,
                        resonances=[fixedResonance0, fixedResonance1])

                elif (atomSets1[0].findFirstAtom().name
                      == 'H') and (atomSets0[0].findFirstAtom().name
                                   == 'H') and (dist > 7):
                    #else:
                    fixedResonance0 = getFixedResonance(
                        constraintStore, resonances[i])
                    fixedResonance1 = getFixedResonance(
                        constraintStore, resonances[j])
                    constrDict[i] = 1
                    constrDict[j] = 1
                    constraint = NmrConstraint.DistanceConstraint(
                        distConstraintList,
                        weight=adcWeight,
                        targetValue=75,
                        upperLimit=175,
                        lowerLimit=5.0,
                        error=94.5)
                    item = NmrConstraint.DistanceConstraintItem(
                        constraint,
                        resonances=[fixedResonance0, fixedResonance1])

        return (distConstraintList, resonances)

    def showConstraints(self):

        if self.distanceConstraintList:
            self.guiParent.browseConstraints(
                constraintList=self.distanceConstraintList)

    def showAntiConstraints(self):

        if self.antiDistConstraintList:
            self.guiParent.browseConstraints(
                constraintList=self.antiDistConstraintList)

    def showPeaks(self):

        self.guiParent.viewPeaks(peaks=self.noesyPeaks)

    def showResonances(self):

        pass
        #self.guiParent.viewResonances(resonances=self.resonances)

    def setupResonances(self):

        if self.noesyPeakList and self.noesy3dPeakList and self.tocsyPeakList and self.hsqcPeakList:

            disambiguateNoesyPeaks(self.noesyPeakList, self.noesy3dPeakList,
                                   self.tocsyPeakList, self.hsqcPeakList)

            (self.origResonances, self.noesyPeaks,
             null) = getCloudsResonanceList(self.guiParent.argumentServer,
                                            hsqcPeakList=self.hsqcPeakList,
                                            tocsy3dPeakList=self.tocsyPeakList,
                                            noesy2dPeakList=self.noesyPeakList)
            self.setButtonStates()

    def setButtonStates(self):

        if self.origResonances:
            self.label03a.set('Resonances found: %d' %
                              (len(self.origResonances)))

        if self.noesyPeaks:
            self.label03b.set('NOESY peaks found: %d' % (len(self.noesyPeaks)))

        if self.noesyPeakList and self.tocsyPeakList and self.hsqcPeakList:
            self.setupButtons.buttons[0].enable()
        else:
            self.setupButtons.buttons[0].disable()

        if self.noesyPeaks:
            self.setupButtons.buttons[1].enable()
        else:
            self.setupButtons.buttons[1].disable()

        if self.origResonances:
            self.setupButtons.buttons[2].enable()
        else:
            self.setupButtons.buttons[2].disable()

        if self.noesyPeaks and self.origResonances:
            self.midgeButtons.buttons[0].enable()
        else:
            self.midgeButtons.buttons[0].disable()

        if self.distanceConstraintList:
            self.midgeButtons.buttons[1].enable()
            self.distConstrLabel.set(
                'Distance constraints: %d' %
                len(self.distanceConstraintList.constraints))
        else:
            self.distConstrLabel.set('Distance constraints:')
            self.midgeButtons.buttons[1].disable()

        if self.antiDistConstraintList:
            self.antiConstrLabel.set(
                'Anti-distance constraints: %d' %
                len(self.antiDistConstraintList.constraints))
            self.midgeButtons.buttons[2].enable()
        else:
            self.antiConstrLabel.set('Anti-distance constraints:')
            self.midgeButtons.buttons[2].disable()

        if (self.distanceConstraintList and self.antiDistConstraintList
                and (self.numClouds > 0) and self.filePrefix):
            self.mdButtons.buttons[0].enable()
            self.mdButtons.buttons[1].enable()
        else:
            self.mdButtons.buttons[0].disable()
            self.mdButtons.buttons[1].disable()

    def getNoesys(self):

        names = []
        spectra = getSpectraByType(self.project, '2dNOESY')
        for spectrum in spectra:
            for peakList in spectrum.peakLists:
                name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                     peakList.serial)
                names.append(name)
                self.peakListDict[name] = peakList
                if not self.noesyPeakList:
                    self.noesyPeakList = peakList

        return names

    def setNoesy(self, index, name=None):

        if not name:
            name = self.noesyPulldown.getSelected()

        self.noesyPeakList = self.peakListDict[name]
        self.setButtonStates()

    def getTocsys(self):

        names = []
        spectra = getSpectraByType(self.project, '3dTOCSY')
        for spectrum in spectra:
            for peakList in spectrum.peakLists:
                name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                     peakList.serial)
                names.append(name)
                self.peakListDict[name] = peakList
                if not self.tocsyPeakList:
                    self.tocsyPeakList = peakList

        return names

    def getNoesy3ds(self):

        names = []
        spectra = getSpectraByType(self.project, '3dNOESY')
        for spectrum in spectra:
            for peakList in spectrum.peakLists:
                name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                     peakList.serial)
                names.append(name)
                self.peakListDict[name] = peakList
                if not self.noesy3dPeakList:
                    self.noesy3dPeakList = peakList

        return names

    def setTocsy(self, index, name=None):

        if not name:
            name = self.tocsyPulldown.getSelected()

        self.tocsyPeakList = self.peakListDict[name]
        self.setButtonStates()

    def setNoesy3d(self, index, name=None):

        if not name:
            name = self.noesy3dPulldown.getSelected()

        self.noesy3dPeakList = self.peakListDict[name]
        self.setButtonStates()

    def getHsqcs(self):

        names = []
        spectra = getSpectraByType(self.project, 'HSQC')
        for spectrum in spectra:
            for peakList in spectrum.peakLists:
                name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                     peakList.serial)
                names.append(name)
                self.peakListDict[name] = peakList
                if not self.hsqcPeakList:
                    self.hsqcPeakList = peakList

        return names

    def setHsqc(self, index, name=None):

        if not name:
            name = self.hsqcPulldown.getSelected()

        self.hsqcPeakList = self.peakListDict[name]
        self.setButtonStates()

    def getMdInitTemp(self, coolingStep):

        self.mdInitTempEntry.set(coolingStep[1])

    def getMdFinTemp(self, coolingStep):

        self.mdFinTempEntry.set(coolingStep[2])

    def getMdCoolSteps(self, coolingStep):

        self.mdCoolStepsEntry.set(coolingStep[3])

    def getMdSimSteps(self, coolingStep):

        self.mdSimStepsEntry.set(coolingStep[4])

    def getMdTau(self, coolingStep):

        self.mdTauEntry.set(coolingStep[5])

    def getMdRepScale(self, coolingStep):

        self.mdRepScaleEntry.set(coolingStep[6])

    def setMdInitTemp(self, event):

        value = self.mdInitTempEntry.get()
        if value is not None:
            self.coolingStep[1] = value

        self.updateCoolingScheme()

    def setMdFinTemp(self, event):

        value = self.mdFinTempEntry.get()
        if value is not None:
            self.coolingStep[2] = value

        self.updateCoolingScheme()

    def setMdCoolSteps(self, event):

        value = self.mdCoolStepsEntry.get()
        if value is not None:
            self.coolingStep[3] = value

        self.updateCoolingScheme()

    def setMdSimSteps(self, event):

        value = self.mdSimStepsEntry.get()
        if value is not None:
            self.coolingStep[4] = value

        self.updateCoolingScheme()

    def setMdTau(self, event):

        value = self.mdTauEntry.get()
        if value is not None:
            self.coolingStep[5] = value

        self.updateCoolingScheme()

    def setMdRepScale(self, event):

        value = self.mdRepScaleEntry.get()
        if value is not None:
            self.coolingStep[6] = value

        self.updateCoolingScheme()

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

        self.coolingStep = object

    def moveStepEarlier(self):

        if self.coolingStep:
            i = self.coolingStep[0] - 1
            if i > 0:
                coolingStep = self.coolingScheme[i - 1]
                coolingStep[0] = i + 1
                self.coolingStep[0] = i
                self.coolingScheme[i - 1] = self.coolingStep
                self.coolingScheme[i] = coolingStep

                self.updateCoolingScheme()
                self.coolingSchemeMatrix.hilightObject(self.coolingStep)

    def moveStepLater(self):

        if self.coolingStep:
            i = self.coolingStep[0] - 1
            if i < len(self.coolingScheme) - 1:
                coolingStep = self.coolingScheme[i + 1]
                coolingStep[0] = i + 1
                self.coolingStep[0] = i + 2
                self.coolingScheme[i + 1] = self.coolingStep
                self.coolingScheme[i] = coolingStep

                self.updateCoolingScheme()
                self.coolingSchemeMatrix.hilightObject(self.coolingStep)

    def addCoolingStep(self):

        i = len(self.coolingScheme) + 1
        datum = [i, 3000, 100, 10, 2500, 0.001, 1]

        self.coolingScheme.append(datum)
        self.updateCoolingScheme()

    def removeCoolingStep(self):

        if self.coolingStep:
            coolingScheme = []
            i = 0
            for coolingStep in self.coolingScheme:
                if coolingStep is not self.coolingStep:
                    i += 1
                    coolingStep[0] = i
                    coolingScheme.append(coolingStep)

            self.coolingScheme = coolingScheme
            self.updateCoolingScheme()

    def updateCoolingScheme(self):

        objectList = self.coolingScheme
        textMatrix = self.coolingScheme
        self.coolingSchemeMatrix.update(objectList=objectList,
                                        textMatrix=textMatrix)

    def updateMidgeParams(self):

        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate, self.maxIntens
        ]

        self.midgeParamsMatrix.update(textMatrix=[
            data,
        ])

    def getSpecFreq(self, obj):

        self.specFreqEntry.set(self.specFreq)

    def getMaxIter(self, obj):

        self.maxIterEntry.set(self.maxIter)

    def getMixTime(self, obj):

        self.mixTimeEntry.set(self.mixTime)

    def getCorrTime(self, obj):

        self.corrTimeEntry.set(self.corrTime)

    def getLeakRate(self, obj):

        self.leakRateEntry.set(self.leakRate)

    def getMaxIntens(self, obj):

        self.maxIntensEntry.set(self.maxIntens)

    def setSpecFreq(self, event):

        value = self.specFreqEntry.get()
        if value is not None:
            self.specFreq = value

        self.updateMidgeParams()

    def setMaxIter(self, event):

        value = self.maxIterEntry.get()
        if value is not None:
            self.maxIter = value

        self.updateMidgeParams()

    def setMixTime(self, event):

        value = self.mixTimeEntry.get()
        if value is not None:
            self.mixTime = value

        self.updateMidgeParams()

    def setCorrTime(self, event):

        value = self.corrTimeEntry.get()
        if value is not None:
            self.corrTime = value

        self.updateMidgeParams()

    def setLeakRate(self, event):

        value = self.leakRateEntry.get()
        if value is not None:
            self.leakRate = value

        self.updateMidgeParams()

    def setMaxIntens(self, event):

        value = self.maxIntensEntry.get()
        if value is not None:
            self.maxIntens = value

        self.updateMidgeParams()

    def destroy(self):

        BasePopup.destroy(self)
Example #10
0
    def body(self, guiFrame):

        self.geometry("500x250")

        self.numAliasingEntry = IntEntry(self,
                                         text='',
                                         returnCallback=self.setNumAliasing,
                                         width=4)

        guiFrame.expandGrid(1, 0)

        div = LabelDivider(guiFrame,
                           text='Peak Dimension Positions',
                           grid=(0, 0))
        utilButtons = UtilityButtonList(guiFrame,
                                        doClone=False,
                                        closeCmd=self.close,
                                        helpUrl=self.help_url,
                                        grid=(0, 1))

        tipTexts = [
            'The peak/spectrum dimension number',
            'The kind of isotope measured in the dimension',
            'The position of the peak in this dimension, in units of ppm',
            'The frequency position of the peak in this dimension, in units of Hz',
            'The data point position (in the spectrum matrix) of the peak in this dimension',
            'Sets the number of spectrum sweep withs to add to the peak dimension position to locate it at its real ppm value. Note an aliasing of "1" moves a peak to a lower ppm',
            'The assignment annotation for the peak dimension'
        ]

        headingList = [
            'Dimension', 'Isotope', 'ppm', 'Hz', 'Points', 'Num.\nAliasing',
            'Annotation'
        ]
        editWidgets = [
            None, None, None, None, None, self.numAliasingEntry, None
        ]
        editGetCallbacks = [
            None, None, None, None, None, self.getNumAliasing, None
        ]
        editSetCallbacks = [
            None, None, None, None, None, self.setNumAliasing, None
        ]
        self.scrolledMatrix = ScrolledMatrix(guiFrame,
                                             tipTexts=tipTexts,
                                             editSetCallbacks=editSetCallbacks,
                                             editGetCallbacks=editGetCallbacks,
                                             editWidgets=editWidgets,
                                             initialCols=5,
                                             initialRows=3,
                                             headingList=headingList,
                                             callback=self.selectCell,
                                             grid=(1, 0),
                                             gridSpan=(1, 2))

        for func in ('__init__', 'delete', 'setAnnotation', 'setNumAliasing',
                     'setPosition'):
            self.registerNotify(self.updateAfter, 'ccp.nmr.Nmr.PeakDim', func)

        self.waiting = False
        self.updateAfter(self.peak)
Example #11
0
class EditPeakAliasingPopup(BasePopup):
    """
  **Move Aliased Peaks to Their Underlying Resonance Position**
  
  This popup window is used to move aliased 'ghost' peaks to their real
  underlying resonance locations by adding or subtracting a whole number of
  spectrum widths to the position in one or more peak dimensions. This is used
  when a resonance, that causes a peak, lies outside the normal recorded bounds
  of the spectrum but the peak nonetheless still appears within the spectrum, as
  an aliased signal that re-appears as if wrapped back onto the opposite side of
  the spectrum.

  The minimum and maximum aliased frequency values for a spectrum dimension, as
  edited in the "Referencing" table of the main Spectra_ popup, may be set
  extend the contour display beyond the normal sweep width (ppm range) of the
  spectrum and thus cover the real ppm position of peaks that have been
  unaliased. In such instances the contours are extended by tiling; one or more
  copies of the contours (not mirror image) are made and placed sequentially
  next to the normal, fundamental region. If a peak is unaliased to a position
  outside the displayed spectrum limits then the contour display will naturally
  be extended to cover the new peak position; all peaks will be visible within
  the spectrum by default. However, the user may at any time reset the minimum
  and maximum aliased frequency for a spectrum display (see the Spectra_ popup);
  deleting all values will reset bounds to the original sweep with, but any
  values may be chosen, within reason.

  A peak can be moved to the unaliased position of its underlying resonances by
  editing the "Num. Aliasing" column of this popup; double-clicking and typing in
  the appropriate number. When this number is changed for a peak dimension the peak
  will be instantly moved to its new location. An aliasing value of zero means that
  the peak lies within the sweep width of the spectrum. For a ppm scale having a
  positive aliasing value will *reduce* the ppm value, placing the peak a number of
  spectrum widths above or to the right of the spectrum bounds. Likewise a negative
  aliasing value will place a peak at a higher ppm value; below or to the left.
  Often aliasing values will be 1 or -1, where a peak has just fallen off the edge
  of a spectrum. For example a glycine amide nitrogen really at 100 ppm may be just
  outside the top of a 15N HSQC and be wrapped back into the bottom to appear as a
  peak at around 135 ppm, which means that the aliasing value should be set to 1,
  moving the peaks position up by a sweep with of 35 ppm, from 135 ppm to 100 ppm.
  The sign of the aliasing number may seem to be backwards, but it is perhaps the
  ppm scale that is 'backwards'. More complex aliasing is often seen in 3D 13C
  spectra where the 13C axis can be folded (wrapped) to reduce the sweep width that
  needs to be recorded, but still avoiding peak overlap because of the way shifts
  correlate. For example a 13C HSQC NOESY may be recorded with a sweep with that
  covers the CA, CB range 25-75 ppm but aliased methyl carbons below 25 ppm and
  aromatic carbons between 110 ppm and 140 ppm will be present; the methyls will
  have aliasing values of 1, and the aromatics -1 or -2.

  It should be noted that picking peaks in the tiled copies of a contour display,
  i.e. outside the sweep width, will automatically set the aliasing value for the
  peak to reflect the displayed chemical shift value. Thus, the user does not need
  to explicitly unalias the peak position. Any peaks that are moved by virtue of
  being unaliased will have their contribution to the chemical shifts, of any
  assigned resonances, adjusted automatically. Chemical shift values are always
  calculated using the underlying resonance positions, not the apparent peak
  position. Also, if it is known that many peaks share the same aliasing values,
  i.e. are in the same sweep width tile, then the user can propagate the aliasing
  value from one peak to many others in a single step via the right-click window
  menu; "Peak::Unaliasing propagate".

  .. _Spectra: EditSpectrumPopup.html
  
  """
    def __init__(self, parent, peak=None, *args, **kw):

        self.peak = peak
        self.peakDim = None
        self.guiParent = parent

        BasePopup.__init__(self,
                           parent=parent,
                           title="Edit Peak Aliasing",
                           **kw)

    def body(self, guiFrame):

        self.geometry("500x250")

        self.numAliasingEntry = IntEntry(self,
                                         text='',
                                         returnCallback=self.setNumAliasing,
                                         width=4)

        guiFrame.expandGrid(1, 0)

        div = LabelDivider(guiFrame,
                           text='Peak Dimension Positions',
                           grid=(0, 0))
        utilButtons = UtilityButtonList(guiFrame,
                                        doClone=False,
                                        closeCmd=self.close,
                                        helpUrl=self.help_url,
                                        grid=(0, 1))

        tipTexts = [
            'The peak/spectrum dimension number',
            'The kind of isotope measured in the dimension',
            'The position of the peak in this dimension, in units of ppm',
            'The frequency position of the peak in this dimension, in units of Hz',
            'The data point position (in the spectrum matrix) of the peak in this dimension',
            'Sets the number of spectrum sweep withs to add to the peak dimension position to locate it at its real ppm value. Note an aliasing of "1" moves a peak to a lower ppm',
            'The assignment annotation for the peak dimension'
        ]

        headingList = [
            'Dimension', 'Isotope', 'ppm', 'Hz', 'Points', 'Num.\nAliasing',
            'Annotation'
        ]
        editWidgets = [
            None, None, None, None, None, self.numAliasingEntry, None
        ]
        editGetCallbacks = [
            None, None, None, None, None, self.getNumAliasing, None
        ]
        editSetCallbacks = [
            None, None, None, None, None, self.setNumAliasing, None
        ]
        self.scrolledMatrix = ScrolledMatrix(guiFrame,
                                             tipTexts=tipTexts,
                                             editSetCallbacks=editSetCallbacks,
                                             editGetCallbacks=editGetCallbacks,
                                             editWidgets=editWidgets,
                                             initialCols=5,
                                             initialRows=3,
                                             headingList=headingList,
                                             callback=self.selectCell,
                                             grid=(1, 0),
                                             gridSpan=(1, 2))

        for func in ('__init__', 'delete', 'setAnnotation', 'setNumAliasing',
                     'setPosition'):
            self.registerNotify(self.updateAfter, 'ccp.nmr.Nmr.PeakDim', func)

        self.waiting = False
        self.updateAfter(self.peak)

    def open(self):

        self.updateAfter()
        BasePopup.open(self)

    def setNumAliasing(self, event):

        value = self.numAliasingEntry.get()
        if (value is not None) and self.peakDim:
            setPeakDimNumAliasing(self.peakDim, value)
            self.updateAfter()

    def getNumAliasing(self, peakDim):

        if peakDim:
            self.numAliasingEntry.set(peakDim.numAliasing)

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

        self.peakDim = object

    def updateAfter(self, object=None):

        if object:
            if object.className == 'Peak':
                self.peak = object
            elif object.peak is not self.peak:
                # object is peakDim & function was called by notifier
                # return if not my peak
                return

        if self.waiting:
            return
        else:
            self.waiting = True
            self.after_idle(self.update)

    def update(self):

        objectList = []
        textMatrix = []
        colorMatrix = []
        colors = [None] * 7
        colors[5] = '#B0FFB0'

        if self.peak:
            for peakDim in self.peak.sortedPeakDims():
                dataDimRef = peakDim.dataDimRef
                if dataDimRef:
                    objectList.append(peakDim)
        else:
            textMatrix.append([])

        for peakDim in objectList:
            dataDimRef = peakDim.dataDimRef
            expDimRef = dataDimRef.expDimRef
            position = aliasedPeakDimPosition(peakDim)
            datum = [
                peakDim.dim, '/'.join(expDimRef.isotopeCodes),
                unit_converter[('point', 'ppm')](position, dataDimRef),
                unit_converter[('point', 'Hz')](position, dataDimRef),
                position, peakDim.numAliasing, peakDim.annotation
            ]

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

        self.scrolledMatrix.update(objectList=objectList,
                                   textMatrix=textMatrix,
                                   colorMatrix=colorMatrix)
        self.waiting = False

    def destroy(self):

        for func in ('__init__', 'delete', 'setAnnotation', 'setNumAliasing',
                     'setPosition'):
            self.unregisterNotify(self.updateAfter, 'ccp.nmr.Nmr.PeakDim',
                                  func)

        BasePopup.destroy(self)
Example #12
0
class SpinSystemTypingPopup(BasePopup):
  """
  **Predict Which Types of Residue Spin Systems Represent**
  
  This popup window uses chemical shift information, obtained from the
  resonances of a spin system group, to predict which kind of residue a spin
  system could be. Naturally, the more resonances/shifts there are in a spin
  system the better the prediction will be. Predictions are either made for a
  single spin system in isolation, or for a whole chain; by shuffling the
  residue to spin system mapping to give the optimum arrangement. Prediction for
  individual spin systems, as accessed by [Show Individual Classification], is
  covered in the `Spin System Type Scores`_ popup and will not be discussed
  here.

  .. _`Spin System Type Scores`: ../popups/SpinSystemTypeScoresPopup.html
  
  **Finding the Optimal Arrangement of Residue Types**
  
  This system attempts to find the best match of spin system to residue type by
  performing a Monte Carlo search to arrange each group of chemical shifts
  amongst the residue types found in the chain. The main principle is that the
  chain's residues dictate how many spin systems of a given type may be found,
  such that for example if there is only one Threonine residue then only one
  spin system may be predicted to be of Threonine type. This result comes
  naturally from shuffling the spin systems, with their chemical shifts, amongst
  the residue slots (disregarding sequence position). 

  The prediction is made my selecting the chain and shift list to use, then
  which kinds of isotope to consider, by toggling the relevant buttons, choosing
  various Monte Carlo search options and finally selecting [Run Typing]. The
  prediction may take some time to run, depending upon the number of residues
  and spin systems that are being matched, but gives a graphical output of the
  progress. If the final prediction looks good the "Highest Scoring Mappings"
  display may be closed and [Assign Types] may be used to set the residue types
  for all of the spin systems in the main table that match only a single type
  and have a score above the assignment threshold value. Spin systems that
  already have a type or full residue assignment will not be affected.

  The default Monte Carlo search options ought to be appropriate for a small
  protein (100 residues) with 1H and 13C chemical shift information. Increasing
  the number of search steps may help if the search does not converge; still
  swaps between optimal assignments toward the end of the search. Increasing the
  ensemble size (how many test mappings are optimised at the same time) may help
  if the prediction gets stuck in local minima; different runs predict different
  arrangement, but larger ensembles require more search steps to converge. Where
  a spin system has multiple residue types predicted these are the types that
  come out of the final ensemble for that set of shifts, i.e. at this point the
  ensemble of solutions differ.

  Overall, it should be noted that if a human being cannot readily predict the
  probably types of a spin system from its shifts alone, then this search tool
  cannot be expected to do a good job; it is merely an optimiser to address the
  problem of shuffling spin systems within a chain.

  The scores are currently unnormalised log-odds values and are not especially
  meaningful in the human sense, other than higher is better (closer to zero
  for negative values). This issue will be addressed in the future.
  Spin systems without a unique type prediction will not get a final score.
  """


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

    self.guiParent = parent
    self.chain     = None
    self.waiting   = False
    self.shiftList = None
    self.spinSystem  = None
    self.preserveTypes = 0
    self.progressBar = None
    self.scoresPopup = None
    self.threshold   = -20.0
    
    BasePopup.__init__(self, parent, title="Assignment : Spin System Typing", **kw)

  def body(self, guiFrame):

    guiFrame.grid_columnconfigure(3, weight=1)

    self.progressBar = TypingEnsemblePopup(self,total=100)
    self.progressBar.close()
    
    row = 0
    label = Label(guiFrame, text=' Chain: ', grid=(row,0))
    tipText = 'Selects which molecular chain the spin system residue types will be predicted for; determines which range of types are available'
    self.chainPulldown = PulldownList(guiFrame, self.changeChain,
                                      grid=(row,1), tipText=tipText)

    tipText = 'Selects which shift list will be used as the source of chemical shift information to make the residue type predictions'
    label = Label(guiFrame, text='Shift List: ', grid=(row,2))
    self.shiftListPulldown = PulldownList(guiFrame, callback=self.setShiftList,
                                          grid=(row,3), tipText=tipText)

    utilButtons = UtilityButtonList(guiFrame, helpUrl=self.help_url)
    utilButtons.grid(row=row, column=4, sticky='w')

    row += 1
    frame = LabelFrame(guiFrame, text='Options', grid=(row,0), gridSpan=(1,5))
    frame.grid_columnconfigure(3, weight=1)

    frow = 0
    label = Label(frame, text='Keep existing types?',
                  grid=(frow,0), sticky='e')
    tipText = 'Whether any existing residue type information should be preserved, when predicting the type of others'
    self.preserveTypesSelect = CheckButton(frame, grid=(frow,1), selected=False, 
                                           callback=self.selectPreserveTypes,
                                           tipText=tipText)
  

    label = Label(frame, text='Assignment threshold: ',
                  grid=(frow,2), sticky='e')
    tipText = 'The lower limit for the predicted residue type to be set with "Assign Types"; needs to be adjusted according to result statistics and amount of shift data'
    self.thresholdEntry = FloatEntry(frame, text=self.threshold,
                                     width=8, grid=(frow,3), tipText=tipText)

    frow += 1
    label = Label(frame, text='Ensemble size: ', grid=(frow,0), sticky='e')
    tipText = 'The number of best scoring residue type mappings, from the Monte Carlo search, to use un the prediction'
    self.ensembleEntry = IntEntry(frame,text=20,width=4,
                                  grid=(frow,1), tipText=tipText)

    label = Label(frame, text='Num Search Steps: ', grid=(frow,2), sticky='e')
    tipText = 'The number of iterative steps that will be used in the Monte Carlo search of best spin system to residue type mappings'
    self.stepsEntry = IntEntry(frame, text=100000, width=8,
                               tipText=tipText, grid=(frow,3))

    frow += 1
    label = Label(frame, text='Isotope shifts to consider:',
                  grid=(frow,0), gridSpan=(1,4))
    
    frow += 1
    self.isotopes = ['1H','13C']
    isos   = ['1H','13C','15N']
    colors = [COLOR_DICT[x] for x in isos] 
    tipText = 'Selects which kinds of resonances, in terms of isotope, the residue type predictions will be made with'
    self.isotopeCheckButtons = PartitionedSelector(frame, labels=isos,
                                                   objects=isos, colors=colors,
                                                   callback=self.toggleIsotope,
                                                   selected=self.isotopes,
                                                   grid=(frow,0),
                                                   gridSpan=(1,4), tipText=tipText)
        
    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    labelFrame = LabelFrame(guiFrame, text='Spin Systems', grid=(row,0), gridSpan=(1,5))
    labelFrame.expandGrid(0,0)
    
    tipTexts = ['The spin system serial number',
                'The residue to which the spin system may currently be assigned',
                'Set whether to include a particular spin system in the type predictions',
                'The spin system to residue type match score for a prediction; higher (less negative) is better',
                'The predicted types of residue that the spin system may be',
                'The chemical shifts in the spin system that will be used in the analysis']
    headingList = ['#','Residue','Use?','Score','Types','Shifts']
    justifyList = ['center','center','center','center','center','left']
    editWidgets      = [None, None, None, None, None, None]
    editGetCallbacks = [None, None, self.toggleInclude, None, None, None]
    editSetCallbacks = [None, None, None, None, None, None]
    self.scrolledMatrix = ScrolledMatrix(labelFrame, headingList=headingList,
                                         justifyList=justifyList,
 					 editSetCallbacks=editSetCallbacks,
                                         editWidgets=editWidgets,
 					 editGetCallbacks=editGetCallbacks,
                                         callback=self.selectCell,
                                         grid=(0,0), tipTexts=tipTexts)

    row += 1
    tipTexts = ['Execute the Monte Carlo search that will make the residue type predictions for the spin systems',
                'Assign the residue type of spin systems with a unique type prediction and prediction score above the stated threshold',
                'Show a residue type prediction for the selected spin system alone; only considers that spin system of shifts, not how all spin systems fit to the sequence',
                'Show a table of peaks that are assigned to the resonances of the selected spin system']
    texts    = ['Run\nTyping','Assign\nTypes',
                'Show Individual\nClassification',
                'Show\nPeaks']
    commands = [self.run, self.assign,
                self.individualScore,
                self.showPeaks]
    bottomButtons = ButtonList(guiFrame, texts=texts, commands=commands,
                               grid=(row,0), gridSpan=(1,5), tipTexts=tipTexts)
    
    self.runButton    = bottomButtons.buttons[0]
    self.assignButton = bottomButtons.buttons[1]
    self.scoreButton  = bottomButtons.buttons[2]
    self.peaksButton  = bottomButtons.buttons[2]
    self.runButton.config(bg='#B0FFB0')
    
    for func in ('__init__','delete'):
      self.registerNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)
      self.registerNotify(self.updateShiftLists, 'ccp.nmr.Nmr.ShiftList', func)
      
    for func in ('__init__','delete','setCcpCode',
                 'setResidue','addResonance', 'setName',
                 'removeResonance','setResonances'):
       self.registerNotify(self.updateSpinSystemsAfter, 'ccp.nmr.Nmr.ResonanceGroup', func)

    self.updateChains()
    self.updateShiftLists()
    self.updateSpinSystems()

  def individualScore(self):
  
    if self.scoresPopup:
      self.scoresPopup.open()
      self.scoresPopup.update(self.spinSystem, self.chain)
    
    else:
      self.scoresPopup = SpinSystemTypeScoresPopup(self.guiParent, spinSystem=self.spinSystem, chain=self.chain)

  def showPeaks(self):
  
    if self.spinSystem:
      peaks = []
      for resonance in self.spinSystem.resonances:
        for contrib in resonance.peakDimContribs:
          peaks.append(contrib.peakDim.peak)

      if len(peaks) > 0:
        self.guiParent.viewPeaks(peaks)
 

  def assign(self):

    for spinSystem in self.scrolledMatrix.objectList:
      if spinSystem.sstSelected == 'Yes':
	if (len(spinSystem.sstTypes) == 1) and (spinSystem.ssScore > self.threshold):
          ccpCode = spinSystem.sstTypes[0]
          
          if spinSystem.residue and (spinSystem.residue.ccpCode != ccpCode):
            assignSpinSystemResidue(spinSystem,residue=None)
          
          if spinSystem.ccpCode != ccpCode:
            assignSpinSystemType(spinSystem,ccpCode,'protein')
         
    self.updateSpinSystems()


  def toggleIsotope(self, isotope):
  
    if isotope in self.isotopes:
      self.isotopes.remove(isotope)
      
    else:
      self.isotopes.append(isotope)
    
    self.updateSpinSystemsAfter()

  def selectPreserveTypes(self, boolean):
  
    self.preserveTypes = boolean

  def toggleInclude(self, *obj):
  
    if self.spinSystem:
      if self.spinSystem.sstSelected == 'Yes':
        self.spinSystem.sstSelected = 'No'
      else:
        self.spinSystem.sstSelected = 'Yes'	
    
      self.updateSpinSystemsAfter()

  def selectCell(self, spinSystem, row, col):
  
    self.spinSystem = spinSystem
    self.updateButtons()


  def updateShiftLists(self, *opt):
   
    shiftLists = getShiftLists(self.nmrProject)
    names = ['Shift List %d' % x.serial for x in shiftLists]
    index = 0
    
    if shiftLists:
      if self.shiftList not in shiftLists:
        self.shiftList = shiftLists[0]
        
      index = shiftLists.index(self.shiftList)	
    
    self.shiftListPulldown.setup(names, shiftLists, index)
  
  def setShiftList(self, shiftList):
  
    self.shiftList = shiftList
    self.updateSpinSystemsAfter()

  def updateButtons(self):
  
    if self.chain and self.scrolledMatrix.objectList:
      self.runButton.enable()
      self.assignButton.enable()
  
    else:
      self.runButton.enable()
      self.assignButton.enable()
      
    if self.spinSystem:
      self.scoreButton.enable()
      self.peaksButton.enable()

    else:
      self.scoreButton.disable()
      self.peaksButton.disable()


  def updateSpinSystemsAfter(self, spinSystem=None):

    if spinSystem:
      spinSystem.sstTypes      = []
      spinSystem.ssScore       = None
      spinSystem.codeScoreDict = {}

    if self.waiting:
      return
      
    else:
      self.waiting = True
      self.after_idle(self.updateSpinSystems)

  def updateSpinSystems(self):

    textMatrix = []
    objectList = []
    if self.project:
      for spinSystem in self.nmrProject.resonanceGroups:
        if not spinSystem.resonances:
          continue
      
        if self.chain:
          if spinSystem.residue and (spinSystem.residue.chain is not self.chain):
            continue
        
          if spinSystem.chains and (self.chain not in spinSystem.chains):
            continue
        
	if hasattr(spinSystem, 'sstSelected'):
	  includeText = spinSystem.sstSelected
      
        else:
	  spinSystem.sstSelected = 'Yes'
	  includeText = 'Yes'

	if not hasattr(spinSystem, 'sstTypes'):
	  spinSystem.sstTypes = []

	if not hasattr(spinSystem, 'ssScore'):
	  spinSystem.ssScore = None
      
        if spinSystem.ssScore:
          scoreText = '%.2f' % spinSystem.ssScore
        else:
          scoreText = None
      
        typesText = ' '.join(spinSystem.sstTypes)
      
        residueText = ''
	
	if spinSystem.residue:
          resCode = getResidueCode(spinSystem.residue)
	  residueText = '%d%s' % (spinSystem.residue.seqCode,resCode)
	
        elif spinSystem.residueProbs:
          resTexts = []
          resSeqs = []
          resCodes = set()
 
          for residueProb in spinSystem.residueProbs:
            if not residueProb.weight:
              continue
 
            residue = residueProb.possibility
            seq = residue.seqCode
            resCode = getResidueCode(residue)
            resText = '%d?%s' % (seq, resCode)

            resTexts.append(resText)
            resSeqs.append('%d?' % seq)
            resCodes.add(resCode)
 
          if len(resCodes) == 1:
            residueText = '/'.join(resSeqs) + resCodes.pop()
          else:
            residueText = '/'.join(resTexts)
          
	elif spinSystem.ccpCode:
	  getResidueCode(spinSystem) 
	
	shifts = []
	if self.shiftList:
	  for resonance in spinSystem.resonances:
            if resonance.isotopeCode in self.isotopes:
	      shift = resonance.findFirstShift(parentList = self.shiftList)
              if shift:
	        shifts.append('%.2f' % shift.value)
	    
	shifts.sort()
	
	shiftsText = ' '.join(shifts)
	
	data = []
	data.append(spinSystem.serial)
	data.append(residueText)
	data.append(includeText)
	data.append(scoreText)
	data.append(typesText)
	data.append(shiftsText)
	
	objectList.append(spinSystem)
        textMatrix.append(data)
        

    self.scrolledMatrix.update(textMatrix=textMatrix, objectList=objectList)
    self.updateButtons()
    self.waiting = False

  def getChains(self):
  
    chains = []
    if self.project:
      for molSystem in self.project.sortedMolSystems():
        for chain in molSystem.sortedChains():
          if chain.molecule.molType in ('protein',None):
            # None moltype may be mixed, including protein component
	    text = '%s:%s' % (molSystem.code, chain.code)
            chains.append( [text, chain] )
	
    return chains


  def changeChain(self, chain):
    
    self.chain = chain
    self.updateSpinSystemsAfter()
    
  def updateChains(self, *chain):
  
    data = self.getChains()
    names = [x[0] for x in  data]
    chains = [x[1] for x in data]
    index = 0
 
    if chains:
      if self.chain not in chains:
       if self.spinSystem:
         if self.spinSystem.residue:
           self.chain = self.spinSystem.residue.chain
         
       else:
         self.chain = chains[0]
      
      index = chains.index(self.chain)
    
    self.chainPulldown.setup(names, chains, index)

    self.updateButtons()
  
  def run(self):
    
    spinSystems = []
    for spinSystem in self.scrolledMatrix.objectList:
      if spinSystem.sstSelected == 'Yes':
        spinSystems.append(spinSystem)
    
    if self.chain and spinSystems:
      if self.progressBar:
        self.progressBar.destroy()
      self.progressBar = TypingEnsemblePopup(self,total=100)
      residues = self.chain.sortedResidues()
      numBest  = self.ensembleEntry.get() or 20
      numSteps = max(100, self.stepsEntry.get() or 100000)
      graph    = self.progressBar.graph
      typeScores, cc0 = getSpinSystemTypes(residues, spinSystems, self.preserveTypes, isotopes=self.isotopes,
                                           shiftList=self.shiftList, numSteps=numSteps, numBest=numBest,
                                           graph=graph, progressBar=self.progressBar)
      threshold = self.thresholdEntry.get()
      
      for ss in typeScores.keys():
        ss.sstTypes = []
        ss.ssScore  = None
        for ccpCode in typeScores[ss].keys():
	  if ccpCode and typeScores[ss][ccpCode] > threshold:
	    if ccpCode not in ss.sstTypes:
	      ss.sstTypes.append(ccpCode)
	
        if len(ss.sstTypes) == 1:
          ss.ssScore = typeScores[ss][ss.sstTypes[0]]
        
      self.updateSpinSystemsAfter()

  def destroy(self):

    for func in ('__init__','delete'):
      self.unregisterNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)
      self.unregisterNotify(self.updateShiftLists, 'ccp.nmr.Nmr.ShiftList', func)
      
    for func in ('__init__','delete','setCcpCode',
                 'setResidue','setName','addResonance',
                 'removeResonance','setResonances'):
       self.unregisterNotify(self.updateSpinSystemsAfter, 'ccp.nmr.Nmr.ResonanceGroup', func)

    if self.scoresPopup:
      self.scoresPopup.destroy()

    BasePopup.destroy(self)
Example #13
0
  def body(self, guiFrame):

    guiFrame.grid_columnconfigure(3, weight=1)

    self.progressBar = TypingEnsemblePopup(self,total=100)
    self.progressBar.close()
    
    row = 0
    label = Label(guiFrame, text=' Chain: ', grid=(row,0))
    tipText = 'Selects which molecular chain the spin system residue types will be predicted for; determines which range of types are available'
    self.chainPulldown = PulldownList(guiFrame, self.changeChain,
                                      grid=(row,1), tipText=tipText)

    tipText = 'Selects which shift list will be used as the source of chemical shift information to make the residue type predictions'
    label = Label(guiFrame, text='Shift List: ', grid=(row,2))
    self.shiftListPulldown = PulldownList(guiFrame, callback=self.setShiftList,
                                          grid=(row,3), tipText=tipText)

    utilButtons = UtilityButtonList(guiFrame, helpUrl=self.help_url)
    utilButtons.grid(row=row, column=4, sticky='w')

    row += 1
    frame = LabelFrame(guiFrame, text='Options', grid=(row,0), gridSpan=(1,5))
    frame.grid_columnconfigure(3, weight=1)

    frow = 0
    label = Label(frame, text='Keep existing types?',
                  grid=(frow,0), sticky='e')
    tipText = 'Whether any existing residue type information should be preserved, when predicting the type of others'
    self.preserveTypesSelect = CheckButton(frame, grid=(frow,1), selected=False, 
                                           callback=self.selectPreserveTypes,
                                           tipText=tipText)
  

    label = Label(frame, text='Assignment threshold: ',
                  grid=(frow,2), sticky='e')
    tipText = 'The lower limit for the predicted residue type to be set with "Assign Types"; needs to be adjusted according to result statistics and amount of shift data'
    self.thresholdEntry = FloatEntry(frame, text=self.threshold,
                                     width=8, grid=(frow,3), tipText=tipText)

    frow += 1
    label = Label(frame, text='Ensemble size: ', grid=(frow,0), sticky='e')
    tipText = 'The number of best scoring residue type mappings, from the Monte Carlo search, to use un the prediction'
    self.ensembleEntry = IntEntry(frame,text=20,width=4,
                                  grid=(frow,1), tipText=tipText)

    label = Label(frame, text='Num Search Steps: ', grid=(frow,2), sticky='e')
    tipText = 'The number of iterative steps that will be used in the Monte Carlo search of best spin system to residue type mappings'
    self.stepsEntry = IntEntry(frame, text=100000, width=8,
                               tipText=tipText, grid=(frow,3))

    frow += 1
    label = Label(frame, text='Isotope shifts to consider:',
                  grid=(frow,0), gridSpan=(1,4))
    
    frow += 1
    self.isotopes = ['1H','13C']
    isos   = ['1H','13C','15N']
    colors = [COLOR_DICT[x] for x in isos] 
    tipText = 'Selects which kinds of resonances, in terms of isotope, the residue type predictions will be made with'
    self.isotopeCheckButtons = PartitionedSelector(frame, labels=isos,
                                                   objects=isos, colors=colors,
                                                   callback=self.toggleIsotope,
                                                   selected=self.isotopes,
                                                   grid=(frow,0),
                                                   gridSpan=(1,4), tipText=tipText)
        
    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    labelFrame = LabelFrame(guiFrame, text='Spin Systems', grid=(row,0), gridSpan=(1,5))
    labelFrame.expandGrid(0,0)
    
    tipTexts = ['The spin system serial number',
                'The residue to which the spin system may currently be assigned',
                'Set whether to include a particular spin system in the type predictions',
                'The spin system to residue type match score for a prediction; higher (less negative) is better',
                'The predicted types of residue that the spin system may be',
                'The chemical shifts in the spin system that will be used in the analysis']
    headingList = ['#','Residue','Use?','Score','Types','Shifts']
    justifyList = ['center','center','center','center','center','left']
    editWidgets      = [None, None, None, None, None, None]
    editGetCallbacks = [None, None, self.toggleInclude, None, None, None]
    editSetCallbacks = [None, None, None, None, None, None]
    self.scrolledMatrix = ScrolledMatrix(labelFrame, headingList=headingList,
                                         justifyList=justifyList,
 					 editSetCallbacks=editSetCallbacks,
                                         editWidgets=editWidgets,
 					 editGetCallbacks=editGetCallbacks,
                                         callback=self.selectCell,
                                         grid=(0,0), tipTexts=tipTexts)

    row += 1
    tipTexts = ['Execute the Monte Carlo search that will make the residue type predictions for the spin systems',
                'Assign the residue type of spin systems with a unique type prediction and prediction score above the stated threshold',
                'Show a residue type prediction for the selected spin system alone; only considers that spin system of shifts, not how all spin systems fit to the sequence',
                'Show a table of peaks that are assigned to the resonances of the selected spin system']
    texts    = ['Run\nTyping','Assign\nTypes',
                'Show Individual\nClassification',
                'Show\nPeaks']
    commands = [self.run, self.assign,
                self.individualScore,
                self.showPeaks]
    bottomButtons = ButtonList(guiFrame, texts=texts, commands=commands,
                               grid=(row,0), gridSpan=(1,5), tipTexts=tipTexts)
    
    self.runButton    = bottomButtons.buttons[0]
    self.assignButton = bottomButtons.buttons[1]
    self.scoreButton  = bottomButtons.buttons[2]
    self.peaksButton  = bottomButtons.buttons[2]
    self.runButton.config(bg='#B0FFB0')
    
    for func in ('__init__','delete'):
      self.registerNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)
      self.registerNotify(self.updateShiftLists, 'ccp.nmr.Nmr.ShiftList', func)
      
    for func in ('__init__','delete','setCcpCode',
                 'setResidue','addResonance', 'setName',
                 'removeResonance','setResonances'):
       self.registerNotify(self.updateSpinSystemsAfter, 'ccp.nmr.Nmr.ResonanceGroup', func)

    self.updateChains()
    self.updateShiftLists()
    self.updateSpinSystems()
Example #14
0
    def body(self, guiFrame):

        self.specFreqEntry = IntEntry(self,
                                      text=self.specFreq,
                                      width=8,
                                      returnCallback=self.setSpecFreq)
        self.maxIterEntry = IntEntry(self,
                                     text=self.maxIter,
                                     width=8,
                                     returnCallback=self.setMaxIter)
        self.mixTimeEntry = FloatEntry(self,
                                       text=self.mixTime,
                                       width=8,
                                       returnCallback=self.setMixTime)
        self.corrTimeEntry = FloatEntry(self,
                                        text=self.corrTime,
                                        width=8,
                                        returnCallback=self.setCorrTime)
        self.leakRateEntry = FloatEntry(self,
                                        text=self.leakRate,
                                        width=8,
                                        returnCallback=self.setLeakRate)

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

        row = 0
        labelFrame0 = LabelFrame(guiFrame, text='Input data')
        labelFrame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame0.grid_columnconfigure(3, weight=1)

        label = Label(labelFrame0, text='Assigned NOESY spectrum')
        label.grid(row=0, column=0, sticky=Tkinter.NW)
        self.noesyPulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.noesyPulldown.grid(row=0, column=1, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='H/D ratio: ')
        label.grid(row=0, column=2, sticky=Tkinter.NW)
        self.ratioHDEntry = FloatEntry(labelFrame0, text=self.ratioHD, width=6)
        self.ratioHDEntry.grid(row=0, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 1:')
        label.grid(row=1, column=0, sticky=Tkinter.NW)
        self.tmix1Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy1,
                                          selected_index=-0,
                                          do_initial_callback=0)
        self.tmix1Pulldown.grid(row=1, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=1, column=2, sticky=Tkinter.NW)
        self.tmix1Entry = FloatEntry(labelFrame0, text=60, width=6)
        self.tmix1Entry.grid(row=1, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 2:')
        label.grid(row=2, column=0, sticky=Tkinter.NW)
        self.tmix2Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy2,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tmix2Pulldown.grid(row=2, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=2, column=2, sticky=Tkinter.NW)
        self.tmix2Entry = FloatEntry(labelFrame0, text=120, width=6)
        self.tmix2Entry.grid(row=2, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 3:')
        label.grid(row=3, column=0, sticky=Tkinter.NW)
        self.tmix3Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy3,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tmix3Pulldown.grid(row=3, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=3, column=2, sticky=Tkinter.NW)
        self.tmix3Entry = FloatEntry(labelFrame0, text=200, width=6)
        self.tmix3Entry.grid(row=3, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='3D NOESY:')
        label.grid(row=4, column=0, sticky=Tkinter.NW)
        self.noesy3dPulldown = PulldownMenu(labelFrame0,
                                            entries=self.getNoesys3d(),
                                            callback=self.setNoesy3d,
                                            selected_index=0,
                                            do_initial_callback=0)
        self.noesy3dPulldown.grid(row=4, column=1, sticky=Tkinter.NW)

        label10 = Label(labelFrame0, text='Num peaks:')
        label10.grid(row=5, column=0, sticky=Tkinter.NW)
        self.numPeaksLabel = Label(labelFrame0, text='0')
        self.numPeaksLabel.grid(row=5, column=1, sticky=Tkinter.NW)

        label11 = Label(labelFrame0, text='Num resonances:')
        label11.grid(row=5, column=2, sticky=Tkinter.NW)
        self.numResonancesLabel = Label(labelFrame0, text='0')
        self.numResonancesLabel.grid(row=5, column=3, sticky=Tkinter.NW)

        row += 1
        labelFrame1 = LabelFrame(guiFrame, text='Parameters')
        labelFrame1.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame1.grid_columnconfigure(3, weight=1)

        label = Label(labelFrame1, text='15N labelled sample:')
        label.grid(row=0, column=0, sticky=Tkinter.NW)
        self.nitrogenSelect = CheckButton(labelFrame1,
                                          callback=self.setNitrogenLabel)
        self.nitrogenSelect.grid(row=0, column=1, sticky=Tkinter.W)
        self.nitrogenSelect.set(1)

        label = Label(labelFrame1, text='13C labelled sample:')
        label.grid(row=0, column=2, sticky=Tkinter.NW)
        self.carbonSelect = CheckButton(labelFrame1,
                                        callback=self.setCarbonLabel)
        self.carbonSelect.grid(row=0, column=3, sticky=Tkinter.W)
        self.carbonSelect.set(0)

        labelFrame1.grid_rowconfigure(1, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate
        ]
        colHeadings = [
            'Spectrometer\nfrequency', 'Max\niterations', 'Mixing\ntime (ms)',
            'Correl.\ntime (ns)', 'Leak\nrate'
        ]
        editWidgets = [
            self.specFreqEntry,
            self.maxIterEntry,
            self.mixTimeEntry,
            self.corrTimeEntry,
            self.leakRateEntry,
        ]
        editGetCallbacks = [
            self.getSpecFreq,
            self.getMaxIter,
            self.getMixTime,
            self.getCorrTime,
            self.getLeakRate,
        ]
        editSetCallbacks = [
            self.setSpecFreq,
            self.setMaxIter,
            self.setMixTime,
            self.setCorrTime,
            self.setLeakRate,
        ]
        self.midgeParamsMatrix = ScrolledMatrix(
            labelFrame1,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=1,
            initialCols=5,
            headingList=colHeadings,
            callback=None,
            objectList=[
                'None',
            ],
            textMatrix=[
                data,
            ])
        self.midgeParamsMatrix.grid(row=1,
                                    column=0,
                                    columnspan=4,
                                    sticky=Tkinter.NSEW)

        label10 = Label(labelFrame1, text='Benchmark structure')
        label10.grid(row=2, column=0, sticky=Tkinter.NW)
        self.structurePulldown = PulldownMenu(labelFrame1,
                                              entries=self.getStructures(),
                                              callback=self.setStructure,
                                              selected_index=0,
                                              do_initial_callback=0)
        self.structurePulldown.grid(row=2, column=1, sticky=Tkinter.NW)

        label11 = Label(labelFrame1, text='ADC atom types:')
        label11.grid(row=2, column=2, sticky=Tkinter.NW)
        self.adcAtomsPulldown = PulldownMenu(labelFrame1,
                                             entries=self.getAdcAtomTypes(),
                                             callback=self.setAdcAtomTypes,
                                             selected_index=0,
                                             do_initial_callback=0)
        self.adcAtomsPulldown.grid(row=2, column=3, sticky=Tkinter.NW)

        row += 1
        labelFrame2 = LabelFrame(guiFrame, text='Output')
        labelFrame2.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame2.grid_columnconfigure(3, weight=1)

        label20 = Label(labelFrame2, text='Distance constraints:')
        label20.grid(row=0, column=0, sticky=Tkinter.NW)
        self.distConstrLabel = Label(labelFrame2, text='0')
        self.distConstrLabel.grid(row=0, column=1, sticky=Tkinter.NW)

        label21 = Label(labelFrame2, text='Anti-distance constraints:')
        label21.grid(row=0, column=2, sticky=Tkinter.NW)
        self.antiConstrLabel = Label(labelFrame2, text='0')
        self.antiConstrLabel.grid(row=0, column=3, sticky=Tkinter.NW)

        texts = [
            'Calculate distances', 'Show distance\nconstraints',
            'Show anti-distance\nconstraints'
        ]
        commands = [
            self.calculateDistances, self.showConstraints,
            self.showAntiConstraints
        ]
        self.midgeButtons = ButtonList(labelFrame2,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.midgeButtons.grid(row=1,
                               column=0,
                               columnspan=4,
                               sticky=Tkinter.NSEW)

        row += 1
        self.bottomButtons = createDismissHelpButtonList(guiFrame,
                                                         expands=0,
                                                         help_url=None)
        self.bottomButtons.grid(row=row,
                                column=0,
                                columnspan=4,
                                sticky=Tkinter.EW)

        self.getPeaks()
        self.getResonances()
        self.update()

        self.geometry('600x400')
Example #15
0
class MidgePopup(BasePopup):
    def __init__(self, parent, *args, **kw):

        self.guiParent = parent
        self.project = parent.getProject()
        self.waiting = 0
        self.specFreq = 800.13
        self.maxIter = 15
        self.mixTime = 60
        self.corrTime = 11.5
        self.leakRate = 2.0
        self.ratioHD = 0.9
        self.peakListDict = {}
        self.peakListDict3d = {}
        self.noesyPeakList = None
        self.noesy3dPeakList = None
        self.carbonLabel = 0
        self.nitrogenLabel = 1
        self.noesyPeakList1 = None
        self.noesyPeakList2 = None
        self.noesyPeakList3 = None
        self.noesyPeakList3d = None

        self.resonances = None
        self.noesyPeaks = None
        self.distanceConstraintList = None
        self.antiDistConstraintList = None
        self.adcAtomTypes = None
        self.structure = None

        BasePopup.__init__(self,
                           parent,
                           title="Relaxation Matrix Optimisation",
                           **kw)

    def body(self, guiFrame):

        self.specFreqEntry = IntEntry(self,
                                      text=self.specFreq,
                                      width=8,
                                      returnCallback=self.setSpecFreq)
        self.maxIterEntry = IntEntry(self,
                                     text=self.maxIter,
                                     width=8,
                                     returnCallback=self.setMaxIter)
        self.mixTimeEntry = FloatEntry(self,
                                       text=self.mixTime,
                                       width=8,
                                       returnCallback=self.setMixTime)
        self.corrTimeEntry = FloatEntry(self,
                                        text=self.corrTime,
                                        width=8,
                                        returnCallback=self.setCorrTime)
        self.leakRateEntry = FloatEntry(self,
                                        text=self.leakRate,
                                        width=8,
                                        returnCallback=self.setLeakRate)

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

        row = 0
        labelFrame0 = LabelFrame(guiFrame, text='Input data')
        labelFrame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame0.grid_columnconfigure(3, weight=1)

        label = Label(labelFrame0, text='Assigned NOESY spectrum')
        label.grid(row=0, column=0, sticky=Tkinter.NW)
        self.noesyPulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.noesyPulldown.grid(row=0, column=1, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='H/D ratio: ')
        label.grid(row=0, column=2, sticky=Tkinter.NW)
        self.ratioHDEntry = FloatEntry(labelFrame0, text=self.ratioHD, width=6)
        self.ratioHDEntry.grid(row=0, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 1:')
        label.grid(row=1, column=0, sticky=Tkinter.NW)
        self.tmix1Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy1,
                                          selected_index=-0,
                                          do_initial_callback=0)
        self.tmix1Pulldown.grid(row=1, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=1, column=2, sticky=Tkinter.NW)
        self.tmix1Entry = FloatEntry(labelFrame0, text=60, width=6)
        self.tmix1Entry.grid(row=1, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 2:')
        label.grid(row=2, column=0, sticky=Tkinter.NW)
        self.tmix2Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy2,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tmix2Pulldown.grid(row=2, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=2, column=2, sticky=Tkinter.NW)
        self.tmix2Entry = FloatEntry(labelFrame0, text=120, width=6)
        self.tmix2Entry.grid(row=2, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='NOESY spectrum 3:')
        label.grid(row=3, column=0, sticky=Tkinter.NW)
        self.tmix3Pulldown = PulldownMenu(labelFrame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy3,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tmix3Pulldown.grid(row=3, column=1, sticky=Tkinter.NW)
        label = Label(labelFrame0, text='Tmix (ms): ')
        label.grid(row=3, column=2, sticky=Tkinter.NW)
        self.tmix3Entry = FloatEntry(labelFrame0, text=200, width=6)
        self.tmix3Entry.grid(row=3, column=3, sticky=Tkinter.NW)

        label = Label(labelFrame0, text='3D NOESY:')
        label.grid(row=4, column=0, sticky=Tkinter.NW)
        self.noesy3dPulldown = PulldownMenu(labelFrame0,
                                            entries=self.getNoesys3d(),
                                            callback=self.setNoesy3d,
                                            selected_index=0,
                                            do_initial_callback=0)
        self.noesy3dPulldown.grid(row=4, column=1, sticky=Tkinter.NW)

        label10 = Label(labelFrame0, text='Num peaks:')
        label10.grid(row=5, column=0, sticky=Tkinter.NW)
        self.numPeaksLabel = Label(labelFrame0, text='0')
        self.numPeaksLabel.grid(row=5, column=1, sticky=Tkinter.NW)

        label11 = Label(labelFrame0, text='Num resonances:')
        label11.grid(row=5, column=2, sticky=Tkinter.NW)
        self.numResonancesLabel = Label(labelFrame0, text='0')
        self.numResonancesLabel.grid(row=5, column=3, sticky=Tkinter.NW)

        row += 1
        labelFrame1 = LabelFrame(guiFrame, text='Parameters')
        labelFrame1.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame1.grid_columnconfigure(3, weight=1)

        label = Label(labelFrame1, text='15N labelled sample:')
        label.grid(row=0, column=0, sticky=Tkinter.NW)
        self.nitrogenSelect = CheckButton(labelFrame1,
                                          callback=self.setNitrogenLabel)
        self.nitrogenSelect.grid(row=0, column=1, sticky=Tkinter.W)
        self.nitrogenSelect.set(1)

        label = Label(labelFrame1, text='13C labelled sample:')
        label.grid(row=0, column=2, sticky=Tkinter.NW)
        self.carbonSelect = CheckButton(labelFrame1,
                                        callback=self.setCarbonLabel)
        self.carbonSelect.grid(row=0, column=3, sticky=Tkinter.W)
        self.carbonSelect.set(0)

        labelFrame1.grid_rowconfigure(1, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate
        ]
        colHeadings = [
            'Spectrometer\nfrequency', 'Max\niterations', 'Mixing\ntime (ms)',
            'Correl.\ntime (ns)', 'Leak\nrate'
        ]
        editWidgets = [
            self.specFreqEntry,
            self.maxIterEntry,
            self.mixTimeEntry,
            self.corrTimeEntry,
            self.leakRateEntry,
        ]
        editGetCallbacks = [
            self.getSpecFreq,
            self.getMaxIter,
            self.getMixTime,
            self.getCorrTime,
            self.getLeakRate,
        ]
        editSetCallbacks = [
            self.setSpecFreq,
            self.setMaxIter,
            self.setMixTime,
            self.setCorrTime,
            self.setLeakRate,
        ]
        self.midgeParamsMatrix = ScrolledMatrix(
            labelFrame1,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=1,
            initialCols=5,
            headingList=colHeadings,
            callback=None,
            objectList=[
                'None',
            ],
            textMatrix=[
                data,
            ])
        self.midgeParamsMatrix.grid(row=1,
                                    column=0,
                                    columnspan=4,
                                    sticky=Tkinter.NSEW)

        label10 = Label(labelFrame1, text='Benchmark structure')
        label10.grid(row=2, column=0, sticky=Tkinter.NW)
        self.structurePulldown = PulldownMenu(labelFrame1,
                                              entries=self.getStructures(),
                                              callback=self.setStructure,
                                              selected_index=0,
                                              do_initial_callback=0)
        self.structurePulldown.grid(row=2, column=1, sticky=Tkinter.NW)

        label11 = Label(labelFrame1, text='ADC atom types:')
        label11.grid(row=2, column=2, sticky=Tkinter.NW)
        self.adcAtomsPulldown = PulldownMenu(labelFrame1,
                                             entries=self.getAdcAtomTypes(),
                                             callback=self.setAdcAtomTypes,
                                             selected_index=0,
                                             do_initial_callback=0)
        self.adcAtomsPulldown.grid(row=2, column=3, sticky=Tkinter.NW)

        row += 1
        labelFrame2 = LabelFrame(guiFrame, text='Output')
        labelFrame2.grid(row=row, column=0, sticky=Tkinter.NSEW)
        labelFrame2.grid_columnconfigure(3, weight=1)

        label20 = Label(labelFrame2, text='Distance constraints:')
        label20.grid(row=0, column=0, sticky=Tkinter.NW)
        self.distConstrLabel = Label(labelFrame2, text='0')
        self.distConstrLabel.grid(row=0, column=1, sticky=Tkinter.NW)

        label21 = Label(labelFrame2, text='Anti-distance constraints:')
        label21.grid(row=0, column=2, sticky=Tkinter.NW)
        self.antiConstrLabel = Label(labelFrame2, text='0')
        self.antiConstrLabel.grid(row=0, column=3, sticky=Tkinter.NW)

        texts = [
            'Calculate distances', 'Show distance\nconstraints',
            'Show anti-distance\nconstraints'
        ]
        commands = [
            self.calculateDistances, self.showConstraints,
            self.showAntiConstraints
        ]
        self.midgeButtons = ButtonList(labelFrame2,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.midgeButtons.grid(row=1,
                               column=0,
                               columnspan=4,
                               sticky=Tkinter.NSEW)

        row += 1
        self.bottomButtons = createDismissHelpButtonList(guiFrame,
                                                         expands=0,
                                                         help_url=None)
        self.bottomButtons.grid(row=row,
                                column=0,
                                columnspan=4,
                                sticky=Tkinter.EW)

        self.getPeaks()
        self.getResonances()
        self.update()

        self.geometry('600x400')

    def setCarbonLabel(self, boolean):

        self.carbonLabel = boolean

    def setNitrogenLabel(self, boolean):

        self.nitrogenLabel = boolean

    def update(self):

        if self.resonances and (
            (self.noesyPeaks and self.noesyPeakList1 and self.noesyPeakList2
             and self.noesyPeakList3) or self.noesyPeakList3d):
            self.midgeButtons.buttons[0].enable()
        else:
            self.midgeButtons.buttons[0].disable()

        if self.distanceConstraintList:
            self.distConstrLabel.set(
                str(len(self.distanceConstraintList.constraints)))
            self.midgeButtons.buttons[1].enable()
        else:
            self.distConstrLabel.set('')
            self.midgeButtons.buttons[1].disable()

        if self.antiDistConstraintList:
            self.antiConstrLabel.set(
                str(len(self.antiDistConstraintList.constraints)))
            self.midgeButtons.buttons[2].enable()
        else:
            self.antiConstrLabel.set('')
            self.midgeButtons.buttons[2].disable()

        if self.resonances:
            self.numResonancesLabel.set(str(len(self.resonances)))
        else:
            self.numResonancesLabel.set('')

        if self.noesyPeaks:
            self.numPeaksLabel.set(str(len(self.noesyPeaks)))
        else:
            self.numPeaksLabel.set('')

    def getStructures(self):

        names = [
            '<None>',
        ]
        for molSystem in self.project.sortedMolSystems():
            for structure in molSystem.sortedStructureEnsembles():
                names.append('%s:%d' % (molSystem.name, structure.ensembleId))

        return names

    def setStructure(self, index, name=None):

        if index < 1:
            self.structure = None
        else:
            structures = []
            for molSystem in self.project.molSystems:
                for structure in molSystem.structureEnsembles:
                    structures.append(structure)

            self.structure = structures[index - 1]

    def getAdcAtomTypes(self):

        return ['<None>', 'HN', 'HN HA', 'HN HA HB']

    def setAdcAtomTypes(self, index, name=None):

        if name is None:
            name = self.adcAtomsPulldown.getSelected()

        if name == '<None>':
            name = None

        self.adcAtomTypes = name

    def getResonances(self):

        resonanceDict = {}
        if self.noesyPeaks:
            for peak in self.noesyPeaks:
                for peakDim in peak.peakDims:
                    for contrib in peakDim.peakDimContribs:
                        resonanceDict[contrib.resonance] = 1
                        # TBD: Set resonance.name for typing

        self.resonances = resonanceDict.keys()

    def getPeaks(self):

        if self.noesyPeakList:
            self.noesyPeaks = self.noesyPeakList.sortedPeaks()

    def calculateDistances(self):

        resonances = list(self.resonances)

        resDict = {}
        for resonance in resonances:
            resDict[resonance.serial] = resonance

        ratioHD = self.ratioHDEntry.get() or self.ratioHD

        tmix1 = self.tmix1Entry.get() or 60
        tmix2 = self.tmix2Entry.get() or 120
        tmix3 = self.tmix3Entry.get() or 200

        data = [(tmix1, self.noesyPeakList1), (tmix2, self.noesyPeakList2),
                (tmix3, self.noesyPeakList3)]
        data.sort()

        mixingTimes = [x[0] for x in data]
        peakLists = [x[1] for x in data]

        # get a clean, symmetric and normalised NOE matrix
        noeMatrix = getNoeMatrixFromPeaks(self.noesyPeaks,
                                          resonances,
                                          peakLists,
                                          mixingTimes,
                                          ratioHD=ratioHD,
                                          analysis=self.guiParent)

        # optimiseRelaxation will remove unconstrained resonances
        self.distanceConstraintList, resonances = optimiseRelaxation(
            resonances,
            noeMatrix,
            self.mixTime,
            self.specFreq,
            self.corrTime,
            self.leakRate,
            self.carbonLabel,
            self.nitrogenLabel,
            maxIter=self.maxIter)

        #constrainSpinSystems(self.distanceConstraintList)
        # for testing calculate distances from structure overrides any resonances: uses assigned ones
        #(self.distanceConstraintList, self.resonances) = self.cheatForTesting()
        #self.antiDistConstraintList = self.distanceConstraintList
        protonNumbs = {'CH3': 3, 'Haro': 2, 'HN': 1, 'H': 1}

        PI = 3.1415926535897931
        GH = 2.6752e4
        HB = 1.05459e-27
        CONST = GH * GH * GH * GH * HB * HB
        tc = 1.0e-9 * self.corrTime
        wh = 2.0 * PI * self.specFreq * 1.0e6
        j0 = CONST * tc
        j1 = CONST * tc / (1.0 + wh * wh * tc * tc)
        j2 = CONST * tc / (1.0 + 4.0 * wh * wh * tc * tc)
        #jself = 6.0*j2 + 3.0*j1 + j0
        jcross = 6.0 * j2 - j0

        if self.distanceConstraintList and self.noesyPeakList:
            constraintHead = self.distanceConstraintList.nmrConstraintStore

            if self.adcAtomTypes:
                adcDict = {
                    'HN': ['H'],
                    'HN HA': ['H', 'HA', 'HA1', 'HA2'],
                    'HN HA HB': ['H', 'HA', 'HA1', 'HA2', 'HB', 'HB2', 'HB3']
                }

                allowedAtomTypes = adcDict[self.adcAtomTypes]

                print "Making ADCs"
                self.antiDistConstraintList = makeNoeAdcs(
                    resonances[:],
                    self.noesyPeakList.dataSource,
                    constraintHead,
                    allowedAtomTypes=allowedAtomTypes)
                print "Done ADCs"

            if self.structure:

                N = len(self.resonances)
                sigmas = [[] for i in range(N)]
                for i in range(N):
                    sigmas[i] = [0.0 for j in range(N)]

                for constraint in self.distanceConstraintList.constraints:
                    item = constraint.findFirstItem()
                    resonances = list(item.resonances)

                    ri = resDict[resonances[0].resonanceSerial]
                    rj = resDict[resonances[1].resonanceSerial]
                    i = self.resonances.index(ri)
                    j = self.resonances.index(rj)
                    atomSets1 = list(ri.resonanceSet.atomSets)
                    atomSets2 = list(rj.resonanceSet.atomSets)
                    if atomSets1 == atomSets2:
                        ass = list(atomSets1)
                        atomSets1 = [
                            ass[0],
                        ]
                        atomSets2 = [
                            ass[-1],
                        ]

                    distance = getAtomSetsDistance(atomSets1, atomSets2,
                                                   self.structure)
                    r = distance * 1e-8
                    nhs = protonNumbs[rj.name]
                    sigma = 0.1 * jcross * nhs / (r**6)
                    sigmas[i][j] = sigma

                    constraint.setOrigData(distance)

        self.update()

    def showConstraints(self):

        if self.distanceConstraintList:
            self.guiParent.browseConstraints(
                constraintList=self.distanceConstraintList)

    def showAntiConstraints(self):

        if self.antiDistConstraintList:
            self.guiParent.browseConstraints(
                constraintList=self.antiDistConstraintList)

    def getNoesys3d(self):

        peakLists = getThroughSpacePeakLists(self.project)

        names = [
            '<None>',
        ]
        for peakList in peakLists:
            spectrum = peakList.dataSource
            if spectrum.numDim != 3:
                continue

            name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                 peakList.serial)
            names.append(name)
            self.peakListDict3d[name] = peakList
            if not self.noesyPeakList:
                self.noesyPeakList = peakList

        return names

    def getNoesys(self):

        peakLists = getThroughSpacePeakLists(self.project)

        names = [
            '<None>',
        ]
        for peakList in peakLists:
            spectrum = peakList.dataSource
            name = '%s:%s:%s' % (spectrum.experiment.name, spectrum.name,
                                 peakList.serial)
            names.append(name)
            self.peakListDict[name] = peakList

            if not self.noesyPeakList:
                self.noesyPeakList = peakList

        return names

    def setNoesy(self, index, name=None):

        if not name:
            name = self.noesyPulldown.getSelected()

        if name == '<None>':
            self.noesyPeakList = None

        else:
            self.noesyPeakList = self.peakListDict[name]

        self.getPeaks()
        self.getResonances()
        self.update()

    def setNoesy1(self, index, name=None):

        if not name:
            name = self.tmix1Pulldown.getSelected()

        if name != '<None>':
            self.noesyPeakList1 = self.peakListDict[name]
        else:
            self.noesyPeakList1 = None

        self.update()

    def setNoesy2(self, index, name=None):

        if not name:
            name = self.tmix2Pulldown.getSelected()

        if name != '<None>':
            self.noesyPeakList2 = self.peakListDict[name]
        else:
            self.noesyPeakList2 = None

        self.update()

    def setNoesy3(self, index, name=None):

        if not name:
            name = self.tmix3Pulldown.getSelected()

        if name != '<None>':
            self.noesyPeakList3 = self.peakListDict[name]
        else:
            self.noesyPeakList3 = None

        self.update()

    def setNoesy3d(self, index, name=None):

        if not name:
            name = self.noesy3dPulldown.getSelected()

        if name != '<None>':
            self.noesyPeakList3d = self.peakListDict3d[name]
            self.noesyPeaks = self.noesyPeakList3d.sortedPeaks()

        else:
            self.noesyPeakList3d = None
            self.noesyPeaks = []

        self.getResonances()
        self.update()

    def updateMidgeParams(self):

        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate
        ]

        self.midgeParamsMatrix.update(textMatrix=[
            data,
        ])

    def getSpecFreq(self, obj):

        self.specFreqEntry.set(self.specFreq)

    def getMaxIter(self, obj):

        self.maxIterEntry.set(self.maxIter)

    def getMixTime(self, obj):

        self.mixTimeEntry.set(self.mixTime)

    def getCorrTime(self, obj):

        self.corrTimeEntry.set(self.corrTime)

    def getLeakRate(self, obj):

        self.leakRateEntry.set(self.leakRate)

    def setSpecFreq(self, event):

        value = self.specFreqEntry.get()
        if value is not None:
            self.specFreq = value

        self.updateMidgeParams()

    def setMaxIter(self, event):

        value = self.maxIterEntry.get()
        if value is not None:
            self.maxIter = value

        self.updateMidgeParams()

    def setMixTime(self, event):

        value = self.mixTimeEntry.get()
        if value is not None:
            self.mixTime = value

        self.updateMidgeParams()

    def setCorrTime(self, event):

        value = self.corrTimeEntry.get()
        if value is not None:
            self.corrTime = value

        self.updateMidgeParams()

    def setLeakRate(self, event):

        value = self.leakRateEntry.get()
        if value is not None:
            self.leakRate = value

        self.updateMidgeParams()

    def destroy(self):

        BasePopup.destroy(self)
Example #16
0
class EditSymmetryPopup(BasePopup):
    def __init__(self, parent, project):

        self.parent = parent
        self.project = project
        self.singleMolecule = True
        self.molSystem = None
        self.molecules = []
        self.symmetrySet = None
        self.symmetryOp = None
        self.waiting = False

        BasePopup.__init__(self, parent=parent, title='Symmetry Operations')

    def body(self, guiFrame):

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

        frame = LabelFrame(guiFrame, text='Options')
        frame.grid(row=0, column=0, sticky='ew')
        frame.grid_columnconfigure(5, weight=1)

        label = Label(frame, text='MolSystem:')
        label.grid(row=0, column=0, sticky='w')
        self.molSystemPulldown = PulldownMenu(frame,
                                              callback=self.selectMolSystem)
        self.molSystemPulldown.grid(row=0, column=1, sticky='w')

        self.molLabel = Label(frame, text='Molecule:')
        self.molLabel.grid(row=0, column=2, sticky='w')
        self.moleculePulldown = PulldownMenu(frame,
                                             callback=self.selectMolecule)
        self.moleculePulldown.grid(row=0, column=3, sticky='w')

        label = Label(frame, text='Same Molecule Symmetry:')
        label.grid(row=0, column=4, sticky='w')
        self.molSelect = CheckButton(frame, callback=self.toggleSingleMolecule)
        self.molSelect.grid(row=0, column=5, sticky='w')
        self.molSelect.set(self.singleMolecule)

        frame = LabelFrame(guiFrame, text='Symmetry Operations')
        frame.grid(row=1, column=0, sticky='nsew')
        frame.grid_columnconfigure(0, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        self.symmCodePulldown = PulldownMenu(self,
                                             callback=self.setSymmCode,
                                             do_initial_callback=False)
        self.segLengthEntry = IntEntry(self,
                                       returnCallback=self.setSegLength,
                                       width=6)
        self.setChainMulti = MultiWidget(self,
                                         CheckButton,
                                         callback=self.setChains,
                                         minRows=0,
                                         useImages=False)
        self.setSegmentMulti = MultiWidget(self,
                                           IntEntry,
                                           callback=self.setSegments,
                                           minRows=0,
                                           useImages=False)

        editWidgets = [
            None, self.symmCodePulldown, self.segLengthEntry,
            self.setChainMulti, self.setSegmentMulti
        ]
        editGetCallbacks = [
            None, self.getSymmCode, self.getSegLength, self.getChains,
            self.getSegments
        ]
        editSetCallbacks = [
            None, self.setSymmCode, self.setSegLength, self.setChains,
            self.setSegments
        ]

        headings = [
            '#', 'Symmetry\nType', 'Segment\nLength', 'Chains',
            'Segment\nPositions'
        ]
        self.symmetryMatrix = ScrolledMatrix(frame,
                                             headingList=headings,
                                             callback=self.selectSymmetry,
                                             editWidgets=editWidgets,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)
        self.symmetryMatrix.grid(row=0, column=0, sticky='nsew')

        texts = ['Add Symmetry Op', 'Remove Symmetrey Op']
        commands = [self.addSymmOp, self.removeSymmOp]
        buttonList = createDismissHelpButtonList(guiFrame,
                                                 texts=texts,
                                                 commands=commands,
                                                 expands=True)
        buttonList.grid(row=2, column=0, sticky='ew')

        self.updateMolSystems()
        self.updateMolecules()
        self.updateSymmetriesAfter()

        self.notify(self.registerNotify)

    def open(self):

        self.updateMolSystems()
        self.updateMolecules()
        self.updateSymmetriesAfter()

        BasePopup.open(self)

    def notify(self, notifyFunc):

        for func in ('__init__', 'delete', 'setSymmetryCode',
                     'setSegmentLength'):
            notifyFunc(self.updateSymmetriesAfter, 'molsim.Symmetry.Symmetry',
                       func)

        for func in ('__init__', 'delete', 'setfirstSeqId'):
            notifyFunc(self.updateSymmetriesAfter, 'molsim.Symmetry.Segment',
                       func)

    def getSymmCode(self, symmetryOp):
        """Get allowed symmetry operators from the model"""

        symmetryOpCodes = symmetryOp.parent.metaclass.container.getElement(
            'SymmetryOpCode').enumeration
        index = 0

        if symmetryOp.symmetryCode in symmetryOpCodes:
            index = symmetryOpCodes.index(symmetryOp.symmetryCode)

        self.symmCodePulldown.setup(symmetryOpCodes, index)

    def getSegLength(self, symmetryOp):

        if symmetryOp and symmetryOp.segmentLength:
            self.segLengthEntry.set(symmetryOp.segmentLength)

    def getChains(self, symmetryOp):

        chains = []
        for chain in self.molSystem.chains:
            if chain.residues:
                if chain.molecule in self.molecules: chains.append(chain.code)
        chains.sort()

        values = []
        for chain in chains:
            if symmetryOp.findFirstSegment(chainCode=chain):
                values.append(True)
            else:
                values.append(False)

        self.setChainMulti.set(values=values, options=chains)

    def getSegments(self, symmetryOp):

        values = []
        names = []

        if symmetryOp:
            for segment in symmetryOp.sortedSegments():
                names.append(segment.chainCode)
                values.append(segment.firstSeqId)

        n = len(values)
        self.setSegmentMulti.maxRows = n
        self.setSegmentMulti.minRows = n
        self.setSegmentMulti.set(values=values, options=names)

    def setSymmCode(self, index, name=None):
        """Set the symmetry code as NCS,C2,C3,C4,C5,C6"""

        if self.symmetryOp:
            symmCode = self.symmCodePulldown.getSelected()
            self.symmetryOp.symmetryCode = symmCode

    def setSegLength(self, event):

        value = self.segLengthEntry.get() or 1
        self.symmetryOp.segmentLength = value

    def setChains(self, obj):

        if self.symmetryOp and obj:
            codes = self.setChainMulti.options
            segment = self.symmetryOp.findFirstSegment()
            values = self.setChainMulti.get()

            if segment: seqId0 = segment.firstSeqId
            else: seqId0 = 1

            for i in range(len(values)):
                segment = self.symmetryOp.findFirstSegment(chainCode=codes[i])

                if segment and not values[i]: segment.delete()
                elif values[i] and not segment:
                    chain = self.molSystem.findFirstChain(code=codes[i])
                    residue = chain.findFirstResidue(seqid=seqId0)

                    if residue: seqId = seqId0
                    else:
                        residue = chain.sortedResidues()[0]
                        seqId = residue.seqId

                    residue2 = chain.findFirstResidue(
                        seqid=seqId + self.symmetryOp.segmentLength)
                    if not residue2:
                        residue2 = chain.sortedResidues()[-1]
                        self.symmetryOp.segmentLength = (residue2.seqId -
                                                         seqId) + 1

                    segment = self.symmetryOp.newSegment(chainCode=codes[i],
                                                         firstSeqId=seqId)

        self.symmetryMatrix.keyPressEscape()

    def setSegments(self, obj):

        if self.symmetryOp and obj:
            segments = self.symmetryOp.sortedSegments()
            values = self.setSegmentMulti.get()

            for i in range(len(values)):
                seqCode = values[i]
                chain = self.molSystem.findFirstChain(
                    code=segments[i].chainCode)
                residue = chain.findFirstResidue(seqCode=seqCode)

                if residue: seqId = residue.seqId
                if segments[i].firstSeqId != seqId:
                    segments[i].delete()
                    segments[i] = self.symmetryOp.newSegment(
                        chainCode=chain.code, firstSeqId=seqId)

        self.symmetryMatrix.keyPressEscape()

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

        self.symmetryOp = obj

    def addSymmOp(self):

        if self.molSystem:
            if not self.symmetrySet:
                self.symmetrySet = self.molSystem.findFirstMolSystemSymmetrySet(
                )

            if not self.symmetrySet:
                objGen = self.project.newMolSystemSymmetrySet
                self.symmetrySet = objGen(symmetrySetId=1,
                                          molSystem=self.molSystem)

            segLen = len(self.molSystem.findFirstChain().residues)
            symmetry = self.symmetrySet.newSymmetry(segmentLength=segLen)

    def removeSymmOp(self):

        if self.symmetryOp: self.symmetryOp.delete()

    def toggleSingleMolecule(self, boolean):

        self.singleMolecule = not boolean
        self.updateMolSystems()
        self.updateMolecules()

    def setMolecules(self, molecules):

        self.molecules = molecules
        if self.symmetrySet:
            for symmetryOp in self.symmetrySet.symmetries:
                for segment in symmetryOp.segments:
                    chain = self.molSystem.findFirstChain(
                        code=segment.chainCode)
                if chain and (chain.molecule not in molecules):
                    segment.delete()

    def selectMolecule(self, index, name):

        self.setMolecules(self.getMolecules()[index])
        self.updateSymmetries()

    def getMolecules(self):

        counts = {}
        moleculesList = []

        for chain in self.molSystem.chains:
            molecule = chain.molecule
            counts[molecule] = counts.get(molecule, 0) + 1

        molecules = counts.keys()
        if self.singleMolecule:
            for molecule in counts:
                if counts[molecule] > 1: moleculesList.append([
                        molecule,
                ])

        elif molecules:
            molecules = counts.keys()
            n = len(molecules)
            moleculesList.append([
                molecules[0],
            ])

            if n > 1:
                moleculesList.append([
                    molecules[1],
                ])
                moleculesList.append([molecules[0], molecules[1]])

            if n > 2:
                moleculesList.append([
                    molecules[2],
                ])
                moleculesList.append([molecules[1], molecules[2]])
                moleculesList.append(
                    [molecules[0], molecules[1], molecules[2]])

            if n > 3:
                moleculesList.append([
                    molecules[3],
                ])
                moleculesList.append([molecules[0], molecules[3]])
                moleculesList.append([molecules[1], molecules[3]])
                moleculesList.append([molecules[2], molecules[3]])
                moleculesList.append(
                    [molecules[0], molecules[1], molecules[3]])
                moleculesList.append(
                    [molecules[0], molecules[2], molecules[3]])
                moleculesList.append(
                    [molecules[1], molecules[2], molecules[3]])
                moleculesList.append(
                    [molecules[0], molecules[1], molecules[2], molecules[3]])

        return moleculesList

    def updateMolecules(self):

        names = []
        index = -1
        moleculesList = self.getMolecules()
        if moleculesList:
            if self.molecules not in moleculesList:
                self.setMolecules(moleculesList[0])
                self.symmetrySet = self.molSystem.findFirstMolSystemSymmetrySet(
                )

            index = moleculesList.index(self.molecules)

            names = []
            for molecules in moleculesList:
                names.append(','.join([mol.name for mol in molecules]))

        else:
            self.molecules = []

        self.moleculePulldown.setup(names, index)

    def selectMolSystem(self, index, name):

        self.molSystem = self.getMolSystems()[index]
        self.symmetrySet = self.molSystem.findFirstMolSystemSymmetrySet()
        self.updateSymmetries()

    def getMolSystems(self):

        molSystems = []
        for molSystem in self.project.sortedMolSystems():
            n = len(molSystem.chains)

            if self.singleMolecule and (n > 1): molSystems.append(molSystem)
            elif n > 0: molSystems.append(molSystem)

        return molSystems

    def updateMolSystems(self):

        names = []
        index = -1
        molSystems = self.getMolSystems()

        if molSystems:
            if self.molSystem not in molSystems: self.molSystem = molSystems[0]

            index = molSystems.index(self.molSystem)
            names = [ms.code for ms in molSystems]
        else:
            self.molSystem = None

        self.molSystemPulldown.setup(names, index)

    def updateSymmetriesAfter(self, obj=None):

        if self.waiting: return
        else:
            self.waiting = True
            self.after_idle(self.updateSymmetries)

    def updateSymmetries(self):

        textMatrix = []
        objectList = []
        if self.symmetrySet:
            for symmetryOp in self.symmetrySet.symmetries:
                chains = []
                segments = []
                length = symmetryOp.segmentLength

                for segment in symmetryOp.sortedSegments():
                    code = segment.chainCode
                    chain = self.molSystem.findFirstChain(code=code)

                    if chain:
                        chains.append(code)
                        seqId = segment.firstSeqId
                        residue1 = chain.findFirstResidue(seqId=seqId)
                        residue2 = chain.findFirstResidue(seqId=seqId +
                                                          length - 1)
                        segments.append(
                            '%s:%d-%d' %
                            (code, residue1.seqCode, residue2.seqCode))

                datum = [
                    symmetryOp.serial, symmetryOp.symmetryCode, length,
                    '\n'.join(chains), '\n'.join(segments)
                ]
                objectList.append(symmetryOp)
                textMatrix.append(datum)

        self.symmetryMatrix.update(objectList=objectList,
                                   textMatrix=textMatrix)
        self.waiting = False

    def destroy(self):

        self.notify(self.unregisterNotify)
        BasePopup.destroy(self)
  def body(self, guiFrame):

    guiFrame.grid_columnconfigure(3, weight=1)
    
    row = 0
    label = Label(guiFrame, text='Molecular system: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.molSysPulldown = PulldownMenu(guiFrame, self.changeMolSystem, selected_index=-1, do_initial_callback=0)
    self.molSysPulldown.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Clouds files: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.filenameEntry = Entry(guiFrame,text='perfect00.pdb')
    self.filenameEntry.grid(row=row, column=3, sticky=Tkinter.NW)


    row += 1
    label = Label(guiFrame, text='Chain: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.chainPulldown = PulldownMenu(guiFrame, self.changeChain, selected_index=-1, do_initial_callback=0)
    self.chainPulldown.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Thread steps: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.numStepsEntry = IntEntry(guiFrame,text=3000)
    self.numStepsEntry.grid(row=row, column=3, sticky=Tkinter.NW)
    row += 1

    label = Label(guiFrame, text='Homologue PDB file: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.pdbEntry = Entry(guiFrame,text='')
    self.pdbEntry.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Dist. Threshold: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.distEntry = FloatEntry(guiFrame,text=3.0)
    self.distEntry.grid(row=row, column=3, sticky=Tkinter.NW)

    row += 1

    label = Label(guiFrame, text='Global score: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.globalScoreLabel = Label(guiFrame, text='')
    self.globalScoreLabel.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Assignment Threshold: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.thresholdEntry = FloatEntry(guiFrame,text=-4.5)
    self.thresholdEntry.grid(row=row, column=3, sticky=Tkinter.NW)

    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    self.graph = ScrolledGraph(guiFrame, width=300, height=200)
    self.graph.grid(row=row, column=0, columnspan=4, sticky = Tkinter.NSEW)

    row += 1
    texts    = ['Run','Assign!']
    commands = [self.run, self.assignSpinSystems]
    bottomButtons = createDismissHelpButtonList(guiFrame,texts=texts,commands=commands,expands=0,help_url=None)
    bottomButtons.grid(row=row, column=0, columnspan=4, sticky=Tkinter.EW)
    self.assignButton = bottomButtons.buttons[1]

    for func in ('__init__','delete'):
      Implementation.registerNotify(self.updateMolSystems, 'ccp.molecule.MolSystem.MolSystem', func)
      Implementation.registerNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)
    
    self.updateMolSystems()
    self.updateChains()
Example #18
0
class NmrPipePseudoPopup(BasePopup):

    pseudoEntries = ('Is Pseudo Expt', 'Is Not Pseudo Expt')

    def __init__(self, parent, params, dim, fileName='', *args, **kw):

        self.dim = dim
        self.params = params
        self.fileName = 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
        self.template = template

        BasePopup.__init__(self,
                           parent=parent,
                           title='NMRPipe Pseudo Data',
                           modal=True,
                           **kw)

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

    def loadValues(self):

        directory = self.parent.fileSelect.getDirectory()
        fileSelectPopup = FileSelectPopup(self,
                                          title='Select Sampled Data File',
                                          dismiss_text='Cancel',
                                          selected_file_must_exist=True,
                                          multiSelect=False,
                                          directory=directory)

        fileName = fileSelectPopup.file_select.getFile()

        if not fileName:
            return

        fileObj = open(fileName, 'rU')

        data = ''
        line = fileObj.readline()
        while line:
            data += line
            line = fileObj.readline()

        fileObj.close()

        data = re.sub(',\s+', ',', data)
        data = re.sub('\s+', ',', data)
        data = re.sub(',,', ',', data)
        data = re.sub('[^0-9,.\-+eE]', '', data)

        self.valueEntry.set(data)

    def chooseDirectory(self):

        directory = os.path.dirname(self.fileName)
        if not directory:
            directory = os.getcwd()
        popup = FileSelectPopup(self, directory=directory, show_file=False)
        directory = popup.getDirectory()
        popup.destroy()

        if directory:
            self.directoryEntry.set(directory)

    def chooseFile(self):

        directory = self.directoryEntry.get()
        if not directory:
            directory = os.getcwd()
        popup = FileSelectPopup(self, directory=directory)
        file = popup.getFile()
        popup.destroy()

        if file:
            template = os.path.basename(file)
            self.templateEntry.set(template)

    def updateParams(self):

        params = self.params
        if self.pseudoButton.get() == self.pseudoEntries[0]:
            npts = self.nptsEntry.get()
            params.npts[self.dim] = npts
            values = self.valueEntry.get()
            try:
                params.setSampledDim(self.dim, values)
            except ApiError, e:
                showError('Set Sampled Dim', e.error_msg, parent=self)
                return
            params.fixNullDims(ignoreDim=self.dim)
        else:
Example #19
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 #20
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 #21
0
    def body(self, guiFrame):

        self.specFreqEntry = IntEntry(self,
                                      text=self.specFreq,
                                      width=8,
                                      returnCallback=self.setSpecFreq)
        self.maxIterEntry = IntEntry(self,
                                     text=self.maxIter,
                                     width=8,
                                     returnCallback=self.setMaxIter)
        self.mixTimeEntry = FloatEntry(self,
                                       text=self.mixTime,
                                       width=8,
                                       returnCallback=self.setMixTime)
        self.corrTimeEntry = FloatEntry(self,
                                        text=self.corrTime,
                                        width=8,
                                        returnCallback=self.setCorrTime)
        self.leakRateEntry = FloatEntry(self,
                                        text=self.leakRate,
                                        width=8,
                                        returnCallback=self.setLeakRate)
        self.maxIntensEntry = IntEntry(self,
                                       text=self.maxIntens,
                                       width=8,
                                       returnCallback=self.setMaxIntens)

        self.mdInitTempEntry = FloatEntry(self,
                                          text='',
                                          returnCallback=self.setMdInitTemp)
        self.mdFinTempEntry = FloatEntry(self,
                                         text='',
                                         returnCallback=self.setMdFinTemp)
        self.mdCoolStepsEntry = IntEntry(self,
                                         text='',
                                         returnCallback=self.setMdCoolSteps)
        self.mdSimStepsEntry = IntEntry(self,
                                        text='',
                                        returnCallback=self.setMdSimSteps)
        self.mdTauEntry = FloatEntry(self,
                                     text='',
                                     returnCallback=self.setMdTau)
        self.mdRepScaleEntry = FloatEntry(self,
                                          text='',
                                          returnCallback=self.setMdRepScale)

        guiFrame.grid_columnconfigure(0, weight=1)

        row = 0
        frame0 = LabelFrame(guiFrame, text='Setup peak lists')
        frame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame0.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame0.grid_columnconfigure(1, weight=1)

        f0row = 0
        label00 = Label(frame0, text='1H-1H NOESY spectrum')
        label00.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.noesyPulldown = PulldownMenu(frame0,
                                          entries=self.getNoesys(),
                                          callback=self.setNoesy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.noesyPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label01 = Label(frame0, text='15N HSQC spectrum')
        label01.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.hsqcPulldown = PulldownMenu(frame0,
                                         entries=self.getHsqcs(),
                                         callback=self.setHsqc,
                                         selected_index=0,
                                         do_initial_callback=0)
        self.hsqcPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label02 = Label(frame0, text='15N HSQC TOCSY spectrum')
        label02.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.tocsyPulldown = PulldownMenu(frame0,
                                          entries=self.getTocsys(),
                                          callback=self.setTocsy,
                                          selected_index=0,
                                          do_initial_callback=0)
        self.tocsyPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        label02 = Label(frame0, text='15N HSQC NOESY spectrum')
        label02.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.noesy3dPulldown = PulldownMenu(frame0,
                                            entries=self.getNoesy3ds(),
                                            callback=self.setNoesy3d,
                                            selected_index=0,
                                            do_initial_callback=0)
        self.noesy3dPulldown.grid(row=f0row, column=1, sticky=Tkinter.NW)

        f0row += 1
        texts = ['Setup resonances & peaks', 'Show Peaks', 'Show resonances']
        commands = [self.setupResonances, self.showPeaks, self.showResonances]
        self.setupButtons = ButtonList(frame0,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.setupButtons.grid(row=f0row,
                               column=0,
                               columnspan=2,
                               sticky=Tkinter.NSEW)

        f0row += 1
        self.label03a = Label(frame0, text='Resonances found: 0')
        self.label03a.grid(row=f0row, column=0, sticky=Tkinter.NW)
        self.label03b = Label(frame0, text='NOESY peaks found: 0')
        self.label03b.grid(row=f0row, column=1, sticky=Tkinter.NW)

        row += 1
        frame1 = LabelFrame(guiFrame, text='Calculate distance constraints')
        frame1.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame1.grid_columnconfigure(3, weight=1)

        f1row = 0
        frame1.grid_rowconfigure(f1row, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate, self.maxIntens
        ]
        colHeadings = [
            'Spectrometer\nfrequency', 'Max\niterations', 'Mixing\ntime (ms)',
            'Correl.\ntime (ns)', 'Leak\nrate', 'Max\nintensity'
        ]
        editWidgets = [
            self.specFreqEntry,
            self.maxIterEntry,
            self.mixTimeEntry,
            self.corrTimeEntry,
            self.leakRateEntry,
            self.maxIntensEntry,
        ]
        editGetCallbacks = [
            self.getSpecFreq,
            self.getMaxIter,
            self.getMixTime,
            self.getCorrTime,
            self.getLeakRate,
            self.getMaxIntens,
        ]
        editSetCallbacks = [
            self.setSpecFreq,
            self.setMaxIter,
            self.setMixTime,
            self.setCorrTime,
            self.setLeakRate,
            self.setMaxIntens,
        ]
        self.midgeParamsMatrix = ScrolledMatrix(
            frame1,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=1,
            initialCols=5,
            headingList=colHeadings,
            callback=None,
            objectList=[
                'None',
            ],
            textMatrix=[
                data,
            ])
        self.midgeParamsMatrix.grid(row=f1row,
                                    column=0,
                                    columnspan=4,
                                    sticky=Tkinter.NSEW)

        f1row += 1
        label10 = Label(frame1, text='Benchmark structure')
        label10.grid(row=f1row, column=0, sticky=Tkinter.NW)
        self.structurePulldown = PulldownMenu(frame1,
                                              entries=self.getStructures(),
                                              callback=self.setStructure,
                                              selected_index=0,
                                              do_initial_callback=0)
        self.structurePulldown.grid(row=f1row, column=1, sticky=Tkinter.NW)

        label11 = Label(frame1, text='ADC atom types:')
        label11.grid(row=f1row, column=2, sticky=Tkinter.NW)
        self.adcAtomsPulldown = PulldownMenu(frame1,
                                             entries=self.getAdcAtomTypes(),
                                             callback=self.setAdcAtomTypes,
                                             selected_index=0,
                                             do_initial_callback=0)
        self.adcAtomsPulldown.grid(row=f1row, column=3, sticky=Tkinter.NW)

        f1row += 1
        texts = [
            'Calculate distances', 'Show distance\nconstraints',
            'Show anti-distance\nconstraints'
        ]
        commands = [
            self.calculateDistances, self.showConstraints,
            self.showAntiConstraints
        ]
        self.midgeButtons = ButtonList(frame1,
                                       expands=1,
                                       texts=texts,
                                       commands=commands)
        self.midgeButtons.grid(row=f1row,
                               column=0,
                               columnspan=4,
                               sticky=Tkinter.NSEW)

        f1row += 1
        self.distConstrLabel = Label(frame1, text='Distance constraints:')
        self.distConstrLabel.grid(row=f1row,
                                  column=0,
                                  columnspan=2,
                                  sticky=Tkinter.NW)
        self.antiConstrLabel = Label(frame1, text='Anti-distance constraints:')
        self.antiConstrLabel.grid(row=f1row,
                                  column=2,
                                  columnspan=2,
                                  sticky=Tkinter.NW)

        row += 1
        guiFrame.grid_rowconfigure(row, weight=1)
        frame2 = LabelFrame(guiFrame, text='Proton cloud molecular dynamics')
        frame2.grid(row=row, column=0, sticky=Tkinter.NSEW)
        frame2.grid_columnconfigure(1, weight=1)

        f2row = 0
        frame2.grid_rowconfigure(f2row, weight=1)
        data = [
            self.specFreq, self.maxIter, self.mixTime, self.corrTime,
            self.leakRate
        ]
        colHeadings = [
            'Step', 'Initial temp.', 'Final temp.', 'Cooling steps',
            'MD steps', 'MD tau', 'Rep. scale'
        ]
        editWidgets = [
            None, self.mdInitTempEntry, self.mdFinTempEntry,
            self.mdCoolStepsEntry, self.mdSimStepsEntry, self.mdTauEntry,
            self.mdRepScaleEntry
        ]
        editGetCallbacks = [
            None, self.getMdInitTemp, self.getMdFinTemp, self.getMdCoolSteps,
            self.getMdSimSteps, self.getMdTau, self.getMdRepScale
        ]
        editSetCallbacks = [
            None, self.setMdInitTemp, self.setMdFinTemp, self.setMdCoolSteps,
            self.setMdSimSteps, self.setMdTau, self.setMdRepScale
        ]
        self.coolingSchemeMatrix = ScrolledMatrix(
            frame2,
            editSetCallbacks=editSetCallbacks,
            editGetCallbacks=editGetCallbacks,
            editWidgets=editWidgets,
            maxRows=9,
            initialRows=12,
            headingList=colHeadings,
            callback=self.selectCoolingStep,
            objectList=self.coolingScheme,
            textMatrix=self.coolingScheme)
        self.coolingSchemeMatrix.grid(row=f2row,
                                      column=0,
                                      columnspan=4,
                                      sticky=Tkinter.NSEW)

        f2row += 1
        texts = ['Move earlier', 'Move later', 'Add step', 'Remove step']
        commands = [
            self.moveStepEarlier, self.moveStepLater, self.addCoolingStep,
            self.removeCoolingStep
        ]
        self.coolingSchemeButtons = ButtonList(frame2,
                                               expands=1,
                                               commands=commands,
                                               texts=texts)
        self.coolingSchemeButtons.grid(row=f2row,
                                       column=0,
                                       columnspan=4,
                                       sticky=Tkinter.EW)

        f2row += 1
        label20 = Label(frame2, text='Number of clouds:')
        label20.grid(row=f2row, column=0, sticky=Tkinter.NW)
        self.numCloudsEntry = FloatEntry(frame2,
                                         text=100,
                                         returnCallback=self.setNumClouds,
                                         width=10)
        self.numCloudsEntry.grid(row=f2row, column=1, sticky=Tkinter.NW)
        label21 = Label(frame2, text='Cloud file prefix:')
        label21.grid(row=f2row, column=2, sticky=Tkinter.NW)
        self.filePrefixEntry = Entry(frame2,
                                     text='cloud_',
                                     returnCallback=self.setFilePrefix,
                                     width=10)
        self.filePrefixEntry.grid(row=f2row, column=3, sticky=Tkinter.NW)

        f2row += 1
        texts = ['Start molecular dynamics', 'Show dynamics progress']
        commands = [self.startMd, self.showMdProgress]
        self.mdButtons = ButtonList(frame2,
                                    expands=1,
                                    commands=commands,
                                    texts=texts)
        self.mdButtons.grid(row=f2row,
                            column=0,
                            columnspan=4,
                            sticky=Tkinter.NSEW)

        row += 1
        self.bottomButtons = createDismissHelpButtonList(guiFrame,
                                                         expands=0,
                                                         help_url=None)
        self.bottomButtons.grid(row=row, column=0, sticky=Tkinter.EW)

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

      Attributes:

          guiParent: gui object this tab is part of.

          frame: the frame in which this element lives.

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

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

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

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

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

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

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

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

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

          spectrum (src.cython.malandro.Spectrum): The spectrum
              that should be assigned.
    '''
    def __init__(self, parent, frame):
        '''Init. args: parent: the guiElement that this
                               tab is part of.
                       frame:  the frame this part of the
                               GUI lives in.
        '''

        self.guiParent = parent
        self.frame = frame

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

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

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

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

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

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

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

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

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

        row = 0

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

        row += 1

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

        row = 0

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

        row += 1

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

        row += 1

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

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

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

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

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

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

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

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

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

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

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

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

        self.dataModel = dataModel
        self.update()

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

        if not self.dataModel:

            return

        spectrum = self.spectrum

        spectra = self.dataModel.getSpectra()

        if spectra:

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

            if self.spectrum not in spectra:

                self.spectrum = spectra[0]

            else:

                index = spectra.index(self.spectrum)

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

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

        self.spectrum = spectrum

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

        if not self.dataModel:

            return

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

        if value is None:

            value = self.solutionNumberEntry.get()

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

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

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

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

        newMinScore = self.minScoreEntry.get()

        if self.minScore != newMinScore:

            if newMinScore <= 50.0:

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

            elif newMinScore > 100.0:

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

            else:

                self.minScore = newMinScore

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

        self.fetchOptions()

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

            return

        strategy = self.strategy

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

        residues = self.dataModel.chain.residues

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

        ccpnSpinSystems = []
        ccpnResidues = []

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

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

                if spinSys and res:

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

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

        if self.resonanceToDimension:

            allSpectra = self.allSpectra

            if self.intra:

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

                    if not spinSystem:

                        continue

                    intraLink = residue.getIntraLink(spinSystem)

                    for pl in intraLink.getPeakLinks():

                        peak = pl.getPeak()

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

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

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

                            continue

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

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

            if self.sequential:

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

                    if not spinSystemA or not spinSystemB:

                        continue

                    link = residue.getLink(spinSystemA, spinSystemB)

                    for pl in link.getPeakLinks():

                        peak = pl.getPeak()

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

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

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

                            continue

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

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

                            assignResToDim(ccpnDimension, ccpnResonance)

        self.guiParent.resultsTab.update()

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

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

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

            assignedResonanceGroup = ccpnResidue.findFirstResonanceGroup()

            if assignedResonanceGroup:

                for spinSystem in spinSystems:

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

                            return spinSystem

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

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

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

            return bestSpinSystem

        return None

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

        userDefinedSpinSystem = residue.userDefinedSolution

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

            return userDefinedSpinSystem

        return None

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

        solutions = residue.solutions

        spinSystem = solutions[self.selectedSolution - 1]

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

            return spinSystem

        return None

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

        if self.strategy == 0:

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

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

                return True

        return False
Example #23
0
class MeccanoPopup(BasePopup):

  def __init__(self, parent, project, *args, **kw):
  
    self.alignMedium = None
    self.chain = None
    self.constraint = None
    self.constraintSet = None
    self.molSystem = None
    self.project = project
    self.run = None
    self.shiftList = None
    self.tensor = None

    
    BasePopup.__init__(self, parent=parent, title='MECCANO', *args, **kw)

    self.curateNotifiers(self.registerNotify)

  def body(self, guiFrame):
  
    guiFrame.grid_columnconfigure(0, weight=1)
    guiFrame.grid_rowconfigure(0, weight=1)

    options = ['Parameters','Restraints','Alignment Media & Tensors','About Meccano']
    tabbedFrame = TabbedFrame(guiFrame, options=options)
    tabbedFrame.grid(row=0, column=0, sticky='nsew')
    
    frameA, frameB, frameC, frameD = tabbedFrame.frames
    frameA.grid_columnconfigure(1, weight=1)
    frameA.grid_rowconfigure(13, weight=1)
    frameB.grid_columnconfigure(1, weight=1)
    frameB.grid_rowconfigure(1, weight=1)
    frameC.grid_columnconfigure(0, weight=1)
    frameC.grid_rowconfigure(1, weight=1)
    frameD.grid_columnconfigure(0, weight=1)
    frameD.grid_rowconfigure(0, weight=1)
    
    texts = ['Run MECCANO!']
    commands = [self.runMeccano]
    bottomButtons = createDismissHelpButtonList(guiFrame, texts=texts,
                                                commands=commands, expands=True)
    bottomButtons.grid(row=1, column=0, sticky='ew')

    if not Meccano:
      bottomButtons.buttons[0].disable()
  
    # Parameters
        
    row = 0
    label = Label(frameA, text='Calculation Run:')
    label.grid(row=row,column=0,sticky='w')
    self.runPulldown = PulldownList(frameA, callback=self.selectRun)
    self.runPulldown.grid(row=row,column=1,sticky='w')
    
    row += 1    
    label = Label(frameA, text='Shift List (for CO):')
    label.grid(row=row,column=0,sticky='w')
    self.shiftListPulldown = PulldownList(frameA, callback=self.selectShiftList)
    self.shiftListPulldown.grid(row=row,column=1,sticky='w')
           
    row += 1    
    label = Label(frameA, text='Keep Copy of Used Shifts:')
    label.grid(row=row,column=0,sticky='w')
    self.toggleCopyShifts = CheckButton(frameA)
    self.toggleCopyShifts.grid(row=row,column=1,sticky='w')
    self.toggleCopyShifts.set(True)
        
    row += 1    
    label = Label(frameA, text='Molecular System:')
    label.grid(row=row,column=0,sticky='w')
    self.molSystemPulldown = PulldownList(frameA, callback=self.selectMolSystem)
    self.molSystemPulldown.grid(row=row,column=1,sticky='w')
        
    row += 1    
    label = Label(frameA, text='Chain:')
    label.grid(row=row,column=0,sticky='w')
    self.chainPulldown = PulldownList(frameA, callback=self.selectChain)
    self.chainPulldown.grid(row=row,column=1,sticky='w')
    self.chainPulldown.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='First Peptide Plane:')
    label.grid(row=row,column=0,sticky='w')
    self.firstResEntry = IntEntry(frameA, text=None, width=8)
    self.firstResEntry.grid(row=row,column=1,sticky='w')
    self.firstResEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Last Peptide Plane:')
    label.grid(row=row,column=0,sticky='w')
    self.lastResEntry = IntEntry(frameA, text=None, width=8)
    self.lastResEntry.grid(row=row,column=1,sticky='w')
    self.lastResEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Max Num Optimisation Steps:')
    label.grid(row=row,column=0,sticky='w')
    self.maxOptStepEntry = IntEntry(frameA, text=500, width=8)
    self.maxOptStepEntry.grid(row=row,column=1,sticky='w')
    self.maxOptStepEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Num Optimisation Peptide Planes:')
    label.grid(row=row,column=0,sticky='w')
    self.numOptPlaneEntry = IntEntry(frameA, text=2, width=8)
    self.numOptPlaneEntry.grid(row=row,column=1,sticky='w')
    self.numOptPlaneEntry.bind('<Leave>', self.updateRunParams) 
        
    row += 1    
    label = Label(frameA, text='Min Num Optimisation Hits:')
    label.grid(row=row,column=0,sticky='w')
    self.numOptHitsEntry = IntEntry(frameA, text=5, width=8)
    self.numOptHitsEntry.grid(row=row,column=1,sticky='w')
    self.numOptHitsEntry.bind('<Leave>', self.updateRunParams) 

    row += 1    
    label = Label(frameA, text='File Name Prefix:')
    label.grid(row=row,column=0,sticky='w')
    self.pdbFileEntry = Entry(frameA, text='Meccano', width=8)
    self.pdbFileEntry.grid(row=row,column=1,sticky='w')
    self.pdbFileEntry.bind('<Leave>', self.updateRunParams) 
           
    row += 1    
    label = Label(frameA, text='Write Output File (.out):')
    label.grid(row=row,column=0,sticky='w')
    self.toggleWriteOutFile = CheckButton(frameA)
    self.toggleWriteOutFile.grid(row=row,column=1,sticky='w')
    self.toggleWriteOutFile.set(False)
    self.toggleWriteOutFile.bind('<Leave>', self.updateRunParams) 
           
    row += 1    
    label = Label(frameA, text='Write PDB File (.pdb):')
    label.grid(row=row,column=0,sticky='w')
    self.toggleWritePdbFile = CheckButton(frameA)
    self.toggleWritePdbFile.grid(row=row,column=1,sticky='w')
    self.toggleWritePdbFile.set(True)
    self.toggleWritePdbFile.bind('<Leave>', self.updateRunParams) 
    
    if not Meccano:
      row += 1    
      label = Label(frameA, text='The Meccano executable is not available (it needs to be compiled)', fg='red')
      label.grid(row=row,column=0,columnspan=2,sticky='w')

    # Restraints
    
    label = Label(frameB, text='Constraint Set:')
    label.grid(row=0,column=0,sticky='w')
    
    self.constraintSetPulldown = PulldownList(frameB, callback=self.selectConstraintSet)
    self.constraintSetPulldown.grid(row=0,column=1,sticky='w')
    
    self.alignMediumPulldown= PulldownList(self, callback=self.setAlignMedium)
    
    headingList = ['#','List Type','Use?','Alignment\nMedium','Num\nRestraints']
    editWidgets      = [None,None,None,self.alignMediumPulldown,None]
    editGetCallbacks = [None,None,self.toggleUseRestraints,self.getAlignMedium,None]
    editSetCallbacks = [None,None,None,self.setAlignMedium,None]
    self.restraintMatrix = ScrolledMatrix(frameB,
                                          headingList=headingList,
                                          editSetCallbacks=editSetCallbacks,
                                          editGetCallbacks=editGetCallbacks, 
                                          editWidgets=editWidgets,
                                          callback=None,
                                          multiSelect=True)
    self.restraintMatrix.grid(row=1,column=0,columnspan=2,sticky='nsew')
    
    
    # Alignment Media
    
    div = LabelDivider(frameC,text='Alignment Media')
    div.grid(row=0,column=0,sticky='ew')
    
    self.mediumNameEntry = Entry(self, returnCallback=self.setMediumName)
    self.mediumDetailsEntry = Entry(self, returnCallback=self.setMediumDetails)
    
    headingList = ['#','Name','Details','Static Tensor','Dynamic Tensor']
    editWidgets      = [None, self.mediumNameEntry, self.mediumDetailsEntry, None, None]
    editGetCallbacks = [None, self.getMediumName, self.getMediumDetails, None, None]
    editSetCallbacks = [None, self.setMediumName, self.setMediumDetails, None, None]
    self.mediaMatrix = ScrolledMatrix(frameC,
                                      headingList=headingList,
                                      editSetCallbacks=editSetCallbacks,
                                      editGetCallbacks=editGetCallbacks, 
                                      editWidgets=editWidgets,
                                      callback=self.selectAlignMedium,
                                      multiSelect=True)
                                 
    self.mediaMatrix.grid(row=1,column=0,sticky='nsew')
     
    
    texts = ['Add Alignment medium','Remove Alignment Medium']
    commands = [self.addAlignMedium,self.removeAlignMedium]
    buttonList = ButtonList(frameC, texts=texts, commands=commands, expands=True)
    buttonList.grid(row=2,column=0,sticky='nsew')
    
    self.editAxialEntry = FloatEntry(self, returnCallback=self.setAxial)
    self.editRhombicEntry = FloatEntry(self, returnCallback=self.setRhombic)
    self.editAlphaEulerEntry = FloatEntry(self, returnCallback=self.setEulerAlpha)
    self.editBetaEulerEntry = FloatEntry(self, returnCallback=self.setEulerBeta)
    self.editGammaEulerEntry = FloatEntry(self, returnCallback=self.setEulerGamma)
    
    
    div = LabelDivider(frameC,text='Alignment Tensors')
    div.grid(row=3,column=0,sticky='ew')
    
    headingList = ['Type', u'Axial (\u03B6)',u'Rhombic (\u03B7)',
                   u'Euler \u03B1',u'Euler \u03B2',u'Euler \u03B3']
    editWidgets      = [None,self.editAxialEntry,
                        self.editRhombicEntry,self.editAlphaEulerEntry,
                        self.editBetaEulerEntry,self.editGammaEulerEntry]
    editSetCallbacks = [None,self.setAxial,self.setRhombic,
                        self.setEulerAlpha,self.setEulerBeta,self.setEulerGamma]
    editGetCallbacks = [None,self.getAxial,self.getRhombic,
                        self.getEulerAlpha,self.getEulerBeta,self.getEulerGamma]
                   
    self.tensorMatrix = ScrolledMatrix(frameC, maxRows=2,
                                       headingList=headingList,
                                       editSetCallbacks=editSetCallbacks,
                                       editGetCallbacks=editGetCallbacks, 
                                       editWidgets=editWidgets,
                                       callback=self.selectTensor,
                                       multiSelect=True)
                                          
    self.tensorMatrix.grid(row=4,column=0,sticky='nsew')
    
    texts = ['Add Static Tensor','Add Dynamic Tensor','Remove Tensor']
    commands = [self.addStaticTensor,self.addDynamicTensor,self.removeTensor]
    buttonList = ButtonList(frameC,texts=texts, commands=commands, expands=True)
    buttonList.grid(row=5,column=0,sticky='ew')
       
    # About
    
    label = Label(frameD, text='About Meccano...')
    label.grid(row=0,column=0,sticky='w')
  
    #
  
    self.geometry('500x400')

    self.updateShiftLists()
    self.updateMolSystems()
    self.updateResidueRanges()
    self.updateConstraintSets()
    self.updateAlignMedia()
    self.updateRuns()
    
  def close(self):
  
    self.updateRunParams()
    
    BasePopup.close(self)
  
  def destroy(self):
  
    self.updateRunParams()
    self.curateNotifiers(self.unregisterNotify)
    
    BasePopup.destroy(self)
  
  def curateNotifiers(self, notifyFunc):
  
    for func in ('__init__', 'delete'):
      notifyFunc(self.updateConstraintSetsAfter, 'ccp.nmr.NmrConstraint.NmrConstraintStore', func)
    
    for func in ('__init__', 'delete','setName','setConditionState'):
      for clazz in ('ccp.nmr.NmrConstraint.CsaConstraintList',
                    'ccp.nmr.NmrConstraint.DihedralConstraintList',
                    'ccp.nmr.NmrConstraint.DistanceConstraintList',
                    'ccp.nmr.NmrConstraint.HBondConstraintList',
                    'ccp.nmr.NmrConstraint.JCouplingConstraintList',
                    'ccp.nmr.NmrConstraint.RdcConstraintList'):
        notifyFunc(self.updateConstraintListsAfter, clazz, func)
        
    for func in ('__init__', 'delete',):
      for clazz in ('ccp.nmr.NmrConstraint.CsaConstraint',
                    'ccp.nmr.NmrConstraint.DihedralConstraint',
                    'ccp.nmr.NmrConstraint.DistanceConstraint',
                    'ccp.nmr.NmrConstraint.HBondConstraint',
                    'ccp.nmr.NmrConstraint.JCouplingConstraint',
                    'ccp.nmr.NmrConstraint.RdcConstraint'):
        notifyFunc(self.updateConstraintsAfter, clazz, func)    
    
    for func in ('__init__', 'delete'):
      notifyFunc(self.updateShiftListsAfter,'ccp.nmr.Nmr.ShiftList', func)

    for func in ('__init__', 'delete'):
      notifyFunc(self.updateMolSystemsAfter,'ccp.molecule.MolSystem.MolSystem', func)

    for func in ('__init__', 'delete'):
      notifyFunc(self.updateChainsAfter,'ccp.molecule.MolSystem.Chain', func)

    for func in ('__init__', 'delete','setDynamicAlignment',
                 'setStaticAlignment','setName','setDetails'):
      notifyFunc(self.updateAlignMediaAfter,'ccp.nmr.NmrConstraint.ConditionState', func)

  def updateAlignMediaAfter(self, alignMedium):
  
     if alignMedium.nmrConstraintStore is self.constraintSet:
       self.after_idle(self.updateAlignMedia)
 
       if alignMedium is self.alignMedium:
         self.after_idle(self.updateTensors)

  def updateConstraintSetsAfter(self, constraintSet):
  
     self.after_idle(self.updateConstraintSets)

  def updateShiftListsAfter(self, shiftList):
  
     self.after_idle(self.updateShiftLists)

  def updateMolSystemsAfter(self, molSystem):
  
     self.after_idle(self.updateMolSystems)

  def updateChainsAfter(self, chain):
  
     self.after_idle(self.updateChains)
  
  def updateConstraintsAfter(self, constraint):
  
     if constraint.parent.parent is self.constraintSet:
       self.after_idle(self.updateConstraintLists)
  
  def updateConstraintListsAfter(self, constraintList):
  
     if constraintList.parent is self.constraintSet:
       self.after_idle(self.updateConstraintLists)
    
  def runMeccano(self):
    
    #
    #
    # Input checks first
    #
    #
  
    warning = ''
    if not self.molSystem:
      warning += 'No molecular system selected\n'
    
    if not self.chain:
      warning += 'No chain selected\n'
  
    if not self.constraintSet:
      warning += 'No selected constraint set\n'  
    else:
      constraintLists = [cl for cl in self.constraintSet.constraintLists if cl.useForMeccano]  
      if not constraintLists:
        warning += 'No constraint lists selected for use\n'   
 
    first, last = self.updateResidueRanges()
    if (last-first) < 2:
      warning += 'Too few peptide planes selected\n'         
  
    if warning:
      showWarning('Cannot run MECCANO','Encountered the following problems:\n' + warning)
      return
      
    if not self.run:
      self.run = self.makeSimRun()
      
    self.updateRunParams()
    
    if self.toggleCopyShifts.get() and self.shiftList:
      shiftList = self.run.findFirstOutputMeasurementList(className='ShiftList')
      
      if not shiftList:
        shiftList = self.project.currentNmrProject.newShiftList(name='Meccano Input')
        
      self.run.setOutputMeasurementLists([shiftList,])
    
      shiftDict = {}
      for shift in shiftList.shifts:
        shiftDict[shift.resonance] = shift
      
    
      for shift in self.shiftList.shifts:
        resonance = shift.resonance
        resonanceSet = resonance.resonanceSet
        
        if resonanceSet:
          atom = resonanceSet.findFirstAtomSet().findFirstAtom()
          
          if (atom.name == 'C') and (atom.residue.molResidue.molType == 'protein'):
            shift2 = shiftDict.get(resonance)
            if shift2:
              shift2.value = shift.value
              shift2.error = shift.error
              
            else:
              shiftList.newShift(resonance=resonance, value=shift.value, error=shift.error)  
    
    #
    #
    # Accumulate data from CCPN data model & GUI
    #
    #

    # Sequence

    residues = self.chain.sortedResidues()
    residueDict = {}
    
    seqData = []
    for residue in residues:
      molResidue = residue.molResidue
      
      code1Letter = molResidue.chemComp.code1Letter
      
      if not code1Letter:
        msg = 'Encountered non-standard residue type: %s'
        showWarning('Cannot run MECCANO', msg % residue.ccpCode)
        return
     
      seqCode = residue.seqCode
      seqData.append((seqCode, code1Letter))
      residueDict[seqCode] = residue.chemCompVar.chemComp.code3Letter

    # Media, RDCs & Dihedrals

    rdcLists = []
    dihedralLists = []

    for constraintList in constraintLists:
      if constraintList.className == 'RdcConsraintList':
        if constraintList.conditionState:
          rdcLists.append(constraintList)
      
      elif constraintList.className == 'DihedralConstraintList':
        dihedralLists.append(dihedralLists)
    
    f = PI_OVER_180  
    mediaData = []
    for constraintList in rdcLists:
      medium = constraintList.conditionState
      dynamicTensor = medium.dynamicAlignment
      staticTensor = medium.staticAlignment
    
      if not (dynamicTensor or staticTensor):
        continue
    
      if dynamicTensor:
        dynamicTensorData = ['Dynamic', dynamicTensor.aAxial, dynamicTensor.aRhombic,
                             f*dynamicTensor.alpha, f*dynamicTensor.beta, f*dynamicTensor.gamma]
   
      if staticTensor:
        staticTensorData = ['Static', staticTensor.aAxial, staticTensor.aRhombic,
                            f*staticTensor.alpha, f*staticTensor.beta, f*staticTensor.gamma]
      
      if not dynamicTensor:
        dynamicTensorData = staticTensorData
      
      elif not staticTensor:
        staticTensorData = dynamicTensorData
      
      rdcData = []
      for restraint in constraintList.constraints:
        items = list(restraint.items)
        
        if len(items) != 1:
          continue
          
        resonanceA, resonanceB = [fr.resonance for fr in items[0].resonances] 
        
        resonanceSetA = resonanceA.resonanceSet
        if not resonanceSetA:
          continue
        
        resonanceSetB = resonanceB.resonanceSet
        if not resonanceSetB:
          continue
        
        resNameA = getResonanceName(resonanceA)
        resNameB = getResonanceName(resonanceB)
          
        residueA = resonanceSetA.findFirstAtomSet().findFirstAtom().residue  
        residueB = resonanceSetB.findFirstAtomSet().findFirstAtom().residue  
        
        seqA = residueA.seqCode
        seqB = residueB.seqCode
        
        value = restraint.targetValue
        error = restraint.error
        
        if error is None:
          key = [resNameA,resNameB]
          key.sort()
          sigma = DEFAULT_ERRORS.get(tuple(key), 1.0)
        
        rdcData.append([seqA, resNameA, seqB, resNameB, value, error])
      
      mediaData.append((dynamicTensorData,staticTensorData,rdcData))
      
    oneTurn = 360.0
    dihedralDict = {}
    for constraintList in dihedralLists:
      for restraint in constraintList.constraints:
        items = list(restraint.items)
        
        if len(items) != 1:
          continue
        
        item = items[0]
        resonances = [fr.resonance for fr in item.resonances] 
        
        resonanceSets = [r.resonanceSet for r in resonances]
        
        if None in resonanceSets:
          continue
          
        atoms = [rs.findFirstAtomSet().findFirstAtom() for rs in resonanceSets]  
    
        atomNames = [a.name for a in atoms]
        
        if atomNames == PHI_ATOM_NAMES:
          isPhi = True
        elif atomNames == PSI_ATOM_NAMES:
          isPhi = False
        else:
          continue
    
        residue = atoms[2].residue
        
        if residue.chain is not self.chain:
          continue
        
        if isPhi:
          residuePrev = getLinkedResidue(residue, linkCode='prev')
          
          if not residuePrev:
            continue
            
          atomC0 = residuePrev.findFirstAtom(name='C')
          atomN  = residue.findFirstAtom(name='N')
          atomCa = residue.findFirstAtom(name='CA')
          atomC  = residue.findFirstAtom(name='C')
          atoms2 = [atomC0, atomN, atomCa, atomC]
          
        else:
          residueNext = getLinkedResidue(residue, linkCode='next')
          
          if not residueNext:
            continue
          
          atomN  = residue.findFirstAtom(name='N')
          atomCa = residue.findFirstAtom(name='CA')
          atomC  = residue.findFirstAtom(name='C')
          atomN2 = residueNext.findFirstAtom(name='N')
          atoms2 = [atomN, atomCa, atomC, atomN2]
          
        if atoms != atoms2:
          continue
        
        value = item.targetValue
        error = item.error
        
        if error is None:
          upper = item.upperLimit
          lower = item.lowerLimit
          
          if (upper is not None) and (lower is not None):
            dUpper = angleDifference(value, lower, oneTurn)
            dLower = angleDifference(upper, value, oneTurn)
            error  = max(dUpper, dLower)
            
          elif lower is not None:
            error = angleDifference(value, lower, oneTurn)
            
          elif upper is not None:
            error = angleDifference(upper, value, oneTurn)
            
          else:
            error = 30.0 # Arbitrary, but sensible for TALOS, DANGLE
        
        seqCode = residue.seqCode
        if not dihedralDict.has_key(seqCode):
          dihedralDict[seqCode] = [None, None, None, None] # Phi, Psi, PhiErr, PsiErr
        
        if isPhi:
          dihedralDict[seqCode][0] = value
          dihedralDict[seqCode][2] = error
        else:
          dihedralDict[seqCode][1] = value
          dihedralDict[seqCode][3] = error
          
          
    phipsiData = []
    seqCodes = dihedralDict.keys()
    seqCodes.sort()
    
    for seqCode in seqCodes:
      data = dihedralDict[seqCode]
      
      if None not in data:
        phi, psi, phiErr, psiErr = data
        phipsiData.append((seqCode, phi, psi, phiErr, psiErr))
        
    
    # User options
    
    firstPPlaneFrag = self.firstResEntry.get() or 1
    lastPPlaneFrag  = self.lastResEntry.get() or 1
    ppNbMin         = self.numOptPlaneEntry.get() or 1
    minValueBest    = self.numOptHitsEntry.get() or 2
    maxValueBest    = self.maxOptStepEntry.get() or 5

    strucData = Meccano.runFwd(firstPPlaneFrag, lastPPlaneFrag, ppNbMin,
                               minValueBest, maxValueBest, RAMACHANDRAN_DATABASE,
                               seqData, mediaData, phipsiData)
   
    if strucData:
      fileName = 'CcpnMeccanoPdb%f.pdb' % time.time()
      fileObj = open(fileName, 'w')
 
      ch = self.chain.pdbOneLetterCode.strip()
      if not ch:
        ch = self.chain.code[0].upper()
 
        i = 1
        for atomType, resNb, x, y, z in strucData:
          resType = residueDict.get(resNb, '???')
          line = PDB_FORMAT % ('ATOM',i,'%-3s' % atomType,'',resType,ch,resNb,'',x,y,z,1.0,1.0)
 
          i += 1

      fileObj.close()
      
      ensemble = getStructureFromFile(self.molSystem, fileName)
      
      
      if not self.toggleWritePdbFile.get():
        os.unlink(fileName)
         
      self.run.outputEnsemble = ensemble
      self.run = None
    
    self.updateRuns()

  def getMediumName(self, alignMedium):
  
    self.mediumNameEntry.set(alignMedium.name)
    
  def getMediumDetails(self, alignMedium):
  
    self.mediumDetailsEntry.set(alignMedium.details)
    
  def setMediumName(self, event): 

    value = self.mediumNameEntry.get()
    self.alignMedium.name = value or None
    
  def setMediumDetails(self, event): 

    value = self.mediumDetailsEntry.get()
    self.alignMedium.details = value or None
      
  def setAlignMedium(self, alignMedium):

    if self.constraintSet:
      self.constraintSet.conditionState = alignMedium
    
  def getAlignMedium(self, constraintList):

    media = self.getAlignmentMedia()
    names = [am.name for am in media]
    
    if constraintList.conditionState in media:
      index = media.index(constraintList.conditionState)
    else:
      index = 0
  
    self.alignMediumPulldown.setup(names, media, index)

  def toggleUseRestraints(self, constraintList):
 
    bool = constraintList.useForMeccano
    bool = not bool
 
    if bool and (not constraintList.conditionState) \
     and (constraintList.className == 'RdcConsraintList'):
      msg = 'Cannot use RDC restraint list for Meccano '
      msg += 'unless it is first associated with an amigment medium'
      showWarning('Warning', msg, parent=self)
    else:
      constraintList.useForMeccano = bool
      
    self.updateConstraintLists()
 
  def addStaticTensor(self):
  
    if self.alignMedium:
      tensor = Implementation.SymmTracelessMatrix(aAxial=0.0,aRhombic=0.0,
                                                  alpha=0.0,beta=0.0,
                                                  gamma=0.0)
      

      self.alignMedium.staticAlignment = tensor
 
      self.updateAlignMediaAfter(self.alignMedium)
 
  def addDynamicTensor(self):
  
    if self.alignMedium:
      tensor = Implementation.SymmTracelessMatrix(aAxial=0.0,aRhombic=0.0,
                                                  alpha=0.0,beta=0.0,
                                                  gamma=0.0)
      self.alignMedium.dynamicAlignment = tensor
      
      self.updateAlignMediaAfter(self.alignMedium)
  
  def removeTensor(self):
  
    if self.alignMedium and self.tensor:
      if self.tensor is self.alignMedium.dynamicAlignment:
        self.alignMedium.dynamicAlignment = None
        
      elif self.tensor is self.alignMedium.staticAlignment:
        self.alignMedium.staticAlignment = None
      
      self.updateAlignMediaAfter(self.alignMedium)
        
  def addAlignMedium(self):
  
    if self.constraintSet:
      medium = self.constraintSet.newConditionState()
      medium.name = 'Align Medium %d' % medium.serial   
  
  def removeAlignMedium(self):

    if self.alignMedium:
      self.alignMedium.delete()

  def updateTensor(self, aAxial=None, aRhombic=None, alpha=None, beta=None, gamma=None):
  
    aAxial   = aAxial   or self.tensor.aAxial
    aRhombic = aRhombic or self.tensor.aRhombic
    alpha    = alpha    or self.tensor.alpha
    beta     = beta     or self.tensor.beta
    gamma    = gamma    or self.tensor.gamma
    
    tensor = Implementation.SymmTracelessMatrix(aAxial=aAxial,
                                                aRhombic=aRhombic,
                                                alpha=alpha,beta=beta,
                                                gamma=gamma)
 
    if self.alignMedium:
      if self.tensor is self.alignMedium.dynamicAlignment:
        self.alignMedium.dynamicAlignment = tensor
        
      elif self.tensor is self.alignMedium.staticAlignment:
        self.alignMedium.staticAlignment = tensor
 
    self.tensor = tensor
 
  def setAxial(self, event): 
  
    value = self.editAxialEntry.get()
    self.updateTensor(aAxial=value)
    self.updateTensors()
    
  def setRhombic(self,  event): 
  
    value = self.editRhombicEntry.get()
    self.updateTensor(aRhombic=value)
    self.updateTensors()
   
  def setEulerAlpha(self,  event): 
  
    value = self.editAlphaEulerEntry.get()
    self.updateTensor(alpha=value)
    self.updateTensors()
    
  def setEulerBeta(self,  event): 
  
    value = self.editBetaEulerEntry.get()
    self.updateTensor(beta=value)
    self.updateTensors()
    
  def setEulerGamma(self,  event): 
  
    value = self.editGammaEulerEntry.get()
    self.updateTensor(gamma=value)
    self.updateTensors()

  def getAxial(self, tensor): 
  
    value = tensor.aAxial
    self.editAxialEntry.set(value)
     
  def getRhombic(self, tensor): 
  
    value = tensor.aRhombic
    self.editRhombicEntry.set(value)
     
  def getEulerAlpha(self, tensor): 
  
    value = tensor.alpha
    self.editAlphaEulerEntry.set(value)
     
  def getEulerBeta(self, tensor): 
  
    value = tensor.beta
    self.editBetaEulerEntry.set(value)
     
  def getEulerGamma(self, tensor): 
  
    value = tensor.gamma
    self.editGammaEulerEntry.set(value)
 
  def selectTensor(self, tensor, row, col):
  
    self.tensor = tensor
 
  def selectAlignMedium(self, alignMedium, row, col):
  
    self.alignMedium = alignMedium
    self.updateTensors()
 
  def getAlignmentMedia(self):
  
    if self.constraintSet:
      return self.constraintSet.sortedConditionStates()
    else:
      return []
 
  def updateAlignMedia(self):

    textMatrix = []
    objectList = []
    
    if self.constraintSet:
      objectList = self.getAlignmentMedia()
        
      for conditionState in objectList:
         
         staticTensor = None
         dyamicTensor = None
         tensor = conditionState.dynamicAlignment
         if tensor:
           vals = (tensor.aAxial, tensor.aRhombic, tensor.alpha, tensor.beta, tensor.gamma)
           dyamicTensor = u'\u03B6:%.3f \u03B7:%.3f \u03B1:%.3f \u03B2:%.3f \u03B3:%.3f ' % vals

         tensor = conditionState.staticAlignment
         if tensor:
           vals = (tensor.aAxial, tensor.aRhombic, tensor.alpha, tensor.beta, tensor.gamma)
           staticTensor = u'\u03B6:%.3f \u03B7:%.3f \u03B1:%.3f \u03B2:%.3f \u03B3:%.3f ' % vals
           
         datum = [conditionState.serial,
                  conditionState.name,
                  conditionState.details,
                  dyamicTensor,
                  staticTensor]
         textMatrix.append(datum)

         if dyamicTensor or staticTensor:
           if not self.alignMedium:
             self.alignMedium = conditionState
   
    self.mediaMatrix.update(textMatrix=textMatrix, objectList=objectList)
      
    if self.alignMedium:
      self.mediaMatrix.selectObject(self.alignMedium)
 
  def updateTensors(self):
    
    textMatrix = []
    objectList = []
    conditionState = self.alignMedium
    
    if conditionState:
    
      tensor = conditionState.dynamicAlignment
      if tensor:
        datum = ['Dynamic', tensor.aAxial, tensor.aRhombic,
                 tensor.alpha, tensor.beta, tensor.gamma]
        textMatrix.append(datum)
        objectList.append(tensor)
      
      tensor = conditionState.staticAlignment
      if tensor:
        datum = ['Static', tensor.aAxial, tensor.aRhombic,
                 tensor.alpha, tensor.beta, tensor.gamma]
        textMatrix.append(datum)
        objectList.append(tensor)

    self.tensorMatrix.update(textMatrix=textMatrix, objectList=objectList)  
 
  def getMolSystems(self):
  
    molSystems = []
    
    for molSystem in self.project.sortedMolSystems():
      if molSystem.chains:
        molSystems.append(molSystem)
        
    return molSystems    
     
     
  def updateMolSystems(self, *notifyObj):
  
    index = 0
    names = []
    
    molSystems = self.getMolSystems()
    molSystem = self.molSystem
    
    if molSystems:
      if molSystem not in molSystems:
        molSystem = molSystems[0]
      
      index = molSystems.index(molSystem)
      names = [ms.code for ms in molSystems] 
    
    else:
      self.molSystem = None
    
    if self.molSystem is not molSystem:
      if self.run:
        self.run.molSystem = molSystem
        
      self.molSystem = molSystem
      self.updateChains()
    
    self.molSystemPulldown.setup(texts=names, objects=molSystems, index=index)
    
  
  def selectMolSystem(self, molSystem):
  
    if self.molSystem is not molSystem:
      if self.run:
        self.run.molSystem = molSystem
        
      self.molSystem = molSystem
      self.updateChains()
     
     
  def updateChains(self, *notifyObj):
  
    index = 0
    names = []
    chains = []
    chain = self.chain
    
    if self.molSystem:
      chains = [c for c in self.molSystem.sortedChains() if c.residues]
    
    if chains: 
      if chain not in chains:
        chain = chains[0]
        
      index = chains.index(chain)
      names = [c.code for c in chains]
    
    if chain is not self.chain:
      self.chain = chain
      self.updateResidueRanges()
    
    self.chainPulldown.setup(texts=names, objects=chains, index=index)
     
  def selectChain(self, chain):
  
    if chain is not self.chain:
      self.chain = chain
      self.updateResidueRanges()

  def updateResidueRanges(self):
  
    first = self.firstResEntry.get()
    last = self.lastResEntry.get()
    
    if self.chain:
      residues = self.chain.sortedResidues()
      firstSeq = residues[0].seqCode
      lastSeq = residues[-2].seqCode
      
      if first < firstSeq:
        first = firstSeq
     
      if last == first:
        last = lastSeq
      
      elif last > lastSeq:
        last = lastSeq
        
      if first > last:
        last, first = first, last    
      
  
    self.firstResEntry.set(first)
    self.lastResEntry.set(last)
 
    return first, last

  def getConstraintSets(self):
  
    constraintSets = []
    nmrProject = self.project.currentNmrProject
    
    for constraintSet in nmrProject.sortedNmrConstraintStores():
      for constraintList in constraintSet.constraintLists:
        if constraintList.className not in ('ChemShiftConstraintList','somethingElse'):
          constraintSets.append(constraintSet)
          break
    
    return constraintSets
  
  def updateConstraintSets(self, *notifyObj):

    index = 0
    names = []
    constraintSets = self.getConstraintSets()
    constraintSet = self.constraintSet

    if constraintSets:
      if constraintSet not in constraintSets:
        constraintSet = constraintSets[0]
        
      index = constraintSets.index(constraintSet)
      names = ['%d' % cs.serial for cs in constraintSets]
    
    if constraintSet is not self.constraintSet:
      if self.run:
        self.run.inputConstraintStore = constraintSet
    
      self.constraintSet = constraintSet
      self.updateConstraintLists()    
    
    self.constraintSetPulldown.setup(texts=names, objects=constraintSets, index=index)

  def selectConstraintSet(self, constraintSet):
  
    if self.constraintSet is not constraintSet:
      if self.run:
        self.run.inputConstraintStore = constraintSet
        
      self.constraintSet = constraintSet
      self.updateConstraintLists() 
  
  def getConstraintLists(self):
  
    constraintLists = []
    if self.constraintSet:
      for constraintList in self.constraintSet.sortedConstraintLists():
        if constraintList.className not in ('ChemShiftConstraintList','somethingElse'):
          constraintLists.append(constraintList)
  
    return constraintLists
    
  def updateConstraintLists(self, *notifyObj):
  
    textMatrix = []
    objectList = self.getConstraintLists()
    
    for constraintList in objectList:
      if not hasattr(constraintList, 'useForMeccano'):
        if constraintList.conditionState \
         or (constraintList.className != 'RdcConstraintList'):
          bool = True
        else:
          bool = False  
      
        constraintList.useForMeccano = bool
    
      if constraintList.conditionState:
        alignMedium = constraintList.conditionState.name
      else:
        alignMedium = None
    
      datum = [constraintList.serial,
               constraintList.className[:-14],
               constraintList.useForMeccano and 'Yes' or 'No',
               alignMedium,
               len(constraintList.constraints)]
  
      textMatrix.append(datum)
  
    self.restraintMatrix.update(textMatrix=textMatrix, objectList=objectList)
  
  def selectConstraint(self, obj, row, column):
  
    if self.constraint is not obj:
      self.constraint = obj

  def getSimStore(self):
  
    simStore = self.project.findFirstNmrSimStore(name='meccano')
    if not simStore:
      simStore = self.project.newNmrSimStore(name='meccano')
    
    return simStore

  def getRuns(self):
  
    runs = [None, ]
    
    if self.molSystem and self.constraintSet:
      simStore = self.getSimStore()
      runs += simStore.sortedRuns()
    
    return runs
  
  def updateRuns(self, *notifyObj):
  
    index = 0
    names = ['<New>']
    runs = self.getRuns()
    run = self.run

    if runs:
      if run not in runs:
        run = runs[0]
    
      index = runs.index(run)
      names += [r.serial for r in runs if r]
    
    if run is not self.run:
      self.updateConstraintSets()
      self.updateMolSystems()
      self.updateShiftLists()
    
    self.runPulldown.setup(names, runs, index)
  
  def updateRunParams(self, event=None):
  
    if self.run and self.molSystem and self.constraintSet:
      simRun = self.run
      
      simRun.inputConstraintStore = self.constraintSet
      simRun.molSystem = self.molSystem
      
      if self.shiftList:
        simRun.setInputMeasurementLists([self.shiftList,])                 

      simRun.newRunParameter(code='FirstPepPlane',id=1, 
                             intValue=self.firstResEntry.get() or 0)
      simRun.newRunParameter(code='LastPepPlane' ,id=1, 
                             intValue=self.lastResEntry.get() or 0)
      simRun.newRunParameter(code='MaxOptSteps',  id=1, 
                             intValue=self.maxOptStepEntry.get() or 0)
      simRun.newRunParameter(code='NumOptPlanes', id=1, 
                             intValue=self.numOptPlaneEntry.get() or 0)
      simRun.newRunParameter(code='MinOptHits',   id=1, 
                             intValue=self.numOptHitsEntry.get() or 0)
  
  def makeSimRun(self, template=None):

    simStore = self.getSimStore()
   
    if template:
      molSystem = template.molSystem
      constraintSet = template.inputConstraintStore
      shiftList = template.findFirstInputMeasurementList(className='ShiftList')
      protocol = template.annealProtocol
    else:
      molSystem = self.molSystem
      constraintSet = self.constraintSet
      shiftList = self.shiftList
      protocol = self.annealProtocol
    
    simRun = simStore.newRun(annealProtocol=protocol,
                             molSystem=molSystem,
                             inputConstraintStore=protocol)
    
    if shiftList:
      simRun.addInputMeasurementList(shiftList)                 
    
    if template:
      for param in template.runParameters:
        simRun.newRunParameter(code=param.code,
                               id=param.id,
                               booleanValue=param.booleanValue,
                               floatValue=param.floatValue,
                               intValue=param.intValue,
                               textValue=param.textValue)
    else:
       if self.chain:
         chainCode = self.chain.code
       else:
         chaincode = 'A'
    
       simRun.newRunParameter(code='FirstPepPlane',id=1, 
                              intValue=self.firstResEntry.get() or 0)
       simRun.newRunParameter(code='LastPepPlane' ,id=1, 
                              intValue=self.lastResEntry.get() or 0)
       simRun.newRunParameter(code='MaxOptSteps',  id=1, 
                              intValue=self.maxOptStepEntry.get() or 0)
       simRun.newRunParameter(code='NumOptPlanes', id=1, 
                              intValue=self.numOptPlaneEntry.get() or 0)
       simRun.newRunParameter(code='MinOptHits',   id=1, 
                              intValue=self.numOptHitsEntry.get() or 0)
       simRun.newRunParameter(code='ChainCode',    id=1,
                              textValue=chainCode)

    return simRun
 
  def selectRun(self, simRun):
  
    if self.run is not simRun:
      if simRun:
        if simRun.outputEnsemble:
          msg  = 'Selected run has already been used to generate a structure.'
          msg += 'A new run will be setup based on the selection.'
          showWarning('Warning',msg)
          simRun = self.makeSimRun(template=simRun)
 
        molSystem = simRun.molSystem
        constraintSet = simRun.inputConstraintStore
        shiftList = simRun.findFirstInputMeasurementList(className='ShiftList')
 
        if molSystem and (self.molSystem is not molSystem):
          self.molSystem = molSystem
          self.updateMolSystems()
 
        if constraintSet and (self.constraintSet is not constraintSet):
          self.constraintSet = constraintSet
          self.updateConstraintSets()
    
        if shiftList and (self.shiftList is not shiftList): 
          self.shiftList = shiftList
          self.updateShiftLists()
        
        firstPepPlane = simRun.findFirstrunParameter(code='FirstPepPlane')
        lastPepPlane = simRun.findFirstrunParameter(code='LastPepPlane')
        maxOptSteps = simRun.findFirstrunParameter(code='MaxOptSteps')
        numOptPlanes = simRun.findFirstrunParameter(code='NumOptPlanes')
        minOptHits = simRun.findFirstrunParameter(code='MinOptHits')
        chainCode = simRun.findFirstrunParameter(code='ChainCode')

        
        if firstPepPlane is not None:
          self.firstResEntry.set(firstPepPlane.intValue or 0)
        
        if lastPepPlane is not None:
          self.lastResEntry.set(lastPepPlane.intValue or 0)
          
        if maxOptSteps is not None:
          self.maxOptStepEntry.set(maxOptSteps.intValue or 0)
            
        if numOptPlanes is not None:
          self.numOptPlaneEntry.set(numOptPlanes.intValue or 0)
          
        if minOptHits is not None:
          self.numOptHitsEntry.set(minOptHits.intValue or 0)
           
        if chainCode is not None:
          chainCode = chainCode.textValue or 'A'
          if self.molSystem:
            chain = self.molSystem.findFirsChain(code=chainCode)
 
            if chain:
              self.selectChain(chain) 
                 
      self.run = simRun

  def updateShiftLists(self, *notifyObj):
    
    index = 0
    names = []
    nmrProject = self.project.currentNmrProject
    
    shiftLists = nmrProject.findAllMeasurementLists(className='ShiftList')
    shiftLists = [(sl.serial, sl) for sl in shiftLists]
    shiftLists.sort()
    shiftLists = [x[1] for x in shiftLists]
    
    shiftList = self.shiftList

    if shiftLists:
      if shiftList not in shiftLists:
        shiftList = shiftLists[0]
    
      index = shiftLists.index(shiftList)
      names = ['%d'% sl.serial for sl in shiftLists]
    
    if shiftList is not self.shiftList:
      if self.run:
        self.run.setInputMeasurementLists([shiftList])
  
    self.shiftListPulldown.setup(texts=names, objects=shiftLists, index=index)

  def selectShiftList(self, shiftList):
  
    if shiftList is not self.shiftList:
      if self.run:
        self.run.setInputMeasurementLists([shiftList])
      
      self.shiftList = shiftList                   
Example #24
0
class EditPeakFindParamsPopup(BasePopup):
    """
  ** Peak Settings and Non-Interactive Peak Finding **
  
  The purpose of this dialog is to allow the user to select settings for
  finding and integrating peaks, and also to be able to find peaks in an
  arbitrary region that is specified in a table rather than via a spectrum
  window.
  
  ** Find Parameters tab **

  This can be used to specify how peak finding works.

  First of all, you can search for just positive peaks, just negative
  peaks or both, and the default is that it is just positive peaks.
  However, this is further filtered by what the contour levels are.
  If there are no positive contour levels for a given spectrum then
  positive peaks are not found even if this dialog says they can be,
  and similarly if there are no negative contour levels for a given
  spectrum then negative peaks are not found even if this dialog says
  they can be.

  The peak finding algorithm looks for local extrema (maximum for
  positive peaks and minima for negative peaks).  But on a grid there
  are various ways to define what you mean by an extremum.  Suppose
  you are trying to determine if point p is a maximum (similar
  considerations apply for minimum).  You would want the intensity
  at all nearby points to be less than or equal to the intensity at p.
  You can just check points that are just +- one point from p in each
  dimension, or you can also check "diagonal" points.  For
  example, if you are looking at point p = (x, y) in 2D, then the
  former would mean checking the four points (x-1, y), (x+1, y)
  (x, y-1) and (x, y+1), whereas for the latter you would also have
  to check (x-1, y-1), (x-1, y+1), (x+1, y-1) and (x+1, y+1).  In
  N dimensions the "diagonal" method involves checking 3^N-1 points
  whereas the "non-diagonal" method involves checking only 2N points.
  In general the "non-diagonal" method is probably the one to use,
  and it is the default.

  Peaks are only found above (for positive peaks) or below (for negative
  peaks) some threshold.  By default this is determined by the contour level
  for the spectrum.  For positive peaks the threshold is the minimum
  positive contour level, and for negative peaks the threshold is the
  maximum negative contour level.  However these levels can be scaled up
  (or down) using the "Scale relative to contour levels" option (default
  value 1).  For example, if you have drawn the contour levels low to
  show a bit of noise, but do not want the noise picked as peaks, then
  you could select a scale of 2 (or whatever) to increase the threshold.

  The "Exclusion buffer around peaks" is so that in crowded regions you
  do not get too many peaks near one location.  By default the exclusion
  buffer is 1 point in each dimension, but this can be increased to make
  the algorithm find fewer peaks.

  By default the peak finding only looks at the orthogonal region that
  is displayed in the given window where peak finding is taking place.
  Sometimes it looks like a peak should be found because in x, y you
  can see an extremum, but unless it is also an extremum in the orthogonal
  dimensions it is not picked.  You can widen out the points being
  examined in the orthogonal dimensions by using the "Extra thickness in
  orthogonal dims" option, which is specified in points.

  The "Minimum drop factor" is by what factor the intensity needs to drop
  from its extreme value for there to be considered to be a peak.  This
  could help remove sinc wiggle peaks, for example.  The default is that
  the drop factor is 0, which in effect means that there is no condition.

  The "Volume method" is what is used to estimate the volume of peaks that
  are found.  The default is "box sum", which just looks at a fixed size
  box around the peak centre and sums the intensities in that.  The size
  of the box is set in the table in the Spectrum Widths tab.  The
  "truncated box sum" is the same as "box sum" except that the summing
  stops in a given direction when (if) the intensities start increasing.
  The "parabolic" fit fits a quadratic equation in each dimension to the
  intensity at the peak centre and ad +- 1 points and then uses the
  equivalent Gaussian fit to estimate the volume.

  ** Spectrum Widths **

  This can be used to specify minimum linewidths (in Hz) for there to be
  considered a peak to exist in the peak finding algorithm.  It is also
  where the Boxwidth for each dimension in each spectrum is specified.

  ** Diagonal Exclusions **

  This can be used to exclude peaks from being found in regions near
  the diagonal (so in homonuclear experiments).  The exclusion region
  is specified in ppm and is independent of spectrum.

  ** Region Peak Find **

  This can be used to find peaks non-interactively (so not having to
  control shift drag inside a spectrum window).  The region being
  analysed is specified in the table.  There are two types of conditions
  that can be specified, "include" for regions that should be included
  and "exclude" for regions that should be excluded.  The regions are
  specified in ppm.

  The "Whole Region" button will set the selected row in the table to be
  the entire fundamental region of the spectrum.

  The "Add Region" button adds an extra row to the table, and the "Delete
  Region" button removes the selected row.

  The "Adjust Params" button goes to the Find Parameters tab.

  The "Find Peaks!" button does the peak finding.

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

        self.spectrum = None

        BasePopup.__init__(self,
                           parent=parent,
                           title='Peak : Peak Finding',
                           **kw)

    def body(self, guiFrame):

        self.geometry('600x350')

        guiFrame.expandGrid(0, 0)

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

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

        # Find Params

        frameA.expandGrid(2, 0)

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

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

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

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

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

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

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

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

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

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

        # Spectrum widths

        frameB.expandGrid(1, 1)

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

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

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

        # Diagonal Exclusions

        frameC.expandGrid(0, 0)

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

        # Region peak find

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

        row = 0

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

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

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

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

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

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

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

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

        self.administerNotifiers(self.registerNotify)

    def administerNotifiers(self, notifyFunc):

        # Many more needed here, esp on the AnalysisProject prams

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

        for func in ('__init__', 'delete'):
            notifyFunc(self.updateRegionPeakLists, 'ccp.nmr.Nmr.PeakList',
                       func)

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

        for func in ('setPeakFindBoxWidth', 'setPeakFindMinLineWidth'):
            notifyFunc(self.updateSpectrumTable,
                       'ccpnmr.Analysis.AnalysisDataDim', func)

    def destroy(self):

        self.administerNotifiers(self.unregisterNotify)
        BasePopup.destroy(self)

    def updateSpectrum(self, spectrum=None):

        if not spectrum:
            spectrum = self.spectrum

        spectra = self.parent.getSpectra()
        if spectra:
            if spectrum not in spectra:
                spectrum = spectra[0]
            index = spectra.index(spectrum)
            names = ['%s:%s' % (x.experiment.name, x.name) for x in spectra]
        else:
            index = 0
            names = []

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

        self.setSpectrumProperties(spectrum)

    def updateNotifier(self, *extra):

        self.updateSpectrum()

    def setLinewidth(self, *event):

        value = self.editLinewidthEntry.get()
        if value is not None:
            PeakFindParams.setPeakFindMinLinewidth(self.dataDim, value)
            self.setSpectrumProperties(self.dataDim.dataSource)

    def getLinewidth(self, dataDim):

        if dataDim:
            self.editLinewidthEntry.set(
                PeakFindParams.getPeakFindMinLinewidth(self.dataDim))

    def setBoxwidth(self, *event):

        value = self.editBoxwidthEntry.get()
        if value is not None:
            PeakFindParams.setPeakFindBoxwidth(self.dataDim, value)
            self.setSpectrumProperties(self.dataDim.dataSource)

    def getBoxwidth(self, dataDim):

        if dataDim:
            self.editBoxwidthEntry.set(
                PeakFindParams.getPeakFindBoxwidth(self.dataDim))

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

        self.dataDim = object

    def setExclusion(self, *extra):

        isotope = self.isotopeMatrix.currentObject
        if not isotope:
            return

        value = self.exclusionEntry.get()
        if value is not None:
            setIsotopeExclusion(isotope, value)
            self.setIsotopeProperties()

    def getExclusion(self, isotope):

        value = getIsotopeExclusion(isotope)
        self.exclusionEntry.set(value)

    def setParamsEntries(self):

        project = self.project
        params = PeakFindParams.getPeakFindParams(project)

        self.scale_entry.set(params['scale'])
        self.buffer_entry.set(params['buffer'])
        self.thickness_entry.set(params['thickness'])
        self.drop_entry.set(params['drop'])
        volumeMethod = params['volumeMethod']
        if volumeMethod == 'parabolic fit':
            volumeMethod = PeakBasic.PEAK_VOLUME_METHODS[0]
        self.method_menu.set(params['volumeMethod'])

        if (params['nonadjacent']):
            n = 1
        else:
            n = 0
        self.adjacent_buttons.setIndex(n)

        have_high = params['haveHigh']
        have_low = params['haveLow']
        if (have_high and have_low):
            n = 0
        elif (have_high):
            n = 1
        else:
            n = 2
        self.extrema_buttons.setIndex(n)

    def apply(self, *extra):

        params = {}
        params['scale'] = self.scale_entry.get()
        params['buffer'] = self.buffer_entry.get()
        params['thickness'] = self.thickness_entry.get()
        params['drop'] = self.drop_entry.get()
        params['volumeMethod'] = self.method_menu.getText()

        n = self.adjacent_buttons.getIndex()
        if (n == 0):
            nonadjacent = False
        else:
            nonadjacent = True
        params['nonadjacent'] = nonadjacent

        n = self.extrema_buttons.getIndex()
        if (n == 0):
            have_high = True
            have_low = True
        elif (n == 1):
            have_high = True
            have_low = False
        elif (n == 2):
            have_high = False
            have_low = True
        params['haveHigh'] = have_high
        params['haveLow'] = have_low

        project = self.project
        try:
            PeakFindParams.setPeakFindParams(project, params)
        except Implementation.ApiError, e:
            showError('Parameter error', e.error_msg, parent=self)
    def body(self):
        '''Describes the body of this tab. It consists
           out of a number of radio buttons, check buttons
           and number entries that allow the user to
           indicate which assignments should be transferred.
        '''

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

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

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

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

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

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

        row = 0

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

        row += 1

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

        row = 0

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

        row += 1

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

        row += 1

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

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

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

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

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

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

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

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

        texts = ['Transfer Assignments']
        commands = [self.transferAssignments]
        self.transferButton = ButtonList(self.frame,
                                         commands=commands,
                                         texts=texts)
        self.transferButton.grid(row=5, column=0, sticky='nsew', columnspan=2)
    def 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')
Example #27
0
    def body(self, guiFrame):

        self.geometry('600x350')

        guiFrame.expandGrid(0, 0)

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

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

        # Find Params

        frameA.expandGrid(2, 0)

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

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

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

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

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

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

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

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

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

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

        # Spectrum widths

        frameB.expandGrid(1, 1)

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

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

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

        # Diagonal Exclusions

        frameC.expandGrid(0, 0)

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

        # Region peak find

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

        row = 0

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

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

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

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

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

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

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

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

        self.administerNotifiers(self.registerNotify)
Example #28
0
class EditSymmetryPopup(BasePopup):

    def __init__(self, parent, project):

        self.parent         = parent
        self.ccpnProject    = project
        self.hProject        = project.currentHaddockProject
        self.molPartner     = None
        self.molecules      = []
        self.symmetrySet    = None
        self.symmetryOp     = None
        self.symmetryCode    = None
        self.waiting        = False

        BasePopup.__init__(self, parent=parent, title='Symmetry Operations')

        self.font = 'Helvetica 12'
        self.setFont()

    def body(self, guiFrame):

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

        frame = LabelFrame(guiFrame, text='Options')
        frame.grid(row=0,column=0,sticky='ew')
        frame.grid_columnconfigure(5, weight=1)

        # Choose type of symmetry set to define or change (if allready present in the model)
        self.molLabel = Label(frame, text='Symmetry Operator:')
        self.molLabel.grid(row=0,column=2,sticky='w')
        self.symmCodePulldown = PulldownMenu(frame, callback=self.setSymmCode, entries=['NCS','C2','C3','C5'], do_initial_callback=False)
        self.symmCodePulldown.grid(row=0,column=3,sticky='w')

        frame = LabelFrame(guiFrame, text='Symmetry Operations')
        frame.grid(row=1,column=0,sticky='nsew')
        frame.grid_columnconfigure(0, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        self.molSysPulldown   = PulldownMenu(self, callback=self.setMolSystem, do_initial_callback=False)
        self.chainSelect      = MultiWidget(self, CheckButton, callback=self.setChains, minRows=0, useImages=False)
        self.segStartEntry    = IntEntry(self, returnCallback=self.setSegStart, width=6)
        self.segLengthEntry   = IntEntry(self, returnCallback=self.setSegLength, width=6)

        headings = ['#','Symmetry\noperator','Mol System','Chains','Start\nresidue','Segment\nlength']  
        editWidgets      = [None, None, self.molSysPulldown, self.chainSelect, self.segStartEntry, self.segLengthEntry] 
        editGetCallbacks = [None, None, self.getMolSystem, self.getChains, self.getSegStart, self.getSegLength]
        editSetCallbacks = [None, self.setSymmCode, self.setMolSystem, self.setChains, self.setSegStart, self.setSegLength]
        
        self.symmetryMatrix = ScrolledMatrix(frame,headingList=headings,
                                             callback=self.selectSymmetry,
                                             editWidgets=editWidgets,
                                             editGetCallbacks=editGetCallbacks,
                                             editSetCallbacks=editSetCallbacks)
        self.symmetryMatrix.grid(row=0,column=0,sticky='nsew')

        texts = ['Add Symmetry Set','Remove Symmetry Set']
        commands = [self.addSymmetrySet,self.removeSymmetrySet]
        self.buttonList = createDismissHelpButtonList(guiFrame, texts=texts, commands=commands, expands=True)
        self.buttonList.grid(row=2,column=0,sticky='ew')
        
        self.updateMolPartners()
        self.notify(self.registerNotify)

        #Temporary report of parameters
        print self.molSystem
        print self.molecules
        print self.symmetrySet
        print self.symmetryOp
        print self.symmetryCode

    def getMolSystem(self, partner):

        """Select molecular system from list of molsystems stored in the project"""

        names = []; index = -1
        molSystem = partner.molSystem
        molSystems = self.ccpnProject.sortedMolSystems()
        if molSystems:
            names = [ms.code for ms in molSystems]
            if molSystem not in molSystems: 
                molSystem = molSystems[0]
                index = molSystems.index(molSystem)

        self.molSysPulldown.setup(names, index)

    def getChains(self, partner):
  
        names  = []
        values = []

        molSystem = partner.molSystem
        if molSystem:
            for chain in molSystem.sortedChains():
                names.append(chain.code)

                if not partner.chains:
                  values.append(True)

                elif partner.findFirstChain(chain=chain):
                  values.append(True)

                else:
                  values.append(False)   

                self.chainSelect.set(values=values,options=names)   

        else:
            showWarning('Warning','Set Mol System or ensemble first',parent=self)
            self.symmetryMatrix.keyPressEscape()        
    
    def getSegLength(self, symmetryOp):
        
        if symmetryOp and symmetryOp.segmentLength: self.segLengthEntry.set(symmetryOp.segmentLength)

    def getSegStart(self):
    
        pass

    def setMolSystem(self, partner, name=None):
  
        """Get all molsystems as stored in the project as list"""

        index =  self.molSysPulldown.getSelectedIndex()
        molSystems = self.ccpnProject.sortedMolSystems()
  
        if molSystems:
            molSystem = molSystems[index]
            self.molPartner.molSystem = molSystem
            chains = molSystem.sortedChains()
            if (not self.molPartner.chains) and chains: setPartnerChains(self.molPartner,chains)

        self.updateAllAfter()

    def setChains(self, obj):

        """Get the list of chains for the selected molsystem"""

        if self.molPartner and self.molPartner.molSystem:
            if obj is not None:
                chains = self.molPartner.molSystem.sortedChains()
                values = self.chainSelect.get()
                chains = [chains[i] for i in range(len(values)) if values[i]]
                setPartnerChains(self.molPartner,chains)

        self.symmetryMatrix.keyPressEscape()  
        self.updateAllAfter()
        
    def setSegLength(self, event):
        
        value = self.segLengthEntry.get() or 1
        self.symmetryOp.segmentLength = value

    def setSegStart(self):
        
        pass    

    def setSymmCode(self, index, name=None): 

        self.symmetryCode = self.symmCodePulldown.getSelected()    

    def selectSymmetry(self, obj, row, col):
        
        self.symmetryOp = obj
        self.updateMolSysPulldown()

    def notify(self, notifyFunc):
  
        for func in ('__init__', 'delete', 'setSymmetryCode','setSegmentLength'):
            notifyFunc(self.updateAllAfter, 'molsim.Symmetry.Symmetry', func)

        for func in ('__init__', 'delete','setfirstSeqId'):
            notifyFunc(self.updateAllAfter, 'molsim.Symmetry.Segment', func)

    def addSymmetrySet(self):
            
        if not self.ccpnProject.molSystems:
            showWarning('Warning','No molecular systems present in CCPN project',parent=self)
            return

            molSystem = self.ccpnProject.findFirstMolSystem()
            partner = self.hProject.newHaddockPartner(code=molSystem.code, molSystem=molSystem)
            setPartnerChains(partner, molSystem.chains)

            self.updateAllAfter()
            
    def removeSymmetrySet(self):
        
        pass            
    
    def updateAllAfter(self, obj=None):

        if self.waiting: return
        else:
            self.waiting = True
            self.after_idle(self.updateSymmetries,
                            self.updateMolPartners)
    
    def updateMolPartners(self):

        textMatrix = []
        objectList = []

        for partner in self.hProject.sortedHaddockPartners():
            datum = [partner.code,
                     self.symmetryCode,
                     partner.molSystem.code,
                     ','.join([c.chain.code for c in partner.chains]),
                     partner.autoHistidinePstate and 'Yes' or 'No',
                     partner.isDna and 'Yes' or 'No']
            
            objectList.append(partner)
            textMatrix.append(datum)

        self.symmetryMatrix.update(objectList=objectList, textMatrix=textMatrix)
        self.updateMolSysPulldown()
    
    def updateMolSysPulldown(self):

        names = []
        index = -1

        partners = self.hProject.sortedHaddockPartners()

        if partners:
            if self.molPartner not in partners:
                self.molPartner = partners[0]

            names = ['Partner %s' % p.code for p in partners]
            index = partners.index(self.molPartner)

        else: self.molPartner = None

        self.molSysPulldown.setup(names, index)
        
    def updateSymmetries(self):

        textMatrix  = []; objectList  = []
        if self.symmetrySet:
            for symmetryOp in self.symmetrySet.symmetries:
                chains = []; segments = [] 
                length = symmetryOp.segmentLength

                for segment in symmetryOp.sortedSegments():
                    code = segment.chainCode
                    chain = self.molSystem.findFirstChain(code=code)

                    if chain:
                        chains.append(code)
                        seqId = segment.firstSeqId
                        residue1 = chain.findFirstResidue(seqId=seqId)
                        residue2 = chain.findFirstResidue(seqId=seqId+length-1)
                        segments.append('%s:%d-%d' % (code,residue1.seqCode,residue2.seqCode))

                datum = [symmetryOp.serial, symmetryOp.symmetryCode, length, '\n'.join(chains), '\n'.join(segments)]
                objectList.append(symmetryOp)
                textMatrix.append(datum)

        self.symmetryMatrix.update(objectList=objectList, textMatrix=textMatrix)
        self.waiting = False

    def destroy(self):

        self.notify(self.unregisterNotify)
        BasePopup.destroy(self)
Example #29
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 #30
0
    def body(self, guiFrame):

        self.geometry('450x500')

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

        options = ['Peak Separator', 'Advanced Settings']

        tabbedFrame = TabbedFrame(guiFrame, options=options)
        tabbedFrame.grid(row=0, column=0, sticky='nsew')

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

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

        #
        # FrameA : Main Settings
        #

        frameA.grid_columnconfigure(1, weight=1)
        row = 0  # Label row

        row += 1
        div = LabelDivider(frameA, text='Peak Separator Parameters')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameA, text='Min. number of peaks:')
        label.grid(row=row, column=0, sticky='w')
        self.minPeaksEntry = IntEntry(frameA, returnCallback=self.applyChange, width=10, \
              tipText='Minimum number of peaks to find (must be > 0)')
        self.minPeaksEntry.grid(row=row, column=1, sticky='n')
        self.minPeaksEntry.bind('<Leave>', self.applyChange, '+')

        row += 1
        label = Label(frameA, text='Max. number of peaks:')
        label.grid(row=row, column=0, sticky='w')
        self.maxPeaksEntry = IntEntry(frameA, returnCallback=self.applyChange, width=10, \
              tipText='Maximum number of peaks to find (0 is unlimited - not recommended)')
        self.maxPeaksEntry.grid(row=row, column=1, sticky='n')
        self.maxPeaksEntry.bind('<Leave>', self.applyChange, '+')

        row += 1
        label = Label(frameA, text='Only pick positive peaks:')
        label.grid(row=row, column=0, sticky='w')
        entries = ['False', 'True']
        self.posPeaksButtons = RadioButtons(
            frameA,
            entries=entries,
            select_callback=self.applyChange,
            direction='horizontal',
            tipTexts=[
                'Search for both positive and negative intensity peaks',
                'Limit search to only positive peaks'
            ])
        self.posPeaksButtons.grid(row=row, column=1, sticky='n')

        row += 1
        label = Label(frameA, text='Peak Model:')
        label.grid(row=row, column=0, sticky='w')
        ### G/L Mixture works, but volume calculation involves Gamma function
        # entries = ['Gaussian', 'Lorentzian', 'G/L Mixture']
        entries = ['Gaussian', 'Lorentzian']
        self.shapeButtons = RadioButtons(
            frameA,
            entries=entries,
            select_callback=self.applyChange,
            direction='horizontal',
            tipTexts=[
                'Choose a Gaussian model peak shape to fit to peaks',
                'Choose a Lorentzian model peak shape to fit to peaks'
            ])
        self.shapeButtons.grid(row=row, column=1, sticky='n')

        row += 1
        div = LabelDivider(frameA,
                           text='Region',
                           tipText='Region that search will limit itself to')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameA, text='Peak List:')
        label.grid(row=row, column=0, sticky='nw')
        self.peakListPulldown = PulldownList(
            frameA,
            callback=self.setManuallyPickPeakList,
            tipText='Select which peak list new peaks are to be added to')
        self.peakListPulldown.grid(row=row, column=1, sticky='nw')

        # tricky scrolled matrix
        row += 1
        self.regionTable = None
        frameA.grid_rowconfigure(row, weight=1)
        headings = ('dim.', 'start (ppm)', 'end (ppm)', 'actual size')

        self.editDimEntry = IntEntry(self,
                                     returnCallback=self.applyChange,
                                     width=5,
                                     tipText='Dimension number')
        self.editStartEntry = FloatEntry(self,
                                         returnCallback=self.applyChange,
                                         width=5,
                                         tipText='Search area lower bound')
        self.editEndEntry = FloatEntry(self,
                                       returnCallback=self.applyChange,
                                       width=5,
                                       tipText='Search area upper bound')

        editWidgets = [
            self.editDimEntry, self.editStartEntry, self.editEndEntry, None
        ]

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

        self.regionTable = ScrolledMatrix(frameA,
                                          headingList=headings,
                                          multiSelect=False,
                                          editWidgets=editWidgets,
                                          editGetCallbacks=editGetCallbacks,
                                          editSetCallbacks=editSetCallbacks,
                                          initialRows=5)

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

        # Run Button
        row += 1
        texts = ['Add Region']
        commands = [self.updateFromRegion]
        self.addResetButtons = ButtonList(
            frameA,
            texts=texts,
            commands=commands,
            tipTexts=['Add selected specrtral region'])
        self.addResetButtons.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        texts = ['Separate Peaks']
        commands = [self.runPeakSeparator]
        self.runButton = ButtonList(frameA,
                                    texts=texts,
                                    commands=commands,
                                    expands=True,
                                    tipTexts=['Run peak search now'])
        self.runButton.grid(row=row, column=0, columnspan=2, sticky='nsew')

        #
        # FrameB : Further Settings
        #

        frameB.grid_columnconfigure(0, weight=1)

        row = 0

        div = LabelDivider(frameB, text='Rate:')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')
        row += 1

        label = Label(frameB, text='Rate of MCMC step size change')
        label.grid(row=row, column=0, columnspan=1, sticky='w')

        self.rateEntry = FloatEntry(frameB, returnCallback=self.applyChange, width=10, \
              tipText='Rate effects speed of run, smaller values take longer but may produce better results')
        self.rateEntry.grid(row=row, column=1, sticky='n')
        self.rateEntry.bind('<Leave>', self.applyChange, '+')
        self.rateEntry.set(self.params.rate)

        # tricky scrolled matrix for line width
        row += 2
        div = LabelDivider(frameB, text='Line Width (Hz):')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameB, text="Descr.")
        label.grid(row=row, rowspan=2, column=0, sticky='w')

        row += 1
        self.lineWidthTable = None
        frameB.grid_rowconfigure(row, weight=1)
        lineWidthHeadings = ('dim.', 'min. σ (Hz)', 'max. σ (Hz)')

        self.editMinSigmaEntry = FloatEntry(self,
                                            returnCallback=self.applyChange,
                                            width=5,
                                            tipText='Minimum line width (Hz)')
        self.editMaxSigmaEntry = FloatEntry(self,
                                            returnCallback=self.applyChange,
                                            width=5,
                                            tipText='Maximum line width (Hz)')

        # self.editDimEntry is also from regionTable
        initialWidthRows = 4

        editLineWidthWidgets = [
            None, self.editMinSigmaEntry, self.editMaxSigmaEntry
        ]
        editLineWidthGetCallbacks = [None, self.getSigmaMin, self.getSigmaMax]
        editLineWidthSetCallbacks = [None, self.setSigmaMin, self.setSigmaMax]

        self.lineWidthTable = ScrolledMatrix(
            frameB,
            headingList=lineWidthHeadings,
            multiSelect=False,
            editWidgets=editLineWidthWidgets,
            editGetCallbacks=editLineWidthGetCallbacks,
            editSetCallbacks=editLineWidthSetCallbacks,
            initialRows=initialWidthRows)

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

        # option to 'repick' exisiting peak list
        row += initialWidthRows
        div = LabelDivider(frameB, text='(optional - repick entire peak list)')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')
        row += 1

        self.repickListPulldown = PulldownList(
            frameB,
            callback=self.setRePickPeakList,
            tipText=
            'Select which peak list to repick (new peaks will be put into a new peak list)'
        )
        self.repickListPulldown.grid(row=row, column=0, sticky='nw')

        texts = ['Repick Peak List']
        commands = [self.runRepickPeaks]
        self.runButton = ButtonList(
            frameB,
            texts=texts,
            commands=commands,
            expands=True,
            tipTexts=['Repick selected peak list into a new peak list.'])
        self.runButton.grid(row=row, column=1, columnspan=1, sticky='nsew')

        row += 1
        div = LabelDivider(frameB)
        row += 1
        texts = ['Separate Peaks']
        commands = [self.runPeakSeparator]
        self.runButton = ButtonList(frameB,
                                    texts=texts,
                                    commands=commands,
                                    expands=True,
                                    tipTexts=['Run peak search now'])
        self.runButton.grid(row=row, column=0, columnspan=2, sticky='nsew')

        self.setWidgetEntries()

        self.administerNotifiers(self.registerNotify)
Example #31
0
  def __init__(self, guiParent, ccpnProject=None, **kw):

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

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

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

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

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

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

    
    #
    # Frame D
    #

  
    self.updateAll()
Example #32
0
class PeakSeparatorGui(BasePopup):
    """
  **Separate Merged Peaks Using Peak Models**

  The Peak Separator code uses a Markov Chain Monte Carlo search which, using
  idealised peak shapes, attempts to deconvolve overlapped peak regions into 
  their separate constituent peaks.
  
  This routine is also suitable for accurately fitting model shapes to single
  peaks in order to calculate precise intensities.
  
  **Options Peak Separator Parameters**
  *Min. Number of peaks* is by default set to one, it is not possible to set 
  this to a value less than one.
  *Max. Number of peaks* is by default set to one, increasing this value allows
  the search routine to fit more models. The best fit may be found with fewer than
  the maximum number models. Higher numbers slow the routine, and setting this
  value to 0 allows the routine to (effectively) fit unlimited peaks.
  *Only pick positive peaks*. If you are not interested in negative peaks, removing
  the possibility of fitting negative peaks can reduce search time.
  *Peak Model* fits the spectra with either a Gaussian peak model or a Lorentzian
  peak model.

  **Options Region**
  *Peak List* choose which peak list newly picked peaks should be added to. Peaks
  picked using this method will have their details appended with 'PeakSepartor' 
  so you know where they came from.
  *Region Table* shows which area of the current spectrum is about to be searched.
  *Add Region*. Once an area of spectra has been highlighted clicking this button
  will pass it's details on to the Peak Separator.
  *Reset All* will reset all search parameters.
  *Separate Peaks* will run the Peak Separator code with your current settings. This
  may take a few minutes to run, depending on the size of the spectral region being
  searched, the number of peaks being fitted and the speed of your machine. Please
  wait while this completes.
  
  After a successful Peak Separation run, the found peaks will be added to the 
  selected peak list. These peaks intensties (volume) have been found using the
  peak model selected.

  **Advanced Settings Tab**
  *Rate* affects the speed of the Markov Chain Monte Carlo routine. A smaller value
  results in longer execution, but possibly higher quality results. The default 
  setting is deemed sensible for the majority of runs.
  *Line Width* offers a finer degree of control over maximum and minimum peak widths
  for each dimension. The default values are *very* stupid and could do with 
  re-checking for each experiment.
  *Re-Pick Entire Peak List* if you would like to use the Peak Separator to repick
  *every* peak in your peak list, try this option - but note that this may take
  a very long time!

  """
    def __init__(self, parent, programName='Peak Separator', **kw):

        self.parent = parent
        self.programName = programName
        self.versionInfo = 'Version 0.2'
        self.help_url = 'http://www.ccpn.ac.uk/'

        self.window = None
        self.waiting = False
        self.rootWindow = None

        # just used for display - PeakSeparator will not see this
        self._minSigmaHz = None
        self._maxSigmaHz = None

        self.customSigma = False
        self.rePickPeakList = False

        self._sampleStartPpm = None
        self._sampleEndPpm = None

        try:
            self.project = parent.project
        except:
            pass

        self.params = PeakSeparatorParams()

        BasePopup.__init__(self,
                           parent=parent,
                           title=programName,
                           location='+100+100',
                           **kw)

        if not self.analysisProject:
            print '&&& init: No analysis project found ...'
        try:
            if parent.argumentServer:
                self.argServer = parent.argumentServer
            else:
                print '&&& init: No argument server found...'
        except:
            print '&&& init: Test'

    ###########################################################################

    def body(self, guiFrame):

        self.geometry('450x500')

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

        options = ['Peak Separator', 'Advanced Settings']

        tabbedFrame = TabbedFrame(guiFrame, options=options)
        tabbedFrame.grid(row=0, column=0, sticky='nsew')

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

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

        #
        # FrameA : Main Settings
        #

        frameA.grid_columnconfigure(1, weight=1)
        row = 0  # Label row

        row += 1
        div = LabelDivider(frameA, text='Peak Separator Parameters')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameA, text='Min. number of peaks:')
        label.grid(row=row, column=0, sticky='w')
        self.minPeaksEntry = IntEntry(frameA, returnCallback=self.applyChange, width=10, \
              tipText='Minimum number of peaks to find (must be > 0)')
        self.minPeaksEntry.grid(row=row, column=1, sticky='n')
        self.minPeaksEntry.bind('<Leave>', self.applyChange, '+')

        row += 1
        label = Label(frameA, text='Max. number of peaks:')
        label.grid(row=row, column=0, sticky='w')
        self.maxPeaksEntry = IntEntry(frameA, returnCallback=self.applyChange, width=10, \
              tipText='Maximum number of peaks to find (0 is unlimited - not recommended)')
        self.maxPeaksEntry.grid(row=row, column=1, sticky='n')
        self.maxPeaksEntry.bind('<Leave>', self.applyChange, '+')

        row += 1
        label = Label(frameA, text='Only pick positive peaks:')
        label.grid(row=row, column=0, sticky='w')
        entries = ['False', 'True']
        self.posPeaksButtons = RadioButtons(
            frameA,
            entries=entries,
            select_callback=self.applyChange,
            direction='horizontal',
            tipTexts=[
                'Search for both positive and negative intensity peaks',
                'Limit search to only positive peaks'
            ])
        self.posPeaksButtons.grid(row=row, column=1, sticky='n')

        row += 1
        label = Label(frameA, text='Peak Model:')
        label.grid(row=row, column=0, sticky='w')
        ### G/L Mixture works, but volume calculation involves Gamma function
        # entries = ['Gaussian', 'Lorentzian', 'G/L Mixture']
        entries = ['Gaussian', 'Lorentzian']
        self.shapeButtons = RadioButtons(
            frameA,
            entries=entries,
            select_callback=self.applyChange,
            direction='horizontal',
            tipTexts=[
                'Choose a Gaussian model peak shape to fit to peaks',
                'Choose a Lorentzian model peak shape to fit to peaks'
            ])
        self.shapeButtons.grid(row=row, column=1, sticky='n')

        row += 1
        div = LabelDivider(frameA,
                           text='Region',
                           tipText='Region that search will limit itself to')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameA, text='Peak List:')
        label.grid(row=row, column=0, sticky='nw')
        self.peakListPulldown = PulldownList(
            frameA,
            callback=self.setManuallyPickPeakList,
            tipText='Select which peak list new peaks are to be added to')
        self.peakListPulldown.grid(row=row, column=1, sticky='nw')

        # tricky scrolled matrix
        row += 1
        self.regionTable = None
        frameA.grid_rowconfigure(row, weight=1)
        headings = ('dim.', 'start (ppm)', 'end (ppm)', 'actual size')

        self.editDimEntry = IntEntry(self,
                                     returnCallback=self.applyChange,
                                     width=5,
                                     tipText='Dimension number')
        self.editStartEntry = FloatEntry(self,
                                         returnCallback=self.applyChange,
                                         width=5,
                                         tipText='Search area lower bound')
        self.editEndEntry = FloatEntry(self,
                                       returnCallback=self.applyChange,
                                       width=5,
                                       tipText='Search area upper bound')

        editWidgets = [
            self.editDimEntry, self.editStartEntry, self.editEndEntry, None
        ]

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

        self.regionTable = ScrolledMatrix(frameA,
                                          headingList=headings,
                                          multiSelect=False,
                                          editWidgets=editWidgets,
                                          editGetCallbacks=editGetCallbacks,
                                          editSetCallbacks=editSetCallbacks,
                                          initialRows=5)

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

        # Run Button
        row += 1
        texts = ['Add Region']
        commands = [self.updateFromRegion]
        self.addResetButtons = ButtonList(
            frameA,
            texts=texts,
            commands=commands,
            tipTexts=['Add selected specrtral region'])
        self.addResetButtons.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        texts = ['Separate Peaks']
        commands = [self.runPeakSeparator]
        self.runButton = ButtonList(frameA,
                                    texts=texts,
                                    commands=commands,
                                    expands=True,
                                    tipTexts=['Run peak search now'])
        self.runButton.grid(row=row, column=0, columnspan=2, sticky='nsew')

        #
        # FrameB : Further Settings
        #

        frameB.grid_columnconfigure(0, weight=1)

        row = 0

        div = LabelDivider(frameB, text='Rate:')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')
        row += 1

        label = Label(frameB, text='Rate of MCMC step size change')
        label.grid(row=row, column=0, columnspan=1, sticky='w')

        self.rateEntry = FloatEntry(frameB, returnCallback=self.applyChange, width=10, \
              tipText='Rate effects speed of run, smaller values take longer but may produce better results')
        self.rateEntry.grid(row=row, column=1, sticky='n')
        self.rateEntry.bind('<Leave>', self.applyChange, '+')
        self.rateEntry.set(self.params.rate)

        # tricky scrolled matrix for line width
        row += 2
        div = LabelDivider(frameB, text='Line Width (Hz):')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')

        row += 1
        label = Label(frameB, text="Descr.")
        label.grid(row=row, rowspan=2, column=0, sticky='w')

        row += 1
        self.lineWidthTable = None
        frameB.grid_rowconfigure(row, weight=1)
        lineWidthHeadings = ('dim.', 'min. σ (Hz)', 'max. σ (Hz)')

        self.editMinSigmaEntry = FloatEntry(self,
                                            returnCallback=self.applyChange,
                                            width=5,
                                            tipText='Minimum line width (Hz)')
        self.editMaxSigmaEntry = FloatEntry(self,
                                            returnCallback=self.applyChange,
                                            width=5,
                                            tipText='Maximum line width (Hz)')

        # self.editDimEntry is also from regionTable
        initialWidthRows = 4

        editLineWidthWidgets = [
            None, self.editMinSigmaEntry, self.editMaxSigmaEntry
        ]
        editLineWidthGetCallbacks = [None, self.getSigmaMin, self.getSigmaMax]
        editLineWidthSetCallbacks = [None, self.setSigmaMin, self.setSigmaMax]

        self.lineWidthTable = ScrolledMatrix(
            frameB,
            headingList=lineWidthHeadings,
            multiSelect=False,
            editWidgets=editLineWidthWidgets,
            editGetCallbacks=editLineWidthGetCallbacks,
            editSetCallbacks=editLineWidthSetCallbacks,
            initialRows=initialWidthRows)

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

        # option to 'repick' exisiting peak list
        row += initialWidthRows
        div = LabelDivider(frameB, text='(optional - repick entire peak list)')
        div.grid(row=row, column=0, columnspan=2, sticky='ew')
        row += 1

        self.repickListPulldown = PulldownList(
            frameB,
            callback=self.setRePickPeakList,
            tipText=
            'Select which peak list to repick (new peaks will be put into a new peak list)'
        )
        self.repickListPulldown.grid(row=row, column=0, sticky='nw')

        texts = ['Repick Peak List']
        commands = [self.runRepickPeaks]
        self.runButton = ButtonList(
            frameB,
            texts=texts,
            commands=commands,
            expands=True,
            tipTexts=['Repick selected peak list into a new peak list.'])
        self.runButton.grid(row=row, column=1, columnspan=1, sticky='nsew')

        row += 1
        div = LabelDivider(frameB)
        row += 1
        texts = ['Separate Peaks']
        commands = [self.runPeakSeparator]
        self.runButton = ButtonList(frameB,
                                    texts=texts,
                                    commands=commands,
                                    expands=True,
                                    tipTexts=['Run peak search now'])
        self.runButton.grid(row=row, column=0, columnspan=2, sticky='nsew')

        self.setWidgetEntries()

        self.administerNotifiers(self.registerNotify)

    def administerNotifiers(self, notifyFunc):

        for func in ('__init__', 'delete'):
            notifyFunc(self.updateAfter, 'ccp.nmr.Nmr.PeakList', func)

        notifyFunc(self.updateAfter, 'ccp.nmr.Nmr.Experiment', 'setName')
        notifyFunc(self.updateAfter, 'ccp.nmr.Nmr.DataSource', 'setName')

    def destroy(self):

        self.administerNotifiers(self.unregisterNotify)
        BasePopup.destroy(self)

    ###########################################################################
    # update parameters from PS Region

    def updateFromRegion(self):

        if not self.params.peakList:
            print '&&& update from region: Need a peak list'
            return

        if (self.argServer.parent.currentRegion) == None:
            showError('No Region',
                      'Please select a peak region to be separated')
            return

        self.rePickPeakList = False

        getRegionParams(self.params, argServer=self.argServer)

        if not self.customSigma: self.initSigmaParams()

        self.setWidgetEntries()

    ###########################################################################
    # update parameters from PS PeakList

    def updateFromPeakList(self):

        if not self.params.peakList:
            print '&&& update from peakList: Need a peak list'
            return

        getPeakListParams(self.params)

        if not self.customSigma: self.initSigmaParams()

        self.setWidgetEntries()

    ###########################################################################
    # Run the C library!

    def runPeakSeparator(self):
        """ run the peak separator """

        # hack for Macs - focus isn't always lost on mouse move
        # so bind event not always called. Shouldn't affect other OS.
        self.applyChange()

        if not self.params.peakList:
            print '&&& Peak list not yet set'
        else:
            # SeparatePeakRoutine(self.params, self.params.peakList, routine='pymc' )
            SeparatePeakRoutine(self.params,
                                self.params.peakList,
                                routine='bayesys')

    def runRepickPeaks(self):
        """ Run the Peak Separator on entire chosen peak list """
        # hack for Macs - focus isn't always lost on mouse move
        # so bind event not always called. Shouldn't affect other OS.
        self.applyChange()

        if not self.params.peakList:
            print '&&& Peak list not yet set'
        else:
            SeparatePeaksInPeakList(self.params)

    ###########################################################################

    def setWidgetEntries(self):

        ### Page One widgets
        self.minPeaksEntry.set(self.params.minAtoms)
        self.maxPeaksEntry.set(self.params.maxAtoms)

        if self.params.positivePeaks == 1:
            self.posPeaksButtons.set('True')  # only pick pos peaks
        else:
            self.posPeaksButtons.set('False')

        # do something fancy if different shapes for each dim!
        n = self.params.peakShape - 3  # shape is only 3, 4, (5)
        self.shapeButtons.setIndex(n)

        if self.project is not None:
            self.updatePeakListList()
        self.updateSpectrumWindow()

        if self.params.sampleStart and self.params.peakList:

            if not self.rePickPeakList:
                objectList = []
                textMatrix = []

                if len(self.params.samplePpmStart) != self.params.Ndim: return

                for i in range(self.params.Ndim):
                    dim_entry = []
                    dim_entry.append('%2d' % (i + 1))
                    dim_entry.append('%7.3f' % self.params.samplePpmStart[i])
                    dim_entry.append('%7.3f' % self.params.samplePpmEnd[i])
                    dim_entry.append('%3d' % self.params.sampleSize[i])
                    textMatrix.append(dim_entry)

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

        ### Page Two widgets
        self.rateEntry.set(self.params.rate)

        if self.params.peakList and self.params.Ndim:

            textMatrix = []
            objectList = []

            for i in range(self.params.Ndim):
                if self.params.isFreqDim[i]:
                    dim_entry = []
                    objectList.append(i)
                    dim_entry.append('%2d' % (i + 1))
                    dim_entry.append('%7.3f' % self._minSigmaHz[i])
                    dim_entry.append('%7.3f' % self._maxSigmaHz[i])
                    textMatrix.append(dim_entry)

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

    def applyChange(self, *event):
        """ Upon change, add settings to params """

        # Page One apply changes
        self.params.minAtoms = self.minPeaksEntry.get()
        self.params.maxAtoms = self.maxPeaksEntry.get()

        if self.posPeaksButtons.get() == 'True':  # asked only pick pos peaks
            self.params.positivePeaks = 1
        else:
            self.params.positivePeaks = 0

        # do something fancy if different shapes for each dim!
        n = self.shapeButtons.getIndex()  # shape is only 3, 4, (5)
        self.params.peakShape = n + 3

        # Page Two apply changes
        self.params.rate = float(self.rateEntry.get())

        self.updateSigmaParams()

    ###########################################################################
    # Peak list functions provide PeakSeparator some inherited params

    def getPeakListList(self):
        """ given a spectrum, get list of peak lists """
        project = self.project

        peakLists = []
        for experiment in self.nmrProject.experiments:
            for spectrum in experiment.dataSources:
                for peakList in spectrum.peakLists:
                    peakLists.append([
                        '%s:%s:%d' %
                        (experiment.name, spectrum.name, peakList.serial),
                        peakList
                    ])
        peakLists.sort()
        return peakLists

    def updatePeakListList(self):
        """ set the peaklist list in the pulldown menu """
        peakListData = self.getPeakListList()

        index = -1
        names = []
        peakList = self.params.peakList

        if peakListData:
            names = [x[0] for x in peakListData]
            peakLists = [x[1] for x in peakListData]

            if peakList not in peakLists:
                peakList = peakLists[0]

            index = peakLists.index(peakList)

        else:
            peakList = None
            peakLists = []

        if peakList is not self.params.peakList:
            self.params.peakList = peakList

        self.peakListPulldown.setup(names, peakLists, index)
        self.repickListPulldown.setup(names, peakLists, index)

    def setRePickPeakList(self, peakList):
        """ Set the peak list to be repicked (and hit a Flag) """
        self.rePickPeakList = True
        self.setPeakList(peakList)

    def setManuallyPickPeakList(self, peakList):
        """ Set the peak list to add new peaks to (and hit a Flag) """
        self.rePickPeakList = False
        self.setPeakList(peakList)

    def setPeakList(self, peakList):
        """ Sets the Peak List """
        if peakList is not self.params.peakList:
            self.params.peakList = peakList
            # # interrogate the peak list and get all the usefull parameters out
            self.updateFromPeakList()
            self.updateSpectrumWindow()
            self.setWidgetEntries()

    ###########################################################################
    # TBD I suspect this is for matching region with peak list, but may be obsolete now

    def getSpectrumWindowList(self):
        """ get list of windows which spectrum could be in """
        windows = {}
        if self.params.peakList:
            views = getSpectrumViews(self.params.peakList.dataSource)
            for view in views:
                windows[view.spectrumWindowPane.spectrumWindow] = None

        return [[w.name, w] for w in windows.keys()]

    def updateSpectrumWindow(self):
        """ update the spectrum window """
        windowData = self.getSpectrumWindowList()

        index = -1
        names = []
        window = self.rootWindow

        if windowData:
            names = [x[0] for x in windowData]
            windows = [x[1] for x in windowData]

            if window not in windows:
                window = windows[0]

            index = windows.index(window)

        else:
            window = None
            windows = []

        if window is not self.rootWindow:
            self.rootWindow = window

    ###########################################################################
    # get and set sigma stuff
    def setSigmaMin(self, dim):

        value = self.editMinSigmaEntry.get()
        self._minSigmaHz[dim] = value

        # dont go and re-write users settings
        self.customSigma = True

        # make sure changes are in params object
        self.updateSigmaParams(dim)
        self.setWidgetEntries()

    def getSigmaMin(self, dim):

        if dim is not None:
            self.editMinSigmaEntry.set(self._minSigmaHz[dim])

    def setSigmaMax(self, dim):

        value = self.editMaxSigmaEntry.get()
        self._maxSigmaHz[dim] = value

        # dont go and re-write users settings
        self.customSigma = True

        # make sure changes are in params object
        self.updateSigmaParams(dim)
        self.setWidgetEntries()

    def getSigmaMax(self, dim):

        if dim is not None:
            self.editMaxSigmaEntry.set(self._maxSigmaHz[dim])

    def updateSigmaParams(self, dim=None):
        """ updateSigmaParams Just updates the parameters (params obj) for sigma values. 
        If dim is None, do this for each dim
    """

        dataDimRefs = self.params.dataDimRefs

        if not dataDimRefs: return

        if not self.params.minSigma or len(
                self.params.minSigma) != self.params.Ndim:
            self.params.minSigma = [0.] * self.params.Ndim

        if not self.params.maxSigma or len(
                self.params.maxSigma) != self.params.Ndim:
            self.params.maxSigma = [0.] * self.params.Ndim

        def updateSigmaParam(dim, dataDimRefs):
            """ Convert and update sigma for dim """

            if self.params.isFreqDim[dim]:
                # note factor of two!
                self.params.minSigma[dim] = self.rHz2pnt(
                    self._minSigmaHz[dim], dataDimRefs[dim]) / 2.
                self.params.maxSigma[dim] = self.rHz2pnt(
                    self._maxSigmaHz[dim], dataDimRefs[dim]) / 2.
            else:
                self.params.minSigma[dim] = 1.0
                self.params.maxSigma[dim] = 1.0

        if dim:
            updateSigmaParam(dim, dataDimRefs)
        else:
            for dim in range(self.params.Ndim):
                updateSigmaParam(dim, dataDimRefs)

    # utility functions for sigma values
    def pnt2rHz(self, point, dataDimRef):
        """ Point to relative Hz frequency relative to frequency at Zeroeth point
        Necessary when (for example) looking for width of peak in Hz
    """
        assert point, dataDimRef

        sigmaBase = pnt2hz(0, dataDimRef)
        sigmaHz = pnt2hz(point, dataDimRef)

        return abs(sigmaHz - sigmaBase)

    def rHz2pnt(self, freq, dataDimRef):
        """ Relative Hz to point frequency relative to frequency at Zeroeth point
        Necessary when (for example) looking for width of peak in Hz
    """
        assert freq, dataDimRef

        sigmaBase = hz2pnt(0, dataDimRef)
        sigmaPoint = hz2pnt(freq, dataDimRef)

        return abs(sigmaPoint - sigmaBase)

    def initSigmaParams(self):
        """ Set some initial default values for sigma """

        self._minSigmaHz = []
        self._maxSigmaHz = []

        if self.params.Ndim:
            for dim in range(self.params.Ndim):
                self._minSigmaHz.append(6.)
                self._maxSigmaHz.append(28.)

    ###########################################################################

    def updateAll(self):

        self.updateSpectrumWindow()
        self.updatePeakListList()

        self.waiting = False

    def updateAfter(self, obj=None):

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

      Attributes:

          guiParent: gui object this tab is part of.

          frame: the frame in which this element lives.

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

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

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

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

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

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

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

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

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

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

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

        self.guiParent = parent
        self.frame = frame

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

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


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

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

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

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

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

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

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

        row = 0

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

        row += 1

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

        row = 0

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

        row += 1

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

        row += 1

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

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

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

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

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

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

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

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

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

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

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

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

        self.dataModel = dataModel
        self.update()

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

        if not self.dataModel:

            return

        spectrum = self.spectrum

        spectra = self.dataModel.getSpectra()

        if spectra:

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

            if self.spectrum not in spectra:

                self.spectrum = spectra[0]

            else:

                index = spectra.index(self.spectrum)

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

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

        self.spectrum = spectrum

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

        if not self.dataModel:

            return

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

        if value is None:

            value = self.solutionNumberEntry.get()

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

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

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

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

        newMinScore = self.minScoreEntry.get()

        if self.minScore != newMinScore:

            if newMinScore <= 50.0:

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

            elif newMinScore > 100.0:

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

            else:

                self.minScore = newMinScore

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

        self.fetchOptions()

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

            return

        strategy = self.strategy

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

        residues = self.dataModel.chain.residues

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

        ccpnSpinSystems = []
        ccpnResidues = []

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

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

                if spinSys and res:

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

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

        if self.resonanceToDimension:

            allSpectra = self.allSpectra

            if self.intra:

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

                    if not spinSystem:

                        continue

                    intraLink = residue.getIntraLink(spinSystem)

                    for pl in intraLink.getPeakLinks():

                        peak = pl.getPeak()

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

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

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

                            continue

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

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

            if self.sequential:

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

                    if not spinSystemA or not spinSystemB:

                        continue

                    link = residue.getLink(spinSystemA, spinSystemB)

                    for pl in link.getPeakLinks():

                        peak = pl.getPeak()

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

                            continue

                        if not peak:

                            continue

                        resonances = pl.getResonances()

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

                            continue

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

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

                            assignResToDim(ccpnDimension, ccpnResonance)

        self.guiParent.resultsTab.update()

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

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

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

            assignedResonanceGroup = ccpnResidue.findFirstResonanceGroup()

            if assignedResonanceGroup:

                for spinSystem in spinSystems:

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

                            return spinSystem

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

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

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

            return bestSpinSystem

        return None

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

        userDefinedSpinSystem = residue.userDefinedSolution

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

            return userDefinedSpinSystem

        return None

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

        solutions = residue.solutions

        spinSystem = solutions[self.selectedSolution - 1]

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

            return spinSystem

        return None

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

        if self.strategy == 0:

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

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

                return True

        return False
class CloudHomologueAssignPopup(BasePopup):

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

    self.guiParent = parent
    self.project   = parent.getProject()
    self.molSystem = None
    self.chain     = None
    self.assignment = None
    self.scores     = []

    BasePopup.__init__(self, parent, title="Cloud Threader", **kw)
  
  def body(self, guiFrame):

    guiFrame.grid_columnconfigure(3, weight=1)
    
    row = 0
    label = Label(guiFrame, text='Molecular system: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.molSysPulldown = PulldownMenu(guiFrame, self.changeMolSystem, selected_index=-1, do_initial_callback=0)
    self.molSysPulldown.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Clouds files: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.filenameEntry = Entry(guiFrame,text='perfect00.pdb')
    self.filenameEntry.grid(row=row, column=3, sticky=Tkinter.NW)


    row += 1
    label = Label(guiFrame, text='Chain: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.chainPulldown = PulldownMenu(guiFrame, self.changeChain, selected_index=-1, do_initial_callback=0)
    self.chainPulldown.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Thread steps: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.numStepsEntry = IntEntry(guiFrame,text=3000)
    self.numStepsEntry.grid(row=row, column=3, sticky=Tkinter.NW)
    row += 1

    label = Label(guiFrame, text='Homologue PDB file: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.pdbEntry = Entry(guiFrame,text='')
    self.pdbEntry.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Dist. Threshold: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.distEntry = FloatEntry(guiFrame,text=3.0)
    self.distEntry.grid(row=row, column=3, sticky=Tkinter.NW)

    row += 1

    label = Label(guiFrame, text='Global score: ')
    label.grid(row=row, column=0, sticky=Tkinter.NW)
    self.globalScoreLabel = Label(guiFrame, text='')
    self.globalScoreLabel.grid(row=row, column=1, sticky=Tkinter.NW)

    label = Label(guiFrame, text='Assignment Threshold: ')
    label.grid(row=row, column=2, sticky=Tkinter.NW)
    self.thresholdEntry = FloatEntry(guiFrame,text=-4.5)
    self.thresholdEntry.grid(row=row, column=3, sticky=Tkinter.NW)

    row += 1
    guiFrame.grid_rowconfigure(row, weight=1)
    self.graph = ScrolledGraph(guiFrame, width=300, height=200)
    self.graph.grid(row=row, column=0, columnspan=4, sticky = Tkinter.NSEW)

    row += 1
    texts    = ['Run','Assign!']
    commands = [self.run, self.assignSpinSystems]
    bottomButtons = createDismissHelpButtonList(guiFrame,texts=texts,commands=commands,expands=0,help_url=None)
    bottomButtons.grid(row=row, column=0, columnspan=4, sticky=Tkinter.EW)
    self.assignButton = bottomButtons.buttons[1]

    for func in ('__init__','delete'):
      Implementation.registerNotify(self.updateMolSystems, 'ccp.molecule.MolSystem.MolSystem', func)
      Implementation.registerNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)
    
    self.updateMolSystems()
    self.updateChains()

  def update(self):
  
    if self.assignment and self.scores:
      self.assignButton.enable()
    else:
      self.assignButton.disable()  

  def run(self):
  
    if self.chain:
      pattern = self.filenameEntry.get()
      nSteps  = self.numStepsEntry.get() or 4000
      pdbFile = self.pdbEntry.get()
      dist    =  self.distEntry.get() or 3.0
      pgb     = ProgressBar(self, text='Searching', total=nSteps)
      files   = getFileNamesFromPattern(pattern , '.')
      if not files:
        return
      clouds  = getCloudsFromFile(files, self.chain.root)
       
      score, self.scores, self.assignment = cloudHomologueAssign(self.chain, clouds, pdbFile, dist, nSteps, self.graph, pgb)
 
      pgb.destroy()
      self.globalScoreLabel.set(str(score))
      self.update()

  def assignSpinSystems(self):
   
    if self.assignment and self.scores:
      if showWarning('Query','Are you sure?'):
        threshold = self.thresholdEntry.get() or -4.0
        i = 0
 
        for residue in self.assignment.keys():
          if self.scores[residue] > threshold:
            spinSystem = self.assignment[residue]
            assignSpinSystemResidue(spinSystem,residue=None)
 
        for residue in self.assignment.keys():
          if self.scores[residue] > threshold:
            i += 1
            spinSystem = self.assignment[residue]
            assignSpinSystemResidue(spinSystem,residue=residue)
      
      showWarning('Done','%d residues assigned' % i)
      
  def getMolSystems(self):
  
    names = []
    for molSystem in self.project.molSystems:
      if molSystem.chains:
        names.append( '%s' % (molSystem.code) )
    return names


  def changeMolSystem(self, i, name):
  
    self.molSystem = self.project.findFirstMolSystem(code=name)


  def updateMolSystems(self, *opt):
  
    names = self.getMolSystems()
    if names:
      if not self.molSystem:
        self.molSystem = self.project.findFirstMolSystem(code=names[0])
      self.molSysPulldown.setup(names, names.index(self.molSystem.code))


  def getChains(self):
  
    chains = []
    if self.molSystem:
      for chain in self.molSystem.chains:
        chains.append( [chain.code, chain] )
	
    return chains


  def changeChain(self, i, name=None):
    
    if not name:
      i = self.chainPulldown.selected_index
    
    chains = self.getChains()
    if chains:
      self.chain = chains[i][1]
    
    
  def updateChains(self, *chain):
  
    chains = self.getChains()
 
    if chains:
      names = [x[0] for x in chains]
      if (not self.chain) or (self.chain.code not in names):
        self.chain = chains[0][1]
      self.chainPulldown.setup(names, names.index(self.chain.code) )

    self.update()

  def destroy(self):

    for func in ('__init__','delete'):
      Implementation.unregisterNotify(self.updateMolSystems, 'ccp.molecule.MolSystem.MolSystem', func)
      Implementation.unregisterNotify(self.updateChains, 'ccp.molecule.MolSystem.Chain', func)

    BasePopup.destroy(self)