示例#1
0
    def read_normal_txt(self, archive, node, icycle, variable_index, unit):
        open_archives = self.get_open_archives()
        # Nodo, ciclo, angulo, tiempo .. variables
        if archive not in open_archives.keys():
            A = loadtxt(archive)
            self.set_open_archives(archive, A)
        else:
            A = open_archives[archive]

        scale, operation = CONVERSIONS[unit]
        A_node_filtered = A[A[:, 0] == node]
        A_node_and_cycle_filtered = A_node_filtered if self.not_check_cycle \
        else A_node_filtered[A_node_filtered[:,1] == int(icycle)]
        data = take(A_node_and_cycle_filtered,
                    [self.normal_x_var, 4 + variable_index],
                    axis=1)
        for idata in data:
            idata[1] = operation(idata[1], scale)

        try:
            assert (len(data) != 0)
        except:
            handle_exception('Cannot find data in %s archive for %s cycle' %
                             (archive, icycle))
        return data
示例#2
0
    def prepare_plot(self, _plot_attributes=None):
        self.ui.plot_pushButton.setEnabled(False)
        QtWidgets.QApplication.processEvents()
        try:
            plot_attributes = _plot_attributes if _plot_attributes else self.get_plot_attributes(
            )
            datas = []
            legends = []
            if self.plot_type < 2:
                (datas, legends) = self.plot_angle_or_time(plot_attributes)
            elif self.plot_type == 2:
                (datas, legends) = self.plot_rpm(plot_attributes)
            elif self.plot_type == 3:
                (datas, legends) = self.plot_cycle(plot_attributes)

            n_plots = self.plot_function(datas, plot_attributes['title'], legends, self.xlabel, plot_attributes['variable'], \
                                         self.xunits, plot_attributes['units'], plot_attributes['figure_number'], self.plot_type)
            if plot_attributes['figure_number'] == -1:
                self.ui.figure_number.addItem('Figure ' + str(n_plots - 1))
            from exception_handling import CURRENT_EXCEPTION
            assert (not CURRENT_EXCEPTION)
        except:
            handle_exception('Error trying to plot the current selection')
        finally:
            self.ui.plot_pushButton.setEnabled(True)
        return
示例#3
0
 def plot_angle_or_time(self, plot_attributes):
     datas = []
     legends = []
     plot_attributes['node'] = int(self.ui.node.currentText())
     for irpm in plot_attributes['selected_rpms']:
         rpm_folder = os.path.join(self.current_run_dir, "RPM_%s" % irpm)
         for icycle in plot_attributes['selected_cycles']:
             (archive,
              extras) = self.archive_to_open(plot_attributes['variable'],
                                             rpm_folder,
                                             plot_attributes['component'])
             try:
                 if extras:
                     data = self.read_extras_txt(
                         archive, icycle, plot_attributes['variable'],
                         plot_attributes['component'],
                         plot_attributes['units'])
                 else:
                     data = self.read_normal_txt(
                         archive, plot_attributes['node'], icycle,
                         plot_attributes['variable_index'],
                         plot_attributes['units'])
                 datas.append(data)
                 legends.append(plot_attributes['label'] + "_RPM_" +
                                str(irpm) + "_Cycle_" + str(icycle))
                 from exception_handling import CURRENT_EXCEPTION
                 assert (not CURRENT_EXCEPTION)
             except:
                 handle_exception(
                     'Error opening archive %s. Cannot plot this selections'
                     % archive)
                 return
     return (datas, legends)
def error_service_routine(error_byte_list,type = 0) :

    if(type == 0) :

        error = {
        0 : 'input voltage error',
        1 : 'angle limit error',
        2 : 'overheating error',
        3 : 'range error',
        4 : 'checksum error',
        5 : 'overheating error',
        6 : 'instruction error',
        7 : 'invalid error byte',
        }
        
        for i in range(len(error_byte_list)) :
            if(error_byte_list[i]) :
                exception_handling.handle_exception(__name__,error.get(i))
                
    elif(type == 1) :
        error = {
        1 : 'communication error'
        }
        error_message += error.get(error_byte_list)
        print(error_message)
        log(error_message)
