示例#1
0
    def ExportSimResult(self, event):
        evt_id = event.GetId()

        if evt_id == cdml.IDF_BUTTON1:

            id_sim = self.cc_id_sim.GetValue()  # Retrieve simulation ID from combo box
            if id_sim == "":
                return
            id_sim = int(id_sim)
            target_id = [
                result.ID
                for result in DB.SimulationResults.values()
                if result.ID == id_sim and result.ProjectID == self.idPrj
            ]
            if len(target_id) != 1:
                return None

            NewPath = self.GetExportFileName()
            if NewPath == None:
                return
            else:
                self.Path = NewPath  # replace previous path with current path
            try:
                DB.SimulationResults[id_sim].ExportAsCSV(self.Path)
            except:
                msg = "Could not complete saving into the selected file, check if the file is not in use or otherwise locked"
                cdml.dlgSimpleMsg("ERROR", msg, wx.OK, wx.ICON_ERROR, Parent=self)
                return False
        return True
示例#2
0
    def ExportSimResult(self, event):
        evt_id = event.GetId()

        if evt_id == cdml.IDF_BUTTON1:

            id_sim = self.cc_id_sim.GetValue(
            )  # Retrieve simulation ID from combo box
            if id_sim == '': return
            id_sim = int(id_sim)
            target_id = [
                result.ID for result in DB.SimulationResults.values()
                if result.ID == id_sim and result.ProjectID == self.idPrj
            ]
            if len(target_id) != 1:
                return None

            NewPath = self.GetExportFileName()
            if NewPath == None:
                return
            else:
                self.Path = NewPath  # replace previous path with current path
            try:
                DB.SimulationResults[id_sim].ExportAsCSV(self.Path)
            except:
                msg = 'Could not complete saving into the selected file, check if the file is not in use or otherwise locked'
                cdml.dlgSimpleMsg('ERROR',
                                  msg,
                                  wx.OK,
                                  wx.ICON_ERROR,
                                  Parent=self)
                return False
        return True
示例#3
0
    def CopyTransitionsFromAnotherStudyModel(self, event=None):
        """
        Allow the user to copy all the transitions from an existing study/model
        This will bring a dialog box for the user and allow choosing the study
        to copy transitions from.
        """

        DestinationStudyModelID = self.openData
        if DestinationStudyModelID == None or DestinationStudyModelID not in DB.StudyModels.keys():
            raise ValueError, "ASSERTION ERROR: invalid destination study model while copying"
            return

        SortedByNameStudyModelKeys = sorted(DB.StudyModels.keys(), key = lambda Entry: ( DB.StudyModels[Entry].Name , Entry))
        # For a study show studies to copy from, for a model show models.
        SourceStudyModelNames = map (lambda Entry: str(DB.StudyModels[Entry].Name), SortedByNameStudyModelKeys)
        
        dlg = wx.SingleChoiceDialog(self, 'Please select a Model to copy transitions from', 'Copy all Transitions From a Model', SourceStudyModelNames, wx.CHOICEDLG_STYLE )
        
        if dlg.ShowModal() == wx.ID_OK: # then open blank project form
            SelectionIndex = dlg.GetSelection()
            if 0 <= SelectionIndex <= (len(SourceStudyModelNames)-1):
                SourceStudyModelID = SortedByNameStudyModelKeys[SelectionIndex]
                frame = self.GetTopLevelParent()
                (RecordsCopied,RecordsToCopy) = DB.StudyModels[DestinationStudyModelID].CopyTransitionsFromAnotherStudyModel(SourceStudyModelID, ProjectBypassID = frame.idPrj)
                cdml.dlgSimpleMsg('Completed transition copying from another model', str(RecordsCopied) +' out of ' + str(RecordsToCopy) +' transitions were copied. ', wx.OK, wx.ICON_INFORMATION, Parent = self)
                self.InitTransitions()
示例#4
0
    def DeleteObjective(self):
        "Deletes an objective from the objectives list box"

        idx = self.lc_objectives.GetFirstSelected()
        if idx == -1:
            cdml.dlgSimpleMsg('ERROR',
                              'Please select an item to remove',
                              Parent=self)
            return

        # Remove from list
        (obj_filter_expr, obj_stat_expr, obj_stat_func, obj_target, obj_weight,
         obj_calculated, obj_error) = self.Objectives.pop(idx)
        # remove from list control display
        self.lc_objectives.DeleteItem(idx)

        if len(self.Objectives) > idx:
            self.lc_objectives.Select(idx, True)

        # update the text boxes with the deleted values
        self.tc_obj_filter_expr.SetValue(obj_filter_expr)
        self.tc_obj_stat_expr.SetValue(obj_stat_expr)
        self.cc_obj_stat_func.GetTextCtrl().SetValue(obj_stat_func)
        self.tc_obj_target.SetValue(DB.SmartStr(obj_target))
        self.tc_obj_weight.SetValue(DB.SmartStr(obj_weight))

        # handle hiding/showing controls according to distribution status
        if self.lc_objectives.GetItemCount() == 0:
            if self.lc_column.GetItemCount() == 0:
                self.HasDistribution = None
                self.ShowTabData()
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
示例#5
0
    def DeleteObjective(self):
        "Deletes an objective from the objectives list box"

        idx = self.lc_objectives.GetFirstSelected()
        if idx == -1 :
            cdml.dlgSimpleMsg('ERROR', 'Please select an item to remove', Parent = self)
            return

        # Remove from list
        (obj_filter_expr, obj_stat_expr, obj_stat_func, obj_target, obj_weight, obj_calculated, obj_error) = self.Objectives.pop(idx)
        # remove from list control display
        self.lc_objectives.DeleteItem(idx)

        if len(self.Objectives)>idx:
            self.lc_objectives.Select(idx, True)

        # update the text boxes with the deleted values
        self.tc_obj_filter_expr.SetValue(obj_filter_expr)
        self.tc_obj_stat_expr.SetValue(obj_stat_expr)
        self.cc_obj_stat_func.GetTextCtrl().SetValue(obj_stat_func)
        self.tc_obj_target.SetValue(DB.SmartStr(obj_target))
        self.tc_obj_weight.SetValue(DB.SmartStr(obj_weight))


        # handle hiding/showing controls according to distribution status
        if self.lc_objectives.GetItemCount() == 0:
            if self.lc_column.GetItemCount() == 0:
                self.HasDistribution = None
                self.ShowTabData()
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
示例#6
0
    def ExportCSV(self, DataColumns, Data):
        """ Export Population Data from a CSV file"""

        wildcard = "CSV File (*.csv)|*.csv| All files (*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose a file name to save the data",
                               os.getcwd(), "", wildcard,
                               wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

        if dialog.ShowModal() == wx.ID_OK:
            try:
                # convert the columns from tuples to strings
                ColumnHeadersToUse = map(
                    lambda (ColumnName, Distribution): ColumnName, DataColumns)
                DB.ExportDataToCSV(dialog.GetPath(), Data, ColumnHeadersToUse)
            except:
                cdml.dlgErrorMsg(Parent=self)

            else:
                # successfully saved the exported data
                cdml.dlgSimpleMsg(
                    'INFO',
                    'The data has been successfully saved to file',
                    wx.OK,
                    wx.ICON_INFORMATION,
                    Parent=self)

        self.Raise()
        dialog.Destroy()  # Destroy file selection dialog
示例#7
0
文件: Project.py 项目: ilanderma/MIST
 def ShowSimResult(self):
     """ Get user response to select simulation result file and open EXCEL to display CSV file"""
     RelevantSimulations = [ result.ID for result in DB.SimulationResults.values() if result.ProjectID == self.idPrj ]
     if RelevantSimulations != [] :
         cdml.OpenForm("ResultViewer", key=self.idPrj, parent=self, id_prj=self.idPrj)
     else:
         cdml.dlgSimpleMsg('INFO', 'No results exist for this project, run the simulation successfully to create results for this project', wx.OK, wx.ICON_INFORMATION, Parent = self)
     return
示例#8
0
    def DelSimResult(self, event):
        id = event.GetId()

        try:
            if id == wx.ID_DELETE:
                id = self.cc_id_sim.GetValue(
                )  # Retrieve simulation ID from combo box
                if id == '':
                    cdml.dlgSimpleMsg('ERROR',
                                      'No Result ID was selected',
                                      Parent=self)
                    return

                if self.cc_id_sim.GetCount() == 1:
                    msg = 'This is the last simulation result. '
                    msg += 'After deleting this result, the form will be closed automatically.'
                    msg += '\nDo you want to continue?'
                    ans = cdml.dlgSimpleMsg('WARNING',
                                            msg,
                                            wx.YES_NO,
                                            wx.ICON_WARNING,
                                            Parent=self)
                    if ans == wx.ID_NO: return

                id_sim = int(id)
                target_id = [
                    result.ID for result in DB.SimulationResults.values()
                    if result.ID == id_sim and result.ProjectID == self.idPrj
                ]

                if target_id == []: return

                DB.SimulationResults.Delete(target_id[0],
                                            ProjectBypassID=self.idPrj)

                self.cc_id_sim.Delete(self.cc_id_sim.GetSelection())
                self.grid.ClearGrid()

                if self.cc_id_sim.GetCount() == 0:
                    self.cc_id_sim.Clear()
                    self.cc_id_sim.SetValue('')
                else:
                    self.cc_id_sim.SetSelection(0)
                self.ShowSimResult()

            else:

                for result in DB.SimulationResults.values():
                    if result.ProjectID != self.idPrj: continue
                    DB.SimulationResults.Delete(result.ID,
                                                ProjectBypassID=self.idPrj)

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

        except:
            cdml.dlgErrorMsg()
