示例#1
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     if not self.output_file == None:
         if not self.array_data == None:
             #write outcome to a file in memory
             memory_file = StringIO.StringIO()
             if self.__output_precision__ == None:
                 np.savetxt(memory_file, self.array_data,
                            delimiter=self.output_separator)
             else:
                 np.savetxt(memory_file, self.array_data,
                        fmt='%{0}.{1}f'.format(self.__output_precision__[0],
                                             self.__output_precision__[1]),
                        delimiter=self.output_separator)
             contents = memory_file.getvalue()
             _file = open(self.output_file, 'w')
             if self.add_headers:
                 _file.write(self.__format_headers__(
                                 contents[:contents.find('\n')],
                                 nvl(self.headers_aliases, self.headers)))
             _file.write(contents)
             _file.close()
             self.saved = True
             memory_file.close()
             memory_file = None
             if self.__print_output_file__:
                 self.info_message = nvl(self.__message__,
                                     'Data saved into the file: ') + \
                                     self.output_file
         else:
             self.info_message = 'No data saved !!!'
     self.array_data = None
     gc.collect()
示例#2
0
    def __init__(self, parent, **params):
        super(DockWidgetWidget, self).__init__(
                            nvl(params.get('title', None), ''), parent)
        if params.get('not_add_widget_to_parent_layout', None) == None:
            params['not_add_widget_to_parent_layout'] = True
        prepareWidget(parent=parent, widget=self, **params)
        self.params = Params(**params)
        if self.params.use_scroll_area == None:
            self.params.use_scroll_area = True
        if not self.params.dock_widget_location_changed == None:
            self.connect(self, DOCK_WIDGET_LOCATION_CHANGED_SIGNAL,
                         self.__dock_widget_location_changed__)
        self.setObjectName(self.__class__.__name__)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea |
                             Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)
        layout = nvl(self.params.layout, QVBoxLayout())
        if hasattr(layout, 'setMargin'):
            layout.setMargin(0)
        self.scrollArea = None
        if self.params.use_scroll_area:
            self.scrollArea = QScrollArea(self)

        self.dockComposite = CompositeWidget(self, layout=layout,
                                        not_add_widget_to_parent_layout=True)

        if self.params.use_scroll_area:
            self.scrollArea.setWidget(self.dockComposite)
            self.scrollArea.setWidgetResizable(True)
            self.setWidget(self.scrollArea)
        else:
            self.setWidget(self.dockComposite)
示例#3
0
    def __init__(self, parent, **params):
        super(DockWidgetWidget,
              self).__init__(nvl(params.get('title', None), ''), parent)
        if params.get('not_add_widget_to_parent_layout', None) == None:
            params['not_add_widget_to_parent_layout'] = True
        prepareWidget(parent=parent, widget=self, **params)
        self.params = Params(**params)
        if self.params.use_scroll_area == None:
            self.params.use_scroll_area = True
        if not self.params.dock_widget_location_changed == None:
            self.connect(self, DOCK_WIDGET_LOCATION_CHANGED_SIGNAL,
                         self.__dock_widget_location_changed__)
        self.setObjectName(self.__class__.__name__)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea
                             | Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)
        layout = nvl(self.params.layout, QVBoxLayout())
        if hasattr(layout, 'setMargin'):
            layout.setMargin(0)
        self.scrollArea = None
        if self.params.use_scroll_area:
            self.scrollArea = QScrollArea(self)

        self.dockComposite = CompositeWidget(
            self, layout=layout, not_add_widget_to_parent_layout=True)

        if self.params.use_scroll_area:
            self.scrollArea.setWidget(self.dockComposite)
            self.scrollArea.setWidgetResizable(True)
            self.setWidget(self.scrollArea)
        else:
            self.setWidget(self.dockComposite)
示例#4
0
 def __init__(self, default, **params):
     params = Params(**params)
     self.active = nvl(params.active, default.active)
     self.button_groups = nvl(params.button_groups, default.button_groups)
     self.handler_name = nvl(params.handler_name, default.handler_name)
     self.icon_id = nvl(params.icon_id, default.icon_id)
     self.title = nvl(params.title, default.title)
     self.handler_callable_name = default.handler_callable_name
示例#5
0
 def __init__(self, default, **params):
     params = Params(**params)
     self.active = nvl(params.active, default.active)
     self.button_groups = nvl(params.button_groups, default.button_groups)
     self.handler_name = nvl(params.handler_name, default.handler_name)
     self.icon_id = nvl(params.icon_id, default.icon_id)
     self.title = nvl(params.title, default.title)
     self.handler_callable_name = default.handler_callable_name
 def __init__(self, **params):
     self.params = Params(**params)
     self.__indexes__ = __Entities__(nvl(self.params.signal_index, -1),
                                     nvl(self.params.annotation_index, -1),
                                     nvl(self.params.time_index, -1))
     self.__headers__ = None
     self.__data_vector__ = None
     if not is_positive(self.params.time_index):
         self.__data_source__ = NumericalFileDataSource(**params)
     else:
         #if there is separate column of time all data are loaded
         #in string format, getDataVector method do further processing
         #and change into numerical values
         self.__data_source__ = TextFileDataSource(**params)
 def __init__(self, **params):
     self.params = Params(**params)
     self.__indexes__ = __Entities__(nvl(self.params.signal_index, -1),
                                    nvl(self.params.annotation_index, -1),
                                    nvl(self.params.time_index, -1))
     self.__headers__ = None
     self.__data_vector__ = None
     if not is_positive(self.params.time_index):
         self.__data_source__ = NumericalFileDataSource(**params)
     else:
         #if there is separate column of time all data are loaded
         #in string format, getDataVector method do further processing
         #and change into numerical values
         self.__data_source__ = TextFileDataSource(**params)
    def check_data_indexes(self, _filename, disp):
        """
        method used by client code explicitly, because of dynamic nature
        of placement of data columns which have to check at runtime
        to manage a situation when columns are specified by names and
        for different files they are placed in different columns
        """
        message = None
        if not nvl(self.signal_label, self.annotation_label,
                   self.time_label) == None:
            headers_count = nvl(self.headers_count, 1)

            file_headers = DataFileHeader(_filename,
                                          _separator=self.separator,
                                          number_of_lines=headers_count)
            #get header's lines
            headers = file_headers.getHeadersLines(headers_count)
            if self.signal_label:
                self.signal_index = get_index_of_string(
                    self.signal_label, headers, _separator=self.separator)
            if self.annotation_label:
                self.annotation_index = get_index_of_string(
                    self.annotation_label, headers, _separator=self.separator)
                if self.annotation_index == -1:
                    message = ('There is no annotation index for label %s !' %
                               (self.annotation_label))
            if self.time_label:
                self.time_index = get_index_of_string(
                    self.time_label, headers, _separator=self.separator)
                if self.time_index == -1:
                    message = ('There is no time index for label %s !' %
                               (self.time_label))
        if self.signal_index == -1:
            if self.time_label:
                message = ('There is no signal index for label %s !' %
                           (self.signal_label))
            else:
                message = 'The signal index has to be set !'

        if is_positive(self.time_index) and self.time_format == None:
            message = 'For time column a time format parameter is required !'

        if not is_positive(self.time_index) and not is_empty(self.time_format):
            message = 'Time format requires time index column selection !'

        if message and disp:
            print('File: %s \n %s \n' % (_filename, message))
            return False
        else:
            return True
