Exemplo n.º 1
0
    def DeleteObjective(self):
        "Deletes an objective from the objectives list box"

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

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

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

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

        # handle hiding/showing controls according to distribution status
        if self.lc_objectives.GetItemCount() == 0:
            if self.lc_column.GetItemCount() == 0:
                self.HasDistribution = None
                self.ShowTabData()
                self.lc_dist.Enable(not self.HasDistribution)
                self.tc_dist_text.Enable(not self.HasDistribution)
Exemplo n.º 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
Exemplo n.º 3
0
def MultipleExportAsCSV(FilePatternForFilesWithSimulationResults,
                        SimulationResultID=None,
                        ColumnsToExport=''):
    """ Generate a CSV file from multiple result files """

    ListOfDataFilesWithResultsUnfiltered = DB.FilePatternMatchOptimizedForNFS(
        FilePatternForFilesWithSimulationResults)
    # Filter out files with a wrong extension as these may be from a previous
    # run of this script
    ListOfDataFilesWithResults = filter(
        lambda Entry: DB.os.path.splitext(Entry)[1].lower() != '.csv',
        ListOfDataFilesWithResultsUnfiltered)
    # Check that the file pattern represents files
    if len(ListOfDataFilesWithResults) == 0:
        raise ValueError, 'The file Pattern ' + FilePatternForFilesWithSimulationResults + ' did not match any file - please make sure the pattern is valid'
    # Traverse all the files
    for FileName in ListOfDataFilesWithResults:
        print ' Processing the file ' + FileName
        DB.LoadAllData(FileName)
        # If no simulation results are defined, then select the first simulation
        # result. Note that once it is set, all files will be accessed with
        # the same ID.
        if SimulationResultID == None:
            SimulationResultID = sorted(DB.SimulationResults.keys())[0]
        # Generate the file names
        SimulationResultInFocus = DB.SimulationResults[SimulationResultID]
        (FileNameBase, FileNameExt) = DB.os.path.splitext(FileName)
        FileNameToUse = FileNameBase + 'Results.csv'

        if ColumnsToExport.strip() == '':
            SimulationResultInFocus.ExportAsCSV(FileNameToUse)
        else:
            # remove white spaces
            ColumnNames = ColumnsToExport.replace(' ',
                                                  '').replace('\t',
                                                              '').split(',')
            ColumnIndices = [
                SimulationResultInFocus.DataColumns.index(ColumnName)
                for ColumnName in ColumnNames
            ]
            NewData = [ColumnNames]
            for DataRow in SimulationResultInFocus.Data:
                NewRow = [
                    DataRow[ColumnIndex] for ColumnIndex in ColumnIndices
                ]
                NewData = NewData + [NewRow]
            # Note that column names are already embeded in the data
            SimulationResultInFocus.ExportAsCSV(FileName=FileNameToUse,
                                                DataToExport=NewData,
                                                ExportTitles=False)
    return
Exemplo n.º 4
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)
Exemplo n.º 5
0
def Get_STOCK_BASIC_Data(CodeList,TimeList,Fields,SpecialConfig={}):
	Ret=DataDef.FM_Ret(DataDef.STATUS.SUCCESS.value,'')
	RetValue=[]
	# 这里传过来的参数和字段时间轴等都是规则化之后的了,这部分需要加上接独特的处理
	# 由于Tushare默认是取上一个交易日的,所以TimeList默认加一
	TempTime=TimeList.Start+datetime.timedelta(days=1)
	# Code是Index,默认去掉
	if 'Code' in Fields:Fields.remove('Code')
	# 暂时没有处理
	RetValue=ts.get_stock_basics(TempTime.date().isoformat())
	# 数据提取完毕,先取相应代码
	try:
		TempCode=[x.Code for x in CodeList]
		RetValue=RetValue.loc[TempCode]
	except:
		Ret.Value=DataDef.STATUS.FAIL.value
		Ret.RetReason='获取相应代码失败'
	# 数据提取完毕,再取相应字段
	Fields=[x for x in Fields if x in TUSHARE_STOCK_BASIC_TRAN_FIELDS.keys()]
	TempFields=[TUSHARE_STOCK_BASIC_TRAN_FIELDS[x] for x in Fields]
	RetValue=RetValue[TempFields]
	RetValue.columns=Fields
	RetValue.index.name='Code'
	# 到此数据已经按字段删选完毕了,接下来返回一个结构体,包含数据,组织方式等信息
	RetValue=DataModify.FM_Data(RetValue,TimeList.StartStr,DataDef.GROUP_BY_TYPE.TIME.value)
	return Ret,RetValue