示例#9
0
    def OnButtonClick(self, event):
        """ Event handler for buttons """

        btn_id = event.GetId()

        try:
            if btn_id == cdml.IDF_BUTTON2:  # Import
                self.ImportCSV()

            if btn_id == cdml.IDF_BUTTON3:  # Export
                try:
                    self.SaveData()
                    self.ShowData(self.DataColumns, self.Data, self.Objectives)
                except:
                    cdml.dlgErrorMsg(Parent=self)
                else:
                    if self.Data == []:
                        cdml.dlgSimpleMsg(
                            'INFO',
                            'No data has been defined so exporting makes no sense',
                            wx.OK,
                            wx.ICON_INFORMATION,
                            Parent=self)
                    else:
                        self.ExportCSV(self.DataColumns, self.Data)

            elif btn_id == cdml.IDF_BUTTON4:  # Undo
                self.Undo()

            elif btn_id == cdml.IDF_BUTTON5 or \
                event.GetEventType() == wx.wxEVT_CLOSE_WINDOW : # Ok or Close
                try:
                    self.SaveData()

                except:
                    cdml.dlgErrorMsg(Parent=self)

                else:
                    cdml.CloseForm(self, False)

            elif btn_id == wx.ID_ADD:  # Up Arrow : Add new State/Distribution
                self.AddColumn()

            elif btn_id == wx.ID_DELETE:  # Down Arrow : Delete State/Distribution
                self.DeleteColumn()

            elif btn_id == cdml.IDF_BUTTON7:  # Down Arrow in objective pane
                self.DeleteObjective()

            elif btn_id == cdml.IDF_BUTTON8:  # Up Arrow in objective pane
                self.AddObjective()

        except:
            cdml.dlgErrorMsg(Parent=self)
示例#10
0
    def DelSimResult(self, event):
        id = event.GetId()

        try:
            if id == wx.ID_DELETE:
                id = self.cc_id_sim.GetValue()  # Retrieve simulation ID from combo box
                if id == "":
                    cdml.dlgSimpleMsg("ERROR", "No Result ID was selected", Parent=self)
                    return

                if self.cc_id_sim.GetCount() == 1:
                    msg = "This is the last simulation result. "
                    msg += "After deleting this result, the form will be closed automatically."
                    msg += "\nDo you want to continue?"
                    ans = cdml.dlgSimpleMsg("WARNING", msg, wx.YES_NO, wx.ICON_WARNING, Parent=self)
                    if ans == wx.ID_NO:
                        return

                id_sim = int(id)
                target_id = [
                    result.ID
                    for result in DB.SimulationResults.values()
                    if result.ID == id_sim and result.ProjectID == self.idPrj
                ]

                if target_id == []:
                    return

                DB.SimulationResults.Delete(target_id[0], ProjectBypassID=self.idPrj)

                self.cc_id_sim.Delete(self.cc_id_sim.GetSelection())
                self.grid.ClearGrid()

                if self.cc_id_sim.GetCount() == 0:
                    self.cc_id_sim.Clear()
                    self.cc_id_sim.SetValue("")
                else:
                    self.cc_id_sim.SetSelection(0)
                self.ShowSimResult()

            else:

                for result in DB.SimulationResults.values():
                    if result.ProjectID != self.idPrj:
                        continue
                    DB.SimulationResults.Delete(result.ID, ProjectBypassID=self.idPrj)

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

        except:
            cdml.dlgErrorMsg()
示例#11
0
    def OnListDblClick(self, event):
        """Open Parameter form when the text control is clicked twice"""

        item = str(event.GetEventObject().GetValue())
        if item not in DB.Params.keys():
            if item != "":
                cdml.dlgSimpleMsg('ERROR', "Can not find a parameter named " + item, Parent = self)
                self.OnRefresh(None)
                return

        types = AllowedParameterTypesThatCanBeUsed
        cdml.OpenForm("Parameters", self, cdml.ID_MODE_SINGL, item, types)
示例#12
0
    def OnButtonClick(self, event):
        """ Event handler for buttons """

        btn_id = event.GetId()

        try:
            if btn_id == cdml.IDF_BUTTON2:  # Import
                self.ImportCSV()

            if btn_id == cdml.IDF_BUTTON3:  # Export
                try:
                    self.SaveData()
                    self.ShowData(self.DataColumns, self.Data, self.Objectives)
                except :
                    cdml.dlgErrorMsg(Parent = self)
                else:
                    if self.Data == []:
                        cdml.dlgSimpleMsg('INFO', 'No data has been defined so exporting makes no sense', wx.OK, wx.ICON_INFORMATION, Parent = self)
                    else:
                        self.ExportCSV(self.DataColumns, self.Data)

            elif btn_id == cdml.IDF_BUTTON4 :   # Undo
                self.Undo()

            elif btn_id == cdml.IDF_BUTTON5 or \
                event.GetEventType() == wx.wxEVT_CLOSE_WINDOW : # Ok or Close
                try:
                    self.SaveData()

                except :
                    cdml.dlgErrorMsg(Parent = self)

                else :
                    cdml.CloseForm(self, False)

            elif btn_id == wx.ID_ADD:           # Up Arrow : Add new State/Distribution
                self.AddColumn()

            elif btn_id == wx.ID_DELETE:        # Down Arrow : Delete State/Distribution
                self.DeleteColumn()

            elif btn_id == cdml.IDF_BUTTON7:    # Down Arrow in objective pane
                self.DeleteObjective()

            elif btn_id == cdml.IDF_BUTTON8:    # Up Arrow in objective pane
                self.AddObjective()
                
                
                

        except:
            cdml.dlgErrorMsg(Parent = self)
示例#13
0
文件: Project.py 项目: ilanderma/MIST
    def OnMenuSelected(self, event):
        """ Do something when action buttons are clicked.
            Action buttons are Save, Run Simulation, View Result and Close"""
        menuId = event.GetId()
        evtType = event.GetEventType()

        if evtType==wx.wxEVT_COMMAND_MENU_SELECTED:
            if menuId not in [cdml.ID_MENU_REPORT_ALL]:
                # Use the default handler first and if no more processing needed return
                if cdml.OnMenuSelected(self, event):
                    return

        try:
            # In any case, if a button - Save, Run, View Result - is clicked, data will be save
            save_ok = self.CheckData()

            if evtType == wx.wxEVT_CLOSE_WINDOW:    # Close Window Event
                #cdml.CloseForm(self, True, self.Collection, self.idPrj)
                cdml.CloseForm(self, True)
                return

            elif menuId == cdml.ID_MENU_COPY_RECORD:
                copy_ok = self.CopyProject()
                if not copy_ok: return
                cdml.dlgSimpleMsg('INFO', 'The project has been successfully copied - you are now working on the new copy', wx.OK, wx.ICON_INFORMATION, Parent = self)
            elif menuId == wx.ID_SAVE :
                if not save_ok: return
                cdml.dlgSimpleMsg('INFO', 'The project data has been saved successfully', wx.OK, wx.ICON_INFORMATION, Parent = self)

            elif menuId == wx.ID_APPLY:             # Run Simulation
                self.RunSimulation()

            elif menuId == wx.ID_VIEW_DETAILS:  # View Results / Extract PopulationSets
                self.ShowSimResult()

            elif menuId == wx.ID_CLEAR:

                result_ids = [ result.ID for result in DB.SimulationResults.values()
                                if result.ProjectID == self.idPrj ]

                if result_ids == [] :
                    cdml.dlgSimpleMsg('ERROR', "There are no simulation results for this project", Parent = self)
                else:
                    ans = cdml.dlgSimpleMsg('WARNING', 'Simulation results will be deleted permanently.\nDo you want to continue with deletion?', wx.YES_NO, wx.ICON_WARNING, Parent = self)
                    if ans == wx.ID_NO: return

                    for id in result_ids:
                        DB.SimulationResults.Delete(id, ProjectBypassID = self.idPrj)

                    cdml.dlgSimpleMsg('INFO', 'All simulation results were deleted', wx.OK, wx.ICON_INFORMATION, Parent = self)

        except:
            (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
            need_ans = cdml.iif(evtType == wx.wxEVT_CLOSE_WINDOW, True, False)
            if cdml.dlgErrorMsg(yesno=need_ans, Parent = self) == wx.ID_NO:
                cdml.CloseForm(self, False)
示例#14
0
 def OnLeftDblClick(self, event):
     """  Event handler to open 'State' form"""
     cc = event.GetEventObject().GetParent()
     id = cc.GetValue()
     frame = self.GetTopLevelParent()
     if id not in DB.States.keys():
         # If this is a listed subprocess - there may be a problem
         # Therefore, add the assertion check for this
         if id != 0:
             cdml.dlgSimpleMsg('Error', "ASSERTION ERROR: Can't find Main Process:" , Parent = self)
             return
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, -1, 'process', frame.idPrj)
     else:
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, id, 'process', frame.idPrj)
示例#15
0
    def OnListDblClick(self, event):
        """Open Parameter form when the text control is clicked twice"""

        item = str(event.GetEventObject().GetValue())
        if item not in DB.Params.keys():
            if item != "":
                cdml.dlgSimpleMsg('ERROR',
                                  "Can not find a parameter named " + item,
                                  Parent=self)
                self.OnRefresh(None)
                return

        types = AllowedParameterTypesThatCanBeUsed
        cdml.OpenForm("Parameters", self, cdml.ID_MODE_SINGL, item, types)