示例#9
0
def AreYouSureWindow(parent=None, **params):
    default_button = nvl(params.get('default_button', None), QMessageBox.Yes)
    ret = QuestionWindow([QMessageBox.Yes, QMessageBox.No],
                         parent,
                         default_button=default_button,
                         message='Are you sure ?', **params)
    return ret == QMessageBox.Yes
示例#10
0
 def preparePlot(self, _canvas):
     _canvas.title_manager.setMainTitle(
                                 HistogramTachogramPlotEngine.DEFAULT_TITLE)
     header = nvl(_canvas.data_accessor.data_vector.signal_header, '')
     unit = _canvas.data_accessor.data_vector.signal_unit
     self.x_label = "{0} [{1}]".format(header, unit.label if unit else '')
     self.y_label = 'Amount'
示例#11
0
    def __init__(self,
                 statistics_names=None,
                 statistics_handlers=None,
                 _use_identity_line=True,
                 use_buffer=True,
                 statistics_classes=None):
        '''
        Constructor
        '''
        self.__statistics_classes__ = statistics_classes \
                                        if statistics_classes else []
        self.__statistics_objects__ = []
        self.__statistics_handlers__ = statistics_handlers
        self.__use_identity_line__ = _use_identity_line
        self.__use_buffer__ = nvl(use_buffer, True)
        global USE_IDENTITY_LINE
        USE_IDENTITY_LINE = self.__use_identity_line__

        #if statistics_names is a string object which included
        #names of statistics separater by comma we change it into list of names
        if not statistics_names == None:
            if isinstance(statistics_names, str):
                statistics_names = expand_to_real_statistics_names(
                    statistics_names)

            for type_or_name in statistics_names:
                #if type_or_name is a string
                if isinstance(type_or_name, str):
                    type_or_name = create_class_object_with_suffix(
                        'hra_math.statistics.statistics', type_or_name,
                        'Statistic')
                #if type_or_name is a class type
                if isinstance(type_or_name, type):
                    self.__statistics_classes__.append(type_or_name)
 def __init__(self, parent, data_vector_accessor_list, label_text=None,
             max_value=None, **params):
     self.parent = parent
     self.label_text = nvl(label_text, "Poincare plot generation")
     self.max_value = max_value
     self.__data_vector_accessor_list__ = data_vector_accessor_list
     self.params = Params(**params)
示例#13
0
def create_toolbar_button(parent, toolbar, button_type, **params):
    params = Params(**params)
    params.handler = getattr(params, button_type.handler_callable_name, None)
    if params.handler == None and button_type.handler_name:
        if hasattr(parent, button_type.handler_name):
            params.handler = getattr(parent, button_type.handler_name)
        elif hasattr(parent.parentWidget(), button_type.handler_name):
            params.handler = getattr(parent.parentWidget(),
                                     button_type.handler_name)
        elif hasattr(params, button_type.handler_name):
            params.handler = getattr(params, button_type.handler_name)
    title = nvl(params.button_title, button_type.title)
    handler = params.handler

    #give ability to call addition toolbar handler after proper button handler
    if button_type.handler_callable_name and \
        hasattr(button_type, 'after_toolbar_handler'):
        class ActionToolbarHandler():
            def __init__(self, button_handler, toolbar, after_toolbar_handler):
                self.__button_handler__ = button_handler
                self.__toolbar__ = toolbar
                self.__after_toolbar_handler__ = after_toolbar_handler

            def __call__(self):
                self.__button_handler__()
                self.__after_toolbar_handler__(toolbar)

        #replace button handler with toolbar button handler
        handler = ActionToolbarHandler(handler, toolbar,
                                getattr(button_type, 'after_toolbar_handler'))

    actionSpec = ActionSpec(iconId=button_type.icon_id, handler=handler,
                                 title=title)
    toolbar.addWidget(ToolButtonCommon(toolbar,
                        action=create_action(toolbar, actionSpec)))
    def __init__(self, pp_specs_manager):
        self.manager = pp_specs_manager
        self.pp_specs = self.manager.getMiniPoincarePlotSpecs()
        if len(self.pp_specs) == 0:
            return
        self.gc = None
        self.p0 = self.pp_specs[0]

        #set up specific values for fonts sizes based on products of a movie
        #height and arbitrary constants to give looking good picture
        if self.manager.movie_axis_font == None:
            self.axis_font = 'modern ' + str(nvl_and_positive(
                self.manager.movie_axis_font_size, self.manager.movie_height / 38))
        else:
            self.axis_font = self.manager.movie_axis_font

        if self.manager.movie_title_font == None:
            self.title_font = 'modern ' + str(nvl_and_positive(
                self.manager.movie_title_font_size, self.manager.movie_height / 30))
        else:
            self.title_font = self.manager.movie_title_font

        self.time_label_font = 'modern ' + str(nvl_and_positive(
            self.manager.movie_time_label_font_size, self.manager.movie_height / 35))

        self.tick_font = nvl(self.manager.movie_tick_font, None)
        self.frame_pad = nvl_and_positive(self.manager.movie_frame_pad, 50)