示例#5
0
文件: utils.py 项目: ProfFan/icesym
def dir_size(start, follow_links=True, start_depth=0):
    """
    Given a directory, returns its size in bytes
    """
    from exception_handling import handle_exception
    # Get a list of all names of files and subdirectories in directory start
    try:
        dir_list = os.listdir(start)
        from exception_handling import CURRENT_EXCEPTION
        assert (not CURRENT_EXCEPTION)
    except:
        handle_exception('Cannot list directory %s' % start)
        return

    total = 0
    for item in dir_list:
        # Get statistics on each item--file and subdirectory--of start
        path = os.path.join(start, item)
        try:
            stats = os.stat(path)
            from exception_handling import CURRENT_EXCEPTION
            assert (not CURRENT_EXCEPTION)
        except:
            handle_exception('Cannot list directory %s' % path)
            return
        # The size in bytes is in the seventh item of the stats tuple, so:
        total += stats[6]
        # recursive descent if warranted
        if os.path.isdir(path) and (follow_links or not os.path.islink(path)):
            bytes = dir_size(path, follow_links, start_depth + 1)
            total += bytes
    return total
示例#6
0
def do_some_work() : 
	global n

	while(n) : 
		i = input('enter something : ').split(' ')
		exception_handling.handle_exception(__name__,i[0],*tuple(i[1:]))

	print('n changed to 0')
示例#7
0
 def plot_rpm(self, plot_attributes):
     datas = []
     legends = []
     if plot_attributes['component'] == 'Globals':
         for icycle in plot_attributes['selected_cycles']:
             [data,legend] = self.ga.return_calculated_variable(plot_attributes['variable'],int(icycle),\
                                                                 plot_attributes['label'],plot_attributes['units'])
             datas.append(data)
             legends.append(legend)
         # flat the lists
         datas = [y for x in datas for y in x]
         legends = [y for x in legends for y in x]
     else:
         plot_attributes['node'] = int(self.ui.node.currentText())
         for icycle in plot_attributes['selected_cycles']:
             data_icycle = []
             for irpm in plot_attributes['selected_rpms']:
                 rpm_folder = os.path.join(self.current_run_dir,
                                           "RPM_%s" % irpm)
                 (archive, extras) = self.archive_to_open(
                     plot_attributes['variable'], rpm_folder,
                     plot_attributes['component'])
                 try:
                     if extras:
                         data = self.read_extras_txt(
                             archive, icycle, plot_attributes['variable'],
                             plot_attributes['component'],
                             plot_attributes['units'])
                     else:
                         data = self.read_normal_txt(
                             archive, plot_attributes['node'], icycle,
                             plot_attributes['variable_index'],
                             plot_attributes['units'])
                     res = self.trapz_data(data)
                     data = [irpm, res]
                     data_icycle.append(data)
                     from exception_handling import CURRENT_EXCEPTION
                     assert (not CURRENT_EXCEPTION)
                 except:
                     handle_exception(
                         'Error opening archive %s. Cannot plot this selections'
                         % archive)
                     return
             datas.append(data_icycle)
             legends.append(plot_attributes['label'] + "_Cycle_" +
                            str(icycle))
     return (datas, legends)
示例#8
0
 def plot_free(self, plot_attributes):
     datas = []
     legends = []
     plot_attributes['node'] = int(self.ui.node.currentText())
     for irpm in plot_attributes['selected_rpms']:
         rpm_folder = os.path.join(self.current_run_dir, "RPM_%s" % irpm)
         for icycle in plot_attributes['selected_cycles']:
             (archive_x, extras_x) = self.archive_to_open(
                 plot_attributes['variable'][0], rpm_folder,
                 plot_attributes['component'])
             (archive_y, extras_y) = self.archive_to_open(
                 plot_attributes['variable'][1], rpm_folder,
                 plot_attributes['component'])
             archives = [archive_x, archive_y]
             extras = [extras_x, extras_y]
             data_p = []
             for index, iarchive in enumerate(archives):
                 try:
                     if extras[index]:
                         data = self.read_extras_txt(
                             iarchive, icycle,
                             plot_attributes['variable'][index],
                             plot_attributes['component'],
                             plot_attributes['units'][index])
                     else:
                         data = self.read_normal_txt(
                             iarchive, plot_attributes['node'], icycle,
                             plot_attributes['variable_index'][index],
                             plot_attributes['units'][index])
                     data_p.append(data)
                     from exception_handling import CURRENT_EXCEPTION
                     assert (not CURRENT_EXCEPTION)
                 except:
                     handle_exception(
                         'Error opening archive %s. Cannot plot this selections.'
                         % iarchive)
                     return
             data_len = min(len(data_p[0]), len(
                 data_p[1]))  # sometimes arrays differs in length
             data_p = [[data_p[0][i], data_p[1][i]]
                       for i in range(data_len)]
             datas.append(data_p)
             legends.append(plot_attributes['label'] + "_RPM_" + str(irpm) +
                            "_Cycle_" + str(icycle))
     return (datas, legends)