示例#16
0
    def OnMenuSelected(self, event):
        """ Event handler for buttons and menu items in main form"""

        menuId = event.GetId()
        if menuId in [ wx.ID_NEW, wx.ID_OPEN ]:     # New and Open menu
            self.OpenDB(menuId)                     # open dialog to select database file


        elif menuId == cdml.ID_MENU_COPY_RECORD:
            self.CopyProjectRecord()        

        elif menuId == cdml.ID_MENU_DELETE_RECORD:
            self.DeleteProjectRecord()        

        elif menuId in [ wx.ID_SAVE, wx.ID_SAVEAS ]: # save or save as menu
            self.SaveDB(menuId)

        elif menuId in range(cdml.IDF_BUTTON1, cdml.IDF_BUTTON10): # Items in Data Menu and buttons
            # check database was loaded
            if not self._db_opened:
                cdml.dlgSimpleMsg('WARNING', "No data is loaded to the system. Please select 'New' or 'Open' in File menu", wx.OK, wx.ICON_WARNING, Parent = self)
                return

            btn = self.FindWindowById(menuId)   # synchronize selected menu to a button
            if btn.userData == None : return  # target for should be assigned to each button
                                                # as user data to avoid import statement.
                                                # See __set_properties method


            if btn.userData == 'Transitions' and len(DB.StudyModels) == 0:
                cdml.dlgSimpleMsg('ERROR', 'A Model should be defined', Parent = self)
                return

            cdml.OpenForm(btn.userData, self)   # open a form as default mode(=None)

        elif menuId in [cdml.ID_MENU_ABOUT, cdml.ID_MENU_HELP, cdml.ID_MENU_HELP_GENERAL]:
            cdml.OnMenuSelected(self, event)

        elif menuId == cdml.ID_MENU_REPORT_THIS: # Create a report for a specific project
            index = self.lc_project.GetFirstSelected()
            if index in [ -1, 0 ]: # -1 : nothing selected, 0 'New Project' selected
                return
            ProjectCode = self.IndexToPID[index]
            if ProjectCode in DB.Projects.keys():
                cdml.OpenForm("ReportViewer",self, key=(DB.Projects[ProjectCode],None) )

        elif menuId == cdml.ID_MENU_REPORT_ALL: # Create a report for all projects
            CollectionObject = DB.Projects
            if CollectionObject != None:
                cdml.OpenForm("ReportViewer",self,key=(CollectionObject,None) )
示例#17
0
    def OnButtonDblClick(self, event):
        """
        Event handler to open child form
        """
        tc = event.GetEventObject()
        cc = tc.GetParent()

        if cc.Id in [cdml.IDP_BUTTON1, cdml.IDP_BUTTON2]:
            collection = DB.States
            key = cc.GetValue()
            form = 'States'
            type_parm = ''

        elif tc.Id == cdml.IDP_BUTTON3:
            collection = DB.Params
            key = tc.GetValue()
            form = 'Parameters'
            if tc.Id == cdml.IDP_BUTTON3:
                type_parm = ['Number', 'Integer', 'Epression']
        else:
            raise ValueError, "Assertion Error: Button does not exist"

        if key == '' or key == 0:
            msg = 'This ' + form[:-1] + ' is not defined yet.\n'
            msg += "Do you want to create a new " + form[:-1] + '?'
            ans = cdml.dlgSimpleMsg('ERROR',
                                    msg,
                                    wx.YES_NO,
                                    wx.ICON_ERROR,
                                    Parent=self)

            if ans == wx.ID_NO: return
            cdml.OpenForm(form, self, cdml.ID_MODE_SINGL, key, type_parm)

        elif not cdml.GetRecordByKey(collection, key):
            msg = 'The entry "' + str(
                key) + '" does not exist in ' + form + '.'
            ans = cdml.dlgSimpleMsg('ERROR',
                                    msg,
                                    wx.OK,
                                    wx.ICON_ERROR,
                                    Parent=self)
            return

        else:
            frame = self.GetTopLevelParent()
            cdml.OpenForm(form, self, cdml.ID_MODE_SINGL, key, type_parm,
                          frame.idPrj)
示例#18
0
    def OpenDB(self, menuId):
        if DB.AccessDirtyStatus():
            ans = cdml.dlgSimpleMsg('WARNING', "The data is not saved in a file. Do you want to save it?", wx.YES_NO|wx.CANCEL, wx.ICON_WARNING, Parent = self)
            if ans == wx.ID_YES :
                if not self.SaveDB(wx.ID_SAVE): return
            if ans == wx.ID_CANCEL:
                return

        if menuId == wx.ID_NEW:                     # if New menu selected,
            path = os.getcwd() + os.sep + 'new_file.zip'        #   set dummy path
        else:
            path = self.GetNameDB(wx.OPEN)          # else get database name

            if path == None : return

            if not os.path.isfile(path):
                cdml.dlgSimpleMsg('ERROR', 'The file does not exist, please make sure the path is valid', Parent = self)
                return
            
        wx.BeginBusyCursor()
        reload(DB)
        try:
            if os.path.isfile(path):
                # test the version of the file:
                (FileVersion, IsCompatible, IsUpgradable, DidLoad, HasResults) = DB.ReconstructDataFileAndCheckCompatibility(InputFileName = path, JustCheckCompatibility = True, RegenerationScriptName = None, ConvertResults = False, KnownNumberOfErrors = 0, CatchError = True)
                if IsCompatible:
                    # If versions are compatible, just load the file
                    DB.LoadAllData(path)   # If Open menu, load data
                elif IsUpgradable:
                    if HasResults:
                        wx.EndBusyCursor()
                        AnswerForConvertResults = cdml.dlgSimpleMsg('Data Conversion', 'This file was generated with an older version of data definitions.: ' + str(FileVersion) +  '. It was converted to the new version ' + str (DB.Version) + ' . Converting simulation results may take a long time and such results may not be reproducible with the current version. Even if simulation results are not loaded, the parameters, states, models, Population sets and projects will be loaded.\nDo you wish to convert simulation results from this file? ', wx.YES_NO, wx.ICON_QUESTION, Parent = self)
                        AnswerForConvertResultsBoolean = AnswerForConvertResults == wx.ID_YES
                        wx.BeginBusyCursor()
                    else:
                        AnswerForConvertResultsBoolean = False
                        print '*** Converting file to the new version. Please wait - this may take a while ***'
                    # if a version upgrade is needed, convert the data
                    (FileVersion, IsCompatible, IsUpgradable, DidLoad, HasResults) = DB.ReconstructDataFileAndCheckCompatibility(InputFileName = path, JustCheckCompatibility = False, RegenerationScriptName = None, ConvertResults = AnswerForConvertResultsBoolean, KnownNumberOfErrors = 0, CatchError = True)
                
            self.ShowProjectList(None)
            self.SetTitle("MIST - " + path)
            self._db_opened = True
            self._path = path

        except:
            cdml.dlgErrorMsg(Parent = self)
        wx.EndBusyCursor()
示例#19
0
文件: MISTGUI.py 项目: ilanderma/MIST
    def DeleteProjectRecord(self):
        """ Delete the Project record pointed on in the list"""
        index = self.lc_project.GetFirstSelected()
        if index in [-1, 0
                     ]:  # -1 : nothing selected, 0 : or selected 'New Project'
            return

        msg = 'Selected project will be deleted permanently.\n'
        msg += 'Are you sure you want to delete the selected project?'
        ans = cdml.dlgSimpleMsg('WARNING',
                                msg,
                                wx.YES_NO,
                                wx.ICON_WARNING,
                                Parent=self)

        if ans == wx.ID_NO: return

        ProjectIndex = self.lc_project.GetItemData(index)

        pid = self.IndexToPID[ProjectIndex]

        if pid not in DB.Projects.keys(): return

        try:
            DB.Projects.Delete(pid)  # delete database object
            self.ShowProjectList()
            # set the focus on the next record after the deleted one
            self.lc_project.Select(index)
        except:
            cdml.dlgErrorMsg(Parent=self)
示例#20
0
    def DeleteProjectRecord(self):
        """ Delete the Project record pointed on in the list"""
        index = self.lc_project.GetFirstSelected()
        if index in [ -1, 0 ]: # -1 : nothing selected, 0 : or selected 'New Project'
            return

        msg = 'Selected project will be deleted permanently.\n'
        msg += 'Are you sure you want to delete the selected project?'
        ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING, Parent = self)

        if ans == wx.ID_NO: return

        ProjectIndex = self.lc_project.GetItemData(index)

        pid = self.IndexToPID[ProjectIndex]

        if pid not in DB.Projects.keys(): return

        try:
            DB.Projects.Delete(pid)                     # delete database object
            self.ShowProjectList()
            # set the focus on the next record after the deleted one
            self.lc_project.Select(index)
        except:
            cdml.dlgErrorMsg(Parent = self)
示例#21
0
 def SaveReport(self, menuId=wx.ID_SAVE):
     """ Save current report"""
     if '*' in self.Path or menuId == wx.ID_SAVEAS:
         NewPath = self.GetReportFileName()
         if NewPath == None: 
             return False
         else:
             self.Path = NewPath # replace previous path with current path
     try:
         OutputFileName = open(self.Path,'w')
         OutputFileName.write(self.ReportText)
         OutputFileName.close()        
     except:
         msg = 'Could not complete saving into the selected file, check if the file is not in use or otherwise locked'
         cdml.dlgSimpleMsg('ERROR', msg, wx.OK, wx.ICON_ERROR, Parent = self)
         return False
     return True
示例#22
0
 def SaveReport(self, menuId=wx.ID_SAVE):
     """ Save current report"""
     if '*' in self.Path or menuId == wx.ID_SAVEAS:
         NewPath = self.GetReportFileName()
         if NewPath == None:
             return False
         else:
             self.Path = NewPath  # replace previous path with current path
     try:
         OutputFileName = open(self.Path, 'w')
         OutputFileName.write(self.ReportText)
         OutputFileName.close()
     except:
         msg = 'Could not complete saving into the selected file, check if the file is not in use or otherwise locked'
         cdml.dlgSimpleMsg('ERROR', msg, wx.OK, wx.ICON_ERROR, Parent=self)
         return False
     return True
