Esempio n. 1
0
def OnGoToLine(self, event):
        dialog = wx.NumberEntryDialog(self, "Go to line","","Line",self.editor.GetCurrentLine(),0,2**30)
        if dialog.ShowModal() == wx.ID_OK:
            line=dialog.GetValue()
            line=max(0,min(self.editor.GetNumberOfLines(),line))
#            self.editor.GotoLine(dialog.GetValue()) # needs wx.stc to be used
        dialog.Destroy()
Esempio n. 2
0
    def new_int(self, evt: wx.CommandEvent):
        selected_item: wx.TreeItemId = self.treeCtrl.GetSelection()
        if not selected_item.IsOk():
            return

        with wx.TextEntryDialog(self, "Name for the new integer:",
                                "New Integer") as dialog:
            dialog: wx.TextEntryDialog
            dialog.ShowModal()
            name: str = dialog.GetValue()

        with wx.NumberEntryDialog(self, "Value for the new integer", "Value:",
                                  "New Integer", 0, -99999999,
                                  +99999999) as dialog:
            dialog: wx.NumberEntryDialog
            dialog.ShowModal()
            value: int = dialog.GetValue()

        selected_item: wx.TreeItemId = self.treeCtrl.GetSelection()
        if selected_item == self.rootItem:
            path = []
        elif selected_item.IsOk():
            path: list = self.treeCtrl.GetItemData(selected_item)["path"]
        else:
            return
        self.new_value(path, selected_item, name, value)
Esempio n. 3
0
 def OnSetMaxHeight(self, evt):
     mh = self.eom.GetMaxHeight()
     dlg = wx.NumberEntryDialog(self, "", "Enter new max height:",
                                "MaxHeight", mh, -1, 1000)
     if dlg.ShowModal() == wx.ID_OK:
         self.eom.SetMaxHeight(dlg.GetValue())
     dlg.Destroy()
Esempio n. 4
0
	def OnMultiply(self, e):
		if self._focusObj is None:
			return
		obj = self._focusObj
		dlg = wx.NumberEntryDialog(self, "How many copies do you want?", "Copies", "Multiply", 1, 1, 100)
		if dlg.ShowModal() != wx.ID_OK:
			dlg.Destroy()
			return
		cnt = dlg.GetValue()
		dlg.Destroy()
		n = 0
		while True:
			n += 1
			newObj = obj.copy()
			self._scene.add(newObj)
			self._scene.centerAll()
			if not self._scene.checkPlatform(newObj):
				break
			if n > cnt:
				break
		if n <= cnt:
			self.notification.message("Could not create more then %d items" % (n - 1))
		self._scene.remove(newObj)
		self._scene.centerAll()
		self.sceneUpdated()
Esempio n. 5
0
def scan_parameter(frame, row):
    ''' scan_parameter(frame, row) --> None
    
    Scans the parameter in row row [int] from max to min in the number
    of steps given by dialog input.
    '''
    if not frame.model.is_compiled():
        ShowNotificationDialog(frame, 'Please conduct a simulation before' +\
        ' scanning a parameter. The script needs to be compiled.')
        return
    
    dlg = wx.NumberEntryDialog(frame,\
                'Input the number of evaluation points for the scan',\
                'Steps', '', 50, 2, 1000)
    if dlg.ShowModal() ==wx.ID_OK:        
        frame.main_frame_statusbar.SetStatusText('Scanning parameter', 1)
        try:
            x, y = frame.solver_control.ScanParameter(row, dlg.GetValue())
            fs, pars = frame.model.get_sim_pars()
            bestx = frame.model.parameters.get_data()[row][1]
            besty = frame.model.fom
            
            frame.plot_fomscan.SetPlottype('scan')
            frame.plot_fomscan.Plot((x, y, bestx, besty,\
                        frame.solver_control.fom_error_bars_level))
            frame.plot_notebook.SetSelection(3)
        except Exception, e:
            outp = StringIO.StringIO()
            traceback.print_exc(200, outp)
            val = outp.getvalue()
            outp.close()
            ShowErrorDialog(frame, val)
            frame.main_frame_statusbar.SetStatusText('Fatal Error - scan fom', 1)
        else:
            frame.main_frame_statusbar.SetStatusText('Scanning finished', 1)