示例#9
0
def init() :

    global system
    global dynamixel
    # global arduino

    system = platform.system()
    # [dynamixel,arduino] = serial_ports_setup.find_dynamixel_and_arduino()
    [dynamixel] = serial_ports_setup.find_dynamixel_and_arduino()
    print('dynamixel : ',dynamixel)
    # print('arduino : ',arduino)

    '''
    EXCEPTION CHECK --> cant connect
    '''
    try : 
        dynamixel = startup(dynamixel)
    except OSError : 
        exception_handling.handle_exception(__name__,'cant connect')
示例#10
0
    def read_normal_txt(self, archive, time, variable_index, unit):
        open_archives = self.get_open_archives()
        # Nodo, ciclo, angulo, tiempo .. variables
        if archive not in open_archives.keys():
            A = loadtxt(archive)
            self.set_open_archives(archive,A)
        else:
            A = open_archives[archive]

        scale, operation = CONVERSIONS[unit]
        times = A[:,3]
        new_time = min(times, key=lambda x:abs(x-time)) # el mas cercano en la lista

        A_time_filtered = A[A[:,3] == new_time]
        data = take(A_time_filtered, [0,4+variable_index], axis=1)
        for idata in data:
            idata[1] = operation(idata[1], scale)
        try:
            assert(len(data) != 0)
        except:
            handle_exception('Cannot find data in %s archive'%(archive))
        return (data,new_time)
示例#11
0
    def read_extras_txt(self, archive, icycle, variable, component, unit):
        offset = 4 if component == 'Cylinders' else 2
        variable_line = CYLEXTRA_LINES[variable][
            0] if component == 'Cylinders' else 1
        variable_col = CYLEXTRA_LINES[variable][
            1] if component == 'Cylinders' else TANKEXTRA_LINES[variable]
        scale, operation = CONVERSIONS[unit]

        open_archives = self.get_open_archives()
        if archive not in open_archives.keys():
            A = self.loadextratxt(archive, offset)
            self.set_open_archives(archive, A)
        else:
            A = open_archives[archive]

        # El extras de cilindro repite un patron cada cuatro lineas.
        # Primer linea: ciclo, angulo, tiempo
        # Segunda, tercera, cuarta linea: varias variables
        # El extras de tanque repite un patron cada 2 lineas.
        # Primer linea: ciclo, angulo, tiempo, ntubos
        # Segunda linea: Mass Flow Rate (ntubos), Entalphy Flow Rate (ntubos), luego dos mas

        if component == 'Tanks':
            ntubes = A[0][3]
            TANKEXTRA_LINES['Enthalpy Flow Rate'] = int(ntubes)
            variable_col = TANKEXTRA_LINES[variable]

        ndata = A.shape[0]
        data = [ operation(A[i+variable_line][variable_col], scale) \
                for i in range(0,ndata,offset) if (int(A[i][0])==int(icycle) or self.not_check_cycle)]

        try:
            assert (len(data) != 0)
        except:
            handle_exception('Cannot find data in %s archive for %s cycle' %
                             (archive, icycle))
        return data