示例#23
0
 def OnLeftDblClick(self, event):
     """  Event handler to open 'State' form"""
     cc = event.GetEventObject().GetParent()
     id = cc.GetValue()
     frame = self.GetTopLevelParent()
     if id not in DB.States.keys():
         # If this is a listed subprocess - there may be a problem
         # Therefore, add the assertion check for this
         if id != 0:
             cdml.dlgSimpleMsg('Error',
                               "ASSERTION ERROR: Can't find Main Process:",
                               Parent=self)
             return
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, -1, 'process',
                       frame.idPrj)
     else:
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, id, 'process',
                       frame.idPrj)
示例#24
0
    def OnButtonClick(self, event):
        """
        Event handler to respond to the button click event.
        Open Transition Form or create a copy of current Model
        New control mechanism may need to make more general method to open and manage child form
        """

        id = event.GetId()
        if id == cdml.IDP_BUTTON1: # open transition form
            if self.Id == 0 :
                cdml.dlgSimpleMsg('ERROR', "This model is Empty. Please enter data before transitions", Parent = self)
                return

            frame = self.GetTopLevelParent()
            cdml.OpenForm('Transitions', self, cdml.ID_MODE_MULTI, self.Key, None, frame.idPrj)

        elif id == cdml.IDP_BUTTON2:
            cdml.dlgNotPrepared()
示例#25
0
    def CopyTransitionsFromAnotherStudyModel(self, event=None):
        """
        Allow the user to copy all the transitions from an existing study/model
        This will bring a dialog box for the user and allow choosing the study
        to copy transitions from.
        """

        DestinationStudyModelID = self.openData
        if DestinationStudyModelID == None or DestinationStudyModelID not in DB.StudyModels.keys(
        ):
            raise ValueError, "ASSERTION ERROR: invalid destination study model while copying"
            return

        SortedByNameStudyModelKeys = sorted(
            DB.StudyModels.keys(),
            key=lambda Entry: (DB.StudyModels[Entry].Name, Entry))
        # For a study show studies to copy from, for a model show models.
        SourceStudyModelNames = map(
            lambda Entry: str(DB.StudyModels[Entry].Name),
            SortedByNameStudyModelKeys)

        dlg = wx.SingleChoiceDialog(
            self, 'Please select a Model to copy transitions from',
            'Copy all Transitions From a Model', SourceStudyModelNames,
            wx.CHOICEDLG_STYLE)

        if dlg.ShowModal() == wx.ID_OK:  # then open blank project form
            SelectionIndex = dlg.GetSelection()
            if 0 <= SelectionIndex <= (len(SourceStudyModelNames) - 1):
                SourceStudyModelID = SortedByNameStudyModelKeys[SelectionIndex]
                frame = self.GetTopLevelParent()
                (RecordsCopied, RecordsToCopy) = DB.StudyModels[
                    DestinationStudyModelID].CopyTransitionsFromAnotherStudyModel(
                        SourceStudyModelID, ProjectBypassID=frame.idPrj)
                cdml.dlgSimpleMsg(
                    'Completed transition copying from another model',
                    str(RecordsCopied) + ' out of ' + str(RecordsToCopy) +
                    ' transitions were copied. ',
                    wx.OK,
                    wx.ICON_INFORMATION,
                    Parent=self)
                self.InitTransitions()
示例#26
0
    def ExportCSV(self, DataColumns, Data ):
        """ Export Population Data from a CSV file"""

        wildcard = "CSV File (*.csv)|*.csv| All files (*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose a file name to save the data", os.getcwd(), "", wildcard, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

        if dialog.ShowModal() == wx.ID_OK:
            try:
                # convert the columns from tuples to strings
                ColumnHeadersToUse = map(lambda (ColumnName , Distribution) : ColumnName, DataColumns)
                DB.ExportDataToCSV(dialog.GetPath(), Data, ColumnHeadersToUse)
            except:
                cdml.dlgErrorMsg(Parent = self)

            else:
                # successfully saved the exported data
                cdml.dlgSimpleMsg('INFO', 'The data has been successfully saved to file', wx.OK, wx.ICON_INFORMATION, Parent = self)

        self.Raise()
        dialog.Destroy() # Destroy file selection dialog
示例#27
0
    def OnExit(self, event):
        """ Event handler for Exit menu or CLOSE_WINDOW event"""

        if DB.AccessDirtyStatus(): # If there is unsaved data
            ans = cdml.dlgSimpleMsg('WARNING', "The data was not saved to a file. Do you want to save it?", wx.YES_NO|wx.CANCEL, wx.ICON_WARNING, Parent = self)
            if ans == wx.ID_YES:
                if not self.SaveDB(wx.ID_CLOSE) : return

            elif ans == wx.ID_CANCEL: return

        self.MyMakeModal(False)
        self.Destroy()
示例#28
0
    def OnButtonClick(self, event):
        """
        Event handler to respond to the button click event.
        Open Transition Form or create a copy of current Model
        New control mechanism may need to make more general method to open and manage child form
        """

        id = event.GetId()
        if id == cdml.IDP_BUTTON1:  # open transition form
            if self.Id == 0:
                cdml.dlgSimpleMsg(
                    'ERROR',
                    "This model is Empty. Please enter data before transitions",
                    Parent=self)
                return

            frame = self.GetTopLevelParent()
            cdml.OpenForm('Transitions', self, cdml.ID_MODE_MULTI, self.Key,
                          None, frame.idPrj)

        elif id == cdml.IDP_BUTTON2:
            cdml.dlgNotPrepared()
示例#29
0
    def OnButtonDblClick(self, event):
        """
        Event handler to open child form
        """
        tc = event.GetEventObject()
        cc = tc.GetParent()

        if cc.Id in [ cdml.IDP_BUTTON1, cdml.IDP_BUTTON2 ]:
            collection = DB.States
            key = cc.GetValue()
            form = 'States'
            type_parm = ''

        elif tc.Id == cdml.IDP_BUTTON3:
            collection = DB.Params
            key = tc.GetValue()
            form = 'Parameters'
            if tc.Id == cdml.IDP_BUTTON3:
                type_parm = [ 'Number', 'Integer', 'Epression']
        else:
            raise ValueError, "Assertion Error: Button does not exist"

        if key == '' or key == 0:
            msg = 'This ' + form[:-1] + ' is not defined yet.\n'
            msg += "Do you want to create a new " + form[:-1] + '?'
            ans = cdml.dlgSimpleMsg('ERROR', msg, wx.YES_NO, wx.ICON_ERROR, Parent = self)

            if ans == wx.ID_NO : return
            cdml.OpenForm(form, self, cdml.ID_MODE_SINGL, key, type_parm)

        elif not cdml.GetRecordByKey(collection, key) :
            msg = 'The entry "' + str(key) + '" does not exist in ' + form + '.'
            ans = cdml.dlgSimpleMsg('ERROR', msg, wx.OK, wx.ICON_ERROR, Parent = self)
            return

        else:
            frame = self.GetTopLevelParent()
            cdml.OpenForm(form, self, cdml.ID_MODE_SINGL, key, type_parm, frame.idPrj)
示例#30
0
    def SaveData(self):
        """ Gather current DataColumns/Data and then save it to list of parent panel"""
        no_column = self.lc_column.GetItemCount()

        DataColumns = self.DataColumns
        Data = []

        if self.nb.GetPageCount() > 2:
            if no_column != self.grid_1.GetNumberCols():
                raise ValueError, 'The number of columns is different from the columns in the data tab'

            for i in range(self.grid_1.GetNumberRows()):
                row = []
                for j in range(no_column):
                    value = self.grid_1.GetCellValue(i, j)
                    if value == '':
                        value = None
                    else:
                        value = float(value)
                    row.append(value)
                Data.append(row)

        if self.Data != Data:
            # If data was changed and distributions exists in a data population
            # then this means that objectives should not be saved verify this
            # with the user before continuing
            if self.Objectives != [] and not self.HasDistribution:
                #
                msg = 'There are Objective information related to this population set - and data was modified by the user. Maintaining the objectives form calculation is therefore not allowed. The system can delete all Objective information for you. Do you want to continue and delete the objective information?'
                ans = cdml.dlgSimpleMsg('WARNING',
                                        msg,
                                        wx.YES_NO,
                                        wx.ICON_WARNING,
                                        Parent=self)
                if ans == wx.ID_YES:
                    # remove from list control display
                    self.lc_objectives.DeleteAllItems()
                    self.Objectives = []
                    self.ShowTabData()
                else:
                    raise ValueError, 'Data was modified by the user while objectives information exists. Either undo data changes or delete objectives to allow retaining the changes'

        self.Data = Data
        Objectives = self.Objectives

        parent = self.GetParent()
        if parent != None:
            parent.DataColumns = DataColumns
            parent.Data = Data
            parent.Objectives = Objectives
示例#31
0
    def SaveData(self):
        """ Gather current DataColumns/Data and then save it to list of parent panel"""
        no_column = self.lc_column.GetItemCount()

        DataColumns = self.DataColumns
        Data = []

        if self.nb.GetPageCount() > 2:
            if no_column != self.grid_1.GetNumberCols():
                raise ValueError, 'The number of columns is different from the columns in the data tab'

            for i in range(self.grid_1.GetNumberRows()):
                row = []
                for j in range(no_column):
                    value = self.grid_1.GetCellValue(i,j)
                    if value == '':
                        value = None
                    else:
                        value = float(value)
                    row.append(value)
                Data.append(row)

        if self.Data != Data:
            # If data was changed and distributions exists in a data population
            # then this means that objectives should not be saved verify this
            # with the user before continuing
            if self.Objectives != [] and not self.HasDistribution:
                # 
                msg = 'There are Objective information related to this population set - and data was modified by the user. Maintaining the objectives form calculation is therefore not allowed. The system can delete all Objective information for you. Do you want to continue and delete the objective information?'
                ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING, Parent = self)
                if ans == wx.ID_YES: 
                    # remove from list control display
                    self.lc_objectives.DeleteAllItems()
                    self.Objectives=[]
                    self.ShowTabData()
                else:
                    raise ValueError, 'Data was modified by the user while objectives information exists. Either undo data changes or delete objectives to allow retaining the changes'
                
        self.Data = Data
        Objectives = self.Objectives

        parent = self.GetParent()
        if parent != None:
            parent.DataColumns = DataColumns
            parent.Data = Data
            parent.Objectives = Objectives