Exemplo n.º 6
0
def Get_K_DAY_Data(CodeList,TimeList,Fields,SpecialConfig={}):
	Ret=DataDef.FM_Ret(DataDef.STATUS.SUCCESS.value,'')
	RetValue=[]
	# 这里传过来的参数和字段时间轴等都是规则化之后的了,这部分需要加上接独特的处理
	# 暂时没有处理
	for TempCode in CodeList:
		if 'Amount' not in Fields:
			RetValue.append(ts.get_k_data(TempCode.Code,TimeList.StartStr,TimeList.EndStr))
		else:
			try:
				RetValue.append(ts.get_h_data(TempCode.Code,TimeList.StartStr,TimeList.EndStr))
			except:
				Fields=Fields.remove('Amount')
				print('可能由于提取时间过长,tushare.get_h_data失败,尝试换成tushare.get_k_data')
				RetValue.append(ts.get_k_data(TempCode.Code,TimeList.StartStr,TimeList.EndStr))
	# Tushare两种不同的方式可能提取的数据可能不是以时间为Index的,设置一下
	try:
		for x in range(0,len(RetValue)):RetValue[x]=RetValue[x].set_index('date')
		# RetValue=[x.set_index('date') for x in RetValue]
	except:
		pass
	# 数据提取完毕,再取相应字段
	Fields=[x for x in Fields if x in TUSHARE_K_DAY_TRAN_FIELDS.keys()]
	TempFields=[TUSHARE_K_DAY_TRAN_FIELDS[x] for x in Fields]
	for x in range(0,len(RetValue)):
		try:
			RetValue[x]=RetValue[x][TempFields]
			RetValue[x].columns=Fields
			RetValue[x].index.name='Time'
		except:
			pass
	# 到此数据已经按字段删选完毕了,接下来返回一个结构体,包含数据,组织方式等信息
	RetValue=DataModify.FM_Data(RetValue,[x.FullCode for x in CodeList],DataDef.GROUP_BY_TYPE.CODE.value)
	return Ret,RetValue
Exemplo n.º 7
0
    def SaveRecord(self, record):
        """
        Save/Modify the data of StudyModel object
        This method is called by CheckFocus mehtod in CDMLib
        RowPanel class must implement this method.
        """

        # Create new StudyModel object
        entry = DB.StudyModel(ID=0,
                              Name=str(record.Name),
                              Notes=str(record.Notes),
                              DerivedFrom=record.DerivedFrom,
                              MainProcess=record.MainProcess)

        # Check the relevance of the new state,

        frame = self.GetTopLevelParent()

        if self.Id == 0:  # if previous panel is new, create new object
            entry = DB.StudyModels.AddNew(entry, ProjectBypassID=frame.idPrj)

        elif self.Id > 0:  # if previous panel is existing one, replace record
            entry = DB.StudyModels.Modify(self.Key,
                                          entry,
                                          ProjectBypassID=frame.idPrj)

        return entry