示例#12
0
    def plot_defaults(self):
        """
        When a simulation finish, this routine reads a series of default lists with
        a particular configuration (in indexs):
        plot_list = [type_of_plot,component,node,[variable],[cycles],[rpms],units,title,figure,legend]
        Then it plot it (if possible)
        In rpms or cycle the negative values implies the last calculated values (-1 last, -2 last last, etc)
        """
        if not self.enable_ppw():
            show_message('Post Process not enabled.')
            return

        if self.default_postProcess_done:
            msg = "The default Post Process has already been carried out. Do you want to do it again?"
            reply = show_message(
                msg, 4, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.No:
                return

        advance_progressBar = 100. / len(DEFAULT_PLOTS)
        success = True
        for index, iplot in enumerate(DEFAULT_PLOTS):
            (tabWidget, plotWidget) = self.choose_widgets(iplot[0])
            plot_attributes = {}
            plot_attributes['component'] = iplot[1]
            plot_attributes['node'] = iplot[2]

            elements_to_plot = []
            if iplot[3] < 0:  # Negative case, all the elements
                for ielement in range(plotWidget.ui.element.count()):
                    elements_to_plot.append(ielement)
            else:  # Positive case, just one element
                elements_to_plot.append(iplot[3])

            plot_attributes['variable'] = iplot[4]
            plot_attributes['units'] = iplot[5]
            plot_attributes['selected_cycles'] = []
            for icycle in iplot[6]:
                plot_attributes['selected_cycles'].append(
                    icycle if icycle > 0 else self.run_attributes['ncycles'])
            plot_attributes['selected_rpms'] = []
            for irpm in iplot[7]:
                plot_attributes['selected_rpms'].append(
                    irpm if irpm > 0 else self.run_attributes['rpms'][irpm])
            if plot_attributes['selected_rpms'] == []:
                plot_attributes['selected_rpms'] = self.run_attributes['rpms']
            plot_attributes['label'] = iplot[8]
            if type(plot_attributes['variable']) != list:
                plot_attributes[
                    'variable_index'] = plotWidget.ui.variable.findText(
                        plot_attributes['variable'])
            else:
                plot_attributes['variable_index'] = []
                plot_attributes['variable_index'].append(
                    plotWidget.ui.x_variable.findText(
                        plot_attributes['variable'][0]))
                plot_attributes['variable_index'].append(
                    plotWidget.ui.y_variable.findText(
                        plot_attributes['variable'][1]))
            plot_attributes['title'] = iplot[9]
            plot_attributes['figure_number'] = -1 if iplot[10] < 0 else len(
                self.plots[iplot[0]]) - 1
            for ielement in elements_to_plot:
                try:
                    plotWidget.current_index_element = ielement
                    plotWidget.prepare_plot(plot_attributes)
                    plot_attributes['figure_number'] = len(
                        self.plots[iplot[0]]) - 1
                    plot_attributes['label'] = '%s_%s' % (iplot[8], ielement)
                    current_progress_value = self.ui_ppw.postPro_progressBar.value(
                    )
                    self.ui_ppw.postPro_progressBar.setValue(
                        current_progress_value + advance_progressBar)
                    QtWidgets.QApplication.processEvents()
                    from exception_handling import CURRENT_EXCEPTION
                    assert (not CURRENT_EXCEPTION)
                except:
                    success = False
                    handle_exception(
                        'Cannot plot the default configuration number %s' %
                        index)

        if success:
            show_message('Default Post Process sucessfully created!', 1)
            self.default_postProcess_done = True
        self.ui_ppw.postPro_progressBar.setValue(0)
        return
示例#13
0
    def plot(self, current_data, title, legend_texts, xlabel, ylabel, xunits,
             yunits, figure_number, plot_type):

        # no permitir dos leyendas iguales en un misma plot, puesto que luego para borrar
        # una curva pyqtgraph usa el nombre
        try:
            legends_to_check = legend_texts
            if figure_number >= 0:
                for item in self.legends[plot_type][figure_number].items:
                    legends_to_check.append(item[1].text)
            two_equals = check_two_equals(legend_texts)
            assert (not two_equals)
            from exception_handling import CURRENT_EXCEPTION
            assert (not CURRENT_EXCEPTION)
        except:
            handle_exception(
                'There are two legends with the same name. Please, select another legend name for this selections'
            )
            return

        pg.setConfigOptions(background='w')
        pg.setConfigOptions(foreground='k')
        added = False
        (tabWidget, plotWidget) = self.choose_widgets(plot_type)

        for index, idata in enumerate(current_data):

            xdata = []
            ydata = []

            for iidata in idata:
                xdata.append(iidata[0])
                ydata.append(iidata[1])

            if figure_number == -1 and not added:
                new_plot = pg.PlotWidget()
                set_plot(new_plot, xlabel, ylabel, title, xunits, yunits)
                new_plot.getPlotItem().getViewBox().menu.addAction(
                    "Delete Figure",
                    lambda: self.remove_figure(new_plot, plot_type))
                new_plot.getPlotItem().getViewBox(
                ).keyPressEvent = self.key_pressed_viewbox
                tab = QtWidgets.QWidget()
                tabWidget.addTab(tab,
                                 'Figure ' + str(len(self.plots[plot_type])))
                tab = tabWidget.widget(len(self.plots[plot_type]))
                self.plots[plot_type].append(new_plot)
                self.colour_plots[plot_type].append(self.colours[0])
                tab.setLayout(QtWidgets.QHBoxLayout())
                tab.layout().addWidget(new_plot)
                legend = pg.LegendItem(offset=(0, 1))
                legend.setParentItem(self.plots[plot_type][-1].getPlotItem())
                self.legends[plot_type].append(legend)
                figure_number = len(self.plots[plot_type]) - 1
                added = True

            it = self.plots[plot_type][figure_number].plot(xdata, ydata,\
                                 pen={'color': self.colour_plots[plot_type][figure_number], 'width': 1})
            it.curve.setClickable(True)
            it.curve.sigClicked.connect(self.curve_clicked)

            self.advance_colour(
                len(self.plots[plot_type]) - 1, self.colour_plots[plot_type])
            self.legends[plot_type][figure_number].addItem(
                it.curve, legend_texts[index])
            self.curve_attributes[it.curve] = [
                legend_texts[index], plot_type, figure_number
            ]
        return len(self.plots[plot_type])