示例#15
0
 def __data_filenames__(self):
     """
     returns all data files according to data_dir and extension
     """
     if self.data_dir:
         path = self.data_dir + nvl(self.extension, '*.*')
         return [self.__shuffle_file__(_file) for _file in glob.glob(path)]
示例#16
0
def generate_movie(movie_name,
                   movie_dir,
                   movie_width,
                   movie_height,
                   movie_fps,
                   movie_frames='*.png',
                   movie_clean_frames=True):
    """
    function used by client code to generate a movie according to
    specified parameters; at this time multiprocessing
    version is used only for Linux OS
    """
    movie_clean_frames = nvl(movie_clean_frames, True)
    if _platform.find("linux") >= 0:
        return __generate_multiprocessing_movie__(movie_name, movie_dir,
                                                  movie_width, movie_height,
                                                  movie_fps, movie_frames,
                                                  movie_clean_frames)
    elif _platform == "darwin":
        # OS X
        raise Exception('Not implemented yet !')
    else:
        # windows family
        movie_specification = MovieSpecification(movie_name, movie_dir,
                                                 movie_width, movie_height,
                                                 movie_fps, None, None,
                                                 movie_frames)
        return __generate_movie__(movie_specification)
示例#17
0
 def __init__(self, parent, **params):
     params = Params(**params)
     super(ListWidgetItemWidget, self).__init__(
                                         nvl(params.text, ''), parent)
     #store in data buffer of list item for later use
     if params.data:
         self.setData(Qt.UserRole, QVariant(params.data))
示例#18
0
 def __init__(self, parent, **params):
     params = Params(**params)
     super(ListWidgetItemWidget, self).__init__(nvl(params.text, ''),
                                                parent)
     #store in data buffer of list item for later use
     if params.data:
         self.setData(Qt.UserRole, QVariant(params.data))
示例#19
0
    def __init__(self, statistics_names=None, statistics_handlers=None,
                 _use_identity_line=True, use_buffer=True,
                 statistics_classes=None):
        '''
        Constructor
        '''
        self.__statistics_classes__ = statistics_classes \
                                        if statistics_classes else []
        self.__statistics_objects__ = []
        self.__statistics_handlers__ = statistics_handlers
        self.__use_identity_line__ = _use_identity_line
        self.__use_buffer__ = nvl(use_buffer, True)
        global USE_IDENTITY_LINE
        USE_IDENTITY_LINE = self.__use_identity_line__

        #if statistics_names is a string object which included
        #names of statistics separater by comma we change it into list of names
        if not statistics_names == None:
            if isinstance(statistics_names, str):
                statistics_names = expand_to_real_statistics_names(
                                                            statistics_names)

            for type_or_name in statistics_names:
                #if type_or_name is a string
                if isinstance(type_or_name, str):
                    type_or_name = create_class_object_with_suffix(
                                            'hra_math.statistics.statistics',
                                            type_or_name, 'Statistic')
                #if type_or_name is a class type
                if isinstance(type_or_name, type):
                    self.__statistics_classes__.append(type_or_name)
示例#20
0
 def __init__(self, parent, **params):
     self.params = Params(**params)
     self.params.label_text = nvl(self.params.label_text, 'Processing...')
     self.params.cancel_text = nvl(self.params.cancel_text, 'Abort')
     self.min_value = nvl(self.params.min_value, 0)
     self.max_value = nvl(self.params.max_value, 10000)
     self.counter = self.min_value
     super(ProgressDialogWidget, self).__init__(self.params.label_text,
                                                self.params.cancel_text,
                                                self.min_value,
                                                self.max_value,
                                                parent)
     self.setWindowTitle(nvl(self.params.title, 'Progress'))
     if params.get('not_add_widget_to_parent_layout', None) == None:
         params['not_add_widget_to_parent_layout'] = True
     prepareWidget(parent=parent, widget=self, **params)
示例#21
0
 def __data_filenames__(self):
     """
     returns all data files according to data_dir and extension
     """
     if self.data_dir:
         path = self.data_dir + nvl(self.extension, '*.*')
         return [self.__shuffle_file__(_file) for _file in glob.glob(path)]
    def prepareParameters(self):
        """
        method prepares poincare plot parameters
        """
        if self.stepper:
            self.stepper_size = extract_number(self.stepper, convert=int)
            self.stepper_unit = extract_alphabetic(self.stepper,
                                                   convert=str.lower)
        self.movie_dir = nvl(self.movie_dir, self.output_dir, '')

        if isinstance(self.excluded_annotations, str):
            self.excluded_annotations = get_as_list(self.excluded_annotations)

        if self.filters_names is not None:
            map(self.addFilter, get_as_list(self.filters_names))

        if self.output_dir:
            # remove leading and trailing whitespaces
            self.output_dir = self.output_dir.strip()

        if self.window_size:
            self.window_size_unit = extract_alphabetic(self.window_size,
                                                       convert=str.lower)
            self.window_size_value = extract_number(self.window_size,
                                                    convert=int)

        self.movie_multiprocessing_factor = nvl(
            self.movie_multiprocessing_factor,
            3 if multiprocessing.cpu_count() > 1 else 0)

        if not self.data_file == None:
            self.group_data_filename = None

        if isinstance(self.output_precision, str):
            self.output_precision = get_as_tuple(self.output_precision,
                                                 convert=int)
        elif self.output_precision == None:
            self.output_precision = DEFAULT_OUTPUT_PRECISION

        if self.add_headers == None:
            self.add_headers = True

        if len(self.statistics_classes) > 0:
            self.statistics_names = [
                s.__name__.replace("Statistic", "")
                for s in self.statistics_classes
            ]