Exemplo n.º 8
0
    def SaveRecord(self, record):
        """
        Save/Modify the data of StudyModel object
        This method is called by CheckFocus mehtod in CDMLib
        RowPanel class must implement this method.
        """

        # create new PopulationSet instance
        entry = DB.PopulationSet(ID=0,
                                 Name=str(record.Name),
                                 Notes=str(record.Notes),
                                 Source=str(record.Source),
                                 DerivedFrom=record.DerivedFrom,
                                 DataColumns=record.DataColumns,
                                 Data=record.Data,
                                 Objectives=record.Objectives)

        frame = self.GetTopLevelParent()
        if self.Id == 0:  # if previous panel is new, create new object
            entry = DB.PopulationSets.AddNew(entry,
                                             ProjectBypassID=frame.idPrj)

        elif self.Id > 0:  # if previous panel is existing one, replace record
            entry = DB.PopulationSets.Modify(self.Key,
                                             entry,
                                             ProjectBypassID=frame.idPrj)

        return entry
Exemplo n.º 9
0
 def LocateParam (ParamName, ParamCalcMethod, Data):
     " locate the parameter in the parameter list in the data"
     ParamIndex = None
     for (RowNum,Row) in enumerate(Data):
         if ParamCalcMethod == '' or Row[1]==None or Row[1]=='':
             # if no calculation method is specified of if it is blank
             # in the data then ignore it - this means that the first 
             # parameter name match will be returned - regardless of
             # calculation method
             RowParamCalc = ''
         else:
             # calculation method may contain an asterisk symbol - ignore
             # it in the data
             if Row[1][-1] == '*':
                 RowParamCalc = Row[1][:-1]
             else:
                 RowParamCalc = Row[1]
         # Handle the case where an empty string is converted to None
         FirstColumnToCompare = DB.Iif(Row[0] == None, '', Row[0])
         # Check if this is correct
         if ParamName == FirstColumnToCompare and ParamCalcMethod == RowParamCalc:
             # row located
             ParamIndex = RowNum
             break
     return ParamIndex
Exemplo n.º 10
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
Exemplo n.º 11
0
    def SaveRecord(self, record):
        """
        Save/Modify the data of StudyModel object
        This method is called by CheckFocus method in CDMLib
        RowPanel class must implement this method.
        """

        # create new State instance
        entry = DB.State(ID=0,
                         Name=record.Name,
                         Notes=record.Notes,
                         IsSplit=record.IsSplit,
                         JoinerOfSplitter=record.JoinerOfSplitter,
                         IsEvent=record.IsEvent,
                         IsTerminal=record.IsTerminal,
                         ChildStates=record.ChildStates)

        frame = self.GetTopLevelParent()

        if self.Id == 0:  # if previous panel is new, create new object
            entry = DB.States.AddNew(entry, ProjectBypassID=frame.idPrj)

        elif self.Id > 0:  # if previous panel is existing one, replace record
            entry = DB.States.Modify(self.Key,
                                     entry,
                                     ProjectBypassID=frame.idPrj)

        return entry
Exemplo n.º 12
0
def GetData(CodeList,
            TimeList=None,
            Fields='All',
            DataType=DataDef.DATA_TYPE.K_DAY.value,
            GroupByType=DataDef.GROUP_BY_TYPE.DEFAULT.value,
            DataSource=DataDef.DATA_SOURCE.CYCLE_ALL.value,
            SpecialConfig={}):
    RetValue = []
    Ret = DataDef.FM_Ret(DataDef.STATUS.SUCCESS.value, '')
    # 参数规则化,转化为MySys的参数
    CodeList, TimeList, Fields = DataModify.ParModify(CodeList, TimeList,
                                                      Fields)
    # 按照不同的数据类型提取数据
    # SpecialConfig={}
    if DataType == DataDef.DATA_TYPE.K_DAY.value:
        Ret, RetValue = Get_K_DAY_Data(RetValue, Ret, CodeList, TimeList,
                                       Fields, SpecialConfig, DataSource)
    elif DataType == DataDef.DATA_TYPE.STOCK_BASIC.value:
        Ret, RetValue = Get_STOCK_BASIC_Data(RetValue, Ret, CodeList, TimeList,
                                             Fields, SpecialConfig, DataSource)
    elif DataType == DataDef.DATA_TYPE.PLATE_COMPONENT.value:
        Ret, RetValue = Get_PLATE_COMPONENT_Data(RetValue, Ret, CodeList,
                                                 TimeList, Fields,
                                                 SpecialConfig, DataSource)
    RetValue = DataModify.DataGroup(RetValue, GroupByType)
    return Ret, RetValue
