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)
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
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)
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)
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)
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)
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()
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)
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
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
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
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
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
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()
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)
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()
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)
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)
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) )
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)
def __init__(self, mode=None, data=None, type=None, id_prj=0, *args, **kwds): """ Constructor of the MainFrame class """ self.idPrj = id_prj self.ParsedStruct = data kwdsnew = copy.copy(kwds) kwdsnew["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwdsnew) self.pn_main = wx.Panel(self, -1) self.label_1 = wx.StaticText(self.pn_main, -1, "Function Type : ") self.cb_type = wx.ComboBox(self.pn_main, -1, choices=["Cost Wizard = Init * 10**Sum(Coefficient*Value)", "Quality of Life Wizard = Init + Sum(Coefficient*Value)"], style=wx.CB_DROPDOWN) self.label_2 = wx.StaticText(self.pn_main, -1, "Initial Value : ") self.ed_ival = wx.TextCtrl(self.pn_main, -1, "") self.lc_vector = cdml.List(self.pn_main, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER) # Up/Down arrow button arrow_up = cdml.getSmallUpArrowBitmap() # arrow bitmap for buttons arrow_dn = cdml.getSmallDnArrowBitmap() self.btn_up = wx.BitmapButton(self.pn_main, wx.ID_ADD, arrow_up) self.btn_dn = wx.BitmapButton(self.pn_main, wx.ID_DELETE, arrow_dn) self.cc_coef = cdml.Combo(self.pn_main, -1) self.tc_valu = cdml.Text(self.pn_main, -1) self.btn_undo = wx.Button(self.pn_main, wx.ID_UNDO, "Undo") self.btn_ok = wx.Button(self.pn_main, wx.ID_OK, "Ok") self.btn_cancel = wx.Button(self.pn_main, wx.ID_CANCEL, "Cancel") cdml.GenerateStandardMenu(self, SkipItems = [cdml.ID_MENU_REPORT_THIS, cdml.ID_MENU_REPORT_ALL]) self.__set_properties() self.__do_layout() self.btn_ok.Bind(wx.EVT_BUTTON, self.OnClose) self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnClose) self.Bind(wx.EVT_CLOSE, self.OnClose) self.cc_coef.GetTextCtrl().Bind(wx.EVT_LEFT_DCLICK, self.OnListDblClick) self.Bind(wx.EVT_END_PROCESS, self.OnRefresh) self.btn_up.Bind(wx.EVT_BUTTON, self.OnEdit) self.btn_dn.Bind(wx.EVT_BUTTON, self.OnEdit) self.btn_undo.Bind(wx.EVT_BUTTON, self.OnEdit) self.InitData()
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)
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)
def SetValues(self, record, init=False): """ Write current data in controls on a row panel RowPanel class must implement this method. """ self.Key = record.ID self.tc_name.SetValue(str(record.Name)) self.tc_source.SetValue(str(record.Source)) self.tc_created.SetValue(record.CreatedOn) self.tc_modified.SetValue(record.LastModified) self.tc_notes.SetValue(str(record.Notes)) # Special treatment needed to discover if a record is distribution # based if record.IsDistributionBased(): self.tc_definitiontype.SetValue('Distribution based') else: self.tc_definitiontype.SetValue('Data based') from_pset = cdml.GetRecordByKey(DB.PopulationSets, record.DerivedFrom) if from_pset: self.tc_derived.SetValue(str(from_pset.Name)) self.DerivedFrom = record.DerivedFrom self.DataColumns = record.DataColumns self.Data = record.Data self.Objectives = record.Objectives
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
def OnMenuSelected(self, event): """ Handles Menu selection """ MenuID = event.GetId() if MenuID in [wx.ID_SAVE, wx.ID_SAVEAS]: # save or save as menu self.SaveReport(MenuID) else: cdml.OnMenuSelected(self, event)
def ShowProjectData(self): """ Display data for current project If current project is new one, do nothing """ self.tc_name.SetValue(str(self.record.Name)) from_prj = cdml.GetRecordByKey(DB.Projects, self.record.DerivedFrom) if from_prj: self.tc_from.SetValue(str(from_prj.Name)) self.tc_created.SetValue(self.record.CreatedOn) self.tc_modified.SetValue(self.record.LastModified) self.tc_notes.SetValue(str(self.record.Notes)) self.cc_pset.SetValue(self.record.PrimaryPopulationSetID) self.cc_model.SetValue(self.record.PrimaryModelID) self.tc_simsteps.SetValue(self.record.NumberOfSimulationSteps) self.tc_repet.SetValue(self.record.NumberOfRepetitions) self.tab0_list.DeleteAllItems() self.tab1_list.DeleteAllItems() self.tab3_list.DeleteAllItems() for rule in self.record.SimulationRules: item = (str(rule.AffectedParam), str(rule.OccurrenceProbability), str(rule.AppliedFormula), str(rule.Notes), -1) list = getattr(self, 'tab' + str(rule.SimulationPhase) + '_list') list.AddItem(item, list.GetItemCount()) self.ClearPanel(self.panel_combo) self.tc_name.SetFocus() self.tc_name.SetInsertionPoint(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
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)
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
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
def FrameEventHandler(self, evt): """ Frame Event Handler """ evtType = evt.GetEventType() # if current event is close window, call CloseForm function if evtType == wx.wxEVT_CLOSE_WINDOW: cdml.CloseForm(self) return
def OnRefresh(self, event): """ Reopen text editor at previous position after closing Parameter form This method has been added because the TextEditMixin close the text box whenever user click of double-click a cell in the list control""" parm = cdml.GetRefreshInfo() # update the list of parameters in the combo box self.SetComboItem() if parm != None: self.cc_coef.GetTextCtrl().SetValue(str(parm))
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
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)
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()
def OnPopupMenu(self, event): """ Event handler to open Popup menu """ if not hasattr(self, 'pup_menus'): return menu = cdml.setupMenu(self, self.pup_menus, False) # crate popup menu and assign event handler page = self.nb.GetCurrentPage() menu_enable = cdml.iif( page.Id == 0, False, True ) item_add = menu.FindItemById(cdml.IDF_BUTTON1) item_del = menu.FindItemById(cdml.IDF_BUTTON2) item_add.Enable(menu_enable) item_del.Enable(menu_enable) self.PopupMenu(menu) # open popup menu menu.Destroy() # remove from memory to show just once when right button is clicked
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)
def OnPopupMenu(self, event): """ Open Popup menu """ if not hasattr(self, 'pup_menus'): return menu = cdml.setupMenu(self, self.pup_menus, False) # crate popup menu and assign event handler self.PopupMenu(menu) # open popup menu menu.Destroy() # remove from memory to show just once when right button is clicked
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
def __init__(self, *args, **kwds): # Create instance of the CDMPanel class. kwdsnew = copy.copy(kwds) kwdsnew['style'] = wx.SIMPLE_BORDER | wx.TAB_TRAVERSAL # Set the style of this RowPanel class cdml.CDMPanel.__init__(self, is_row = True, *args, **kwdsnew) # Second argument should be 'True' always # Create variables using State class and initialize those variables # using initial values defined in State Class self.record = cdml.GetInstanceAttr(DB.State) # create controls self.btn_del = cdml.Button(self, wx.ID_DELETE, "x") # Second argument should be wx.ID_DELETE self.st_status = wx.StaticText(self, -1, "") # Create controls to enter/display the variables in State object # For controls include text area set wx.TE_NOHIDESEL always. # This style need for the Find function self.tc_name = cdml.Text(self, -1, "", style=wx.TE_NOHIDESEL) self.cb_isSplit = cdml.Checkbox(self, -1, "") self.cb_isEvent = cdml.Checkbox(self, -1, "") self.cb_isTerminal = cdml.Checkbox(self, -1, "") self.cc_joiner_split = cdml.Combo(self, -1, validator=cdml.KeyValidator(cdml.NO_EDIT)) self.tc_notes = cdml.Text(self, -1, "", style=wx.TE_MULTILINE|wx.TE_NOHIDESEL) self.lc_states = cdml.List(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER) self.cc_states = cdml.Combo(self, -1, validator=cdml.KeyValidator(cdml.NO_EDIT)) arrow_up = cdml.getSmallUpArrowBitmap() # arrow bitmap for buttons arrow_dn = cdml.getSmallDnArrowBitmap() # add buttons for child States self.btn_add_state = cdml.BitmapButton(self, -1, arrow_up) self.btn_del_state = cdml.BitmapButton(self, -1, arrow_dn) self.__set_properties() self.__do_layout() # Opening another instance of the form is currently disabled since # recursive opening of this form and updating a parent form according # to a modification performed with a child is not supported. However, # doing this from the list box is ok since the record is saved and # changing the data is not possible in the child form # self.cc_states.GetTextCtrl().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDblClick) self.lc_states.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnLeftDblClick)
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)
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)
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)
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()
def SetComboItem(self): """ Set items of ComboCtrl in RowPanel class when focus is moved in current RowPanel instance The items are removed when lost focus --> Implemented in CDMFrame class RowPanel class that have combo controls must implement this method. """ parm_type = [(str(Type), -1) for Type in DB.ParameterTypes if (cdml.GetAdminMode() or Type not in ['State Indicator', 'System Reserved']) ] self.cc_type.SetItems(parm_type)
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
def GetCurrTarget(self, type='obj', what='both'): """ Dummy method to return the Project ID """ # ignore any input as this just imitates the cdml function id = self.idPrj if id == '': return None # Just create a dummy structure with enough information to allow # processing it by the general menu handler function DummyStructToReturn = cdml.Struct() DummyStructToReturn.Id = 1 DummyStructToReturn.Key = id return DummyStructToReturn
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()
def Initialize(self): """ Assign initial values to the controls """ self.record.ID = self.idPrj project = cdml.GetRecordByKey(DB.Projects, self.idPrj) if cdml.Exist(project): # if project != None, create temporary copy of the project data self.record.Name = str(project.Name) self.record.Notes = str(project.Notes) self.record.PrimaryModelID = project.PrimaryModelID self.record.DerivedFrom = project.DerivedFrom self.record.PrimaryPopulationSetID = project.PrimaryPopulationSetID self.record.NumberOfSimulationSteps = project.NumberOfSimulationSteps self.record.NumberOfRepetitions = project.NumberOfRepetitions self.record.CreatedOn = project.CreatedOn self.record.LastModified = project.LastModified self.record.SimulationRules = project.SimulationRules self.SimRule = [[], [], [], []] for rule in self.record.SimulationRules: self.SimRule[rule.SimulationPhase].append(rule) self.ShowProjectData()
def OnButtonClick(self, event): """ Method to respond the action taken by user""" id = event.GetId() if id == cdml.IDP_BUTTON1: # Copy this set cdml.dlgNotPrepared() elif id == cdml.IDP_BUTTON2: # PopulationStructure cdml.dlgNotPrepared() elif id == cdml.IDP_BUTTON3: # PopulationData frame = self.GetTopLevelParent() if self.Id == 0: PopulationID = None else: PopulationID = self.Key CurrentName = str(self.tc_name.GetValue()) cdml.OpenForm("PopulationData", self, CurrentName, PopulationID, None, frame.idPrj)
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
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)
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