示例#23
0
 def time_signal(self):
     """
     helper method which returns a time array if it is not None or a signal
     array otherwise; the purpose of the method is return not empty
     time array in the case when a signal array is not expressed in time
     units
     """
     return nvl(self.time, self.signal)
示例#24
0
def AreYouSureWindow(parent=None, **params):
    default_button = nvl(params.get('default_button', None), QMessageBox.Yes)
    ret = QuestionWindow([QMessageBox.Yes, QMessageBox.No],
                         parent,
                         default_button=default_button,
                         message='Are you sure ?',
                         **params)
    return ret == QMessageBox.Yes
示例#25
0
 def time_signal(self):
     """
     helper method which returns a time array if it is not None or a signal
     array otherwise; the purpose of the method is return not empty
     time array in the case when a signal array is not expressed in time
     units
     """
     return nvl(self.time, self.signal)
 def __init__(self, parent, data_vector_accessor_list, movie_parameters, label_text=None, max_value=None, **params):
     PoincarePlotGeneratorProgressBar.__init__(
         self,
         parent,
         data_vector_accessor_list,
         label_text=nvl(label_text, "Poincare plot movie generator"),
         max_value=max_value,
         **params
     )
     self.movie_parameters = movie_parameters
     self.data_vector_accessor_list = data_vector_accessor_list
示例#27
0
    def __init__(self, parent, **params):
        get_or_put(params, 'i18n_def', 'Separator')
        self.params = Params(**params)
        self.separatorsGroupBox = GroupBoxWidget(parent,
                            i18n="separator.widget.group.title",
                            i18n_def=nvl(self.params.i18n_def, "Separator"),
                            layout=QVBoxLayout())

        self.predefinedSeparatorsComposite = CompositeWidget(
                                                    self.separatorsGroupBox,
                                                    layout=QHBoxLayout())
        self.predefinedSeparatorsButtonsGroup = ButtonGroupWidget(
                                            self.predefinedSeparatorsComposite)

        self.predefinedSeparatorsSpecs = Separator.getSeparatorsSpec(
                                                    separator_label_handler)
        for separatorSpec in self.predefinedSeparatorsSpecs:
            label = separatorSpec.label
            if not label == Separator.CUSTOM.label:  # @UndefinedVariable
                predefinedSeparatorCheckBox = CheckBoxWidget(
                                            self.predefinedSeparatorsComposite)
                #attach artificially a separatorSpec object used later in
                #def setSeparator(self, _separator) method
                predefinedSeparatorCheckBox.separator_spec = separatorSpec
                predefinedSeparatorCheckBox.setText(label)
                predefinedSeparatorCheckBox.sep_spec = separatorSpec
                if self.params.default_separator and \
                    separatorSpec.id_ == self.params.default_separator.id_:
                    predefinedSeparatorCheckBox.setChecked(True)
                self.predefinedSeparatorsButtonsGroup.addButton(
                                                predefinedSeparatorCheckBox)

        self.separatorsGroupBox.connect(self.predefinedSeparatorsButtonsGroup,
                                    SIGNAL("buttonClicked(QAbstractButton *)"),
                                    self.predefinedSeparatorButtonClicked)

        if not self.params.no_custom_separator == True:
            self.customSeparatorCheckBox = CheckBoxWidget(
                                        self.predefinedSeparatorsComposite,
                                        i18n="separator.custom.checkbox",
                                        i18n_def="Custom")
            self.customSeparatorCheckBox.sep_spec = Separator.CUSTOM
            self.separatorsGroupBox.connect(self.customSeparatorCheckBox,
                                        SIGNAL("clicked()"),
                                        self.customSeparatorButtonClicked)

            self.customSeparatorEdit = LineEditWidget(
                        self.predefinedSeparatorsComposite,
                        maxLength=15,
                        width=get_width_of_n_letters(14),
                        text_changed_handler=self.customSeparatorButtonClicked,
                        enabled=False)

        self.setEnabled(self.params.enabled)