Exemplo n.º 13
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
Exemplo n.º 14
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)
Exemplo n.º 15
0
            def ReportGenerationStartMiniScript():
                "Generate the report and copy the text"

                # Define an encapsulating function so no arguments will be needed
                def FunctionToRunAsProcess():
                    ReturnVal = self.ReportObject.GenerateReport(FormatOptions)
                    return ReturnVal

                # Now run this function as a process - if possible
                (ProcessList,
                 PipeList) = DB.RunFunctionAsProcess(FunctionToRunAsProcess)
                return (ProcessList, PipeList)
Exemplo n.º 16
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
Exemplo n.º 17
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)
Exemplo n.º 18
0
    def ShowData(self, Columns, Data, Objectives):
        """ Display DataColums/Data in the List Controls and Grid control if necessary"""

        self.lc_column.SetItems(
            Columns, do_sort=False)  # Clear and add new Column names

        self.lc_objectives.SetItems(
            Objectives, do_sort=False)  # Clear and add new Column names

        self.ShowTabData()  # Create or delete 'Data' tab

        if Data == []:
            if self.HasDistribution:
                # if this is distribution based, make sure the grid is clear
                # do nothing
                return
        # Display Data on the grid control
        no_col = len(Columns)
        no_row = len(Data)

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

        # Adjust grid size according to the size of Data
        if no_col > no_grid_col:
            self.grid_1.AppendCols(no_col - no_grid_col)

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

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

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

        self.grid_1.ClearGrid()  # Delete existing data in grid control

        # Set the column header of grid control
        for i, column in enumerate(Columns):
            self.grid_1.SetColLabelValue(i, column[0])

        # Write Data in each cell
        for i, row in enumerate(Data):
            for j, col in enumerate(row):
                value = cdml.iif(row[j] == None, '', DB.SmartStr(row[j]))
                self.grid_1.SetCellValue(i, j, value)
        self.__do_layout()
Exemplo n.º 19
0
    def OnExit(self, event):
        """ Event handler for Exit menu or CLOSE_WINDOW event"""

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

            elif ans == wx.ID_CANCEL: return

        self.MyMakeModal(False)
        self.Destroy()
Exemplo n.º 20
0
def TimeListModify(TimeList):
    if DataDef.IsEnumMember(TimeList, DataDef.NONE_DATA):
        # 如果为空,直接返回
        return TimeList
    Temp = FM_TimeList()
    TempRet = ['', '']
    if type(TimeList) is list and len(TimeList) == 2:
        TempRet = [parser.parse(x) for x in TimeList]
        # 输出类
        Temp.Start = TempRet[0]
        Temp.End = TempRet[1]
        Temp.ToStr()
    elif type(TimeList) is str and TimeList != '':
        TempRet = parser.parse(TimeList)
        Temp.Start = TempRet
        Temp.End = TempRet
        Temp.ToStr()
    return Temp
Exemplo n.º 21
0
    def SaveRecord(self, record):
        """
        Save/Modify the data of StudyModel object
        This method is called by CheckFocus mehtod in CDMLib
        RowPanel class must implement this method.
        """

        # create new Param object
        entry = DB.Param(Name=str(record.Name),
                         Formula=str(record.Formula),
                         ParameterType=str(record.ParameterType),
                         ValidationRuleParams=str(record.ValidationRuleParams),
                         Notes=str(record.Notes))

        if self.Id == 0:  # if previous panel is new, create new object
            entry = DB.Params.AddNew(entry)

        else:  # if previous panel is existing one, replace record
            entry = DB.Params.Modify(self.Key, entry)

        return entry