示例#32
0
文件: MISTGUI.py 项目: ilanderma/MIST
    def OnExit(self, event):
        """ Event handler for Exit menu or CLOSE_WINDOW event"""

        if DB.AccessDirtyStatus():  # If there is unsaved data
            ans = cdml.dlgSimpleMsg(
                'WARNING',
                "The data was not saved to a file. Do you want to save it?",
                wx.YES_NO | wx.CANCEL,
                wx.ICON_WARNING,
                Parent=self)
            if ans == wx.ID_YES:
                if not self.SaveDB(wx.ID_CLOSE): return

            elif ans == wx.ID_CANCEL: return

        self.MyMakeModal(False)
        self.Destroy()
示例#33
0
 def OnLeftDblClick(self, event):
     """  Event handler to open 'State' form"""
     eventType = event.GetEventType()
     if eventType == wx.EVT_LEFT_DCLICK.typeId:
         id = self.cc_states.GetValue()
     elif eventType == wx.EVT_LIST_ITEM_ACTIVATED.typeId:
         index = self.lc_states.GetFirstSelected()
         id = self.lc_states.GetItemData(index)
     frame = self.GetTopLevelParent()
     if id not in DB.States.keys():
         # This code will never be reached since an empty list box
         # will not trigger this function. However, it is left here
         # since in the future this function may be called from another
         # control without properly defining a state.
         msg = "No state was selected" 
         msg += "\nDo you want to create new state?"
         ans = cdml.dlgSimpleMsg('ERROR', msg, wx.YES_NO , Parent = self)
         if ans == wx.ID_NO : return
         id =-1
     NoError = frame.ForceRecordSaveAttempt()
     if NoError:
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, id, '', frame.idPrj)
示例#34
0
文件: States.py 项目: ilanderma/MIST
 def OnLeftDblClick(self, event):
     """  Event handler to open 'State' form"""
     eventType = event.GetEventType()
     if eventType == wx.EVT_LEFT_DCLICK.typeId:
         id = self.cc_states.GetValue()
     elif eventType == wx.EVT_LIST_ITEM_ACTIVATED.typeId:
         index = self.lc_states.GetFirstSelected()
         id = self.lc_states.GetItemData(index)
     frame = self.GetTopLevelParent()
     if id not in DB.States.keys():
         # This code will never be reached since an empty list box
         # will not trigger this function. However, it is left here
         # since in the future this function may be called from another
         # control without properly defining a state.
         msg = "No state was selected"
         msg += "\nDo you want to create new state?"
         ans = cdml.dlgSimpleMsg('ERROR', msg, wx.YES_NO, Parent=self)
         if ans == wx.ID_NO: return
         id = -1
     NoError = frame.ForceRecordSaveAttempt()
     if NoError:
         cdml.OpenForm('States', self, cdml.ID_MODE_SINGL, id, '',
                       frame.idPrj)
示例#35
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
示例#36
0
文件: Project.py 项目: ilanderma/MIST
    def RunSimulation(self):
        """ Simulation control routine. Check user response to begin simulation and display messages"""

        ans = cdml.dlgSimpleMsg('INFO', 'Running a simulation may take some time. Do you want to continue?', wx.YES_NO, wx.ICON_INFORMATION, Parent = self)
        if ans == wx.ID_NO: return

        TheProgressDialog = None
        try:
            def ExtractTraceBack():
                try:
                    # Extract Traceback if exists
                    TraceBackText = self.tab2_tc_TraceBack.GetValue()
                    if TraceBackText == '':
                        SimulationTraceBack = None
                    else:
                        SimulationTraceBack = DB.pickle.loads(TraceBackText)
                except:
                    raise ValueError, 'TraceBack Error: Could not properly extract TraceBack - please make sure a proper TraceBack was entered'
                    SimulationTraceBack = None
                return SimulationTraceBack
                            
            # 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"
                prj = DB.Projects[self.idPrj]
                PopID = prj.PrimaryPopulationSetID
                NumberOfRepetitions = prj.NumberOfRepetitions
                Pop = DB.PopulationSets[PopID]
                
                if Pop.IsDistributionBased():
                    SimulationTraceBack = ExtractTraceBack()
                    if SimulationTraceBack == None:
                        PopulationTraceBack = None
                    else:
                        PopulationTraceBack = SimulationTraceBack[-1]
                    # if the population is distribution based, then 
                    # Compile the generation script with default options
                    ScriptFileNameFullPath = Pop.CompilePopulationGeneration(GeneratedPopulationSize = NumberOfRepetitions, 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)
                else:
                    # otherwise don't run anything                    
                    (ProcessList, PipeList) = (None,None)
                return (ProcessList, PipeList)
            
            def GenerationEndMiniScript(ProcessList, PipeList):
                "Complete Generation by collecting results"
                prj = DB.Projects[self.idPrj]
                PopID = prj.PrimaryPopulationSetID
                Pop = DB.PopulationSets[PopID]
                if (ProcessList, PipeList) == (None,None):
                    # if nothing was run, then return no replacement population
                    RetVal = None
                else:
                    # If a process was run, return the replacement population
                    RetVal = Pop.CollectResults(ProcessList, PipeList)
                # Collect the results
                return RetVal

            def SimulationStartMiniScript():
                "Compile and execute the simulation"
                SimulationTraceBack = ExtractTraceBack()
                prj = DB.Projects[self.idPrj]
                # if an override population is defined, this means it was
                # generated from distributions and therefore repetitions should
                # be 1 as the number of repetitions defined the population size
                if self.TempOverridePopulationSet == None:
                    OverrideRepetitionCount = None
                else:
                    OverrideRepetitionCount = 1
                ScriptFileName = prj.CompileSimulation(OverrideRepetitionCount = OverrideRepetitionCount, OverridePopulationSet = self.TempOverridePopulationSet, RecreateFromTraceBack = SimulationTraceBack)
                # run the simulation once without collecting results
                # also do nto delete the compiled script file if in Admin mode
                DeleteScriptFileAfterRun = not cdml.GetAdminMode()
                (ProcessList, PipeList) = prj.RunSimulation(ScriptFileName, NumberOfProcessesToRun = -1, DeleteScriptFileAfterRun = DeleteScriptFileAfterRun)
                return (ProcessList, PipeList)

            def SimulationEndMiniScript(ProcessList, PipeList):
                "Complete Simulation by collecting results"
                prj = DB.Projects[self.idPrj]
                RetVal = prj.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
            # Figure out if cancel was pressed:
            WasCanceled = TheProgressDialog.WasCanceled
            if not WasCanceled:
                # set the override population to the result - None means no override
                self.TempOverridePopulationSet = Info
                # Now actually run the simulation
                ThreadObject = cdml.WorkerThread(SimulationStartMiniScript,SimulationEndMiniScript)
                # Tell the dialog box what to do when cancel is pressed
                TheProgressDialog.FunctionToRunUponCancel = ThreadObject.StopProcess
                # 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
            # Properly destroy the dialog 
            TheProgressDialog.Destroy()
            TheProgressDialog = None
                
            if WasCanceled:
                cdml.dlgSimpleMsg('INFO', 'The simulation was canceled by request!', wx.OK, wx.ICON_INFORMATION, Parent = self)
            elif Info.ProjectID == self.idPrj:
                cdml.dlgSimpleMsg('INFO', 'The simulation has finished successfully!', wx.OK, wx.ICON_INFORMATION, Parent = self)
            else:
                raise ValueError, 'ASSERTION ERROR: wrong project ID returned'
        except:
            cdml.dlgErrorMsg(Parent = self)
        # Release the override population if set
        self.TempOverridePopulationSet = None

        # Properly destroy the progress dialog box if not done before
        if TheProgressDialog != None:
            TheProgressDialog.Destroy()
示例#37
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
示例#38
0
文件: MISTGUI.py 项目: ilanderma/MIST
if __name__ == "__main__":
    # uncomment the next four lines for inspection and replace the app for
    # inspection mode
    #from wx.lib.mixins.inspection import InspectableApp
    #app = InspectableApp()
    #import wx.lib.inspection
    #wx.lib.inspection.InspectionTool().Show()
    app = wx.App(0)
    # wx.InitAllImageHandlers() - deprecated - no longer needed

    if len(sys.argv) > 1 and str(
            sys.argv[1]).lower() in ['admin', 'administrator']:
        print "Running Application in Admin Mode"
        cdml.SetAdminMode(True)
    else:
        cdml.SetAdminMode(False)

    w, h = wx.GetDisplaySize()
    if w < 1024 or h < 768:
        msg = 'Minimum resolution for this program is 1024x768.\n'
        msg += 'Some forms may not be displayed properly. Do you want to continue?'
        ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING)
        if ans == wx.ID_NO: wx.Exit()

    frame_1 = Main(None, -1, "")
    app.SetTopWindow(frame_1)
    frame_1.MyMakeModal(True)
    frame_1.CenterOnScreen()
    frame_1.Show()
    app.MainLoop()
