Пример #1
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)
Пример #2
0
    def ImportCSV(self):
        """ Import Population Data from a CSV file"""

        wildcard = "CSV File (*.csv)|*.csv| All files (*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN)

        if dialog.ShowModal() == wx.ID_OK:
            try:
                (DataColumns, Data) = DB.ImportDataFromCSV(dialog.GetPath())
                Objectives = [] # currently no objectives imported
                # Make sure that DataColumns is composed of strings
                # alone and not numbers or other data types
                # this is a minimal precaution - no other validity checks
                # are made other than what made in ImportDataFromCSV
                AllStrings = all(map(lambda (ColumnName,Distribution): DB.IsStr(ColumnName), DataColumns))
                if not AllStrings:
                    raise ValueError, 'Error Loading CSV file - headers are not all strings'
            except:
                cdml.dlgErrorMsg(Parent = self)
            else:
                # set the HasDistribution flag to False since loading
                # a distribution is not currently supported.
                self.HasDistribution = False
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
                # also load this data to the object
                self.ShowTabData()
                self.DataColumns = DataColumns
                self.Data = Data
                self.Objectives = Objectives
                self.ShowData(DataColumns, Data, Objectives)

        self.Raise()
        dialog.Destroy() # Destroy file selection dialog
Пример #3
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
Пример #4
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)
Пример #5
0
    def ImportCSV(self):
        """ Import Population Data from a CSV file"""

        wildcard = "CSV File (*.csv)|*.csv| All files (*.*)|*.*"
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN)

        if dialog.ShowModal() == wx.ID_OK:
            try:
                (DataColumns, Data) = DB.ImportDataFromCSV(dialog.GetPath())
                Objectives = [] # currently no objectives imported
                # Make sure that DataColumns is composed of strings
                # alone and not numbers or other data types
                # this is a minimal precaution - no other validity checks
                # are made other than what made in ImportDataFromCSV
                AllStrings = all(map(lambda (ColumnName,Distribution): DB.IsStr(ColumnName), DataColumns))
                if not AllStrings:
                    raise ValueError, 'Error Loading CSV file - headers are not all strings'
            except:
                cdml.dlgErrorMsg(Parent = self)
            else:
                # set the HasDistribution flag to False since loading
                # a distribution is not currently supported.
                self.HasDistribution = False
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
                # also load this data to the object
                self.ShowTabData()
                self.DataColumns = DataColumns
                self.Data = Data
                self.Objectives = Objectives
                self.ShowData(DataColumns, Data, Objectives)

        self.Raise()
        dialog.Destroy() # Destroy file selection dialog
Пример #6
0
 def LoadReportOptions(self):
     """ Load report options from file"""
     path = self.GetReportOptionsFileName(wx.FD_OPEN)
     if path != None:
         try:
             BackupFormatOptions = copy.deepcopy(self.FormatOptions)
             FormatOptions = DB.LoadOptionList(path)
             KeyFilterOptionValue = DB.HandleOption('KeyFilter', self.FormatOptions, Value = None, UseNewValue = False, DeleteThisOption = False)
             if KeyFilterOptionValue != None:
                 DB.HandleOption('KeyFilter', FormatOptions, Value = KeyFilterOptionValue, UseNewValue = True, DeleteThisOption = False)
             # now load the data to the controls to reflect the newly loaded data
             # note that not validity checks are made, so if the file loaded
             # properly and had bad data this may be reflected as bad text in
             # the control or even raise an error that can be caught. Since this
             # is not disruptive to data stored in the system no additional
             # checks are made beyond what the system will allow in the controls
             self.PopulateOptionsOnScreen(FormatOptions)
             # now after data was updated update self with the new options
             self.FormatOptions = FormatOptions
             # Everything went fine - no need for backup anymore
             BackupFormatOptions = None
         except:
             cdml.dlgErrorMsg(Parent = self)
         if BackupFormatOptions != None:
             try:
                 # in case of a bad file or an error, restore blank values
                 self.PopulateOptionsOnScreen(BackupFormatOptions)
             except:
                 answer = cdml.dlgErrorMsg(msg_prefix='ASSERTION ERROR: Unable to recover from Error. Here are additional details: ',yesno=True, Parent = self)
                 if answer == wx.ID_YES :
                     return
                 else:
                     cdml.CloseForm(self, False)
     return
