Пример #1
0
class LibMaster(BaseWidget):
    def __init__(self, title='LibMaster'):
        super(LibMaster, self).__init__(title)
        self.debug = False
        #Import controls
        self._openImportFile = None
        self._openImportDir = None
        self._importPathText = ControlText()
        self._openFileButton = ControlButton('Open a file')
        self._openDirButton = ControlButton('Open a directory')
        self._importButton = ControlButton('Import')
        self._importTextArea = ControlTextArea()
        #Configure controls
        self._configCombo = ControlCombo('Library')
        self._configNameText = ControlText('Loop name')
        self._configPageNumber = ControlNumber('Start page',
                                               default=1,
                                               min=1,
                                               max=20000)
        self._configDict = {}
        self._configList = ControlList('Application Plan',
                                       add_function=self.__buttonAction_Add,
                                       remove_function=self.__buttonAction_Del)
        self._configLoadButton = ControlButton('Load')
        self._configAddButton = ControlButton('Add')
        self._configDelButton = ControlButton('Delete')
        self._configClearButton = ControlButton('Clear')
        self._configSaveButton = ControlButton('Save')
        self._configGenButton = ControlButton('Generate')
        self._configTextArea = ControlTextArea()
        #Combine controls
        self._openDBFile = ControlFileOpen('Choose the database file:	',
                                           opened_file_type='txt')
        self._openArgFile = ControlFileOpen('Choose the argument file:	',
                                            opened_file_type='xlsx')
        self._combineButton = ControlButton('Combine')
        self._combineTextArea = ControlTextArea()

        #setup all controls
        self.formset = [{
            '	1. Import	': [
                '', ('', '_importPathText', ''),
                ('', '_openFileButton', '', '_openDirButton', ''),
                (' ', '_importButton', ' '), '', ('', '_importTextArea', ''),
                ''
            ],
            '	2. Configure	': [
                '',
                ('', '_configCombo', '', '_configNameText', '',
                 '_configPageNumber', ''), ('', '_configList', ''),
                ('', '_configAddButton', '', '_configDelButton', '',
                 '_configClearButton', ''),
                ('', '_configLoadButton', '', '_configSaveButton', '',
                 '_configGenButton', ''), '', ('', '_configTextArea', ''), ''
            ],
            '	3. Combine	': [
                '', ('', '_openDBFile', ''), ('', '_openArgFile', ''),
                (' ', '_combineButton', ' '), '', ('', '_combineTextArea', ''),
                ''
            ]
        }]

        #Button Actions
        self._openFileButton.value = self.__buttonAction_OpenFile
        self._openDirButton.value = self.__buttonAction_OpenDir
        self._importButton.value = self.__buttonAction_Import
        self._configLoadButton.value = self.__buttonAction_Load
        self._configAddButton.value = self.__buttonAction_Add
        self._configDelButton.value = self.__buttonAction_Del
        self._configClearButton.value = self.__buttonAction_Clear
        self._configSaveButton.value = self.__buttonAction_Save
        self._configGenButton.value = self.__buttonAction_Gen
        self._combineButton.value = self.__buttonAction_Combine

        #set all text area to read only
        self._importTextArea.readonly = True
        self._configTextArea.readonly = True
        self._combineTextArea.readonly = True

        #Combo box lists correct library files in './Library' directory
        self._configCombo += 'Select library'
        if not os.path.exists('Library'):
            os.mkdir('Library')
        else:
            file_lst = os.listdir('Library')
            for file in file_lst:
                if file[-4:] == '.txt' and (file[:-4] + '.xlsx') in file_lst:
                    self._configCombo += file[:-4]
                else:
                    pass

        #set configuration list property
        headers = []
        headers.append(' ' * 10 + 'Library' + ' ' * 10)
        headers.append(' ' * 10 + 'Loop Name' + ' ' * 10)
        headers.append(' Start Page ')
        headers.append(' End Page ')
        self._configList.horizontal_headers = headers
        self._configList.select_entire_row = True
        self._configList.readonly = True

    def __buttonAction_OpenFile(self):
        try:
            self._openImportFile = ControlFileOpen('Choose library file:',
                                                   opened_file_type='txt')
            self._openImportFile.click()
            self._importPathText.value = self._openImportFile.value
        except Exception as err:
            self._importTextArea.__add__('Open file error: ' + repr(err))
            if self.debug:
                self._importTextArea.__add__(traceback.format_exc())

    def __buttonAction_OpenDir(self):
        try:
            self._openImportDir = ControlDir('Choose directory:')
            self._openImportDir.click()
            self._importPathText.value = self._openImportDir.value
        except Exception as err:
            self._importTextArea.__add__('Open file error: ' + repr(err))
            if self.debug:
                self._importTextArea.__add__(traceback.format_exc())

    def __buttonAction_Import(self):
        try:
            #import a file, using main import function from 'Import.py'
            if self._openImportFile is not None and self._openImportFile.value == self._importPathText.value:
                addedFiles = Import([self._openImportFile.value],
                                    self._importTextArea.__add__)
                self._importTextArea.__add__(
                    'Import finish. Libraries are exported under \'./Library\' directory.'
                )
                for add_file in addedFiles:
                    self._configCombo += addedFiles[0][:-4]
            #import a directory, find valid files in directory before calling Import
            elif self._openImportDir is not None and self._openImportDir.value == self._importPathText.value:
                files = []
                dirs = os.listdir(self._openImportDir.value)
                for file in dirs:
                    if file[-4:] == '.txt':
                        files.append(self._openImportDir.value + '/' + file)
                    else:
                        pass
                if len(files) > 0:
                    addedFiles = Import(files, self._importTextArea.__add__)
                    self._importTextArea.__add__(
                        'Import finish. Libraries are exported under \'./Library\' directory.'
                    )
                    for add_file in addedFiles:
                        self._configCombo += add_file[:-4]
                else:
                    self._importTextArea.__add__(
                        'No valid file in the directory.')
            #no file selected
            else:
                self._importTextArea.__add__('No file or directory selected.')
        except Exception as err:
            self._importTextArea.__add__('Error: ' + repr(err))
            if self.debug:
                self._importTextArea.__add__(traceback.format_exc())

    def __helper_Add2Dict(self, lst):
        combo, name, pageNum = lst[0], lst[1], int(lst[2])
        if name in self._configDict.values():
            raise Exception('Loop name conflict.')
        else:
            pass
        wb = load_workbook('./Library/' + combo + '.xlsx')
        ws = wb['Info']
        for row in list(ws.rows):
            if row[0].value == 'Page count':
                pageCount = row[1].value
            else:
                pass
        for i in range(pageCount):
            if pageNum + i in self._configDict:
                raise Exception('Page conflict.')
            else:
                pass
        lst[3] = pageNum + pageCount - 1
        for i in range(pageCount):
            self._configDict[pageNum + i] = name

    def __buttonAction_Load(self):
        try:
            self._loadConfigFile = ControlFileOpen(opened_file_type='json')
            self._loadConfigFile.click()
            if self._loadConfigFile.value != '':
                with open(self._loadConfigFile.value, 'r') as f:
                    jstr = json.load(f)
                    table = jstr['value']
                    self._configDict.clear()
                    for row in table:
                        self.__helper_Add2Dict(row)
                    self._configList.load_form(jstr, None)
            else:
                raise Exception('No file selected.')
            self._configTextArea.__add__('List loaded from ' +
                                         self._loadConfigFile.value)
        except Exception as err:
            self._configTextArea.__add__('\'Load\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Add(self):
        try:
            nameText = '__' + self._configCombo.text if self._configNameText.value == '' else self._configNameText.value
            lst = [
                self._configCombo.text, nameText, self._configPageNumber.value,
                0
            ]
            self.__helper_Add2Dict(lst)
            self._configList.__add__(lst)
            self._configList.resizecolumns = False
        except Exception as err:
            self._configTextArea.__add__('\'Add\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Del(self):
        try:
            if self._configList.selected_row_index is None:
                raise Exception('No row selected.')
            for i in range(int(self._configList.get_currentrow_value()[2]),
                           int(self._configList.get_currentrow_value()[3]) +
                           1):
                del self._configDict[i]
            self._configList.__sub__(self._configList.selected_row_index)
        except Exception as err:
            self._configTextArea.__add__('\'Delete\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Clear(self):
        try:
            self._configDict.clear()
            self._configList.clear()
        except Exception as err:
            self._configTextArea.__add__('\'Clear\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Save(self):
        try:
            self._saveConfigFile = ControlFileSave(saved_file_type='json')
            self._saveConfigFile.click()
            if self._saveConfigFile.value != '':
                with open(self._saveConfigFile.value, 'w') as f:
                    json.dump(self._configList.save_form({}, None), f)
            else:
                raise Exception('File not specified.')
            self._configTextArea.__add__('List saved to ' +
                                         self._saveConfigFile.value)
        except Exception as err:
            self._configTextArea.__add__('\'Save\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Gen(self):
        try:
            table = self._configList.value
            for i in range(len(table)):
                table[i][0] += '.txt'
            table.insert(0, ['Library', 'Loop Name', 'Start Page', 'End Page'])
            self._saveArgFile = ControlFileSave(saved_file_type='xlsx')
            self._saveArgFile.click()
            Config(table, self._saveArgFile.value)
            self._configTextArea.__add__('Arguments file is generated.')
            self._openArgFile.value = self._saveArgFile.value
        except Exception as err:
            self._configTextArea.__add__('\'Generate\' error: ' + repr(err))
            if self.debug:
                self._configTextArea.__add__(traceback.format_exc())

    def __buttonAction_Combine(self):
        try:
            self._saveDPUFile = ControlFileSave(saved_file_type='txt')
            self._saveDPUFile.click()
            Combine(self._openDBFile.value, self._saveDPUFile.value,
                    self._openArgFile.value)
            self._combineTextArea.__add__('New DPU file is generated.')
        except Exception as err:
            self._combineTextArea.__add__('Error: ' + repr(err))
            if self.debug:
                self._combineTextArea.__add__(traceback.format_exc())
Пример #2
0
class AlyaGUI(BaseWidget):


    
    def __init__(self):
        super(AlyaGUI,self).__init__('Alya Case Editor')

        #Layer for IO handling
        self._fileio = AlyaFileIO()

        self._log         = ControlTextArea('Log')
        self._fileio.SetLogControl(self.__addlog)



        #Main form fields
        self._casepath     = ControlDir('Case path', default='/home/costa/Downloads/1111')

        self._fileio.SetCasePath(self._casepath._value)


        self._casename    = ControlCombo('Case')

        
        
        
        self._casePathScan = ControlButton('Scan Path')
        self._casePathScan.value = self.___casePathScan_pressed
        
        self._caseReload = ControlButton('Load Case')
        self._caseReload.value = self.___caseReload_pressed
        
        self._casepath.changed_event = self.__casePathChanged
        
        #General tab. Here everythong most important to check
        self._dat_casename = ControlText('Name','')
        self._dat_run_type = ControlText('Run type','')
        self._dat_time_interval = ControlText('Time interval to run','')
        self._dat_number_of_steps = ControlText('Number of steps to run','')

        self._dom_nodal_points = ControlText('Number of points','')
        self._dom_elements = ControlText('Number of all elements','')
        self._dom_number_of_boundary_faces = ControlText('Number of boundary faces','')
        self._dom_mesh_numbers_verify_button = ControlButton('Verify')

        self._dom_types_of_elements = ControlText('Types of elements','')
        self._dom_domain_integration_points = ControlText('Number of integration points','')
        self._ker_density = ControlText('Density','')        
        self._ker_viscosity = ControlText('Viscosity','')        
        self._ker_steps_to_save = ControlText('Every how many steps to save','')        
        self._nsi_boundary_conditions = ControlTextArea('Nastin boundary conditions')
        general_tab = [('_dat_casename','_dat_run_type'),('_dat_time_interval','_dat_number_of_steps'),\
                       ('_dom_nodal_points','_dom_elements','_dom_number_of_boundary_faces','_dom_mesh_numbers_verify_button'),\
                       ('_dom_types_of_elements','_dom_domain_integration_points'),\
                       ('_ker_density','_ker_viscosity'),\
                       '_ker_steps_to_save','_nsi_boundary_conditions']
        
        #Raw casefile tab
        self._FileEditor = ControlTextArea('File editor')
        self._FileEditorSaveButton = ControlButton("Save file")
        self._DatPicker = ControlList('Dat files')
        self._DatPicker.horizontal_headers = ['Filename','Relative Path']
        self._DatPicker.item_selection_changed_event = self.__DAT_selection_changed
        self._DatPicker.readonly = True
        
        self._IncludedFilePicker = ControlList('Included files')
        self._IncludedFilePicker.horizontal_headers = ['Filename','Section']
        self._IncludedFilePicker.readonly = True
        self._IncludedFilePicker.item_selection_changed_event = self.__INCLUDE_selection_changed
        
        
        self.formset = [ ('_casepath','_casePathScan','||','_casename','_caseReload'),\
                        {'General': general_tab, \
                         'Raw Casefile':[('_FileEditor','||','_DatPicker','||','_IncludedFilePicker'),\
                         '_FileEditorSaveButton']},'=','_log']    

        self._log.autoscroll = True
        self._log.readonly = True
        
        
    def ___fill_general_tab(self, params):
        self._dat_casename.value = params['alya']
        self._dat_run_type.value = params['run_type']
        self._dat_time_interval.value = params['time_interval']
        self._dat_number_of_steps.value = params['number_of_steps']
        self._dom_nodal_points.value = params['nodal_points']
        self._dom_elements.value = params['elements']
        self._dom_number_of_boundary_faces.value = params['boundaries']
        self._dom_types_of_elements.value = params['types_of_elements']
        self._dom_domain_integration_points.value = params['domain_integration_points']
        self._ker_density.value = params['density']
        self._ker_viscosity.value = params['viscosity']
        self._ker_steps_to_save.value = params['steps']
        self._nsi_boundary_conditions.value = params['nsi_boundary_conditions']

        
    def ___caseReload_pressed(self):
        #
        # Reload the case
        #
        self.__addlog(f'Loading case {self._casename.value}')
        
        params = self._fileio.ExtractImportantParameters( self._casename.value )
        self.__addlog(f'Loaded parameters {params}')
        self.___fill_general_tab(params)


    def ___casePathScan_pressed(self):
        #
        # Scan path for the cases, fill the listbox of cases
        # Not fully implmented. Does not support more than one case per path yet
        #
        self._fileio.SetCasePath(self._casepath._value)
        self.__addlog(f'Scanning {self._casepath._value} for cases')
        
        cases = self._fileio.ListCases()
        self.__addlog(f'Found the following cases {cases}')

        self._casename.clear()
        if cases!=[]:
            for case in cases:
                self._casename.add_item(case)
                
            self._casename.current_index = 0
            self.___caseReload_pressed()
            
            dats = self._fileio.ListDats()
            self._DatPicker.clear()

            for dat in dats:
                self._DatPicker += [dat, '.'] 
       
    
    def __casePathChanged(self):
        self.__addlog(f'Case path changed to: {self._casepath._value}')
        self.___casePathScan_pressed()
        return True
    
    def __addlog(self, string):
        self._log.__add__(f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: {string}')
        
        

    def __INCLUDE_selection_changed(self):
        #
        # Activated when user clicks on an INCLUDED file
        #
        selection = self._IncludedFilePicker.get_currentrow_value()        
        print(selection[0])
        data = self._fileio.ReadFullFile( selection[0] )

        self._FileEditor.value = ''
        if data!=[]:
            self._FileEditor.value = ''.join(data)

        
    def __DAT_selection_changed(self):
        #
        # Activated when user clicks on a dat file
        #
        selection = self._DatPicker.get_currentrow_value()   
        data = self._fileio.ReadFullFile( os.path.join(selection[1],selection[0]) )
        
        includes = self._fileio.FindAllIncludedFiles(selection[0])
        self.__addlog(f'Found {includes} included files')
        
        self._IncludedFilePicker.clear()
        if includes!=[]:
            for include in includes:
                self._IncludedFilePicker += [include[0], include[1]] 
            
        
        
        self._FileEditor.value = ''
        if data!=[]:
            self._FileEditor.value = ''.join(data)
Пример #3
0
class AlyaGUI(BaseWidget):
    def __init__(self):
        super(AlyaGUI, self).__init__('Alya Case Editor')

        #Layer for IO handling
        self._fileio = AlyaFileIO()

        self._log = ControlTextArea('Log')
        self._fileio.SetLogControl(self.__addlog)

        #Main form fields
        self._casepath = ControlDir('Case path',
                                    default='/home/costa/Downloads/1111')

        self._fileio.SetCasePath(self._casepath._value)

        self._casename = ControlCombo('Case')

        self._casePathScan = ControlButton('Scan Path')
        self._casePathScan.value = self.___casePathScan_pressed

        self._caseReload = ControlButton('Load Case')
        self._caseReload.value = self.___caseReload_pressed

        self._casepath.changed_event = self.__casePathChanged

        #General tab. Here everythong most important to check
        self._dat_casename = ControlText('Name', '')
        self._dat_run_type = ControlText('Run type', '')
        self._dat_time_interval = ControlText('Time interval to run', '')
        self._dat_number_of_steps = ControlText('Number of steps to run', '')

        self._dom_nodal_points = ControlText('Number of points', '')
        self._dom_elements = ControlText('Number of all elements', '')
        self._dom_number_of_boundary_faces = ControlText(
            'Number of boundary faces', '')
        self._dom_mesh_numbers_verify_button = ControlButton('Verify')

        self._dom_types_of_elements = ControlText('Types of elements', '')
        self._dom_domain_integration_points = ControlText(
            'Number of integration points', '')
        self._ker_density = ControlText('Density', '')
        self._ker_viscosity = ControlText('Viscosity', '')
        self._ker_steps_to_save = ControlText('Every how many steps to save',
                                              '')
        self._nsi_boundary_conditions = ControlTextArea(
            'Nastin boundary conditions')
        general_tab = [('_dat_casename','_dat_run_type'),('_dat_time_interval','_dat_number_of_steps'),\
                       ('_dom_nodal_points','_dom_elements','_dom_number_of_boundary_faces','_dom_mesh_numbers_verify_button'),\
                       ('_dom_types_of_elements','_dom_domain_integration_points'),\
                       ('_ker_density','_ker_viscosity'),\
                       '_ker_steps_to_save','_nsi_boundary_conditions']

        #Raw casefile tab
        self._FileEditor = ControlTextArea('File editor')
        self._FileEditorSaveButton = ControlButton("Save file")
        self._DatPicker = ControlList('Dat files')
        self._DatPicker.horizontal_headers = ['Filename', 'Relative Path']
        self._DatPicker.item_selection_changed_event = self.__DAT_selection_changed
        self._DatPicker.readonly = True

        self._IncludedFilePicker = ControlList('Included files')
        self._IncludedFilePicker.horizontal_headers = ['Filename', 'Section']
        self._IncludedFilePicker.readonly = True
        self._IncludedFilePicker.item_selection_changed_event = self.__INCLUDE_selection_changed


        self.formset = [ ('_casepath','_casePathScan','||','_casename','_caseReload'),\
                        {'General': general_tab, \
                         'Raw Casefile':[('_FileEditor','||','_DatPicker','||','_IncludedFilePicker'),\
                         '_FileEditorSaveButton']},'=','_log']

        self._log.autoscroll = True
        self._log.readonly = True

    def ___fill_general_tab(self, params):
        self._dat_casename.value = params['alya']
        self._dat_run_type.value = params['run_type']
        self._dat_time_interval.value = params['time_interval']
        self._dat_number_of_steps.value = params['number_of_steps']
        self._dom_nodal_points.value = params['nodal_points']
        self._dom_elements.value = params['elements']
        self._dom_number_of_boundary_faces.value = params['boundaries']
        self._dom_types_of_elements.value = params['types_of_elements']
        self._dom_domain_integration_points.value = params[
            'domain_integration_points']
        self._ker_density.value = params['density']
        self._ker_viscosity.value = params['viscosity']
        self._ker_steps_to_save.value = params['steps']
        self._nsi_boundary_conditions.value = params['nsi_boundary_conditions']

    def ___caseReload_pressed(self):
        #
        # Reload the case
        #
        self.__addlog(f'Loading case {self._casename.value}')

        params = self._fileio.ExtractImportantParameters(self._casename.value)
        self.__addlog(f'Loaded parameters {params}')
        self.___fill_general_tab(params)

    def ___casePathScan_pressed(self):
        #
        # Scan path for the cases, fill the listbox of cases
        # Not fully implmented. Does not support more than one case per path yet
        #
        self._fileio.SetCasePath(self._casepath._value)
        self.__addlog(f'Scanning {self._casepath._value} for cases')

        cases = self._fileio.ListCases()
        self.__addlog(f'Found the following cases {cases}')

        self._casename.clear()
        if cases != []:
            for case in cases:
                self._casename.add_item(case)

            self._casename.current_index = 0
            self.___caseReload_pressed()

            dats = self._fileio.ListDats()
            self._DatPicker.clear()

            for dat in dats:
                self._DatPicker += [dat, '.']

    def __casePathChanged(self):
        self.__addlog(f'Case path changed to: {self._casepath._value}')
        self.___casePathScan_pressed()
        return True

    def __addlog(self, string):
        self._log.__add__(
            f'{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}: {string}'
        )

    def __INCLUDE_selection_changed(self):
        #
        # Activated when user clicks on an INCLUDED file
        #
        selection = self._IncludedFilePicker.get_currentrow_value()
        print(selection[0])
        data = self._fileio.ReadFullFile(selection[0])

        self._FileEditor.value = ''
        if data != []:
            self._FileEditor.value = ''.join(data)

    def __DAT_selection_changed(self):
        #
        # Activated when user clicks on a dat file
        #
        selection = self._DatPicker.get_currentrow_value()
        data = self._fileio.ReadFullFile(
            os.path.join(selection[1], selection[0]))

        includes = self._fileio.FindAllIncludedFiles(selection[0])
        self.__addlog(f'Found {includes} included files')

        self._IncludedFilePicker.clear()
        if includes != []:
            for include in includes:
                self._IncludedFilePicker += [include[0], include[1]]

        self._FileEditor.value = ''
        if data != []:
            self._FileEditor.value = ''.join(data)