示例#28
0
 def __init__(self,
              parent,
              data_vector_accessor_list,
              label_text=None,
              max_value=None,
              **params):
     self.parent = parent
     self.label_text = nvl(label_text, "Poincare plot generation")
     self.max_value = max_value
     self.__data_vector_accessor_list__ = data_vector_accessor_list
     self.params = Params(**params)
    def check_data_indexes(self, _filename, disp):
        """
        method used by client code explicitly, because of dynamic nature
        of placement of data columns which have to check at runtime
        to manage a situation when columns are specified by names and
        for different files they are placed in different columns
        """
        message = None
        if not nvl(self.signal_label, self.annotation_label, self.time_label) == None:
            headers_count = nvl(self.headers_count, 1)

            file_headers = DataFileHeader(_filename, _separator=self.separator, number_of_lines=headers_count)
            # get header's lines
            headers = file_headers.getHeadersLines(headers_count)
            if self.signal_label:
                self.signal_index = get_index_of_string(self.signal_label, headers, _separator=self.separator)
            if self.annotation_label:
                self.annotation_index = get_index_of_string(self.annotation_label, headers, _separator=self.separator)
                if self.annotation_index == -1:
                    message = "There is no annotation index for label %s !" % (self.annotation_label)
            if self.time_label:
                self.time_index = get_index_of_string(self.time_label, headers, _separator=self.separator)
                if self.time_index == -1:
                    message = "There is no time index for label %s !" % (self.time_label)
        if self.signal_index == -1:
            if self.time_label:
                message = "There is no signal index for label %s !" % (self.signal_label)
            else:
                message = "The signal index has to be set !"

        if is_positive(self.time_index) and self.time_format == None:
            message = "For time column a time format parameter is required !"

        if not is_positive(self.time_index) and not is_empty(self.time_format):
            message = "Time format requires time index column selection !"

        if message and disp:
            print("File: %s \n %s \n" % (_filename, message))
            return False
        else:
            return True
    def prepareParameters(self):
        """
        method prepares poincare plot parameters
        """
        if self.stepper:
            self.stepper_size = extract_number(self.stepper, convert=int)
            self.stepper_unit = extract_alphabetic(self.stepper, convert=str.lower)
        self.movie_dir = nvl(self.movie_dir, self.output_dir, "")

        if isinstance(self.excluded_annotations, str):
            self.excluded_annotations = get_as_list(self.excluded_annotations)

        if self.filters_names is not None:
            map(self.addFilter, get_as_list(self.filters_names))

        if self.output_dir:
            # remove leading and trailing whitespaces
            self.output_dir = self.output_dir.strip()

        if self.window_size:
            self.window_size_unit = extract_alphabetic(self.window_size, convert=str.lower)
            self.window_size_value = extract_number(self.window_size, convert=int)

        self.movie_multiprocessing_factor = nvl(
            self.movie_multiprocessing_factor, 3 if multiprocessing.cpu_count() > 1 else 0
        )

        if not self.data_file == None:
            self.group_data_filename = None

        if isinstance(self.output_precision, str):
            self.output_precision = get_as_tuple(self.output_precision, convert=int)
        elif self.output_precision == None:
            self.output_precision = DEFAULT_OUTPUT_PRECISION

        if self.add_headers == None:
            self.add_headers = True

        if len(self.statistics_classes) > 0:
            self.statistics_names = [s.__name__.replace("Statistic", "") for s in self.statistics_classes]
    def __createFileHeadersPreview__(self, _separator=None):

        dataFileHeader = self.__getDataFileHeader__(_separator)
        if dataFileHeader == None:
            return

        self.__createHeadersTablePreview__()

        colCount = dataFileHeader.getHeadersCount()
        model = self.__createHeadersTablePreviewModel__(colCount)

        self.__widgetsHorizontalHeader__ = WidgetsHorizontalHeader(
                                                    self.headersTablePreview)

        # create header line
        pathFile = self.filesTableView.getSelectedPathAndFilename()
        self.__headerWidgets__ = []
        for headerLine in dataFileHeader.getHeadersLines(1):
            for num, header in enumerate(headerLine):
                widget = HeaderWidget(self.__widgetsHorizontalHeader__,
                                      header,
                                      [self.__signal_header_element__,
                                       self.__annotation_header_element__,
                                       self.__time_header_element__])
                self.__headerWidgets__.append(widget)
                # some value of global indicator have to be not None
                if not nvl(*self.__globalIndex__) == None:
                    widget.enabledAll(False)
                    if self.__globalIndex__.signal == num:  # signal index
                        widget.check(self.__signal_header_element__.name)
                    elif self.__globalIndex__.annotation == num:  # annotation index @IgnorePep8
                        widget.check(self.__annotation_header_element__.name)
                    if self.__globalIndex__.time == num:  # time index
                        widget.check(self.__time_header_element__.name)
                elif self.__signalColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__signal_header_element__.name)
                elif self.__annotationColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__annotation_header_element__.name)
                elif self.__timeColumnIndexes__.get(pathFile) == num:
                    widget.check(self.__time_header_element__.name)
        self.__widgetsHorizontalHeader__.setWidgets(self.__headerWidgets__)

        # create data lines
        for rowData in dataFileHeader.getDataLines():
            modelData = list()
            for idx in range(colCount):
                modelData.append(QStandardItem(rowData[idx]
                                        if colCount <= len(rowData) else ""))
            model.appendRow(modelData)

        self.fileHeaderPreviewGroup.setEnabled(True)
        self.fileHeaderPreviewGroup.show()
示例#32
0
    def __init__(self, **params):
        # params: _file, pathname, filename, separator
        self.params = Params(**params)
        self.__file__ = None
        if not self.params._file == None:
            self.__file__ = self.params._file
        elif not self.params.pathname == None and not self.params.filename == None:
            self.__file__ = os.path.join(self.params.pathname, self.params.filename)
        self.__file_headers__ = None

        # number of lines of headers explicitly specified
        self.__headers_count__ = nvl(self.params.headers_count, 0)

        # contents of a file
        self.__file_data__ = None
示例#33
0
 def __init__(self,
              parent,
              data_vector_accessor_list,
              movie_parameters,
              label_text=None,
              max_value=None,
              **params):
     PoincarePlotGeneratorProgressBar.__init__(
         self,
         parent,
         data_vector_accessor_list,
         label_text=nvl(label_text, "Poincare plot movie generator"),
         max_value=max_value,
         **params)
     self.movie_parameters = movie_parameters
     self.data_vector_accessor_list = data_vector_accessor_list
示例#34
0
def create_many_plots(_source_file, headers, separator, window_size=None):
    """
    draws many plots base on data from _source_file and collection of headers
    grouped by a semicolon, elements in a group are separated by a comma
    """
    colors = ['red', 'green', 'blue', 'yellow', 'black', 'cyan', 'magenta']

    first_line = get_first_lines(_source_file)
    if len(first_line) == 0:
        return
    file_headers = [
        header.strip().lower() for header in first_line[0].split(separator)
    ]
    for sub_headers in get_as_list(headers, separator=';'):
        labels = [label.strip().lower() for label in get_as_list(sub_headers)]
        try:
            cols = tuple([file_headers.index(label) for label in labels])
        except ValueError:
            continue
        if separator == None:
            values = np.loadtxt(_source_file,
                                skiprows=1,
                                unpack=True,
                                usecols=cols)
        else:
            values = np.loadtxt(_source_file,
                                skiprows=1,
                                unpack=True,
                                usecols=cols,
                                delimiter=separator)

        plt.gca().set_color_cycle(colors[:len(labels)])

        filename = get_filename(_source_file)
        title = "%s %s" % (filename, nvl(window_size + " window size", ''))
        plt.title(title)

        for value in values:
            plt.plot(value)

        plt.legend(labels, loc='upper right')
        plt.axes().set_xlabel('Time')

        plot_filename = "%s_%s.png" % (filename, '_'.join(labels))
        _file = as_path(fs.dirname(_source_file), plot_filename)
        plt.savefig(_file)
        plt.cla()