Пример #7
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()
Пример #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 ChangeSimulaionRules(self, event):
        """ Add/Remove simulation rules when user click up/down button"""
        id_btn = event.GetId()

        lc = getattr( self, 'tab' + str(self.curPage) + '_list' )
        index = lc.GetFirstSelected()

        try :
            list_rules = getattr(self, 'SimRule')[self.curPage]
            if id_btn == wx.ID_ADD: # UP ARROW - Add/Insert a rule
                if index == -1 : index = lc.GetItemCount()

                rule = []
                no_blank = 0
                for i in range(3):
                    cc = getattr(self, 'combo_box_'+str(i+1))
                    rule.append( str(cc.GetValueString()) )
                    if rule[i] == '' : no_blank += 1

                if no_blank == 3 : return  # no rules are set in the combo boxes

                notes = str(self.tc_notes_rule.GetValue())
                new_rule = DB.SimulationRule(rule[0], self.curPage, rule[1], rule[2], notes)


                list_rules.insert(index, new_rule)
                lc.AddItem((rule[0], rule[1], rule[2], notes, -1), index)
                # Do not clear panel so that it can be used as a clipboard
                # for copy operations. 
                #self.ClearPanel(self.panel_combo)

            else: # DOWN ARROW - Remove a rule
                if index == -1 : return

                # the new implementation is:
                # get the information from the list_rules buffer rather than
                # from the listbox in the screen. 
                cur_rule = [str(list_rules[index].AffectedParam), str(list_rules[index].OccurrenceProbability), str(list_rules[index].AppliedFormula), str(list_rules[index].Notes) ]
                for i in range(3):
                    cc = getattr(self, 'combo_box_' + str(i+1))
                    cc.GetTextCtrl().SetValue(cur_rule[i])
                self.tc_notes_rule.SetValue(cur_rule[-1])

                list_rules.pop(index)
                lc.DeleteItem(index)
                if len(list_rules) > index:
                    lc.Select(index, True)
        except:
            cdml.dlgErrorMsg(Parent = self)
Пример #10
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()
Пример #11
0
    def CopyProject(self):
        """ Copies project and refreshes the form accordingly with the copied Data """
        # It is assumed that the data is saved
        # Eclose the copying in a try statement just in case of an error
        copy_ok = False
        try:
            new_record = DB.Projects.Copy(self.idPrj)
            copy_ok = True
        except:
            cdml.dlgErrorMsg(Parent = self)
       
        if copy_ok:
            self.idPrj = new_record.ID
            self.Initialize()

        return copy_ok
Пример #12
0
    def OnClose(self, event):
        """ Event handler activated when this dialog is closed"""

        if event.GetId() == wx.ID_OK:
            type_wizard = cdml.iif( 'Cost' in self.cb_type.GetValue(), 0, 1)
            ival = self.ed_ival.GetValue()

            coef, val = [], []
            item_num = self.lc_vector.GetItemCount()
            for i in range(item_num):
                coef.append(str(self.lc_vector.GetItem(i,0).GetText()))
                val.append(str(self.lc_vector.GetItem(i,1).GetText()))

            wizard_output = [ type_wizard, ival, coef, val ]
            try :
                CostWizardOutput = DB.ConstructCostWizardString(wizard_output)
                cdml.SetRefreshInfo(self, '', CostWizardOutput)

            except:
                CostWizardOutput = None
                ans = cdml.dlgErrorMsg(0, True, Parent = self)
                if ans == wx.ID_YES : return
            cdml.CloseForm(self, True, '', CostWizardOutput)

        else:
            cdml.CloseForm(self, False)
Пример #13
0
    def OnClose(self, event):
        """ Event handler activated when this dialog is closed"""

        if event.GetId() == wx.ID_OK:
            type_wizard = cdml.iif('Cost' in self.cb_type.GetValue(), 0, 1)
            ival = self.ed_ival.GetValue()

            coef, val = [], []
            item_num = self.lc_vector.GetItemCount()
            for i in range(item_num):
                coef.append(str(self.lc_vector.GetItem(i, 0).GetText()))
                val.append(str(self.lc_vector.GetItem(i, 1).GetText()))

            wizard_output = [type_wizard, ival, coef, val]
            try:
                CostWizardOutput = DB.ConstructCostWizardString(wizard_output)
                cdml.SetRefreshInfo(self, '', CostWizardOutput)

            except:
                CostWizardOutput = None
                ans = cdml.dlgErrorMsg(0, True, Parent=self)
                if ans == wx.ID_YES: return
            cdml.CloseForm(self, True, '', CostWizardOutput)

        else:
            cdml.CloseForm(self, False)