Esempio n. 6
0
 def test_numdlg1(self):
     dlg = wx.NumberEntryDialog(None, "Message", "Prompt", "Caption", 50, 0,
                                100)
     wx.CallLater(250, dlg.EndModal, wx.ID_OK)
     dlg.ShowModal()
     self.assertEqual(dlg.GetValue(), 50)
     dlg.Destroy()
Esempio n. 7
0
 def MenuAdjSp(self, event):
     dlg = wx.NumberEntryDialog(
         self, "Set the milliseconds to wait after each move",
         "between 1 and 100", "Adjust speed", self.showMovesSpeed, 1, 100)
     if dlg.ShowModal() == wx.ID_OK:
         self.showMovesSpeed = dlg.GetValue()
         dlg.Destroy()
Esempio n. 8
0
 def on_set_brightness(self, event):
     dlg = wx.NumberEntryDialog(self.myapp_frame, "Enter brightness",
                                "Value", "Enter brightness",
                                const.CURRENT_BRIGHTNESS, 0, 255)
     if dlg.ShowModal() == wx.ID_OK:
         const.CURRENT_BRIGHTNESS = dlg.GetValue()
         send("b %s" % const.CURRENT_BRIGHTNESS)
     dlg.Destroy()
Esempio n. 9
0
 def on_set_speed(self, event):
     dlg = wx.NumberEntryDialog(self.myapp_frame, "Enter speed", "Value",
                                "Enter speed", const.CURRENT_SPEED, 10,
                                65535)
     if dlg.ShowModal() == wx.ID_OK:
         const.CURRENT_SPEED = dlg.GetValue()
         send("s %s" % const.CURRENT_SPEED)
     dlg.Destroy()
Esempio n. 10
0
	def doCustomSplitLap( self ):
		dlg = wx.NumberEntryDialog( self, message = "", caption = _("Add Missing Splits"), prompt = _("Missing Splits to Add:"),
									value = 1, min = 1, max = 500 )
		splits = None
		if dlg.ShowModal() == wx.ID_OK:
			splits = dlg.GetValue() + 1
		dlg.Destroy()
		if splits is not None:
			self.doSplitLap( splits )
Esempio n. 11
0
 def gotoline(self, e):
     dlg = wx.NumberEntryDialog(self, 'Enter line no:', 'Go', 'Goto Line',
                                1, 1, 9999)
     ans = dlg.ShowModal()
     n = dlg.GetValue()
     if ans == wx.ID_OK:
         self.control.GotoLine(n - 1)
     else:
         pass
Esempio n. 12
0
 def OnCompress(self,event):
     dlg = wx.NumberEntryDialog(self,'Reduce spectra resolution by',"compression ratio:","Compression Ratio",
                                 value=4, min=1, max=99)
     if dlg.ShowModal()== wx.ID_OK:
         cnum = dlg.GetValue()
         self.dataNew=self.compress(self.dataNew,cnum)
         MainWindow.dataNew=self.dataNew
         
     dlg.Destroy()
Esempio n. 13
0
 async def on_NumberEntryDialog(self, event):
     dlg = wx.NumberEntryDialog(self,
                                "message",
                                "prompt",
                                "caption",
                                100,
                                0,
                                1000,
                                pos=DefaultPosition)
     await self.ShowDialog(dlg)
Esempio n. 14
0
 def repeat_count(self, event):
     """Set the repeat count."""
     current_value = settings.CONFIG.getint('DEFAULT', 'Repeat Count')
     dialog = wx.NumberEntryDialog(None, message="Choose a repeat count",
                                   prompt="", caption="Repeat Count", value=current_value, min=1, max=999)
     dialog.ShowModal()
     new_value = str(dialog.Value)
     dialog.Destroy()
     settings.CONFIG['DEFAULT']['Repeat Count'] = new_value
     self.main_dialog.remaining_plays.Label = new_value