示例#35
0
    def __init__(self, **params):
        #params: _file, pathname, filename, separator
        self.params = Params(**params)
        self.__file__ = None
        if not self.params._file == None:
            self.__file__ = self.params._file
        elif not self.params.pathname == None and \
            not self.params.filename == None:
            self.__file__ = os.path.join(self.params.pathname,
                                         self.params.filename)
        self.__file_headers__ = None

        #number of lines of headers explicitly specified
        self.__headers_count__ = nvl(self.params.headers_count, 0)

        #contents of a file
        self.__file_data__ = None
示例#36
0
def create_many_plots(_source_file, headers, separator, window_size=None):
    """
    draws many plots base on data from _source_file and collection of headers
    grouped by a semicolon, elements in a group are separated by a comma
    """
    colors = ['red', 'green', 'blue', 'yellow', 'black', 'cyan', 'magenta']

    first_line = get_first_lines(_source_file)
    if len(first_line) == 0:
        return
    file_headers = [header.strip().lower()
            for header in first_line[0].split(separator)]
    for sub_headers in get_as_list(headers, separator=';'):
        labels = [label.strip().lower()
                  for label in get_as_list(sub_headers)]
        try:
            cols = tuple([file_headers.index(label) for label in labels])
        except ValueError:
            continue
        if separator == None:
            values = np.loadtxt(_source_file, skiprows=1, unpack=True,
                                usecols=cols)
        else:
            values = np.loadtxt(_source_file, skiprows=1, unpack=True,
                                usecols=cols, delimiter=separator)

        plt.gca().set_color_cycle(colors[:len(labels)])

        filename = get_filename(_source_file)
        title = "%s %s" % (filename, nvl(window_size + " window size", ''))
        plt.title(title)

        for value in values:
            plt.plot(value)

        plt.legend(labels, loc='upper right')
        plt.axes().set_xlabel('Time')

        plot_filename = "%s_%s.png" % (filename, '_'.join(labels))
        _file = as_path(fs.dirname(_source_file), plot_filename)
        plt.savefig(_file)
        plt.cla()
示例#37
0
def create_toolbar_button(parent, toolbar, button_type, **params):
    params = Params(**params)
    params.handler = getattr(params, button_type.handler_callable_name, None)
    if params.handler == None and button_type.handler_name:
        if hasattr(parent, button_type.handler_name):
            params.handler = getattr(parent, button_type.handler_name)
        elif hasattr(parent.parentWidget(), button_type.handler_name):
            params.handler = getattr(parent.parentWidget(),
                                     button_type.handler_name)
        elif hasattr(params, button_type.handler_name):
            params.handler = getattr(params, button_type.handler_name)
    title = nvl(params.button_title, button_type.title)
    handler = params.handler

    #give ability to call addition toolbar handler after proper button handler
    if button_type.handler_callable_name and \
        hasattr(button_type, 'after_toolbar_handler'):

        class ActionToolbarHandler():
            def __init__(self, button_handler, toolbar, after_toolbar_handler):
                self.__button_handler__ = button_handler
                self.__toolbar__ = toolbar
                self.__after_toolbar_handler__ = after_toolbar_handler

            def __call__(self):
                self.__button_handler__()
                self.__after_toolbar_handler__(toolbar)

        #replace button handler with toolbar button handler
        handler = ActionToolbarHandler(
            handler, toolbar, getattr(button_type, 'after_toolbar_handler'))

    actionSpec = ActionSpec(iconId=button_type.icon_id,
                            handler=handler,
                            title=title)
    toolbar.addWidget(
        ToolButtonCommon(toolbar, action=create_action(toolbar, actionSpec)))
示例#38
0
def generate_movie(movie_name, movie_dir,
                   movie_width, movie_height,
                   movie_fps, movie_frames='*.png',
                   movie_clean_frames=True):
    """
    function used by client code to generate a movie according to
    specified parameters; at this time multiprocessing
    version is used only for Linux OS
    """
    movie_clean_frames = nvl(movie_clean_frames, True)
    if _platform.find("linux") >= 0:
        return __generate_multiprocessing_movie__(movie_name, movie_dir,
                                              movie_width, movie_height,
                                              movie_fps, movie_frames,
                                              movie_clean_frames)
    elif _platform == "darwin":
        # OS X
        raise Exception('Not implemented yet !')
    else:
        # windows family
        movie_specification = MovieSpecification(movie_name, movie_dir,
                            movie_width, movie_height, movie_fps, None,
                            None, movie_frames)
        return __generate_movie__(movie_specification)