Пример #14
0
 def LoadReportOptions(self):
     """ Load report options from file"""
     path = self.GetReportOptionsFileName(wx.FD_OPEN)
     if path != None:
         try:
             BackupFormatOptions = copy.deepcopy(self.FormatOptions)
             FormatOptions = DB.LoadOptionList(path)
             KeyFilterOptionValue = DB.HandleOption('KeyFilter',
                                                    self.FormatOptions,
                                                    Value=None,
                                                    UseNewValue=False,
                                                    DeleteThisOption=False)
             if KeyFilterOptionValue != None:
                 DB.HandleOption('KeyFilter',
                                 FormatOptions,
                                 Value=KeyFilterOptionValue,
                                 UseNewValue=True,
                                 DeleteThisOption=False)
             # now load the data to the controls to reflect the newly loaded data
             # note that not validity checks are made, so if the file loaded
             # properly and had bad data this may be reflected as bad text in
             # the control or even raise an error that can be caught. Since this
             # is not disruptive to data stored in the system no additional
             # checks are made beyond what the system will allow in the controls
             self.PopulateOptionsOnScreen(FormatOptions)
             # now after data was updated update self with the new options
             self.FormatOptions = FormatOptions
             # Everything went fine - no need for backup anymore
             BackupFormatOptions = None
         except:
             cdml.dlgErrorMsg(Parent=self)
         if BackupFormatOptions != None:
             try:
                 # in case of a bad file or an error, restore blank values
                 self.PopulateOptionsOnScreen(BackupFormatOptions)
             except:
                 answer = cdml.dlgErrorMsg(
                     msg_prefix=
                     'ASSERTION ERROR: Unable to recover from Error. Here are additional details: ',
                     yesno=True,
                     Parent=self)
                 if answer == wx.ID_YES:
                     return
                 else:
                     cdml.CloseForm(self, False)
     return