Esempio n. 15
0
    def OnGoToLine(self, event):
        editor = self.notebook.GetCurrentEditor()

        if editor:
            count = editor.GetLineCount()
            current = editor.GetCurrentLine()
            dlg = wx.NumberEntryDialog(self, 'Line Number', 'Go To Line', '',
                                       current, 1, count)

            if dlg.ShowModal() == wx.ID_OK:
                self.notebook.GoToLine(dlg.GetValue())
            dlg.Destroy()
Esempio n. 16
0
    def recording_timer(event):
        """Set the recording timer."""
        # Workaround for user upgrading from a previous version
        try:
            current_value = settings.CONFIG.getint(
                'DEFAULT', 'Recording Timer')
        except:
            current_value = 0

        dialog = wx.NumberEntryDialog(None, message="Choose an amount of time (seconds)",
                                      prompt="", caption="Recording Timer", value=current_value, min=0, max=999)
        dialog.ShowModal()
        new_value = dialog.Value
        dialog.Destroy()
        settings.CONFIG['DEFAULT']['Recording Timer'] = str(new_value)
Esempio n. 17
0
def OnGoToLine(self, event):
    (x, y) = self.editor.PositionToXY(self.editor.GetInsertionPoint())
    maxLine = self.editor.GetNumberOfLines()
    dialog = wx.NumberEntryDialog(self,
                                  caption="GoToLine",
                                  message="Go to line",
                                  prompt="Line",
                                  value=y,
                                  min=0,
                                  max=maxLine)
    if dialog.ShowModal() == wx.ID_OK:
        line = dialog.GetValue()
        line = max(0, min(self.editor.GetNumberOfLines(), line))
        self.editor.SetInsertionPoint(
            self.editor.XYToPosition(0, dialog.GetValue()))
    dialog.Destroy()
 def onPatchSize(self, e):
     '''Opens menu to set patch size'''
     ps = 'Enter patch size value:'
     dlg = wx.NumberEntryDialog(self, '', ps, 'Patch Size', self.patch_size,
                                1, 1000)
     wrongPS = 'Patch size must be odd.'
     if dlg.ShowModal() == wx.ID_OK:
         if dlg.GetValue() % 2 == 0:
             # patch size must be odd
             errorMsg = wx.MessageDialog(self, wrongPS, '', wx.OK)
             errorMsg.ShowModal()
             errorMsg.Destroy()
             dlg.ShowModal()
         else:
             self.patch_size = dlg.GetValue()
     dlg.Destroy()
Esempio n. 19
0
    def open_port_handler(self, event):
        import pyprt.sim.comm as comm
        common.interface = comm.ControlInterface(
            log=common.config_manager.get_comm_log_file())

        dialog = wx.NumberEntryDialog(
            self,
            message=
            "Debugging Tool.\nOpens the specified TCP port.\nThe sim will block until a controller\nconnects at the specified port.\n\nChoose connection port (TCP)",
            prompt='Port:',
            caption='Connect External Controller...',
            value=common.config_manager.get_TCP_port(),
            min=
            49152,  # Dynamic/Private port range. See: http://www.iana.org/assignments/port-numbers
            max=65535)
        if dialog.ShowModal() == wx.ID_OK:
            port_num = dialog.GetValue()
            common.interface.setup_server_sockets(TCP_port=port_num)
            common.interface.accept_connections(1)
            # Sim blocks, then resumes once connection is made.
            self.menubar_manager.controllers_connected()
Esempio n. 20
0
def number_entry_dialog(message="",prompt="",caption="",default=0,min=-2147483647,max=2147483647):
    response = None
    with wx.NumberEntryDialog(None,message,prompt,caption,default,min,max) as dialog:
        dialog.ShowModal()
        response = dialog.GetValue()
    return response