示例#39
0
文件: MISTGUI.py 项目: ilanderma/MIST
    def OpenDB(self, menuId):
        if DB.AccessDirtyStatus():
            ans = cdml.dlgSimpleMsg(
                'WARNING',
                "The data is not saved in a file. Do you want to save it?",
                wx.YES_NO | wx.CANCEL,
                wx.ICON_WARNING,
                Parent=self)
            if ans == wx.ID_YES:
                if not self.SaveDB(wx.ID_SAVE): return
            if ans == wx.ID_CANCEL:
                return

        if menuId == wx.ID_NEW:  # if New menu selected,
            path = os.getcwd() + os.sep + 'new_file.zip'  #   set dummy path
        else:
            path = self.GetNameDB(wx.OPEN)  # else get database name

            if path == None: return

            if not os.path.isfile(path):
                cdml.dlgSimpleMsg(
                    'ERROR',
                    'The file does not exist, please make sure the path is valid',
                    Parent=self)
                return

        wx.BeginBusyCursor()
        reload(DB)
        try:
            if os.path.isfile(path):
                # test the version of the file:
                (FileVersion, IsCompatible, IsUpgradable, DidLoad,
                 HasResults) = DB.ReconstructDataFileAndCheckCompatibility(
                     InputFileName=path,
                     JustCheckCompatibility=True,
                     RegenerationScriptName=None,
                     ConvertResults=False,
                     KnownNumberOfErrors=0,
                     CatchError=True)
                if IsCompatible:
                    # If versions are compatible, just load the file
                    DB.LoadAllData(path)  # If Open menu, load data
                elif IsUpgradable:
                    if HasResults:
                        wx.EndBusyCursor()
                        AnswerForConvertResults = cdml.dlgSimpleMsg(
                            'Data Conversion',
                            'This file was generated with an older version of data definitions.: '
                            + str(FileVersion) +
                            '. It was converted to the new version ' +
                            str(DB.Version) +
                            ' . Converting simulation results may take a long time and such results may not be reproducible with the current version. Even if simulation results are not loaded, the parameters, states, models, Population sets and projects will be loaded.\nDo you wish to convert simulation results from this file? ',
                            wx.YES_NO,
                            wx.ICON_QUESTION,
                            Parent=self)
                        AnswerForConvertResultsBoolean = AnswerForConvertResults == wx.ID_YES
                        wx.BeginBusyCursor()
                    else:
                        AnswerForConvertResultsBoolean = False
                        print '*** Converting file to the new version. Please wait - this may take a while ***'
                    # if a version upgrade is needed, convert the data
                    (FileVersion, IsCompatible, IsUpgradable, DidLoad,
                     HasResults) = DB.ReconstructDataFileAndCheckCompatibility(
                         InputFileName=path,
                         JustCheckCompatibility=False,
                         RegenerationScriptName=None,
                         ConvertResults=AnswerForConvertResultsBoolean,
                         KnownNumberOfErrors=0,
                         CatchError=True)

            self.ShowProjectList(None)
            self.SetTitle("MIST - " + path)
            self._db_opened = True
            self._path = path

        except:
            cdml.dlgErrorMsg(Parent=self)
        wx.EndBusyCursor()
示例#40
0
if __name__ == "__main__":
    # uncomment the next four lines for inspection and replace the app for 
    # inspection mode
    #from wx.lib.mixins.inspection import InspectableApp
    #app = InspectableApp()
    #import wx.lib.inspection
    #wx.lib.inspection.InspectionTool().Show()
    app = wx.App(0)
    # wx.InitAllImageHandlers() - deprecated - no longer needed

   
    if len(sys.argv)>1 and str(sys.argv[1]).lower() in ['admin', 'administrator']:
        print "Running Application in Admin Mode"
        cdml.SetAdminMode(True)
    else:
        cdml.SetAdminMode(False)

    w, h = wx.GetDisplaySize()
    if w<1024 or h<768:
        msg = 'Minimum resolution for this program is 1024x768.\n'
        msg += 'Some forms may not be displayed properly. Do you want to continue?'
        ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING)
        if ans == wx.ID_NO : wx.Exit()

    frame_1 = Main(None, -1, "")
    app.SetTopWindow(frame_1)
    frame_1.MyMakeModal(True)
    frame_1.CenterOnScreen()
    frame_1.Show()
    app.MainLoop()
示例#41
0
文件: MISTGUI.py 项目: ilanderma/MIST
    def OnMenuSelected(self, event):
        """ Event handler for buttons and menu items in main form"""

        menuId = event.GetId()
        if menuId in [wx.ID_NEW, wx.ID_OPEN]:  # New and Open menu
            self.OpenDB(menuId)  # open dialog to select database file

        elif menuId == cdml.ID_MENU_COPY_RECORD:
            self.CopyProjectRecord()

        elif menuId == cdml.ID_MENU_DELETE_RECORD:
            self.DeleteProjectRecord()

        elif menuId in [wx.ID_SAVE, wx.ID_SAVEAS]:  # save or save as menu
            self.SaveDB(menuId)

        elif menuId in range(
                cdml.IDF_BUTTON1,
                cdml.IDF_BUTTON10):  # Items in Data Menu and buttons
            # check database was loaded
            if not self._db_opened:
                cdml.dlgSimpleMsg(
                    'WARNING',
                    "No data is loaded to the system. Please select 'New' or 'Open' in File menu",
                    wx.OK,
                    wx.ICON_WARNING,
                    Parent=self)
                return

            btn = self.FindWindowById(
                menuId)  # synchronize selected menu to a button
            if btn.userData == None:
                return  # target for should be assigned to each button
            # as user data to avoid import statement.
            # See __set_properties method

            if btn.userData == 'Transitions' and len(DB.StudyModels) == 0:
                cdml.dlgSimpleMsg('ERROR',
                                  'A Model should be defined',
                                  Parent=self)
                return

            cdml.OpenForm(btn.userData,
                          self)  # open a form as default mode(=None)

        elif menuId in [
                cdml.ID_MENU_ABOUT, cdml.ID_MENU_HELP,
                cdml.ID_MENU_HELP_GENERAL
        ]:
            cdml.OnMenuSelected(self, event)

        elif menuId == cdml.ID_MENU_REPORT_THIS:  # Create a report for a specific project
            index = self.lc_project.GetFirstSelected()
            if index in [-1,
                         0]:  # -1 : nothing selected, 0 'New Project' selected
                return
            ProjectCode = self.IndexToPID[index]
            if ProjectCode in DB.Projects.keys():
                cdml.OpenForm("ReportViewer",
                              self,
                              key=(DB.Projects[ProjectCode], None))

        elif menuId == cdml.ID_MENU_REPORT_ALL:  # Create a report for all projects
            CollectionObject = DB.Projects
            if CollectionObject != None:
                cdml.OpenForm("ReportViewer",
                              self,
                              key=(CollectionObject, None))
示例#42
0
    def DeleteColumn(self):
        """ Delete Column Name from list control"""

        idx = self.lc_column.GetFirstSelected()
        if idx == -1 :
            cdml.dlgSimpleMsg('ERROR', 'Please select an item to remove', Parent = self)
            return

        
        # generate a warning message only if data is about to be deleted
        if self.nb.GetPageCount() > 2:
            msg = 'This column may include data. The data will be deleted also. Do you want to continue?'
            ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING, Parent = self)
            if ans == wx.ID_NO: 
                return
                
            if self.Objectives != []:
                msg = 'There are Objective information related to this population set - modifying this population set is not allowed while objectives are defined. The system can delete all Objective information for you. Do you want to continue and delete the objective information along with this column?'
                ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING, Parent = self)
                if ans == wx.ID_YES: 
                    # remove from list control display
                    self.lc_objectives.DeleteAllItems()
                    self.Objectives=[]
                    self.ShowTabData()
                else:
                    return
                
                

        # Remove from list
        (parm,dist) = self.DataColumns.pop(idx)
        # remove from list control display
        self.lc_column.DeleteItem(idx)

        if len(self.DataColumns)>idx:
            self.lc_column.Select(idx, True)

        oldidx = self.lc_parm.GetFirstSelected()
        self.lc_parm.Select(oldidx, False)

        idx2 = self.lc_parm.FindItem(-1, parm)

        if idx2 != wx.NOT_FOUND:
            self.lc_parm.Select(idx2,True)

        self.tc_dist_text.SetValue(dist)

        if self.nb.GetPageCount() > 2:
            self.grid_1.DeleteCols(idx,1, False)

            # refresh Column Labels
            for i in range(idx, self.lc_column.GetItemCount()):
                label = str(self.lc_column.GetItem(idx,0).GetText())
                self.grid_1.SetColLabelValue(i, label)

        if self.lc_column.GetItemCount() == 0:
            if self.nb.GetPageCount() > 2:
                self.grid_1.ClearGrid()
            if self.lc_objectives.GetItemCount() == 0:
                self.HasDistribution = None
                self.ShowTabData()
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
示例#43
0
    def AddColumn(self):
        """ Add Column name and distribution to list control"""

        idx = self.lc_parm.GetFirstSelected()
        if idx == -1:
            cdml.dlgSimpleMsg('ERROR',
                              'Please select a parameter',
                              wx.OK,
                              wx.ICON_ERROR,
                              Parent=self)
            return
        parm = str(self.lc_parm.GetItem(idx, 0).GetText())
        dist = str(self.tc_dist_text.GetValue())
        dist_strip = dist.strip()
        # Validate that this is a valid expression
        try:
            DB.Expr(dist)
        except:
            cdml.dlgErrorMsg(Parent=self)
            return

        if self.HasDistribution and dist_strip == '':
            cdml.dlgSimpleMsg(
                'ERROR',
                'You are trying to add data based parameter while this population is currently defined by distributions - please either delete distribution parameters or make sure you defined a distribution for the parameter you are trying to add.',
                wx.OK,
                wx.ICON_ERROR,
                Parent=self)
            return

        if self.Objectives != [] and (dist_strip == ''):
            msg = 'You are trying to add data while at least one objective is defined, all objectives have to be removed to define a data based population  - modifying this population set is not allowed while objectives are defined. The system can delete all Objective information for you. Do you want to continue and delete the objective information along with this column?'
            ans = cdml.dlgSimpleMsg('WARNING',
                                    msg,
                                    wx.YES_NO,
                                    wx.ICON_WARNING,
                                    Parent=self)
            if ans == wx.ID_YES:
                # remove from list control display
                self.lc_objectives.DeleteAllItems()
                self.Objectives = []
                self.ShowTabData()
            else:
                return

        no_page = self.nb.GetPageCount()
        no_column = self.lc_column.GetItemCount()
        if no_column == 0:  # if first item being added to column listbox
            self.HasDistribution = (dist_strip != '')
            self.ShowTabData()
            self.lc_dist.Enable(self.HasDistribution)
            self.tc_dist_text.Enable(self.HasDistribution)

        else:  # add more columns
            if no_page == 1 and dist_strip == '':
                cdml.dlgSimpleMsg('ERROR',
                                  'Please select a distribution',
                                  wx.OK,
                                  wx.ICON_ERROR,
                                  Parent=self)
                return

        # If this point was reached, then the distribution is ok
        # Add new column name (and distribution) to list control
        idx = self.lc_column.GetFirstSelected()
        if idx == -1: idx = self.lc_column.GetItemCount()
        ItemToAdd = (parm, dist)
        # add to display
        self.lc_column.AddItem(ItemToAdd, idx, False)
        # update the data columns - this duality is needed for windows systems
        # that store only 512 characters in a listbox
        self.DataColumns.insert(idx, ItemToAdd)

        if self.nb.GetPageCount() == 2: return

        if idx == self.lc_column.GetItemCount():  # Append New Column
            self.grid_1.AppendCols(1)

        else:  # insert new column
            self.grid_1.InsertCols(idx, 1, True)

        self.grid_1.SetColLabelValue(idx, parm)