Пример #15
0
    def CopyProjectRecord(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

        ProjectIndex = self.lc_project.GetItemData(index)

        pid = self.IndexToPID[ProjectIndex]

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

        try:
            DB.Projects.Copy(pid)
            self.ShowProjectList()
        except:
            cdml.dlgErrorMsg(Parent = self)
Пример #16
0
    def SaveDB(self, menuId=wx.ID_SAVE):
        """ Save current database. If current database is new one, remove asterisk(*) from title"""

        if not self._db_opened : return

        if menuId == wx.ID_SAVEAS or (self._path == (os.getcwd() + os.sep + 'new_file.zip')):
            path = self.GetNameDB(wx.SAVE)
            if path == None: return False
            self._path = path # replace previous path with current path

        try:
            DB.SaveAllData(FileName = self._path, Overwrite = True, CompressFile = True, CreateBackupBeforeSave = True)
        except:
            (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
            cdml.dlgErrorMsg(Parent = self)

        self.SetTitle('MIST - ' + self._path)
        return True
Пример #17
0
    def CopyProjectRecord(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

        ProjectIndex = self.lc_project.GetItemData(index)

        pid = self.IndexToPID[ProjectIndex]

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

        try:
            DB.Projects.Copy(pid)
            self.ShowProjectList()
        except:
            cdml.dlgErrorMsg(Parent=self)
Пример #18
0
 def SaveReportOptions(self):
     """ Save report options to file"""
     FormatOptions = self.ExtractReportOptions()
     if FormatOptions != None:
         # filter out the KeyFilter options since it is internal to the system
         # and should not be loaded or saved
         FormatOptionModified = DB.HandleOption('KeyFilter', FormatOptions, Value = None, UseNewValue = False, DeleteThisOption = True)
         if FormatOptionModified == None:
             # if KeyFilter did not exist, then use the original OptionList
             FormatOptionModified = FormatOptions
         # get path name
         path = self.GetReportOptionsFileName(wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
         if path != None:
             try:
                 DB.SaveOptionList(path,FormatOptionModified)
             except:
                 cdml.dlgErrorMsg(Parent = self)
     return
Пример #19
0
    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)
Пример #20
0
    def AddObjective(self):
        "Adds an objective to the objectives list box"

        obj_filter_expr_txt = str(self.tc_obj_filter_expr.GetValue())
        obj_stat_expr_txt = str(self.tc_obj_stat_expr.GetValue())
        obj_stat_func = str(self.cc_obj_stat_func.GetTextCtrl().GetValue())
        obj_target_txt = str(self.tc_obj_target.GetValue())
        obj_weight_txt = str(self.tc_obj_weight.GetValue())

        # Validate that this is a valid entry
        try:
            ErrorControl = "Filter Expression"
            obj_filter_expr = DB.Expr(obj_filter_expr_txt)
            ErrorControl = "Statistics Expression"
            obj_stat_expr = DB.Expr(obj_stat_expr_txt)
            ErrorControl = "Statistics Function"
            if obj_stat_func.strip() == '':
                raise ValueError, 'Empty statistics function cannot be used'
            ErrorControl = "Target Value"
            obj_target = float(obj_target_txt)
            if not DB.IsFinite(obj_target):
                raise ValueError, 'Target Value must be finite'
            ErrorControl = "Weight"
            obj_weight = float(obj_weight_txt)
            if not DB.IsFinite(obj_weight):
                raise ValueError, 'Weight Value must be finite'
        except:
            cdml.dlgErrorMsg(msg_prefix='Error detected while processing ' +
                             ErrorControl + ': ',
                             Parent=self)
            return

        # If this point was reached, then the objective is ok
        # Add new the new objective to the list in the appropriate place
        idx = self.lc_objectives.GetFirstSelected()
        if idx == -1: idx = self.lc_objectives.GetItemCount()
        ItemToAdd = (obj_filter_expr, obj_stat_expr, obj_stat_func, obj_target,
                     obj_weight, None, None)
        # add to display
        self.lc_objectives.AddItem(ItemToAdd, idx, False)
        # update the objectives - this duality is needed for windows systems
        # that store only 512 characters in a listbox
        self.Objectives.insert(idx, ItemToAdd)
Пример #21
0
    def AddObjective(self):
        "Adds an objective to the objectives list box"

        obj_filter_expr_txt = str(self.tc_obj_filter_expr.GetValue())
        obj_stat_expr_txt = str(self.tc_obj_stat_expr.GetValue())
        obj_stat_func = str(self.cc_obj_stat_func.GetTextCtrl().GetValue())        
        obj_target_txt = str(self.tc_obj_target.GetValue())
        obj_weight_txt = str(self.tc_obj_weight.GetValue())

        # Validate that this is a valid entry
        try:
            ErrorControl = "Filter Expression"
            obj_filter_expr = DB.Expr(obj_filter_expr_txt)
            ErrorControl = "Statistics Expression"
            obj_stat_expr = DB.Expr(obj_stat_expr_txt)
            ErrorControl = "Statistics Function"
            if obj_stat_func.strip() == '':
                raise ValueError, 'Empty statistics function cannot be used'
            ErrorControl = "Target Value"
            obj_target = float(obj_target_txt)
            if not DB.IsFinite(obj_target):
                raise ValueError, 'Target Value must be finite'
            ErrorControl = "Weight"
            obj_weight = float(obj_weight_txt)            
            if not DB.IsFinite(obj_weight):
                raise ValueError, 'Weight Value must be finite'
        except:
            cdml.dlgErrorMsg(msg_prefix = 'Error detected while processing ' + ErrorControl + ': ', Parent = self)
            return



        # If this point was reached, then the objective is ok
        # Add new the new objective to the list in the appropriate place
        idx = self.lc_objectives.GetFirstSelected()
        if idx == -1 : idx = self.lc_objectives.GetItemCount()
        ItemToAdd = (obj_filter_expr, obj_stat_expr, obj_stat_func, obj_target, obj_weight, None, None)
        # add to display
        self.lc_objectives.AddItem(ItemToAdd, idx, False)
        # update the objectives - this duality is needed for windows systems
        # that store only 512 characters in a listbox
        self.Objectives.insert(idx, ItemToAdd)
Пример #22
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
Пример #23
0
    def SaveDB(self, menuId=wx.ID_SAVE):
        """ Save current database. If current database is new one, remove asterisk(*) from title"""

        if not self._db_opened: return

        if menuId == wx.ID_SAVEAS or (self._path == (os.getcwd() + os.sep +
                                                     'new_file.zip')):
            path = self.GetNameDB(wx.SAVE)
            if path == None: return False
            self._path = path  # replace previous path with current path

        try:
            DB.SaveAllData(FileName=self._path,
                           Overwrite=True,
                           CompressFile=True,
                           CreateBackupBeforeSave=True)
        except:
            (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
            cdml.dlgErrorMsg(Parent=self)

        self.SetTitle('MIST - ' + self._path)
        return True
Пример #24
0
 def SaveReportOptions(self):
     """ Save report options to file"""
     FormatOptions = self.ExtractReportOptions()
     if FormatOptions != None:
         # filter out the KeyFilter options since it is internal to the system
         # and should not be loaded or saved
         FormatOptionModified = DB.HandleOption('KeyFilter',
                                                FormatOptions,
                                                Value=None,
                                                UseNewValue=False,
                                                DeleteThisOption=True)
         if FormatOptionModified == None:
             # if KeyFilter did not exist, then use the original OptionList
             FormatOptionModified = FormatOptions
         # get path name
         path = self.GetReportOptionsFileName(wx.FD_SAVE
                                              | wx.FD_OVERWRITE_PROMPT)
         if path != None:
             try:
                 DB.SaveOptionList(path, FormatOptionModified)
             except:
                 cdml.dlgErrorMsg(Parent=self)
     return
Пример #25
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)
Пример #26
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)
Пример #27
0
    def OnLeftDblClick(self, event):
        """ Event handler to open child form"""

        ctrl = event.GetEventObject()

        type = ''
        if ctrl.Id == cdml.IDF_BUTTON3: # Population Set
            cc = self.cc_pset
            id_obj = cc.GetValue()
            form = 'PopulationSets'

        elif ctrl.Id == cdml.IDF_BUTTON4 : # Primary Model
            cc = self.cc_model
            id_obj = cc.GetValue()
            form = 'StudyModels'

        elif ctrl.Id == cdml.IDP_BUTTON4:
            # The notes rule text
            cc = ctrl
            TheTextControl = cc
            id_obj = cc.GetValue()
            DefaultText = id_obj
            form = ''

        else:

            cc = ctrl.GetParent()
            TheTextControl = cc.GetTextCtrl()
            if cc.Id == cdml.IDF_BUTTON1:
                id_obj = cc.GetValue()
                form = 'PopulationSets'

            elif cc.Id == cdml.IDF_BUTTON2:
                id_obj = cc.GetValue()
                form = 'StudyModels'

           
            else:
                id_obj = str(cc.GetValueString())
                DefaultText = id_obj

                if cc.Id == cdml.IDP_BUTTON1:
                    form = 'Parameters'
                    type = ['System Option']*(self.curPage==0) + ['Number','Integer','State Indicator']


                elif cc.Id == cdml.IDP_BUTTON2:
                    form = ''
                    type = 'Expression'

                elif cc.Id == cdml.IDP_BUTTON3:
                    form = ''
                    type = 'Expression'
                    if ('CostWizard' in DefaultText):
                        form = 'WIZARD'

        self.curCtrl = cc

        if form == 'WIZARD':
            try:
                Sequence = DB.CostWizardParserForGUI(DefaultText, True)
                dlg_wizard = Wizard.WizardDialog(data=Sequence, parent=self)
                dlg_wizard.CenterOnScreen()

                dlg_wizard.Show()
                dlg_wizard.MyMakeModal()
    
            except:
                cdml.dlgErrorMsg(Parent = self)

        elif form == '':
            TheText = cdml.dlgTextEntry(Message = 'Modify Text and Press OK, or Press Cancel to ignore changes', Caption = type, DefaultValue = DefaultText, Parent = self)
            TheTextControl.SetValue(str(TheText))
            # make sure focus returne properly to this form
            self.MyMakeModal()  
            self.Raise()
            
        else:
            if id_obj == 0 or id_obj == '' : id_obj = -1
            cdml.OpenForm(form, self, cdml.ID_MODE_SINGL, id_obj, type, self.idPrj)
Пример #28
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)
Пример #29
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
Пример #30
0
    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()
Пример #31
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()
Пример #32
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
Пример #33
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)