Exemplo n.º 22
0
    def SetComboItems(self, ctrl=None, page=-1):
        """
        Build list for the combo controls for a simulation  project
        """

        if ctrl == None :
            id_ctrl = None
        else:
            id_ctrl = ctrl.Id


        if ctrl is None or id_ctrl in [ cdml.IDF_BUTTON1, cdml.IDF_BUTTON3 ]:
            # distribution population sets are now allowed, the next commented
            pset = [ (str(ps.Name), DB.Iif(ps.IsDistributionBased(),'Distribution','Data'), str(ps.Notes), ps.ID) for ps in DB.PopulationSets.values() ]
            self.cc_pset.SetItems(pset)

        if ctrl is None or id_ctrl in [ cdml.IDF_BUTTON2, cdml.IDF_BUTTON4 ]:
            model = [(str(sm.Name), str(sm.Notes), sm.ID)
                        for sm in DB.StudyModels.values() ]
            self.cc_model.SetItems(model)


        parameters = DB.Params.values()
        if ctrl is None or id_ctrl == cdml.IDP_BUTTON1:
            if page in [0,1,3]:
                items = [ (str(parm), parm.Notes, -1)
                          for parm in parameters if parm.ParameterType in (['System Option']*(page==0) + ['Number','Integer','State Indicator'])]
            self.combo_box_1.SetItems(items)


        if ctrl is None or id_ctrl == cdml.IDP_BUTTON2:
            function = [ (str(parm), str(parm.Formula), str(parm.Notes), -1)
                         for parm in parameters if parm.ParameterType == 'Expression']
            self.combo_box_2.SetItems(function)

        if ctrl is None or id_ctrl == cdml.IDP_BUTTON3:
            function = [ (str(parm), str(parm.Formula), str(parm.Notes), -1)
                         for parm in parameters if parm.ParameterType == 'Expression']
            self.combo_box_3.SetItems(function)
Exemplo n.º 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
Exemplo n.º 24
0
def Get_STOCK_BASIC_Data(CodeList, TimeList, Fields, SpecialConfig={}):
    # ret, errMsg = QtLogin("nblfm_qt", "199568")
    Ret = DataDef.FM_Ret(DataDef.STATUS.SUCCESS.value, '')
    RetValue = []
    # Fields先转化为QTAPI能识别的
    TempCodeList = [
        x for x in CodeList if x.Exchange in GTA_QTAPI_EXCHANGE_TRAN.keys()
    ]
    TempCodeList = [
        x.Code + '.' + GTA_QTAPI_EXCHANGE_TRAN[x.Exchange]
        for x in TempCodeList
    ]
    if "Code" not in Fields: Fields.append("Code")
    Fields = [
        x for x in Fields if x in GTA_QTAPI_STOCK_BASIC_TRAN_FIELDS.keys()
    ]
    TempFields = [GTA_QTAPI_STOCK_BASIC_TRAN_FIELDS[x] for x in Fields]
    # 开始提数
    if "GTA_QTApi_PLATE_ID" in SpecialConfig.keys():
        TempPlate = [SpecialConfig["GTA_QTApi_PLATE_ID"] + ".*"]
        Ret.Value, Ret.RetReason, RetValue = GetSecurityCurInfo(
            TempPlate, [], TempFields)
        if Ret.Value == 0: Ret.Value = DataDef.STATUS.SUCCESS.value
    else:
        Ret.Value, Ret.RetReason, RetValue = GetSecurityCurInfo(
            TempCodeList, [], TempFields)
        if Ret.Value == 0: Ret.Value = DataDef.STATUS.SUCCESS.value
    # 数据提取完毕,再取相应字段
    RetValue = RetValue[TempFields]
    RetValue.columns = Fields
    RetValue = RetValue.set_index('Code')
    RetValue.index.name = 'Code'
    # 到此数据已经按字段删选完毕了,接下来返回一个结构体,包含数据,组织方式等信息
    RetValue = DataModify.FM_Data(RetValue,
                                  datetime.datetime.now().date().isoformat(),
                                  DataDef.GROUP_BY_TYPE.TIME.value)
    return Ret, RetValue