示例#44
0
    def ExtractReportOptions(self):
        " Extract the options from the screen "
        FormatOptions = self.FormatOptions
        # Detail level
        DetailLevelStr = str(self.cc_DetailLevel.GetTextCtrl().GetValue())
        if DetailLevelStr != '':
            try:
                DetailLevel = int(DetailLevelStr)
            except:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'The text in the detail level box is not a number, please enter a positive number in the detail level box or leave it blank for the default',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            if DetailLevel < 0:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'The number in the detail level box is negative, please enter a positive number in the detail level box or leave it blank for the default',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            FormatOptions = DB.HandleOption('DetailLevel', FormatOptions,
                                            DetailLevel, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('DetailLevel', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        # Show Dependency
        ShowDependencyStr = str(
            self.cc_ShowDependency.GetTextCtrl().GetValue())
        if ShowDependencyStr != '':
            FormatOptions = DB.HandleOption('ShowDependency', FormatOptions,
                                            ShowDependencyStr == 'Yes', True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ShowDependency', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Summary Intervals
        SummaryIntevalStr = str(self.tc_SummaryIntevals.GetValue())
        if SummaryIntevalStr != '':
            # Analyze the Summary Interval and make sure there
            # are only numbers there and valid punctuations there
            for Char in SummaryIntevalStr:
                if Char not in (DB.NumericCharacters + '[], '):
                    raise ValueError, 'Summary Interval may contain only numeric characters, brackets, commas, and spaces'
            try:
                # Transform this to a number
                SummaryInterval = eval(SummaryIntevalStr, DB.EmptyEvalDict)
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'Summary Interval does not evaluate to a valid expression. Here are Additional Details: '
                    + str(ExceptValue),
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            if not DB.IsList(SummaryInterval):
                # Handle the case that the user asked for only one
                # Summary Interval
                if DB.IsInt(SummaryInterval):
                    # Convert integer to list
                    SummaryInterval = [SummaryInterval]
                elif DB.IsTuple(SummaryInterval):
                    # Convert Tuple to list
                    SummaryInterval = list(SummaryInterval)
                else:
                    cdml.dlgSimpleMsg('Report Parameter Error',
                                      'Invalid Summary Interval format',
                                      wx.OK,
                                      wx.ICON_ERROR,
                                      Parent=self)
                    return
            # Now verify that each member of the list is valid:
            for Member in SummaryInterval:
                if not (DB.IsInt(Member) or
                        (DB.IsList(Member) and len(Member) == 2
                         and all(map(lambda Entry: DB.IsInt(Entry), Member)))):
                    cdml.dlgSimpleMsg(
                        'Report Parameter Error',
                        'A member of the Summary interval list is not valid, i.e. not an integer or a list of two integers. The offending member is: '
                        + str(Member),
                        wx.OK,
                        wx.ICON_ERROR,
                        Parent=self)
                    return
            FormatOptions = DB.HandleOption('SummaryIntervals', FormatOptions,
                                            SummaryInterval, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('SummaryIntervals',
                                               FormatOptions, None, False,
                                               True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Number Formats
        ColumnNumberFormatFloatStr = str(
            self.tc_ColumnNumberFormatFloat.GetValue())
        ColumnNumberFormatIntegerStr = str(
            self.tc_ColumnNumberFormatInteger.GetValue())
        if ColumnNumberFormatFloatStr != '' or ColumnNumberFormatIntegerStr != '':
            if ColumnNumberFormatFloatStr == '' or ColumnNumberFormatIntegerStr == '':
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'If a number format is defined, it should be defined both for floats and for integers',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            ColumnNumberFormatFloatTest = ColumnNumberFormatFloatStr
            # Test that the float format is valid
            try:
                ColumnNumberFormatFloatTest % 123.456
            except:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'Float format is invalid - format should correspond to python string formatting conventions',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            # Test that the Integer format is valid
            try:
                ColumnNumberFormatIntegerStr % 123456
            except:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'Integer format is invalid - format should correspond to python string formatting conventions',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            # If reached here, format options can be specified
            FormatOptions = DB.HandleOption(
                'ColumnNumberFormat', FormatOptions,
                (ColumnNumberFormatFloatStr, ColumnNumberFormatIntegerStr),
                True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnNumberFormat',
                                               FormatOptions, None, False,
                                               True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Column Separator
        ColumnSeparatorStr = str(self.tc_ColumnSeparator.GetValue())
        if ColumnSeparatorStr != '':
            FormatOptions = DB.HandleOption('ColumnSpacing', FormatOptions,
                                            ColumnSeparatorStr, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnSpacing', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Show Hidden
        ShowHiddenStr = str(self.cc_ShowHidden.GetTextCtrl().GetValue())
        if ShowHiddenStr != '':
            FormatOptions = DB.HandleOption('ShowHidden', FormatOptions,
                                            ShowHiddenStr == 'Yes', True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ShowHidden', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        # Column Selections
        NumberOfSelectedColumns = self.lc_SelectedColumns.GetItemCount()
        if NumberOfSelectedColumns > 0:
            ColumnList = []
            for Index in range(NumberOfSelectedColumns):
                ColumnText = str(
                    self.lc_SelectedColumns.GetItem(Index, 0).Text)
                CalculationMethod = str(
                    self.lc_SelectedColumns.GetItem(Index, 1).Text)
                ColumnTitle = str(
                    self.lc_SelectedColumns.GetItem(Index, 2).Text)
                ColumnList.append((ColumnText, CalculationMethod, ColumnTitle))
            FormatOptions = DB.HandleOption('ColumnFilter', FormatOptions,
                                            ColumnList, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnFilter', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        # Stratification table
        StratificationTableStr = str(
            self.tc_StratificationTable.GetValue()).strip()
        if StratificationTableStr != '':
            try:
                #first verify that this is a valid expression
                DB.Expr(StratificationTableStr)
                #then verify that this is a valid expression
                DB.TableClass(StratificationTableStr)
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'The text in the Stratification Table box is not a valid table, please enter a valid table in the box or leave it blank for the default of no stratification. Here are Additional Details: '
                    + str(ExceptValue),
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            FormatOptions = DB.HandleOption('StratifyBy', FormatOptions,
                                            StratificationTableStr, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('StratifyBy', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        return FormatOptions
示例#45
0
    def ExtractReportOptions(self):
        " Extract the options from the screen "
        FormatOptions = self.FormatOptions
        # Detail level
        DetailLevelStr = str(self.cc_DetailLevel.GetTextCtrl().GetValue())
        if DetailLevelStr != '':
            try:
                DetailLevel = int (DetailLevelStr)
            except:
                cdml.dlgSimpleMsg('Report Parameter Error', 'The text in the detail level box is not a number, please enter a positive number in the detail level box or leave it blank for the default' , wx.OK, wx.ICON_ERROR, Parent = self)
                return
            if DetailLevel < 0:
                cdml.dlgSimpleMsg('Report Parameter Error', 'The number in the detail level box is negative, please enter a positive number in the detail level box or leave it blank for the default' , wx.OK, wx.ICON_ERROR, Parent = self)
                return
            FormatOptions = DB.HandleOption('DetailLevel', FormatOptions, DetailLevel, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('DetailLevel', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        
        # Show Dependency
        ShowDependencyStr = str(self.cc_ShowDependency.GetTextCtrl().GetValue())
        if ShowDependencyStr != '':
            FormatOptions = DB.HandleOption('ShowDependency', FormatOptions, ShowDependencyStr == 'Yes', True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ShowDependency', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Summary Intervals
        SummaryIntevalStr = str(self.tc_SummaryIntevals.GetValue())
        if SummaryIntevalStr != '':
            # Analyze the Summary Interval and make sure there
            # are only numbers there and valid punctuations there
            for Char in SummaryIntevalStr:
                if Char not in (DB.NumericCharacters + '[], '):
                    raise ValueError, 'Summary Interval may contain only numeric characters, brackets, commas, and spaces'
            try:
                # Transform this to a number
                SummaryInterval = eval(SummaryIntevalStr , DB.EmptyEvalDict)
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                cdml.dlgSimpleMsg('Report Parameter Error', 'Summary Interval does not evaluate to a valid expression. Here are Additional Details: '+ str(ExceptValue), wx.OK, wx.ICON_ERROR, Parent = self)
                return
            if not DB.IsList(SummaryInterval):
                # Handle the case that the user asked for only one
                # Summary Interval
                if DB.IsInt(SummaryInterval):
                    # Convert integer to list
                    SummaryInterval = [SummaryInterval]
                elif DB.IsTuple(SummaryInterval):
                    # Convert Tuple to list
                    SummaryInterval = list(SummaryInterval)
                else:
                    cdml.dlgSimpleMsg('Report Parameter Error', 'Invalid Summary Interval format', wx.OK, wx.ICON_ERROR, Parent = self)
                    return
            # Now verify that each member of the list is valid:
            for Member in SummaryInterval:
                if not (DB.IsInt(Member) or (DB.IsList(Member) and len(Member)==2 and all(map(lambda Entry: DB.IsInt(Entry), Member)))):
                    cdml.dlgSimpleMsg('Report Parameter Error', 'A member of the Summary interval list is not valid, i.e. not an integer or a list of two integers. The offending member is: ' + str(Member), wx.OK, wx.ICON_ERROR, Parent = self)
                    return
            FormatOptions = DB.HandleOption('SummaryIntervals', FormatOptions, SummaryInterval, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('SummaryIntervals', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Number Formats
        ColumnNumberFormatFloatStr = str(self.tc_ColumnNumberFormatFloat.GetValue())
        ColumnNumberFormatIntegerStr = str(self.tc_ColumnNumberFormatInteger.GetValue())
        if ColumnNumberFormatFloatStr != '' or ColumnNumberFormatIntegerStr != '':
            if ColumnNumberFormatFloatStr == '' or ColumnNumberFormatIntegerStr == '':
                cdml.dlgSimpleMsg('Report Parameter Error', 'If a number format is defined, it should be defined both for floats and for integers', wx.OK, wx.ICON_ERROR, Parent = self)
                return
            ColumnNumberFormatFloatTest = ColumnNumberFormatFloatStr
            # Test that the float format is valid
            try:
                ColumnNumberFormatFloatTest % 123.456
            except:
                cdml.dlgSimpleMsg('Report Parameter Error', 'Float format is invalid - format should correspond to python string formatting conventions', wx.OK, wx.ICON_ERROR, Parent = self)
                return
            # Test that the Integer format is valid
            try:
                ColumnNumberFormatIntegerStr % 123456
            except:
                cdml.dlgSimpleMsg('Report Parameter Error', 'Integer format is invalid - format should correspond to python string formatting conventions', wx.OK, wx.ICON_ERROR, Parent = self)
                return
            # If reached here, format options can be specified
            FormatOptions = DB.HandleOption('ColumnNumberFormat', FormatOptions, (ColumnNumberFormatFloatStr,ColumnNumberFormatIntegerStr), True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnNumberFormat', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Column Separator
        ColumnSeparatorStr = str(self.tc_ColumnSeparator.GetValue())
        if ColumnSeparatorStr != '':
            FormatOptions = DB.HandleOption('ColumnSpacing', FormatOptions , ColumnSeparatorStr, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnSpacing', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
        # Show Hidden
        ShowHiddenStr = str(self.cc_ShowHidden.GetTextCtrl().GetValue())
        if ShowHiddenStr != '':
            FormatOptions = DB.HandleOption('ShowHidden', FormatOptions, ShowHiddenStr == 'Yes', True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ShowHidden', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        # Column Selections
        NumberOfSelectedColumns = self.lc_SelectedColumns.GetItemCount()
        if NumberOfSelectedColumns > 0:
            ColumnList = []
            for Index in range(NumberOfSelectedColumns):
                ColumnText = str(self.lc_SelectedColumns.GetItem(Index,0).Text)
                CalculationMethod = str(self.lc_SelectedColumns.GetItem(Index,1).Text)
                ColumnTitle = str(self.lc_SelectedColumns.GetItem(Index,2).Text)
                ColumnList.append((ColumnText,CalculationMethod,ColumnTitle))
            FormatOptions = DB.HandleOption('ColumnFilter', FormatOptions, ColumnList, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('ColumnFilter', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

        # Stratification table
        StratificationTableStr = str(self.tc_StratificationTable.GetValue()).strip()
        if StratificationTableStr != '':
            try:
                #first verify that this is a valid expression
                DB.Expr(StratificationTableStr)
                #then verify that this is a valid expression
                DB.TableClass(StratificationTableStr)
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                cdml.dlgSimpleMsg('Report Parameter Error', 'The text in the Stratification Table box is not a valid table, please enter a valid table in the box or leave it blank for the default of no stratification. Here are Additional Details: '+ str(ExceptValue) , wx.OK, wx.ICON_ERROR, Parent = self)
                return
            FormatOptions = DB.HandleOption('StratifyBy', FormatOptions, StratificationTableStr, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('StratifyBy', FormatOptions, None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions
                
        return FormatOptions
示例#46
0
    def DeleteColumn(self):
        """ Delete Column Name from list control"""

        idx = self.lc_column.GetFirstSelected()
        if idx == -1:
            cdml.dlgSimpleMsg('ERROR',
                              'Please select an item to remove',
                              Parent=self)
            return

        # generate a warning message only if data is about to be deleted
        if self.nb.GetPageCount() > 2:
            msg = 'This column may include data. The data will be deleted also. Do you want to continue?'
            ans = cdml.dlgSimpleMsg('WARNING',
                                    msg,
                                    wx.YES_NO,
                                    wx.ICON_WARNING,
                                    Parent=self)
            if ans == wx.ID_NO:
                return

            if self.Objectives != []:
                msg = 'There are Objective information related to this population set - modifying this population set is not allowed while objectives are defined. The system can delete all Objective information for you. Do you want to continue and delete the objective information along with this column?'
                ans = cdml.dlgSimpleMsg('WARNING',
                                        msg,
                                        wx.YES_NO,
                                        wx.ICON_WARNING,
                                        Parent=self)
                if ans == wx.ID_YES:
                    # remove from list control display
                    self.lc_objectives.DeleteAllItems()
                    self.Objectives = []
                    self.ShowTabData()
                else:
                    return

        # Remove from list
        (parm, dist) = self.DataColumns.pop(idx)
        # remove from list control display
        self.lc_column.DeleteItem(idx)

        if len(self.DataColumns) > idx:
            self.lc_column.Select(idx, True)

        oldidx = self.lc_parm.GetFirstSelected()
        self.lc_parm.Select(oldidx, False)

        idx2 = self.lc_parm.FindItem(-1, parm)

        if idx2 != wx.NOT_FOUND:
            self.lc_parm.Select(idx2, True)

        self.tc_dist_text.SetValue(dist)

        if self.nb.GetPageCount() > 2:
            self.grid_1.DeleteCols(idx, 1, False)

            # refresh Column Labels
            for i in range(idx, self.lc_column.GetItemCount()):
                label = str(self.lc_column.GetItem(idx, 0).GetText())
                self.grid_1.SetColLabelValue(i, label)

        if self.lc_column.GetItemCount() == 0:
            if self.nb.GetPageCount() > 2:
                self.grid_1.ClearGrid()
            if self.lc_objectives.GetItemCount() == 0:
                self.HasDistribution = None
                self.ShowTabData()
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
示例#47
0
    def AddColumn(self):
        """ Add Column name and distribution to list control"""

        idx = self.lc_parm.GetFirstSelected()
        if idx == -1:
            cdml.dlgSimpleMsg('ERROR', 'Please select a parameter', wx.OK, wx.ICON_ERROR, Parent = self)
            return
        parm = str(self.lc_parm.GetItem(idx,0).GetText())
        dist = str(self.tc_dist_text.GetValue())
        dist_strip = dist.strip()
        # Validate that this is a valid expression
        try:
            DB.Expr(dist)
        except:
            cdml.dlgErrorMsg(Parent = self)
            return

        if self.HasDistribution and dist_strip == '':
            cdml.dlgSimpleMsg('ERROR', 'You are trying to add data based parameter while this population is currently defined by distributions - please either delete distribution parameters or make sure you defined a distribution for the parameter you are trying to add.', wx.OK, wx.ICON_ERROR, Parent = self)            
            return
            
        if self.Objectives != [] and (dist_strip == ''):
            msg = 'You are trying to add data while at least one objective is defined, all objectives have to be removed to define a data based population  - modifying this population set is not allowed while objectives are defined. The system can delete all Objective information for you. Do you want to continue and delete the objective information along with this column?'
            ans = cdml.dlgSimpleMsg('WARNING', msg, wx.YES_NO, wx.ICON_WARNING, Parent = self)
            if ans == wx.ID_YES: 
                # remove from list control display
                self.lc_objectives.DeleteAllItems()
                self.Objectives=[]
                self.ShowTabData()
            else:
                return

            
        no_page = self.nb.GetPageCount()
        no_column = self.lc_column.GetItemCount()
        if no_column == 0 : # if first item being added to column listbox            
            self.HasDistribution = (dist_strip != '')
            self.ShowTabData()
            self.lc_dist.Enable(self.HasDistribution)
            self.tc_dist_text.Enable(self.HasDistribution)

        else : # add more columns
            if no_page == 1 and dist_strip == '':
                cdml.dlgSimpleMsg('ERROR', 'Please select a distribution', wx.OK, wx.ICON_ERROR, Parent = self)
                return

        # If this point was reached, then the distribution is ok
        # Add new column name (and distribution) to list control
        idx = self.lc_column.GetFirstSelected()
        if idx == -1 : idx = self.lc_column.GetItemCount()
        ItemToAdd = (parm,dist)
        # add to display
        self.lc_column.AddItem(ItemToAdd, idx, False)
        # update the data columns - this duality is needed for windows systems
        # that store only 512 characters in a listbox
        self.DataColumns.insert(idx, ItemToAdd)

        if self.nb.GetPageCount() == 2 : return

        if idx == self.lc_column.GetItemCount():    # Append New Column
            self.grid_1.AppendCols(1)

        else:                                       # insert new column
            self.grid_1.InsertCols(idx, 1, True)

        self.grid_1.SetColLabelValue(idx, parm)