Esempio n. 21
0
    def ShowSimResult(self, event=None):
        """
        Display simulation results in the grid control
        """

        id = self.cc_id_sim.GetValue()  # Retrieve simulation ID from combo box
        if id == '': return
        id = int(id)

        # Find simulation results object related to current project
        cur_result = None
        for result in DB.SimulationResults.values():
            if result.ID == id and result.ProjectID == self.idPrj:
                cur_result = result
                break

        no_col = len(cur_result.DataColumns)
        no_row = len(cur_result.Data)

        no_grid_col = self.grid.GetNumberCols()
        no_grid_row = self.grid.GetNumberRows()

        # If there are too many records, allow the user to decide how many
        # to load to the system to reduce the load. It is impractical to show
        # very large simulation results.
        if no_col * no_row > 50000:
            dlg = wx.NumberEntryDialog(
                self, 'Define number or records to show',
                'The result grid is very large (' + str(no_row) + ' rows x ' +
                str(no_col) +
                ' columns) \nand it is probably not practical to show it on the screen. \nPlease decide how many rows you wish to view. \nNote that you can later export the results to view them in full in another application. \nPressing Cancel will show all rows and in some cases may overwhelm the system.',
                'Rows to show', 1000, 0, 100000)
            dlg.CenterOnScreen()
            if dlg.ShowModal() == wx.ID_OK:
                no_row = min(dlg.GetValue(), no_row)

        # adjust the number of rows and columns of the grid congtrol
        if no_col > no_grid_col:
            self.grid.AppendCols(no_col - no_grid_col)

        elif no_col < no_grid_col:
            self.grid.DeleteCols(no_col, no_grid_col - no_col)

        if no_row > no_grid_row:
            self.grid.AppendRows(no_row - no_grid_row)

        elif no_row < no_grid_row:
            self.grid.DeleteRows(no_row, no_grid_row - no_row)

        self.grid.ClearGrid()  # Clear current values in grid control

        dlg = wx.GenericProgressDialog(
            "Load Data",
            "Loading Data. Please wait......",
            maximum=no_col + no_row,
            parent=self,
            style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
        dlg.CenterOnScreen()

        for i, column in enumerate(
                cur_result.DataColumns):  # write column header on grid control
            self.grid.SetColLabelValue(i, column)
            dlg.Update(i)  # update length of gauge in progress dialog

        for i, row in enumerate(cur_result.Data[0:no_row]
                                ):  # write data in each cell in the range
            for j, col in enumerate(row):
                value = cdml.iif(row[j] == None, '', str(row[j]))
                self.grid.SetCellValue(i, j, value)

            dlg.Update(i + no_col)

        dlg.Destroy()
Esempio n. 22
0
    def OnCalibrateAstigmatism(self, event):
        #TODO - move all non-GUI logic for this out of this file?
        from PYME.recipes.measurement import FitPoints
        from PYME.IO.FileUtils import nameUtils
        import matplotlib.pyplot as plt
        import mpld3
        import json
        from PYME.Analysis.PSFEst import extractImages
        import wx
        from PYME.Analysis.points.astigmatism import astigTools

        # query user for type of calibration
        # NB - GPU fit is not enabled here because it exits on number of iterations, which is not necessarily convergence for very bright beads!
        ftypes = ['BeadConvolvedAstigGaussFit',
                  'AstigGaussFitFR']  # , 'AstigGaussGPUFitFR']
        fitType_dlg = wx.SingleChoiceDialog(self.dsviewer,
                                            'Fit-type selection',
                                            'Fit-type selection', ftypes)
        fitType_dlg.ShowModal()
        fitMod = ftypes[fitType_dlg.GetSelection()]

        if (fitMod == 'BeadConvolvedAstigGaussFit') and (
                'Bead.Diameter' not in self.image.mdh.keys()):
            beadDiam_dlg = wx.NumberEntryDialog(None, 'Bead diameter in nm',
                                                'diameter [nm]',
                                                'diameter [nm]', 100, 1, 9e9)
            beadDiam_dlg.ShowModal()
            beadDiam = float(beadDiam_dlg.GetValue())
            # store this in metadata
            self.image.mdh['Analysis.Bead.Diameter'] = beadDiam

        ps = self.image.pixelSize

        obj_positions = {}

        obj_positions['x'] = ps * self.image.data.shape[0] * 0.5 * np.ones(
            self.image.data.shape[2])
        obj_positions['y'] = ps * self.image.data.shape[1] * 0.5 * np.ones(
            self.image.data.shape[2])
        obj_positions['t'] = np.arange(self.image.data.shape[2])
        z = np.arange(
            self.image.data.shape[2]) * self.image.mdh['voxelsize.z'] * 1.e3
        obj_positions['z'] = z - z.mean()

        ptFitter = FitPoints()
        ptFitter.trait_set(roiHalfSize=11)
        ptFitter.trait_set(fitModule=fitMod)

        namespace = {'input': self.image, 'objPositions': obj_positions}

        results = []

        for chanNum in range(self.image.data.shape[3]):
            # get z centers
            dx, dy, dz = extractImages.getIntCenter(self.image.data[:, :, :,
                                                                    chanNum])

            ptFitter.trait_set(channel=chanNum)
            ptFitter.execute(namespace)

            res = namespace['fitResults']

            dsigma = abs(res['fitResults_sigmax']) - abs(
                res['fitResults_sigmay'])
            valid = ((res['fitError_sigmax'] > 0) *
                     (res['fitError_sigmax'] < 50) *
                     (res['fitError_sigmay'] < 50) *
                     (res['fitResults_A'] > 0) > 0)

            results.append({
                'sigmax':
                abs(res['fitResults_sigmax'][valid]).tolist(),
                'error_sigmax':
                abs(res['fitError_sigmax'][valid]).tolist(),
                'sigmay':
                abs(res['fitResults_sigmay'][valid]).tolist(),
                'error_sigmay':
                abs(res['fitError_sigmay'][valid]).tolist(),
                'dsigma':
                dsigma[valid].tolist(),
                'z':
                obj_positions['z'][valid].tolist(),
                'zCenter':
                obj_positions['z'][int(dz)]
            })

        #generate new tab to show results
        use_web_view = True
        if not '_astig_view' in dir(self):
            try:
                self._astig_view = wx.html2.WebView.New(self.dsviewer)
                self.dsviewer.AddPage(self._astig_view, True,
                                      'Astigmatic calibration')

            except NotImplementedError:
                use_web_view = False

        # find reasonable z range for each channel, inject 'zRange' into the results. FIXME - injection is bad
        results = astigTools.find_and_add_zRange(results)

        #do plotting
        plt.ioff()
        f = plt.figure(figsize=(10, 4))

        colors = iter(
            plt.cm.Dark2(np.linspace(0, 1, 2 * self.image.data.shape[3])))
        plt.subplot(121)
        for i, res in enumerate(results):
            nextColor1 = next(colors)
            nextColor2 = next(colors)
            lbz = np.absolute(res['z'] - res['zRange'][0]).argmin()
            ubz = np.absolute(res['z'] - res['zRange'][1]).argmin()
            plt.plot(res['z'], res['sigmax'], ':',
                     c=nextColor1)  # , label='x - %d' % i)
            plt.plot(res['z'], res['sigmay'], ':',
                     c=nextColor2)  # , label='y - %d' % i)
            plt.plot(res['z'][lbz:ubz],
                     res['sigmax'][lbz:ubz],
                     label='x - %d' % i,
                     c=nextColor1)
            plt.plot(res['z'][lbz:ubz],
                     res['sigmay'][lbz:ubz],
                     label='y - %d' % i,
                     c=nextColor2)

        #plt.ylim(-200, 400)
        plt.grid()
        plt.xlabel('z position [nm]')
        plt.ylabel('Sigma [nm]')
        plt.legend()

        plt.subplot(122)
        colors = iter(plt.cm.Dark2(np.linspace(0, 1,
                                               self.image.data.shape[3])))
        for i, res in enumerate(results):
            nextColor = next(colors)
            lbz = np.absolute(res['z'] - res['zRange'][0]).argmin()
            ubz = np.absolute(res['z'] - res['zRange'][1]).argmin()
            plt.plot(res['z'], res['dsigma'], ':', lw=2,
                     c=nextColor)  # , label='Chan %d' % i)
            plt.plot(res['z'][lbz:ubz],
                     res['dsigma'][lbz:ubz],
                     lw=2,
                     label='Chan %d' % i,
                     c=nextColor)
        plt.grid()
        plt.xlabel('z position [nm]')
        plt.ylabel('Sigma x - Sigma y [nm]')
        plt.legend()

        plt.tight_layout()

        plt.ion()
        #dat = {'z' : objPositions['z'][valid].tolist(), 'sigmax' : res['fitResults_sigmax'][valid].tolist(),
        #                   'sigmay' : res['fitResults_sigmay'][valid].tolist(), 'dsigma' : dsigma[valid].tolist()}

        if use_web_view:
            fig = mpld3.fig_to_html(f)
            data = json.dumps(results)

            template = env.get_template('astigCal.html')
            html = template.render(astigplot=fig, data=data)
            #print html
            self._astig_view.SetPage(html, '')
        else:
            plt.show()

        fdialog = wx.FileDialog(
            None,
            'Save Astigmatism Calibration as ...',
            wildcard='Astigmatism Map (*.am)|*.am',
            style=wx.FD_SAVE,
            defaultDir=nameUtils.genShiftFieldDirectoryPath(
            ))  #, defaultFile=defFile)
        succ = fdialog.ShowModal()
        if (succ == wx.ID_OK):
            fpath = fdialog.GetPath()

            fid = open(fpath, 'w', encoding='utf8')
            json.dump(results, fid, indent=4, sort_keys=True)
            fid.close()

        return results
    # Pick a Seeds.py file:
    seedPointsFile = wx.FileSelector('Pick a Seeds.py file')
    if os.path.split(seedPointsFile)[1] != 'Seeds.py':
        del (seedPointsFile)
        wx.MessageBox('You picked a file that was not a Seeds.py !')
        exit()

    # Load all the variables:
    Seeds = SWS.LoadSeedPointsFile(seedPointsFile)
    if Seeds == None:  # Exit if seedList or seedVals is missing
        exit()

    oldLength = len(Seeds.seedList)
    # Choose a new length:
    ndialog = wx.NumberEntryDialog(
        None, 'Choose a new length for\n' + seedPointsFile +
        '\n(old length is ' + str(oldLength) + ')', '', 'Set Seeds.py Length',
        oldLength, 0, 2**31 - 1)
    if ndialog.ShowModal() == wx.ID_CANCEL:
        exit()

    newLength = ndialog.GetValue()

    if newLength < oldLength:
        mdialog = wx.MessageDialog(
            None, 'You are potentially deleting data from\n' + seedPointsFile +
            '\n(You might want to make a backup first)' +
            '\nAre you sure you want to do this?')
        if mdialog.ShowModal() == wx.ID_CANCEL:
            exit()

    # Change all the variables:
Esempio n. 24
0
 def onChangeBtn(event):
     ned = wx.NumberEntryDialog(parent, "更改遍历层级数", "请输入数字", "更改配置",
                                int(val.GetLabel()), 1, maxLevelCnt)
     if ned.ShowModal() == wx.ID_OK:
         self.__cfg["level"] = int(ned.GetValue())
         val.SetLabel(str(ned.GetValue()))
Esempio n. 25
0
    def change_value(self, path, item):
        value_ = self.get_value(path, self.data)
        type_ = self.get_type(path, self.data)
        # print(value_)
        # print(type_)
        if type_:
            if type_ == int:
                with wx.NumberEntryDialog(self, "Change integer",
                                          "Enter value without a dot",
                                          "Integer", value_, -99999999,
                                          +99999999) as dialog:
                    dialog: wx.NumberEntryDialog
                    dialog.ShowModal()
                    value_ = dialog.GetValue()

                data = self.treeCtrl.GetItemData(item)
                data["value"] = value_
                self.treeCtrl.SetItemData(item, data)
            elif type_ == str:
                with wx.TextEntryDialog(self, "Change integer", "Integer",
                                        value_) as dialog:
                    dialog: wx.TextEntryDialog
                    dialog.ShowModal()
                    value_ = dialog.GetValue()

                data = self.treeCtrl.GetItemData(item)
                data["value"] = value_
                self.treeCtrl.SetItemData(item, data)
            elif type_ == bool:
                with wx.SingleChoiceDialog(self, "Choose 'True' or 'False'",
                                           "Boolean",
                                           ["True", "False"]) as dialog:
                    dialog: wx.SingleChoiceDialog
                    dialog.ShowModal()
                    choosen = dialog.GetStringSelection()
                    if choosen == "True":
                        data = self.treeCtrl.GetItemData(item)
                        data["value"] = True
                        self.treeCtrl.SetItemData(item, data)
                    elif choosen == "False":
                        data = self.treeCtrl.GetItemData(item)
                        data["value"] = False
                        self.treeCtrl.SetItemData(item, data)
                    else:
                        data = self.treeCtrl.GetItemData(item)
                        data["value"] = False
                        self.treeCtrl.SetItemData(item, data)
            elif type_ == float:
                with wx.TextEntryDialog(self, "Enter a decimal value (float)",
                                        "Float", str(value_)) as dialog:
                    dialog: wx.TextEntryDialog
                    dialog.ShowModal()

                    try:
                        value_ = float(dialog.GetValue())
                    except ValueError:
                        with wx.MessageDialog(
                                self, "Invalid Value!", "Error", wx.OK
                                | wx.CENTRE | wx.ICON_ERROR) as messageDialog:
                            messageDialog: wx.MessageDialog
                            messageDialog.ShowModal()
                        return

                    data = self.treeCtrl.GetItemData(item)
                    data["value"] = value_
                    self.treeCtrl.SetItemData(item, data)
            else:
                return

            if data["index"]:
                self.treeCtrl.SetItemText(item, self.nameColumn,
                                          f"{repr(data['index'])}")
                self.treeCtrl.SetItemText(item, self.valueColumn,
                                          f"{repr(data['value'])}")
            else:
                self.treeCtrl.SetItemText(item, self.nameColumn,
                                          f"{repr(data['name'])}")
                self.treeCtrl.SetItemText(item, self.valueColumn,
                                          f"{repr(data['value'])}")

            self.set_value(path, self.data, data['value'])
Esempio n. 26
0
    def SpecialRecordAdd(self, ClickedPanel):
        """ Add a special record - In this case this means a new population set
            Generated from a distribution population set """
        if ClickedPanel != None:
            RecordID = ClickedPanel.Key
            if (RecordID == 0 or RecordID
                    == None) or not DB.PopulationSets.has_key(RecordID):
                ReturnRecord = None
            else:
                if not DB.PopulationSets[RecordID].IsDistributionBased():
                    # This is a data population set
                    cdml.dlgSimpleMsg(
                        'ERROR',
                        'This population set is not based on distribution and therefore cannot be used to generate new population data',
                        Parent=self)
                    ReturnRecord = None
                else:
                    # This means this population set is defined by distributions
                    dlg = wx.NumberEntryDialog(
                        self, 'Define population size',
                        'Please enter the size of the population to generate ',
                        'Population Size', 1000, 0, 100000)
                    dlg.CenterOnScreen()
                    if dlg.ShowModal() != wx.ID_OK:
                        # If 'Cancel' button is clicked
                        ReturnRecord = None
                    else:
                        NumberOfIndividuals = dlg.GetValue(
                        )  # Get selection index
                        dlg.Destroy()
                        PopulationTraceBack = None
                        # When in admin mode, also ask for traceback info
                        AskForTraceBack = cdml.GetAdminMode()
                        if AskForTraceBack:
                            TraceBackText = cdml.dlgTextEntry(
                                Message=
                                'Please enter the Pickled TraceBack information as appear in the hidden report of the population you are trying to reconstruct ',
                                Caption='Enter Pickled TraceBack Info',
                                DefaultValue='',
                                Parent=self)
                            if TraceBackText == '':
                                PopulationTraceBack = None
                            else:
                                try:
                                    PopulationTraceBack = DB.pickle.loads(
                                        TraceBackText)
                                except:
                                    raise ValueError, 'TraceBack Error: Could not properly extract TraceBack - please make sure a proper TraceBack was entered'
                                    PopulationTraceBack = None

                        TheProgressDialog = None
                        try:
                            # version 2.5 does not support canceling simulation
                            TheProgressDialog = cdml.ProgressDialogTimeElapsed(
                                Parent=self,
                                StartTimerUponCreation=False,
                                AllowCancel=DB.SystemSupportsProcesses)

                            # Define the Function to run on a thread/process
                            def GenerationStartMiniScript():
                                "Compile and execute the generation"
                                Pop = DB.PopulationSets[RecordID]
                                # Compile the generation script with default options
                                ScriptFileNameFullPath = Pop.CompilePopulationGeneration(
                                    GeneratedPopulationSize=NumberOfIndividuals,
                                    GenerationFileNamePrefix=None,
                                    OutputFileNamePrefix=None,
                                    RandomStateFileNamePrefix=None,
                                    GenerationOptions=None,
                                    RecreateFromTraceBack=PopulationTraceBack)
                                # run the generation script
                                DeleteScriptFileAfterRun = not cdml.GetAdminMode(
                                )
                                (ProcessList,
                                 PipeList) = Pop.RunPopulationGeneration(
                                     GenerationFileName=ScriptFileNameFullPath,
                                     NumberOfProcessesToRun=-1,
                                     DeleteScriptFileAfterRun=
                                     DeleteScriptFileAfterRun)
                                return (ProcessList, PipeList)

                            def GenerationEndMiniScript(ProcessList, PipeList):
                                "Complete Generation by collecting results"
                                Pop = DB.PopulationSets[RecordID]
                                # Collect the results
                                RetVal = Pop.CollectResults(
                                    ProcessList, PipeList)
                                return RetVal

                            ThreadObject = cdml.WorkerThread(
                                GenerationStartMiniScript,
                                GenerationEndMiniScript)
                            # Tell the dialog box what to do when cancel is pressed
                            TheProgressDialog.FunctionToRunUponCancel = ThreadObject.StopProcess
                            # Now start the timer for the progress dialog box
                            TheProgressDialog.StartTimer()
                            # wait until thread/process exits
                            Info = ThreadObject.WaitForJob()
                            # Cancel through the dialog box is no longer possible
                            TheProgressDialog.FunctionToRunUponCancel = None
                            # Properly destroy the dialog

                            WasCanceled = TheProgressDialog.WasCanceled
                            TheProgressDialog.Destroy()
                            TheProgressDialog = None

                            if WasCanceled:
                                cdml.dlgSimpleMsg(
                                    'INFO',
                                    'The Population generation was canceled by request!',
                                    wx.OK,
                                    wx.ICON_INFORMATION,
                                    Parent=self)
                                ReturnRecord = None
                            else:
                                cdml.dlgSimpleMsg(
                                    'INFO',
                                    'The Population generation has finished successfully! After you press OK your cursor will be focused on the new population set.',
                                    wx.OK,
                                    wx.ICON_INFORMATION,
                                    Parent=self)
                                ReturnRecord = Info
                        except:
                            cdml.dlgErrorMsg()
                            ReturnRecord = None

                        # Properly destroy the progress dialog box if not done before
                        if TheProgressDialog != None:
                            TheProgressDialog.Destroy()

        return ReturnRecord
Esempio n. 27
0
 def onChangeBtn(event):
     ned = wx.NumberEntryDialog(parent, "更改遍历层级数", "请输入数字", "更改配置",
                                int(val.GetLabel()), 1, maxLevelCnt)
     if ned.ShowModal() == wx.ID_OK:
         _GG("CacheManager").setCache("maxLevel", int(ned.GetValue()))
         val.SetLabel(str(ned.GetValue()))