Exemplo n.º 25
0
    def SaveRecord(self, record):
        """
        Save/Modify the data of StudyModel object
        This method is called by CheckFocus method in CDMLib
        RowPanel class must implement this method.
        """

        # create new Transition object
        entry = DB.Transition(StudyModelID=record.StudyModelID,
                              FromState=record.FromState,
                              ToState=record.ToState,
                              Probability=str(record.Probability),
                              Notes=str(record.Notes))

        frame = self.GetTopLevelParent()
        if self.Id == 0:  # if previous panel is new, create new object
            entry = DB.Transitions.AddNew(entry, ProjectBypassID=frame.idPrj)

        elif self.Id > 0:  # if previous panel is existing one, replace record
            entry = DB.Transitions.Modify(self.Key,
                                          entry,
                                          ProjectBypassID=frame.idPrj)

        return entry
Exemplo n.º 26
0
        DummyStructToReturn.Key = target_id[0]
        return DummyStructToReturn

    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

    # Define the default method to handle the menu selections
    OnMenuSelected = cdml.OnMenuSelected


if __name__ == "__main__":
    DB.LoadAllData('InData' + DB.os.sep + 'Testing.zip')
    ProjectKeyToShow = min(DB.Projects.keys())
    SimulationScriptFullPath = DB.Projects[ProjectKeyToShow].CompileSimulation(
    )
    ResultInfo = DB.Projects[ProjectKeyToShow].RunSimulationAndCollectResults(
        SimulationScriptFullPath)
    app = wx.App(0)
    #wx.InitAllImageHandlers() Deprecated
    frame_1 = MainFrame(id_prj=ProjectKeyToShow, parent=None)
    app.SetTopWindow(frame_1)
    frame_1.Center()
    frame_1.Show()
    app.MainLoop()
Exemplo n.º 27
0
 def PopulateOptionsOnScreen(self, FormatOptions):
     """ updates controls with values from an option list """
     # Detail level
     DetailLevelStr = str(DB.HandleOption('DetailLevel', FormatOptions, ''))
     self.cc_DetailLevel.GetTextCtrl().SetValue(DetailLevelStr)
     # Show Dependency
     ShowDependency = str(
         DB.HandleOption('ShowDependency', FormatOptions, ''))
     ShowDependencyStr = DB.Iif(ShowDependency == '', '',
                                DB.Iif(ShowDependency, 'Yes', 'No'))
     self.cc_ShowDependency.GetTextCtrl().SetValue(ShowDependencyStr)
     # Summary Intervals
     SummaryIntevalStr = str(
         DB.HandleOption('SummaryIntervals', FormatOptions, ''))
     self.tc_SummaryIntevals.SetValue(SummaryIntevalStr)
     # Number Formats
     (ColumnNumberFormatFloatStr,
      ColumnNumberFormatIntegerStr) = DB.HandleOption(
          'ColumnNumberFormat', FormatOptions, ('', ''))
     self.tc_ColumnNumberFormatFloat.SetValue(ColumnNumberFormatFloatStr)
     self.tc_ColumnNumberFormatInteger.SetValue(
         ColumnNumberFormatIntegerStr)
     # Column Separator
     ColumnSeparatorStr = str(
         DB.HandleOption('ColumnSpacing', FormatOptions, ''))
     self.tc_ColumnSeparator.SetValue(ColumnSeparatorStr)
     # Show Hidden
     ShowHidden = str(DB.HandleOption('ShowHidden', FormatOptions, ''))
     ShowHiddenStr = DB.Iif(ShowHidden == '', '',
                            DB.Iif(ShowHidden, 'Yes', 'No'))
     self.cc_ShowHidden.GetTextCtrl().SetValue(ShowHiddenStr)
     # Column Selections
     ColumnList = DB.HandleOption('ColumnFilter', FormatOptions, [])
     # first delete all items to allow rebuilding the list
     self.lc_SelectedColumns.DeleteAllItems()
     # add to column list
     for Item in reversed(ColumnList):
         # each item is of the following format
         #Item = (ColumnText,CalculationMethod,ColumnTitle)
         self.lc_SelectedColumns.AddItem(Item, 0, False)
     # Stratification table
     StratificationTableStr = str(
         DB.HandleOption('StratifyBy', FormatOptions, ''))
     self.tc_StratificationTable.SetValue(StratificationTableStr)
     return