示例#39
0
    def start(self):
        """
        method initiate show up of poincare progress bar
        """
        self.__interrupted__ = False

        #parameter formatted_summary_statistics is used to store
        #calculated summary statistics
        if not self.params.formatted_summary_statistics == None:
            self.params.formatted_summary_statistics[:] = []

        outcomes_exist_info = []
        progressManager = ProgressDialogManager(
            self.parent, count=len(self.__data_vector_accessor_list__))
        for data_vector_accessor in self.__data_vector_accessor_list__:
            parameters = \
                data_vector_accessor.parameters_container.parameters.get(PoincarePlotParameters.NAME) #  alias @IgnorePep8
            parameters.prepareParameters()
            pp_generator = PoincarePlotGenerator(
                output_file_listener=self.params.output_file_listener,
                parameters=parameters)
            if self.params.save_csv == True:
                (ok,
                 _) = pp_generator.precheck(data_vector_accessor.source_name)
                if ok == False:
                    if pp_generator.outcome_exists:
                        outcomes_exist_info.append(
                            data_vector_accessor.source_name)
                    continue

            message = parameters.validateParameters(self.params.check_level)
            if message:
                ErrorWindow(message=message)
                return
            count = pp_generator.segment_count(
                data_vector_accessor.data_vector)  # @IgnorePep8

            #add artificially 1% of the count to avoid the second show
            #of progress bar when in fact total number of segment count
            #is greater then total count calculated by segment_count method
            count = count + int(count * (1 / 100))

            #extends label text with source name (if not None)
            label_text = "{0} [{1}]".format(
                self.label_text, nvl(data_vector_accessor.source_name, ""))
            with progressManager.initialize(label_text=label_text,
                                            max_value=count) as progress:
                start_progress = self.__StartProgress__()
                if not self.params.progress_handler == None:
                    #give ability to pass custom progress handler
                    progress_handler = self.params.progress_handler
                elif self.params.save_csv == True:
                    progress_handler = self.__CSVProgressHandler__()
                else:
                    progress_handler = self.__ProgressHandler__()
                progress_handler.progress = progress
                if self.params.save_csv == True:
                    pp_generator.generate_CSV(
                        data_vector_accessor.data_vector,
                        data_vector_accessor.source_name,
                        start_progress=start_progress,
                        progress_handler=progress_handler)
                else:
                    pp_generator.generate(data_vector_accessor.data_vector,
                                          start_progress=start_progress,
                                          progress_handler=progress_handler)
                #store information about interrupt signal if it has happened
                self.__interrupted__ = progress_handler.interrupted

                if self.__interrupted__ == False and \
                    not self.params.formatted_summary_statistics == None:
                    self.params.formatted_summary_statistics.append(
                        pp_generator.formatted_summary_statistics)

                #if interrupted break the whole loop
                if self.__interrupted__:
                    return
        if len(outcomes_exist_info) > 0:
            message = "For the following files, outcomes already exist:"
            for outcome in outcomes_exist_info:
                message += ("\n" + outcome)
            InformationWindow(message=message)
示例#40
0
 def reset(self, _min=None, _max=None):
     self.min_value = nvl(_min, DEFAULT_MIN_VALUE)
     self.max_value = nvl(_max, DEFAULT_MAX_VALUE)
示例#41
0
 def __init__(self, _shift=1, **params):
     super(SquareFilter, self).__init__(_shift=_shift)
     params = Params(**params)
     self.min_value = nvl(params.min_value, DEFAULT_MIN_VALUE)
     self.max_value = nvl(params.max_value, DEFAULT_MAX_VALUE)
     self.__value_unit__ = Millisecond
    def start(self):
        """
        method initiate show up of poincare progress bar
        """
        self.__interrupted__ = False

        #parameter formatted_summary_statistics is used to store
        #calculated summary statistics
        if not self.params.formatted_summary_statistics == None:
            self.params.formatted_summary_statistics[:] = []

        outcomes_exist_info = []
        progressManager = ProgressDialogManager(self.parent,
                                count=len(self.__data_vector_accessor_list__))
        for data_vector_accessor in self.__data_vector_accessor_list__:
            parameters = \
                data_vector_accessor.parameters_container.parameters.get(PoincarePlotParameters.NAME) #  alias @IgnorePep8
            parameters.prepareParameters()
            pp_generator = PoincarePlotGenerator(
                        output_file_listener=self.params.output_file_listener,
                        parameters=parameters)
            if self.params.save_csv == True:
                (ok, _) = pp_generator.precheck(
                                        data_vector_accessor.source_name)
                if ok == False:
                    if pp_generator.outcome_exists:
                        outcomes_exist_info.append(
                                        data_vector_accessor.source_name)
                    continue

            message = parameters.validateParameters(self.params.check_level)
            if message:
                ErrorWindow(message=message)
                return
            count = pp_generator.segment_count(data_vector_accessor.data_vector) # @IgnorePep8

            #add artificially 1% of the count to avoid the second show
            #of progress bar when in fact total number of segment count
            #is greater then total count calculated by segment_count method
            count = count + int(count * (1 / 100))

            #extends label text with source name (if not None)
            label_text = "{0} [{1}]".format(self.label_text,
                                    nvl(data_vector_accessor.source_name, ""))
            with progressManager.initialize(label_text=label_text,
                                            max_value=count) as progress:
                start_progress = self.__StartProgress__()
                if not self.params.progress_handler == None:
                    #give ability to pass custom progress handler
                    progress_handler = self.params.progress_handler
                elif self.params.save_csv == True:
                    progress_handler = self.__CSVProgressHandler__()
                else:
                    progress_handler = self.__ProgressHandler__()
                progress_handler.progress = progress
                if self.params.save_csv == True:
                    pp_generator.generate_CSV(data_vector_accessor.data_vector,
                                            data_vector_accessor.source_name,
                                            start_progress=start_progress,
                                            progress_handler=progress_handler)
                else:
                    pp_generator.generate(data_vector_accessor.data_vector,
                                          start_progress=start_progress,
                                          progress_handler=progress_handler)
                #store information about interrupt signal if it has happened
                self.__interrupted__ = progress_handler.interrupted

                if self.__interrupted__ == False and \
                    not self.params.formatted_summary_statistics == None:
                    self.params.formatted_summary_statistics.append(
                                  pp_generator.formatted_summary_statistics)

                #if interrupted break the whole loop
                if self.__interrupted__:
                    return
        if len(outcomes_exist_info) > 0:
            message = "For the following files, outcomes already exist:"
            for outcome in outcomes_exist_info:
                message += ("\n" + outcome)
            InformationWindow(message=message)
示例#43
0
                    self.__p__.addParameterInfo(
                                        group=group.title,
                                        name=action.dest,
                                        default=action.default,
                                        _help=action.help,
                                        group_description=group.description)
        return parser