Exemplo n.º 28
0
    def ExtractReportOptions(self):
        " Extract the options from the screen "
        FormatOptions = self.FormatOptions
        # Detail level
        DetailLevelStr = str(self.cc_DetailLevel.GetTextCtrl().GetValue())
        if DetailLevelStr != '':
            try:
                DetailLevel = int(DetailLevelStr)
            except:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'The text in the detail level box is not a number, please enter a positive number in the detail level box or leave it blank for the default',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            if DetailLevel < 0:
                cdml.dlgSimpleMsg(
                    'Report Parameter Error',
                    'The number in the detail level box is negative, please enter a positive number in the detail level box or leave it blank for the default',
                    wx.OK,
                    wx.ICON_ERROR,
                    Parent=self)
                return
            FormatOptions = DB.HandleOption('DetailLevel', FormatOptions,
                                            DetailLevel, True)
        else:
            # Handle the defualt case by removing the option form the list
            NewFormatOptions = DB.HandleOption('DetailLevel', FormatOptions,
                                               None, False, True)
            if NewFormatOptions != None:
                FormatOptions = NewFormatOptions

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

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

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

        return FormatOptions
Exemplo n.º 29
0
    def LoadDataAndApplyOverrides(InputFileName, ProjectIndex, ModelOverride,
                                  PopulationSetOverride,
                                  InitializeCoefficientValues):
        " Loads the data file, and applies overrides for further handling "
        # First load the data - this also erases old results
        DB.LoadAllData(InputFileName)
        # First detect the population override
        try:
            # Handle PopulationSetOverride
            if DB.IsList(PopulationSetOverride):
                # [x] means ModelID = x
                # The override is provided as a list, pull out the number is the
                # list. This number is the actual ID, not the sort order
                PopulationToUseID = PopulationSetOverride[0]
            elif DB.IsInt(PopulationSetOverride):
                # Extract the PopulationSetID from the sort order of populations
                # This way the user has to tell the index the same way it is
                #  shown in the GUI
                PopulationToUseID = sorted(
                    DB.PopulationSets.keys())[PopulationSetOverride]
            elif PopulationSetOverride == None:
                PopulationToUseID = None
            elif PopulationSetOverride != None:
                # raise the error to show the error message
                raise ValueError, "Unrecognized input for population"
        except:
            (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
            raise ValueError, 'Run Multiple Simulations Error: The system could not figure out the index of the populations set - please make sure there are population sets in your file and that you specified the index correctly. Note that a populations set index of 0 means the first populations set and if there are n population sets in a file, the index of the last population set is n-1. If you specified the population set index in bracket, make sure you are not using the population set sort order as without brackets. Here are more details regarding the error: ' + str(
                ExceptValue)

        # Find the project to use if not defined - auto detect
        try:
            if DB.IsList(ProjectIndex):
                # [x] means ProjectID = x
                # The override is provided as a list, pull out the number in the
                # list. This number is the actual ID, not the sort order
                ProjectID = ProjectIndex[0]
            elif DB.IsInt(ProjectIndex):
                # otherwise use the index to pull out the correct project from
                # the list. This number is the actual ID, not the sort order
                # This way the user has to tell the index the same way it is
                # shown in the GUI
                ProjectID = sorted(DB.Projects.keys())[ProjectIndex]
            elif ProjectIndex == None and PopulationToUseID != None:
                # None means the first project in the list
                ProjectID = sorted(DB.Projects.keys())[0]
            else:
                raise ValueError, "Unrecognized input for project"
        except:
            (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
            raise ValueError, 'Run Multiple Simulations Error: The system could not figure out the index of the project - please make sure there are projects in your file and that you specified the index correctly. Note that a project index of 0 means the first project and if there are n projects in a file, the index of the last project is n-1. If you specified the project index in bracket, make sure you are not using the project sort order as without brackets. Here are more details regarding the error: ' + str(
                ExceptValue)
        ProjectToRun = DB.Projects[ProjectID]
        # Do not continue changing the project if no simulation requested
        if NumberOfSimulationStepsOverride != 0:
            # Handle NumberOfSimulationStepsOverride - ignore zero since it
            # means population generation
            if NumberOfSimulationStepsOverride != None:
                ProjectToRun.NumberOfSimulationSteps = NumberOfSimulationStepsOverride
            # Handle PopulationRepetitionsOverride
            if PopulationRepetitionsOverride != None:
                ProjectToRun.NumberOfRepetitions = PopulationRepetitionsOverride
            try:
                # Handle ModelOverride
                if DB.IsList(ModelOverride):
                    # [x] means ModelID = x
                    # The override is provided as a list, pull out the number
                    # in the list. This number is the actual ID, not sort order
                    ProjectToRun.PrimaryModelID = ModelOverride[0]
                    ProjectToRun.Notes = '!!! Model override during simulation launch !!! ' + ProjectToRun.Notes
                elif DB.IsInt(ModelOverride):
                    # Extract the ModelID from the sort order of Models
                    # This way the user has to tell the index the same way it
                    # is shown in the GUI
                    ProjectToRun.PrimaryModelID = sorted(
                        DB.StudyModels.keys())[ModelOverride]
                    ProjectToRun.Notes = '!!! Model override during simulation launch !!! ' + ProjectToRun.Notes
                elif ModelOverride != None:
                    # raise the error to show the error message
                    raise ValueError, "Unrecognized input for model"
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                raise ValueError, 'Run Multiple Simulations Error: The system could not figure out the index of the model - please make sure there are models in your file and that you specified the index correctly. Note that a model index of 0 means the first model and if there are n models in a file, the index of the last model is n-1. If you specified the model index in bracket, make sure you are not using the model sort order as without brackets. Here are more details regarding the error: ' + str(
                    ExceptValue)
            # Record the population Override in Project
            if PopulationToUseID != None:
                ProjectToRun.PrimaryPopulationSetID = PopulationToUseID
                ProjectToRun.Notes = '!!! Population set override during simulation launch !!! ' + ProjectToRun.Notes
            try:
                # Handle InitializeCoefficientValues Rule overrides
                for (RuleEnum,
                     InitValue) in enumerate(InitializeCoefficientValues):
                    RuleToReplace = ProjectToRun.SimulationRules[RuleEnum]
                    if RuleToReplace.SimulationPhase != 0:
                        raise ValueError, "ASSERTION ERROR: Attempt to replace a rule not in initialization"
                    # Create a new rule using the old one
                    ReplaceRule = DB.SimulationRule(
                        AffectedParam=RuleToReplace.AffectedParam,
                        SimulationPhase=RuleToReplace.SimulationPhase,
                        AppliedFormula=DB.Expr(DB.SmartStr(InitValue)),
                        Notes=
                        '!!! Initialization value override during simulation launch !!! '
                        + RuleToReplace.Notes)
                    # Now actually replace the rule in the sequence
                    ProjectToRun.SimulationRules[RuleEnum] = ReplaceRule
            except:
                (ExceptType, ExceptValue, ExceptTraceback) = sys.exc_info()
                raise ValueError, 'Run Multiple Simulations Error: The system could not apply an initial value override to one or more of the rules. Make sure that the overrides do not exceed the number of initialization rules and that the values are reasonable. Here are more details regarding the error: ' + str(
                    ExceptValue)
            # Make sure that all changes made are valid
            ProjectToRun.VerifyData()
        return (ProjectToRun, PopulationToUseID)
Exemplo n.º 30
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)