if __name__ == '__main__':

    ppManager = PoincarePlotManager()
    __args = ppManager.getParser().parse_args()
    #copy all parameters from __args object into ppManager object
    copy_object(__args, ppManager)
    ppManager.movie_dir = nvl(__args.movie_dir, ppManager.output_dir)

    _disp = False
    if __args.display_annotation_values == True:
        _disp = True
        print('Annotations: ' + commas(ppManager.getUniqueAnnotations(),
                                       _default='none'))
    if __args.headers == True:
        _disp = True
        print('Headers:')
        for header in ppManager.getHeaders():
            print(header)
    if _disp == False:
        if ppManager.movie_name == None:
            ppManager.generate()
        else:
示例#44
0
 def reset(self, _min=None, _max=None):
     self.min_value = nvl(_min, DEFAULT_MIN_VALUE)
     self.max_value = nvl(_max, DEFAULT_MAX_VALUE)
示例#45
0
 def movie_dpi(self):
     return nvl(self.__movie_dpi__, 70)
 def movie_dpi(self):
     return nvl(self.__movie_dpi__, 70)
示例#47
0
 def __init__(self, _shift=1, **params):
     super(SquareFilter, self).__init__(_shift=_shift)
     params = Params(**params)
     self.min_value = nvl(params.min_value, DEFAULT_MIN_VALUE)
     self.max_value = nvl(params.max_value, DEFAULT_MAX_VALUE)
     self.__value_unit__ = Millisecond
示例#48
0
                    self.__p__.addParameterInfo(
                        group=group.title,
                        name=action.dest,
                        default=action.default,
                        _help=action.help,
                        group_description=group.description)
        return parser


if __name__ == '__main__':

    ppManager = PoincarePlotManager()
    __args = ppManager.getParser().parse_args()
    #copy all parameters from __args object into ppManager object
    copy_object(__args, ppManager)
    ppManager.movie_dir = nvl(__args.movie_dir, ppManager.output_dir)

    _disp = False
    if __args.display_annotation_values == True:
        _disp = True
        print('Annotations: ' +
              commas(ppManager.getUniqueAnnotations(), _default='none'))
    if __args.headers == True:
        _disp = True
        print('Headers:')
        for header in ppManager.getHeaders():
            print(header)
    if _disp == False:
        if ppManager.movie_name == None:
            ppManager.generate()
        else:
    def initiate(self):
        if len(self.pp_specs) == 0:
            return False

        # only positive values are accepted
        x = self.p0.x_data[pl.where(self.p0.x_data > 0)]
        y = self.p0.y_data[pl.where(self.p0.y_data > 0)]

        x_min = pl.amin(x)
        x_max = pl.amax(x)
        y_min = pl.amin(y)
        y_max = pl.amax(y)
        value_min = x_min if x_min < y_min else y_min
        self.value_max = x_max if x_max > y_max else y_max

        self.pd = ArrayPlotData()
        self.pd.set_data("index", x)
        self.pd.set_data("value", y)

        index_ds = ArrayDataSource(x)
        value_ds = ArrayDataSource(y)

        # Create the plot
        self._plot = Plot(self.pd)

        axis_defaults = {
                         #'axis_line_weight': 2,
                         #'tick_weight': 2,
                         #'tick_label_color': 'green',
                         'title_font': self.axis_font,
                         }
        if self.tick_font:
            axis_defaults['tick_label_font'] = self.tick_font

        #a very important and weird trick; used to remove default ticks labels
        self._plot.x_axis = None
        self._plot.y_axis = None
        #end trick

        #add new x label and x's ticks labels
        x_axis = PlotAxis(orientation='bottom',
                  title=nvl(self.manager.x_label, 'RR(n) [ms]'),
                  mapper=self._plot.x_mapper,
                  **axis_defaults)
        self._plot.overlays.append(x_axis)

        #add new y label and y's ticks labels
        y_axis = PlotAxis(orientation='left',
                   title=nvl(self.manager.y_label, 'RR(n+1) [ms]'),
                   mapper=self._plot.y_mapper,
                   **axis_defaults)
        self._plot.overlays.append(y_axis)

        self._plot.index_range.add(index_ds)
        self._plot.value_range.add(value_ds)

        self._plot.index_mapper.stretch_data = False
        self._plot.value_mapper.stretch_data = False
        self._plot.value_range.set_bounds(value_min, self.value_max)
        self._plot.index_range.set_bounds(value_min, self.value_max)

        # Create the index and value mappers using the plot data ranges
        imapper = LinearMapper(range=self._plot.index_range)
        vmapper = LinearMapper(range=self._plot.value_range)

        color = "white"

        self.scatter = __PoincarePlotScatterPlot__(
                        self.p0,
                        self.manager,
                        index=index_ds,
                        value=value_ds,
                        #color_data=color_ds,
                        #color_mapper=color_mapper,
                        #fill_alpha=0.4,
                        color=color,
                        index_mapper=imapper,
                        value_mapper=vmapper,
                        marker='circle',
                        marker_size=self.manager.active_point_size,
                        line_width=0
                        #outline_color='white'
                        )
        self._plot.add(self.scatter)

        #self._plot.plots['var_size_scatter'] = [self.scatter]

        # Tweak some of the plot properties
        _title = nvl(self.manager.movie_title, "Poincare plot")
        if len(_title) > 0:
            self._plot.title = _title
            self._plot.title_font = self.title_font

        self._plot.line_width = 0.5
        self._plot.padding = self.frame_pad

        self._plot.do_layout(force=True)
        self._plot.outer_bounds = [self.manager.movie_width,
                                   self.manager.movie_height]

        self.gc = PlotGraphicsContext(self._plot.outer_bounds,
                                      dpi=self.manager.movie_dpi)
        self.gc.render_component(self._plot)
        self.gc.set_line_width(0)

        self.gc.save(self._get_filename(self.p0))

        self.x_mean_old = None
        self.y_mean_old = None
        self._time_label_font = None

        return True