def __init__(self, title='Variables graphs'): super(GraphApp,self).__init__(title) self._graph = ControlVisVis("Graph") self._toggleVars = ControlButton('Show/Hide variables', checkable=True) self._loadGraph = ControlButton('Apply') self._varsList = ControlCheckBoxList('Variables') self._varsList += ('Frames',True) self._varsList += ('X',True) self._varsList += ('Y',True) self._varsList += ('Z',False) self._varsList += ('Velocity',False) self._varsList += ('Acceleration',False) self._modules_tabs.update({ 'Graphs': [ ('_toggleVars',' '), '_varsList', '_loadGraph', '_graph'], }) self._loadGraph.value = self.__calculate_graph self._toggleVars.value = self.__show_hide_variables self._varsList.hide() self._loadGraph.hide()
def __init__(self, parent_win=None): BaseWidget.__init__(self, 'Videos selector', parent_win=parent_win) self._videos = ControlCheckBoxList('Videos filter') Dialog.__init__(self) self.formset = ['_videos'] self._videos.selection_changed_event = self.__selection_changed_event
def __init__(self, parent_win=None): BaseWidget.__init__(self, 'Images selector', parent_win=parent_win) self._videos = ControlCheckBoxList('Videos filter') self._images = ControlCheckBoxList('Images filter') Dialog.__init__(self) self.formset = [('_videos', '||', '_images')] self._videos.selection_changed_event = self.__selection_changed_event self._videos.changed_event = self.__update_images
def __init__(self, project=None): """ :param project: project where this board belongs :type project: pycontrolgui.models.project.Project """ BaseWidget.__init__(self, 'Board') self.layout().setContentsMargins(5, 10, 5, 5) self._name = ControlText('Box name') self._serial_port = ControlCombo('Serial port') self._refresh_serials = ControlButton( '', icon=QtGui.QIcon(conf.REFRESH_SMALL_ICON), default=self.__refresh_serials_pressed, helptext="Press here to refresh the list of available devices.") self._log_btn = ControlButton('Console') self._active_bnc = ControlCheckBoxList('BNC') self._active_wired = ControlCheckBoxList('Wired') self._active_behavior = ControlCheckBoxList('Behavior') self._loadports_btn = ControlButton('Load board info') self._netport = ControlNumber('Net port', default=36000 + len(project.boards), minimum=36000, maximum=36100) self._events = ControlList('Events', readonly=True) self._inputchannels = ControlList('Input channels', readonly=True) self._outputchannels = ControlList('Output channels', readonly=True) self._saved_serial_port = None Board.__init__(self, project) self._formset = [ '_name', ('_serial_port', '_refresh_serials'), '_netport', '_log_btn', '=', '_loadports_btn', { 'Ports': [ 'Enabled or disable ports', '_active_bnc', '_active_wired', '_active_behavior', ], 'Events': ['_events'], 'Input ch.': ['_inputchannels'], 'Output ch.': ['_outputchannels'] } ] self._name.changed_event = self.__name_changed_evt self._loadports_btn.value = self.__load_bpod_ports self._fill_serial_ports()
def __init__(self, parent_win=None): ObjectsDialog.__init__( self, parent_win=parent_win, title='Datasets selector', ) self._datasets = ControlCheckBoxList('Datasets filter') self.formset = [('_videos', '||', '_objects', '||', '_datasets')] self._objects.changed_event = self.__update_datasets self._datasets.changed_event = self.__datasets_changed_event self.load_order = ['_videos', '_objects', '_datasets']
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._repos = ControlCheckBoxList('Repositories', headers=['', 'Repositories paths']) self._authors = ControlCheckBoxList( 'Authors', headers=['', 'Author name', 'Email']) self._load = ControlButton('Load', default=self.load_data) self._save = ControlButton('Save', default=self.save_data) self.formset = [no_columns('_load', '_save'), '_repos', '_authors'] if os.path.exists(self.CONF_FILENAME): with open(self.CONF_FILENAME, 'r') as infile: self._repos.value, self._authors.value = json.load(infile)
def __init__(self, parent=None): BaseWidget.__init__(self, 'Export data', parent_win=parent) self.set_margin(5) self.setMinimumHeight(600) self.setMinimumWidth(800) self._tree = ControlTree('Data') self._apply = ControlButton('Apply', checkable=True) self._progress = ControlProgress('Progress') self._add = ControlButton('Add') self._remove = ControlButton('Remove') self._export_list = ControlList('Columns to export') self._outdir = ControlDir('Output directory') self._outfile = ControlText('Output file name') self._toggleevts = ControlCheckBox('Split files by events') self._splitevents = ControlCheckBoxList('Events') self._evtsreload = ControlButton('Reload events') self._formset = [[['_add', '_tree'], '||', ['_remove', '_export_list']], '_toggleevts', '_evtsreload', '_splitevents', '_outdir', '_outfile', '_apply', '_progress'] self._add.value = self.__add_column_event self._remove.value = self.__remove_column_event self._apply.value = self.__apply_btn_event self._evtsreload.value = self.__reload_events self._outdir.changed_event = self.__update_outfile_name_event self._outfile.changed_event = self.__update_outfile_name_event self._toggleevts.changed_event = self.__toggleevents_visibility self._splitevents.changed_event = self.__update_outfile_name_event self._splitevents.selection_changed_event = self.__update_outfile_name_event self._tree.show_header = False self._apply.icon = conf.ANNOTATOR_ICON_MOTION self._evtsreload.icon = conf.ANNOTATOR_ICON_REFRESH self._add.icon = conf.ANNOTATOR_ICON_ADD self._remove.icon = conf.ANNOTATOR_ICON_REMOVE self._progress.hide() self._splitevents.hide() self._evtsreload.hide() self._apply.enabled = False self._properties = []
def __init__(self, *args, **kwargs): super().__init__('Astrocat GUI') self._input_file = ControlFile('Imaging record (*.lsm or *.tiff)') #self._json_file = ControlFile('Parameter JSON file') self._flags = ControlCheckBoxList('Flags') self._morphology_channel = ControlNumber("Morphology channel", minimum=0, maximum=5, default=0) self._ca_channel = ControlNumber("Ca channel", minimum=0, maximum=5, default=1) self._suff = ControlText("Name suffix", default='astrocat004') self._fps = ControlNumber("Movie fps", default=25) self._codec = ControlText('Movie codec', default='libx264') self._detection_label = ControlLabel('Detection') self._detection_loc_nhood = ControlNumber('Nhood', default=5) self._detection_loc_stride = ControlNumber('Stride', default=2) self._detection_spatial_filter = ControlNumber('Spatial filter', default=3) self._run_button = ControlButton('Process') self._run_button.value = self.__run_button_fired self._formset = [ '_input_file', '=', [ '_detection_label', '_detection_loc_nhood', '_detection_loc_stride' ], ('_codec', '_fps'), ('_run_button') ]
def __init__(self, *args, **kwargs): super().__init__('4-Cam') self.set_margin(10) # Definition of the forms fields self._player1 = ControlPlayer('Player1') self._player2 = ControlPlayer('Player2') self._player3 = ControlPlayer('Player3') self._player4 = ControlPlayer('Player4') self._runbutton = ControlButton('Stop') self._screenshot = ControlButton('Screenshot') self._outputfile = ControlDir('Screenshots Ausgabe Ordner') self._cams = ControlCheckBoxList('Kameras') # Define the event that will be called when the run button is processed self._runbutton.value = self.__stopEvent self._screenshot.value = self._saveImages self.__check_all_avaliable_cameras() self.formset = [{ '0-Kameras': [('_runbutton'), ('_player1', '_player2'), ('_player3', '_player4')], '1-Einstellungen': [('_outputfile'), ('_cams')] }] self._player1.value = self.__assign_capture(0) self._player2.value = self.__assign_capture(1) self._player3.value = self.__assign_capture(2) self._player4.value = self.__assign_capture(3) self._outputfile.value = os.getcwd() self.__runEvent()
def __init__(self): super(Example1, self).__init__('dir examples') self.parent = None self._directory = ControlDir('Choose a directory') self._file = ControlFile('Choose a file') self._filetree = ControlFilesTree('Choose a file') self._image = ControlImage('Image') self._boundaries = ControlBoundingSlider('Bounding', horizontal=True) self._button = ControlButton('Click') self._button.value = self.onButtonClick # self._directory.value=self.onButtonClick self._checkbox = ControlCheckBox('Choose a directory') self._checkboxList = ControlCheckBoxList('Choose a file') self._player = ControlPlayer('Choose a file') self._slider = ControlSlider('Slider') self._player.show() self._checkboxList.value = [('Item 1', True), ('Item 2', False), ('Item 3', True)] self._combobox = ControlCombo('Choose a item') self._list = ControlList('List label') self._progress = ControlProgress('Progress bar') self._visvisVolume = ControlVisVisVolume('Visvis') self._timeline = ControlEventTimeline('Timeline') self._combobox.add_item('Item 1', 'Value 1') self._combobox.add_item('Item 2', 'Value 2') self._combobox.add_item('Item 3', 'Value 3') self._combobox.add_item('Item 4') self._list.value = [('Item1', 'Item2', 'Item3',), ('Item3', 'Item4', 'Item5',)] imageWithVolume = np.zeros((100, 100, 100), np.uint8) imageWithVolume[30:40, 30:50, :] = 255 imageWithVolume[30:40, 70:72, :] = 255 self._visvisVolume.value = imageWithVolume self._visvis = ControlVisVis('Visvis') values1 = [(i, random.random(), random.random()) for i in range(130)] values2 = [(i, random.random(), random.random()) for i in range(130)] self._visvis.value = [values1, values2] self.formset = [ '_visvis' , '_directory' , '_button' , '_file' , '_boundaries' , '_filetree' , '_image' , '_slider' , ('_checkboxList', '_player') , ('_checkbox', ' ') , ('_combobox', ' ') , '_progress' , '=' , ('_visvisVolume', '||', '_list') , '_timeline' ]
def __init__(self, parent_win=None, title='Objects selector'): BaseWidget.__init__(self, title, parent_win=parent_win) self._objects_filter = None self._videos = ControlCheckBoxList('Videos filter') self._objects = ControlCheckBoxList('Objects filter') self._videos.add_popup_menu_option('Select video', self.__selection_changed_event) Dialog.__init__(self) self.formset = [('_videos', '||', '_objects')] self._videos.selection_changed_event = self.__selection_changed_event self._videos.changed_event = self.update_objects self._objects.changed_event = self.__objects_changed_event
def _set_chckbx_list(self): self.ctrld_w._chckbx_list = \ ControlCheckBoxList( 'Select desired surfaces for {} boundary' .format(self.flld_ctrl_label)) print('self.su2_cfg_obj.available_srfs') print(self.su2_cfg_obj.available_srfs) self._set_chckbx_list_vals() # \
def __init__(self): # Class Vars: self.__players = [] # List of players # Player Setup Tab -- Init UI Elements #super(MBUI, self).__init__("Millennium Blades Helper") BaseWidget.__init__(self, "Millennium Blades Helper") self._lstPlayers = ControlList('Player List') self._btnAddPl = ControlButton('Add Player') self._btnRemPl = ControlButton('Remove Selected Player') self._btnGenPl = ControlButton('Generate Player Setup') # Player Setup Tab -- Set up properties of UI elements, attach callbacks, etc. self._lstPlayers.horizontal_headers = [ 'Name', 'Character', 'Starter Deck' ] self._btnAddPl.value = self.__onAddPlayerClick self._btnRemPl.value = self.__onRemoveSelectedPlayerClick self._btnGenPl.value = self.__onGeneratePlayerSetupClick # Store Setup Tab -- Init UI Elements self._lstStore = ControlList('Store Components') self._ckAreaLabel = ControlLabel('Sets To Use') self._btnGenerateSt = ControlButton('Generate Store') # Store Setup Tab -- Set up properties of UI elements, attach callbacks etc. self._lstStore.horizontal_headers = ['Category', 'Sets'] self._btnGenerateSt.value = self.__onGenerateStoreClick # Scoring Tab -- Init UI Components self._scoringPanel = ControlEmptyWidget() self._btnGetScoring = ControlButton('Generate Score Sheet') # Scoring Tab -- Set up properties of UI elements, attach callbacks etc. self._btnGetScoring.value = self.__onGenerateScoringClick # Set Selection Tab -- Init UI Components self._chkArea = ControlCheckBoxList('Sets To Use') # Set Selection Tab -- Set up properties of UI elements, attach callbacks etc. self._chkArea += ('Base Set', True) self._chkArea += ('Set Rotation', True) self._chkArea += ('MX #1: Crossover', True) self._chkArea += ('MX #2: Sponsors', True) self._chkArea += ('MX #3: Fusion Chaos', True) self._chkArea += ('MX #4: Final Bosses', True) self._chkArea += ('MX #5: Futures', True) self._chkArea += ('MX #6: Professionals', True) # Set up tabs and component flow for UI self.formset = [{ '1. Player Setup': ['_lstPlayers', ' ', ('_btnAddPl', '_btnRemPl', '_btnGenPl')], '2. Store Setup': ['_lstStore', ' ', '_btnGenerateSt'], '3. Scoring': ['_scoringPanel', '_btnGetScoring'], '4. Set Selection': ['_chkArea'] }]
def __init__(self, session): """ :param session: session reference :type session: pycontrolgui.windows.detail.entities.session_window.SessionWindow """ BaseWidget.__init__(self, session.name) self.session = session self._refreshbtn = ControlButton('Refresh Timeline') self._list = ControlCheckBoxList('Events to show') self._events = ControlEventsGraph(session.name) self._list.hide() self._events.add_popup_menu_option('Show / Hide Events', self.__toggle_events_to_show_evt) self._events.add_track('') # for state_id, state_name in sorted(self.session.setup.board_task.states.items(), key=lambda x: x[0]): # self._events.add_track(state_name) self._history_index = 0 self._last_event = None self._session_start_timestamp = datetime_now.now() self.formset = ['_refreshbtn', '_list', '=', '_events'] self._list_of_states_colors = [ '#E0E0E0', '#FFCC99', '#FFFF99', 'CCFF99', '#99FFFF', '#99CCFF', '#FF99CC' ] self._states_names = {} self._timer = QTimer() self._timer.timeout.connect(self.read_message_queue) self._refreshbtn.value = self.__refresh_evt self._list.value = [(evt_type.__name__, True) for evt_type in self.EVENTS_TO_SHOW] self._list.changed_event = self.__list_changed_evt self._available_events = dict([(evt_type.__name__, evt_type) for evt_type in self.EVENTS_TO_SHOW]) self.__list_changed_evt()
def __init__(self): super(AutoStartPrograms, self).__init__('Autostart programs') # select script self._selectScript = ControlFile('select startup script: ') self._selectScript.changed_event = self.SelectScriptChanged # select list self._autoStartList = ControlCheckBoxList('autostart items') self._autoStartList.value = self.AutoStartList() self._autoStartList.changed_event = self.AutoStartListChanged # delete button self._buttonDelete = ControlButton('delete') self._buttonDelete.value = self._buttonDeleteAction # close button self._buttonClose = ControlButton('close') self._buttonClose.value = self._buttonCloseAction
def __init__(self, object2d=None): DatasetGUI.__init__(self) Contours.__init__(self, object2d) BaseWidget.__init__(self, '2D Object', parent_win=object2d) self._sel_pts = [] self._remove_btn = ControlButton('Remove') self._layers = ControlCheckBoxList('Layers') self._sel_pto_btn = ControlButton('Select point') self._switchangle_btn = ControlButton('Switch orientation') self._pickcolor = ControlButton('Pick a color', default=self.__pick_a_color_event) self._formset = [ '_name', '_remove_btn', '_sel_pto_btn', '_switchangle_btn', ' ', '_pickcolor', ' ', '_layers' ] self._switchangle_btn.hide() #### set controls ############################################## self._remove_btn.icon = conf.ANNOTATOR_ICON_REMOVE self._sel_pto_btn.icon = conf.ANNOTATOR_ICON_SELECTPOINT self._switchangle_btn.icon = conf.ANNOTATOR_ICON_REMOVE #### set events ################################################# self._remove_btn.value = self.remove_dataset self._sel_pto_btn.value = self.__sel_pto_btn_event self._switchangle_btn.value = self.__switchangle_btn_event self.create_tree_nodes() self._layers.value = [('contours', True), ('angle', True), ('velocity vector', True), ('bounding rect', False), ('fit ellipse', False), ('extreme points', False), ('convex hull', False), ('rotated rectangle', False), ('minimum enclosing circle', False), ('minimum enclosing triangle', False)]
def __init__(self, subjectlist, selectedsubjects): super(SubjectSelectPopup, self).__init__('Add Subjects') self._ok_btn = ControlButton('OK') self._cancel_btn = ControlButton('Cancel', default=self.cancel_evt) self._subjectslist = ControlCheckBoxList('Subject List') self._formset = [ '', ('', '_subjectslist', ''), ('', '_ok_btn', '_cancel_btn', ''), '' ] for subject in sorted([s for s in subjectlist], key=lambda x: x.name.lower()): b = False for a in selectedsubjects.value: if subject.name == a[0]: self._subjectslist += (subject, True) b = True if b is False: self._subjectslist += (subject, False)
def __init__(self, parent=None, parent_win=None): BaseWidget.__init__(self, 'Events stats', parent_win=parent_win) self._parent = parent self._bounds = ControlBoundingSlider('Frames range', 1, 100, horizontal=True) self._nframes = ControlNumber('Merge in a group of', 1800) self._videofsp = ControlNumber('FPS', 30.0) self._analyseButton = ControlButton('Calculate graphs') self._events = ControlCheckBoxList() self._graph = ControlVisVis('Graph') self._showTotalCounts = ControlCheckBox('Show total events counting') self._showEvtsCounts = ControlCheckBox('Show events counting', True) self._progress = ControlProgress() self._exportDurations = ControlButton('Export durations') self._exportTotals = ControlButton('Export totals') self._formset = [(' ', '_showEvtsCounts', '|', '_showTotalCounts', '|', '_nframes', '_videofsp', '_analyseButton', '_exportDurations', '_exportTotals'), '_bounds', { 'a:Graph': ['_graph'], 'c:Events selection': ['_events'] }, '_progress'] self._analyseButton.value = self.__generate_graph self._exportDurations.value = self.__export_durations self._exportTotals.value = self.__export_totals self._progress.hide() self.__load_events() self.set_margin(5) self.setMinimumWidth(800) self.setMinimumHeight(600)
def set_init_chckbx_list_vals(self): """ Creates sections selection checkbox list and populates the list with available sections Returns ------- None None """ if not self.su2_cfg_obj: raise ValueError( 'please check value of su2_cfg_obj - it seems that it`s empty') available_sections = self.su2_cfg_obj.init_cfg_sections_labels self.sections_chckbox_list = \ ControlCheckBoxList('Please select desired sections') # self._checkbox_list = ControlCheckBoxList('Sample chbx list') self.sections_chckbox_list.value = \ ((el, True) for el in available_sections) CFGSectionSelWidgetCtrl.ctrld_widget.sections_chckbox_list = \ self.sections_chckbox_list self.is_sections_list_set = True
class ExportWindow(BaseWidget): def __init__(self, parent=None): BaseWidget.__init__(self, 'Export data', parent_win=parent) self.set_margin(5) self.setMinimumHeight(600) self.setMinimumWidth(800) self._tree = ControlTree('Data') self._apply = ControlButton('Apply', checkable=True) self._progress = ControlProgress('Progress') self._add = ControlButton('Add') self._remove = ControlButton('Remove') self._export_list = ControlList('Columns to export') self._outdir = ControlDir('Output directory') self._outfile = ControlText('Output file name') self._toggleevts = ControlCheckBox('Split files by events') self._splitevents = ControlCheckBoxList('Events') self._evtsreload = ControlButton('Reload events') self._formset = [[['_add', '_tree'], '||', ['_remove', '_export_list']], '_toggleevts', '_evtsreload', '_splitevents', '_outdir', '_outfile', '_apply', '_progress'] self._add.value = self.__add_column_event self._remove.value = self.__remove_column_event self._apply.value = self.__apply_btn_event self._evtsreload.value = self.__reload_events self._outdir.changed_event = self.__update_outfile_name_event self._outfile.changed_event = self.__update_outfile_name_event self._toggleevts.changed_event = self.__toggleevents_visibility self._splitevents.changed_event = self.__update_outfile_name_event self._splitevents.selection_changed_event = self.__update_outfile_name_event self._tree.show_header = False self._apply.icon = conf.ANNOTATOR_ICON_MOTION self._evtsreload.icon = conf.ANNOTATOR_ICON_REFRESH self._add.icon = conf.ANNOTATOR_ICON_ADD self._remove.icon = conf.ANNOTATOR_ICON_REMOVE self._progress.hide() self._splitevents.hide() self._evtsreload.hide() self._apply.enabled = False self._properties = [] ########################################################################### ### EVENTS ################################################################ ########################################################################### def __toggleevents_visibility(self): if self._toggleevts.value: self._splitevents.show() self._evtsreload.show() else: self._splitevents.hide() self._evtsreload.hide() def __field_full_name(self, tree_item): name = tree_item.text(0) while True: tree_item = tree_item.parent() if tree_item is None: break name = "{0} > {1}".format(tree_item.text(0), name) return name def __add_column_event(self): self.__update_outfile_name_event() item = self._tree.selected_item if item is None: return if hasattr(item, 'data_function'): self._export_list += [self.__field_full_name(item)] self._properties.append((len(item.win), item.data_function)) elif isinstance(item.win, Value): self._export_list += [self.__field_full_name(item)] self._properties.append((len(item.win), item.win.get_value)) def __remove_column_event(self): self.__update_outfile_name_event() if self._export_list.selected_row_index is None: return elif self._export_list.selected_row_index >= 0: self._properties.pop(self._export_list.selected_row_index) self._export_list -= -1 def __update_outfile_name_event(self): """ Update the output filename """ filename = self._outfile.value if len(filename.strip()) == 0: return outfilepath, outfile_extension = os.path.splitext(filename) names = [outfilepath] if len(outfilepath) > 0 else [] if len(list(self._splitevents.value)) > 0: if '{event}' not in outfilepath: names.append('{event}') if '{start}' not in outfilepath: names.append('{start}') if '{end}' not in outfilepath: names.append('{end}') self._outfile.value = ('-'.join(names) + '.csv') self._apply.enabled = True def __apply_btn_event(self): if self._apply.checked: if len(self._properties) == 0: QMessageBox.about( self, "Error", "You need to select at least one value to export.") self._apply.checked = False return if self._outfile.value is None or len( self._outfile.value.strip()) == 0: QMessageBox.about( self, "Error", "You need to select the name of the output file.") self._apply.checked = False return if self._outdir.value is None or len(self._outdir.value) == 0: QMessageBox.about( self, "Error", "You need to select the name of the output directory.") self._apply.checked = False return self.__update_outfile_name_event() self._export_list.enabled = False self._tree.enabled = False self._add.enabled = False self._remove.enabled = False self._outdir.enabled = False self._outfile.enabled = False self._apply.label = 'Cancel' ### calculate the video cuts ############################# timeline = self.parent().timeline selected_events = self._splitevents.value videocuts = [] if len(selected_events): # use the events to cut the video totalframes = 0 for row in timeline.rows: for event in row.events: if event.title not in selected_events: continue b = event.begin e = event.end totalframes += e - b videocuts.append((int(b), int(e), event.title)) videocuts = sorted(videocuts, key=lambda x: x[0]) else: # no events were selected end = max([size for size, func in self._properties]) totalframes = end videocuts = [(0, int(end), None)] ########################################################## self._progress.min = 0 self._progress.max = totalframes self._progress.show() for b, e, eventname in videocuts: filename = self._outfile.value filename = filename.format(event=eventname, start=b, end=e) filename = os.path.join(self._outdir.value, filename) with open(filename, 'w') as out: ## write the csv columns headers out.write('frame;') for values in self._export_list.value: out.write(('{0};'.format(values[0]))) out.write('\n') ## write the values for index in range(b, e): out.write('{0};'.format(index)) for _, func in self._properties: out.write('{0};'.format(func(index))) out.write('\n') self._progress += 1 self._export_list.enabled = True self._tree.enabled = True self._add.enabled = True self._remove.enabled = True self._outdir.enabled = True self._outfile.enabled = True self._apply.label = 'Apply' self._apply.checked = False self._progress.hide() def __copy_tree_node(self, item, new_item): new_item.win = item.win if hasattr(item, 'data_function'): new_item.data_function = item.data_function def __reload_events(self): """ Find all the events available on the timeline """ timeline = self.parent().timeline rows = timeline.rows events = {} for row in rows: for event in row.events: events[event.title] = True events = sorted(events.keys()) loaded_events = dict(self._splitevents.items) self._splitevents.value = [(e, loaded_events.get(e, False)) for e in events] @property def project(self): return self._project @project.setter def project(self, value): self._project = value self._tree.clear() self._tree.clone_tree(value.tree, copy_function=self.__copy_tree_node) self.__reload_events()
class GraphApp(BaseApp): """Application form""" def __init__(self, title='Variables graphs'): super(GraphApp,self).__init__(title) self._graph = ControlVisVis("Graph") self._toggleVars = ControlButton('Show/Hide variables', checkable=True) self._loadGraph = ControlButton('Apply') self._varsList = ControlCheckBoxList('Variables') self._varsList += ('Frames',True) self._varsList += ('X',True) self._varsList += ('Y',True) self._varsList += ('Z',False) self._varsList += ('Velocity',False) self._varsList += ('Acceleration',False) self._modules_tabs.update({ 'Graphs': [ ('_toggleVars',' '), '_varsList', '_loadGraph', '_graph'], }) self._loadGraph.value = self.__calculate_graph self._toggleVars.value = self.__show_hide_variables self._varsList.hide() self._loadGraph.hide() def __show_hide_variables(self): #Show and hide the variables list if self._toggleVars.checked: self._varsList.show() self._loadGraph.show() else: self._varsList.hide() self._loadGraph.hide() def __calculate_graph(self): #Render the graph if self._data==None: self.warning("Please load the data first.", "The data is missing") return lower = 0 if self._boundings.value[0]<0 else self._boundings.value[0] higher = len(self._data) if self._boundings.value[1]>(len(self._data)+1) else self._boundings.value[1] self._progress.min = lower self._progress.max = higher values = [] variables = self._varsList.value if len(variables)>3: self.warning("Please select the maximum of 3 variables.", "Too many variables selected") return for i in range(int(lower), int(higher)-2 ): self._progress.value = i if self._data[i]!=None: val = [] pos = self._data[i].position if 'Frames' in variables: val.append(i) if 'X' in variables: val.append(pos[0]) if 'Y' in variables: val.append(pos[1]) if 'Z' in variables: val.append(pos[2]) if 'Velocity' in variables: val.append(self._velocities[i]) if 'Acceleration' in variables: val.append(self._accelerations[i]) values.append( val ) self._graph.value = [values]
def __init__(self): super(OCSConfig, self).__init__('Restrictor de permisos') avail_apps = "" avail_apps_list = [] internet = False external = False admin = False try: f = open(FILE) for line in f: if line[0] != "#": if line.find("AVAILABLE_APPS") > -1: avail_apps = line.split("=")[1][:-1] elif line.find("ALLOW_INTERNET") > -1: if line.split("=")[1].find("YES") > -1: internet = True else: internet = False elif line.find("ALLOW_MOUNT_EXTERNAL") > -1: if line.split("=")[1].find("YES") > -1: external = True else: external = False elif line.find("ADMIN") > -1: if line.split("=")[1].find("YES") > -1: admin = True else: admin = False f.close() avail_apps_list = avail_apps.split(",") except: print("Fitxer " + FILE + " inexistent. El cream.") #Definition of the forms fields self._internet = ControlCheckBox('Permet Internet') self._internet.value = internet self._externaldev = ControlCheckBox('Permet dispositius externs') self._externaldev.value = external self._apps = ControlCheckBoxList("Llista d'aplicacions disponibles") self._apps += ('libreoffice-calc', 'libreoffice-calc' in avail_apps_list) self._apps += ('libreoffice-writer', 'libreoffice-writer' in avail_apps_list) self._apps += ('libreoffice-startcenter', 'libreoffice-startcenter' in avail_apps_list) self._apps += ('pluma', 'pluma' in avail_apps_list) self._apps += ('galculator', 'galculator' in avail_apps_list) self._admin = ControlCheckBox('Mode administrador', admin) self._admin.value = admin self._brestore = ControlButton('Restaura escriptori') self._bapply = ControlButton('Aplica') self._bexit = ControlButton('Surt') self._brestore.value = self.__buttonActionRestore self._bapply.value = self.__buttonActionApply self._bexit.value = self.__buttonActionCancel self.formset = [('_internet', '_externaldev'), '_apps', '_admin', ' ', '_brestore', ('_bapply', '_bexit'), ' ']
def __init__(self, parent=None): super(VideosExporterGui, self).__init__('Videos exporter', parent_win=parent) self.set_margin(5) self.setMinimumHeight(400) self.setMinimumWidth(400) self._toolbox = ControlToolBox('Tool') self._panel_area = ControlEmptyWidget('Set the object area', default=DatasetsDialog(self)) self._panel_colors = ControlEmptyWidget('Set the object color', default=DatasetsDialog(self)) self._panel_imgs = ControlEmptyWidget('Set the video background', default=ImagesDialog(self)) #### path panel ################################################ self._panel_path = ControlEmptyWidget('Set the object path', default=DatasetsDialog(self)) self._drawpath = ControlCheckBox('Draw paths') ################################################################ #### draw events ############################################### self._drawevents = ControlCheckBoxList('Events') self._eventstitles = ControlCheckBox('Draw titles') self._evtsreload1 = ControlButton('Reload events') ################################################################ #### split by events ########################################### self._splitevents = ControlCheckBoxList('Events') self._evtsreload2 = ControlButton('Reload events') ################################################################ self._codec = ControlCheckBox('Force AVI') self._outdir = ControlDir('Output directory') self._outfile = ControlText('Output file name') self._player = ControlPlayer('Player') self._progress = ControlProgress('Progress') self._apply = ControlButton('Export video(s)', checkable=True) self._apply.icon = conf.ANNOTATOR_ICON_PATH self._apply.enabled = False self._usefixedsize = ControlCheckBox('Use a fixed size') self._usefixedcolor = ControlCheckBox('Use a fixed color') self._radius = ControlSlider('Circle radius', default=10, minimum=1, maximum=300) self._color = ControlText('BGR color', default='255,255,255') self.formset = [('_toolbox', '||', '_player'), '=', '_outdir', ('_outfile', '_codec'), '_apply', '_progress'] self._toolbox.value = [ ('Path', [self._panel_path, self._drawpath]), ('Circle (optional)', [self._panel_area, (self._usefixedsize, self._radius)]), ('Circle color (optional)', [self._panel_colors, (self._usefixedcolor, self._color)]), ('Background (optional)', [self._panel_imgs]), ('Draw events (optional)', [self._evtsreload1, self._drawevents, self._eventstitles]), ('Split files by events (optional)', [self._evtsreload2, self._splitevents]), ] self._panel_path.value.datasets_filter = lambda x: isinstance( x, (Contours, Path)) #self._panel_area.value.datasets_filter = lambda x: isinstance(x, Value ) self._panel_colors.value.datasets_filter = lambda x: isinstance( x, (Contours, Path)) and hasattr(x, 'has_colors_avg' ) and x.has_colors_avg ### Set the controls events ############################################# self._evtsreload1.value = self.__reload_events self._evtsreload2.value = self.__reload_events self._outfile.changed_event = self.outputfile_changed_event self._usefixedsize.changed_event = self.__usefixedsize_changed_event self._usefixedcolor.changed_event = self.__usefixedcolor_changed_event self._splitevents.selection_changed_event = self.outputfile_changed_event self._panel_path.value.video_selection_changed_event = self.__video_selection_changed_event self._codec.changed_event = self.__video_selection_changed_event ## function from VideosExporterProcess class self._apply.value = self.apply_event ## function from VideosExporterPreview class self._player.process_frame_event = self.player_processframe_event self._evtsreload1.icon = conf.ANNOTATOR_ICON_REFRESH self._evtsreload2.icon = conf.ANNOTATOR_ICON_REFRESH self._progress.hide() self._radius.hide() self._color.hide() self.__check_areatab_event()
class ImagesDialog(Dialog, BaseWidget): def __init__(self, parent_win=None): BaseWidget.__init__(self, 'Images selector', parent_win=parent_win) self._videos = ControlCheckBoxList('Videos filter') self._images = ControlCheckBoxList('Images filter') Dialog.__init__(self) self.formset = [('_videos', '||', '_images')] self._videos.selection_changed_event = self.__selection_changed_event self._videos.changed_event = self.__update_images #for video in conf.PROJECT.videos: self += video ##################################################################### ### PRIVATE FUNCTIONS ############################################### ##################################################################### def __selection_changed_event(self): self.video_selection_changed_event() ##################################################################### ### EVENTS ########################################################## ##################################################################### def video_selection_changed_event(self): pass ##################################################################### ### FUNCTIONS ####################################################### ##################################################################### # used to update automaticly the name of the videos, objects and paths def refresh(self): self._videos.refresh() self._images.refresh() def __add__(self, other): if isinstance(other, Video): self._videos += (other, False) if isinstance(other, Image): self.__update_images() return self def __sub__(self, other): if isinstance(other, Video): self._videos -= other self.__update_images() if isinstance(other, Image): self.__update_images() return self def __update_images(self): """ Update the objects in the list """ images = [elem for elem, checked in self._images.items] images_list = [] for video, checked in self._videos.items: for img in video.images: images_list.append(img) if not checked and img in images: self._images -= img elif checked and img not in images: self._images += (img, False) for img in images: if img not in images_list: self._images -= img ##################################################################### ### PROPERTIES ###################################################### ##################################################################### @property def single_select(self): return self._images.value @single_select.setter def single_select(self, value): return self._images.value @property def images(self): return self._images.value @property def selected_data(self): videos = self._videos.value images = self._images.value res = [] for video in videos: images_list = [] for img in video.images: images_list.append(img) res.append((video, images_list)) return res @property def selected_video(self): ########################################### # current mouse selected video ########################################### index = self._videos.selected_row_index if index < 0: return None video, selected = self._videos.items[index] return video
class SceneApp(HeatMapApp): def __init__(self, title=''): self._points_values = None #used to map a color for each tracking point super(SceneApp, self).__init__(title) ##### CONTROLS ############################################################################## self._scene_file = ControlFile('Scene') self._scene_toggle_objs_list = ControlButton('Show/Hide objects', checkable=True) self._scene_objs_list = ControlCheckBoxList('Objects') self._scene_opengl = ControlOpenGL('OpengGL Scene') self._scene_points_alfa = ControlSlider('Transparency', 10, 0, 100) self._scene_bg_color = ControlCombo('Background color') self._scene_apply_colorBnds = ControlButton('Apply colors boundaries') self._scene_points_size = ControlCombo('Points size') self._scene_obj_color = ControlText('Object color') ############################################################################################# self._modules_tabs.update({ 'Heat map': [('_heatmapColor', ' | ', 'Filters:', '_toggleHeatmapVars', '_toggleSphereVisibility', '_sphere', ' | ', '_apply2Heatmap', ' '), ('_heatmapVarsList', '_heatmapVars', '_heatmapHigherVarsValues', '_heatMapMinVar', '_heatmapVarsBnds', '_heatMapMaxVar'), ({ '1:Map': ['_heatmap'], '0:Scene': [[('_scene_file', ' ', '_scene_toggle_objs_list', ' ', '_scene_bg_color', ' | ', '_scene_points_size', ' | ', '_scene_apply_colorBnds'), '_scene_points_alfa', '_scene_obj_color', '_scene_objs_list'], '=', '_scene_opengl'] }, '_heatmapColorsBnds')] }) ############################################################################################# self._scene_bg_color += ('White', '1,1,1,1.0') self._scene_bg_color += ('Gray', '0.3,0.3,0.3,1.0') self._scene_bg_color += ('Black', 'None') self._scene_points_size += '1' self._scene_points_size += '3' self._scene_points_size += '6' self._scene_points_size += '8' self._scene_objs_list.hide() self._scene_obj_color.hide() self._scene_objs_list.changed = self.__changed_objects_list_event self._scene_toggle_objs_list.value = self.__toggle_objects_list_event self._scene_points_alfa.changed = self.__changed_scene_points_alfa_event self._scene_bg_color.changed = self.__changed_background_color_event self._scene_apply_colorBnds.value = self.__scene_apply_color_bnds_event self._scene_points_size.changed = self.__changed_scene_points_size_event self._scene_objs_list.selectionChanged = self.__selectionchanged_object_list_event self._scene_obj_color.changed = self.__changed_object_color_event self._scene = None self._scene_file.changed = self.__scene_file_selected self._scene_opengl.clear_color = 1, 1, 1, 1 #self._scene_file.value = '/home/ricardo/Desktop/01Apollo201403210900/01Apollo201403210900_Scenario.obj' def initForm(self): super(SceneApp, self).initForm() #self._splitters[0].setStretchFactor(0,10) #self._splitters[0].setStretchFactor(1,90) ############################################################################################ ### EVENTS ################################################################################# ############################################################################################ def __changed_object_color_event(self): index = self._scene_objs_list.mouseSelectedRowIndex self._scene.objects[index].color = eval(self._scene_obj_color.value) self._scene_opengl.repaint() def __selectionchanged_object_list_event(self): index = self._scene_objs_list.mouseSelectedRowIndex self._scene_obj_color.value = str(self._scene.objects[index].color) self._scene_obj_color.label = 'Object color ({0})'.format( self._scene.objects[index].name) def __changed_scene_points_size_event(self): self._scene.points_size = eval(self._scene_points_size.value) self._scene_opengl.repaint() def __toggle_objects_list_event(self): if self._scene_toggle_objs_list.checked: self._scene_objs_list.show() self._scene_obj_color.show() else: self._scene_objs_list.hide() self._scene_obj_color.hide() def __changed_background_color_event(self): self._scene_opengl.clear_color = eval(self._scene_bg_color.value) def __changed_scene_points_alfa_event(self): if self._points_values != None: self._scene.colors = self.__gen_colors(self._points_values.copy()) self._scene_opengl.repaint() def __changed_objects_list_event(self): x, y, z = 0.0, 0.0, 0.0 count = 0.0 for obj in self._scene.objects: obj.active = obj.name in self._scene_objs_list.value obj.draw_faces = True if obj.active: for point in obj.points: x += point[0] y += point[1] z += point[2] count += 1.0 if count == 0.0: count = 1.0 self._scene._center = x / count, y / count, z / count self._scene_opengl.repaint() def __scene_file_selected(self): if len(self._scene_file.value) == 0: return self._scene = CustomScene() w = WavefrontOBJReader(self._scene_file.value) self._scene.objects = w.objects self._scene_opengl.value = self._scene self._scene_objs_list.clear() for obj in self._scene.objects: self._scene_objs_list += (obj.name, True) def __gen_colors(self, values): if len(values) == 0: return [] if self._heatmapColor.value == vv.CM_BONE: func = 'bone' if self._heatmapColor.value == vv.CM_COOL: func = 'cool' if self._heatmapColor.value == vv.CM_COPPER: func = 'copper' if self._heatmapColor.value == vv.CM_GRAY: func = 'gray' if self._heatmapColor.value == vv.CM_HOT: func = 'hot' if self._heatmapColor.value == vv.CM_HSV: func = 'hsv' if self._heatmapColor.value == vv.CM_PINK: func = 'pink' if self._heatmapColor.value == vv.CM_JET: func = 'jet' if self._heatmapColor.value == vv.CM_AUTUMN: func = 'autumn' if self._heatmapColor.value == vv.CM_SPRING: func = 'spring' if self._heatmapColor.value == vv.CM_SUMMER: func = 'summer' if self._heatmapColor.value == vv.CM_WINTER: func = 'winter' normalized_vals = np.float32(values) / np.float32(values).max() normalized_vals = normalized_vals - normalized_vals.min() maximum = normalized_vals.max() func = getattr(cm, func) colors = [] alpha = float(self._scene_points_alfa.value) / 100.0 for v in normalized_vals: color = func(v / maximum) colors.append((color[0], color[1], color[2], alpha)) return colors def __scene_apply_color_bnds_event(self): self._scene_apply_colorBnds.form.setStyleSheet("") if self._heatmapImg is None or not self._heatmapImg.any(): return lower, higher = self._heatmapColorsBnds.value a = self._points_values.copy() a[a < lower] = lower a[a > higher] = higher self._scene.colors = self.__gen_colors(a) def changed_heatmap_colors_bounds_event(self): super(SceneApp, self).changed_heatmap_colors_bounds_event() self._scene_apply_colorBnds.form.setStyleSheet("color: red") def changed_heatmap_color_event(self): super(SceneApp, self).changed_heatmap_color_event() if self._points_values != None: self._scene.colors = self.__gen_colors(self._points_values.copy()) self._scene_opengl.repaint() def calculate_heatmap_event(self): super(SceneApp, self).calculate_heatmap_event() if self._scene: #Filter for the data from a lower and upper frame self._progress.min = lower = 0 if self._boundings.value[ 0] < 0 else int(self._boundings.value[0]) self._progress.max = higher = len( self._data) if self._boundings.value[1] > ( len(self._data) + 1) else int(self._boundings.value[1]) #Calculate the size of the map x_diff = self._data.xRange[1] - self._data.xRange[0] y_diff = self._data.yRange[1] - self._data.yRange[0] z_diff = self._data.zRange[1] - self._data.zRange[0] scale = self.fit_scale(x_diff, y_diff, z_diff) #Fit the best scale value try: sphere = sphere_x, sphere_y, sphere_z, sphere_r = eval( self._sphere.value) except: sphere = None min_var, max_var = self._heatmapVarsBnds.value which_var = 0 if self._heatmapVarsList.value == 'Velocity' else 1 values = [] points = [] for i in range(lower, higher): if (i % 3000) == 0: self._progress.value = i if self._data[i] != None: x, y, z = position = self._data[i].position x += abs(self._data.xRange[0]) y += abs(self._data.yRange[0]) z += abs(self._data.zRange[0]) x = int(round(x * scale)) y = int(round(y * scale)) z = int(round(z * scale)) #Filter position by a defined sphere if sphere != None and lin_dist3d( (x, y, z), (sphere_x, sphere_y, sphere_z)) > sphere_r: continue #Use variables to construct the map, or positions if self._toggleHeatmapVars.checked: #velocities array has less 1 element than positions array if which_var == 0 and len(self._velocities) <= i: continue #accelarations array has less 2 element than positions array if which_var == 1 and len(self._accelerations) <= i: continue var = self._velocities[ i] if which_var == 0 else self._accelerations[i] #Filter by variable boundaries if not (min_var <= var <= max_var): continue values.append(self._heatmapImg[z, x, y]) points.append(position) self._progress.value = higher self._points_values = np.float32(values) self._scene.points = points self._scene.colors = self.__gen_colors(self._points_values.copy()) self._scene_apply_colorBnds.form.setStyleSheet("") self._scene_opengl.repaint()
def __init__(self, title=''): self._points_values = None #used to map a color for each tracking point super(SceneApp, self).__init__(title) ##### CONTROLS ############################################################################## self._scene_file = ControlFile('Scene') self._scene_toggle_objs_list = ControlButton('Show/Hide objects', checkable=True) self._scene_objs_list = ControlCheckBoxList('Objects') self._scene_opengl = ControlOpenGL('OpengGL Scene') self._scene_points_alfa = ControlSlider('Transparency', 10, 0, 100) self._scene_bg_color = ControlCombo('Background color') self._scene_apply_colorBnds = ControlButton('Apply colors boundaries') self._scene_points_size = ControlCombo('Points size') self._scene_obj_color = ControlText('Object color') ############################################################################################# self._modules_tabs.update({ 'Heat map': [('_heatmapColor', ' | ', 'Filters:', '_toggleHeatmapVars', '_toggleSphereVisibility', '_sphere', ' | ', '_apply2Heatmap', ' '), ('_heatmapVarsList', '_heatmapVars', '_heatmapHigherVarsValues', '_heatMapMinVar', '_heatmapVarsBnds', '_heatMapMaxVar'), ({ '1:Map': ['_heatmap'], '0:Scene': [[('_scene_file', ' ', '_scene_toggle_objs_list', ' ', '_scene_bg_color', ' | ', '_scene_points_size', ' | ', '_scene_apply_colorBnds'), '_scene_points_alfa', '_scene_obj_color', '_scene_objs_list'], '=', '_scene_opengl'] }, '_heatmapColorsBnds')] }) ############################################################################################# self._scene_bg_color += ('White', '1,1,1,1.0') self._scene_bg_color += ('Gray', '0.3,0.3,0.3,1.0') self._scene_bg_color += ('Black', 'None') self._scene_points_size += '1' self._scene_points_size += '3' self._scene_points_size += '6' self._scene_points_size += '8' self._scene_objs_list.hide() self._scene_obj_color.hide() self._scene_objs_list.changed = self.__changed_objects_list_event self._scene_toggle_objs_list.value = self.__toggle_objects_list_event self._scene_points_alfa.changed = self.__changed_scene_points_alfa_event self._scene_bg_color.changed = self.__changed_background_color_event self._scene_apply_colorBnds.value = self.__scene_apply_color_bnds_event self._scene_points_size.changed = self.__changed_scene_points_size_event self._scene_objs_list.selectionChanged = self.__selectionchanged_object_list_event self._scene_obj_color.changed = self.__changed_object_color_event self._scene = None self._scene_file.changed = self.__scene_file_selected self._scene_opengl.clear_color = 1, 1, 1, 1
class AutoStartPrograms(BaseWidget): def __init__(self): super(AutoStartPrograms, self).__init__('Autostart programs') # select script self._selectScript = ControlFile('select startup script: ') self._selectScript.changed_event = self.SelectScriptChanged # select list self._autoStartList = ControlCheckBoxList('autostart items') self._autoStartList.value = self.AutoStartList() self._autoStartList.changed_event = self.AutoStartListChanged # delete button self._buttonDelete = ControlButton('delete') self._buttonDelete.value = self._buttonDeleteAction # close button self._buttonClose = ControlButton('close') self._buttonClose.value = self._buttonCloseAction def AutoStartScriptSet(self): script = self._selectScript.value print(script) if script != '': self.writeAutoStartScript(script) self.alert("script set as autostart" + script) def writeAutoStartScript(self, script): scriptContent = self.AutoStartFileContent(script) f = open(self.AutoStartFullName(), "w") f.write(scriptContent) f.close() # close button def _buttonCloseAction(self): sys.exit() # delete button def _buttonDeleteAction(self): index = self._autoStartList.selected_row_index deleteFile = self.AutoStartFolder() + self.AutoStartListIndex(index) os.remove(deleteFile) self.AutoStartListRefresh() # functions def AutoStartFolder(self): return (str(Path.home()) + '/.config/autostart/') def AutoStartFileName(self): scriptfile = self._selectScript.value return (os.path.basename(scriptfile) + '.desktop') def AutoStartFullName(self): return (self.AutoStartFolder() + self.AutoStartFileName()) def AutoStartFileContent(self, scriptFile): text = "[Desktop Entry]\n" text = text + "Exec=" + scriptFile text = text + """ Name=screen Terminal=false Type=Application StartupNotify=false """ return (text) def setAutoStart(self, autostartfile, status): if (autostartfile.endswith('.desktop') and status == False): os.rename(autostartfile, autostartfile[:-8]) if (autostartfile.endswith('.desktop') == False and status == True): os.rename(autostartfile, autostartfile + '.desktop') def AutoStartList(self): allentries = [] for entry in os.listdir(self.AutoStartFolder()): if os.path.isfile(os.path.join(self.AutoStartFolder(), entry)): if (entry.endswith('.desktop')): allentries += [(entry, True)] else: allentries += [(entry, False)] return (allentries) def AutoStartListRefresh(self): self._autoStartList.clear() self._autoStartList.value = self.AutoStartList() def AutoStartFilesList(self): allentries = [] for entry in os.listdir(self.AutoStartFolder()): if os.path.isfile(os.path.join(self.AutoStartFolder(), entry)): allentries += [entry] return (allentries) def AutoStartListIndex(self, index): filesList = self.AutoStartFilesList() return (filesList[index]) def SelectScriptChanged(self): self.AutoStartScriptSet() self.AutoStartListRefresh() def AutoStartListChanged(self): checkedindexes = self._autoStartList.checked_indexes itemsCount = self._autoStartList.count files = self.AutoStartFilesList() for i in range(itemsCount): checked = False for t in checkedindexes: if t == i: checked = True self.setAutoStart(self.AutoStartFolder() + str(files[i]), checked)
class TrialsPlotWindow(BaseWidget): """ Show all boxes live state for an experiment""" EVENTS_TO_SHOW = [StateOccurrence, EventOccurrence] def __init__(self, session): """ :param session: session reference :type session: pycontrolgui.windows.detail.entities.session_window.SessionWindow """ BaseWidget.__init__(self, session.name) self.session = session self._refreshbtn = ControlButton('Refresh Timeline') self._list = ControlCheckBoxList('Events to show') self._events = ControlEventsGraph(session.name) self._list.hide() self._events.add_popup_menu_option('Show / Hide Events', self.__toggle_events_to_show_evt) self._events.add_track('') # for state_id, state_name in sorted(self.session.setup.board_task.states.items(), key=lambda x: x[0]): # self._events.add_track(state_name) self._history_index = 0 self._last_event = None self._session_start_timestamp = datetime_now.now() self.formset = ['_refreshbtn', '_list', '=', '_events'] self._list_of_states_colors = [ '#E0E0E0', '#FFCC99', '#FFFF99', 'CCFF99', '#99FFFF', '#99CCFF', '#FF99CC' ] self._states_names = {} self._timer = QTimer() self._timer.timeout.connect(self.read_message_queue) self._refreshbtn.value = self.__refresh_evt self._list.value = [(evt_type.__name__, True) for evt_type in self.EVENTS_TO_SHOW] self._list.changed_event = self.__list_changed_evt self._available_events = dict([(evt_type.__name__, evt_type) for evt_type in self.EVENTS_TO_SHOW]) self.__list_changed_evt() def __refresh_evt(self): """Clears the entire timeline and re-draws all the checked events from T = 0 """ self._events.clear() self._history_index = 0 self.read_message_queue() def __list_changed_evt(self): self._events_2_draw = tuple([ self._available_events[event_name] for event_name in self._list.value ] + [SessionInfo]) def __toggle_events_to_show_evt(self): if self._list.visible: self._list.hide() else: self._list.show() def show(self): # Prevent the call to be recursive because of the mdi_area if hasattr(self, '_show_called'): BaseWidget.show(self) return self._show_called = True self.mainwindow.mdi_area += self del self._show_called self._stop = False # flag used to close the gui in the middle of a loading self.read_message_queue() if not self._stop: self._timer.start(conf.TIMELINE_PLUGIN_REFRESH_RATE) def hide(self): self._timer.stop() self._stop = True def before_close_event(self): self._timer.stop() self._stop = True self.session.trialsplot_action.setEnabled(True) def __add_event(self, start_timestamp, end_timestamp, track_id, name): self._last_event = self._events.add_event( start_timestamp, end_timestamp, track=track_id, title=name, color=self._list_of_states_colors[track_id % len( self._list_of_states_colors)]) self._events.value = start_timestamp def timediff_ms(self, time_f, time_i): diff = datetime_now.now() diff = time_f - time_i elapsed_ms = (diff.days * 86400000) + \ (diff.seconds * 1000) + (diff.microseconds / 1000) return elapsed_ms def read_message_queue(self): """ Update board queue and retrieve most recent messages """ try: recent_history = self.session.messages_history[self. _history_index:] for message in recent_history: if self._stop: return if not isinstance(message, self._events_2_draw): continue if isinstance(message, StateOccurrence): if message.state_name not in self._states_names.keys(): self._states_names[message.state_name] = len( self._states_names) if not (math.isnan(message.start_timestamp) or math.isnan(message.end_timestamp)): bpod_start = int(round(message.start_timestamp * 1000)) bpod_end = int(round(message.end_timestamp * 1000)) self.__add_event( bpod_start, bpod_end, self._states_names[message.state_name], message.state_name) elif isinstance(message, SessionInfo): if message.content == 'SESSION-STARTED': self._session_start_timestamp = message.pc_timestamp elif isinstance(message, EventOccurrence): ts = None # in case we don't find any valid timestamp, don't add the event to the timeline # check which timestamp will be used. host timestamp wins over pc timestamp if message.pc_timestamp is not None: ts = self.timediff_ms(message.pc_timestamp, self._session_start_timestamp) # proceed if we have a valid timestamp if ts is not None: # create a new event slot in the timeline in case current message is entirely new if message.event_name not in self._states_names.keys(): self._states_names[message.event_name] = len( self._states_names) # add a time delta to ts so the event can be shown in the timeline self.__add_event( ts - 10, ts + 10, self._states_names[message.event_name], message.event_name) self._history_index += 1 QEventLoop() except RunSetupError as err: logger.error(str(err), exc_info=True) self._timer.stop() @property def mainwindow(self): return self.session.mainwindow @property def title(self): return BaseWidget.title.fget(self) @title.setter def title(self, value): title = 'Trials-plot: {0}'.format(value) BaseWidget.title.fset(self, title)
class ObjectsDialog(Dialog, BaseWidget): def __init__(self, parent_win=None, title='Objects selector'): BaseWidget.__init__(self, title, parent_win=parent_win) self._objects_filter = None self._videos = ControlCheckBoxList('Videos filter') self._objects = ControlCheckBoxList('Objects filter') self._videos.add_popup_menu_option('Select video', self.__selection_changed_event) Dialog.__init__(self) self.formset = [('_videos', '||', '_objects')] self._videos.selection_changed_event = self.__selection_changed_event self._videos.changed_event = self.update_objects self._objects.changed_event = self.__objects_changed_event ##################################################################### ### PRIVATE FUNCTIONS ############################################### ##################################################################### def __selection_changed_event(self): self.video_selection_changed_event() def __objects_changed_event(self): self.objects_changed_event() ##################################################################### ### EVENTS ########################################################## ##################################################################### def video_selection_changed_event(self): pass def objects_changed_event(self): pass ##################################################################### ### FUNCTIONS ####################################################### ##################################################################### # used to update automaticly the name of the videos, objects and paths def refresh(self): self._videos.refresh() self._objects.refresh() def __add__(self, other): if isinstance(other, Video): self._videos += (other, False) if isinstance(other, VideoObject): self.update_objects() return self def __sub__(self, other): if isinstance(other, Video): self._videos -= other self.update_objects() if isinstance(other, VideoObject): self.update_objects() return self def update_objects(self): """ Update the objects in the list """ objects = [elem for elem, checked in self._objects.items] objects_list = [] for video, checked in self._videos.items: for obj in video.objects: if self._objects_filter and not self._objects_filter(obj): continue objects_list.append(obj) if not checked and obj in objects: self._objects -= obj elif checked and obj not in objects: self._objects += (obj, False) for obj in objects: if obj not in objects_list: self._objects -= obj ##################################################################### ### PROPERTIES ###################################################### ##################################################################### @property def objects(self): return self._objects.value @property def selected_video(self): ########################################### # current mouse selected video ########################################### index = self._videos.selected_row_index if index < 0: return None video, selected = self._videos.items[index] return video @property def selected_data(self): videos = self._videos.value objects = self._objects.value res = [] for video in videos: objects_list = [] for obj in video.objects: if obj in objects: objects_list.append(obj) res.append((video, objects_list)) return res @property def objects_filter(self): return self._objects_filter @objects_filter.setter def objects_filter(self, value): self._objects_filter = value
def __init__(self, parent=None): super(ContoursImagesWindow, self).__init__('Contour images', parent_win=parent) self.mainwindow = parent self.set_margin(5) self.setMinimumHeight(400) self.setMinimumWidth(800) self._contourspanel = ControlEmptyWidget('Contours datasets') self._progress = ControlProgress('Progress', visible=False) self._apply = ControlButton('Apply', checkable=True) self._toolbox = ControlToolBox('Toolbox') self._exportdir = ControlDir('Export images to folder', default='images-from-contour') #### mask ###################################################### self._usemaskimg = ControlCheckBox('Apply a mask to the image') self._usemaskdilate = ControlCheckBox('Dilate the mask and apply it to the image') self._maskdilatesize = ControlSlider('Dilate size', default=0, minimum=0, maximum=100) self._usemaskellipse = ControlCheckBox('Apply the min. ellipse as a mask to the image') self._usemaskcircular = ControlCheckBox('Apply a circular mask to the image') self._maskcircularsize = ControlSlider('Circular radius', default=0, minimum=0, maximum=100) self._usemaskrect = ControlCheckBox('Apply the min. rect as a mask to the image') ################################################################ #### margin #################################################### self._margin = ControlSlider('Margin size', default=0, minimum=0, maximum=100) ################################################################ #### imagesize ################################################# self._imagesize = ControlSlider('Image size', default=0, minimum=0, maximum=400) ################################################################ #### cut ####################################################### self._usecut = ControlCheckBox('Cut image') self._cutx = ControlBoundingSlider('X cut', default=(10,30), minimum=0, maximum=1000) self._cuty = ControlBoundingSlider('Y cut', default=(10,30), minimum=0, maximum=1000) ################################################################ #### use stretch ############################################### self._usestretch = ControlCheckBox('Stretch image') ################################################################ #### filter per events ######################################### self._eventslst = ControlCheckBoxList('Events', enabled=True) self._reloadevts = ControlButton('Reload events', enabled=True, default=self.__reload_events_btn_evt) ################################################################ #### rotation ################################################## self._userotup = ControlCheckBox('Turn the contour always up') self._userotdown = ControlCheckBox('Turn the contour always down') self._usefixedangle = ControlCheckBox('Use a fixed orientation') self._fixedangle = ControlSlider('Rotate the images using a fixed angle', enabled=True, default=0, minimum=0, maximum=360) self._usedatasetangle = ControlCheckBox('Use the orientation of other contour') self._datasetanglepanel = ControlEmptyWidget('Datasets for the orientation', enabled=True) ################################################################ #### image position ############################################ self._useposdataset = ControlCheckBox('Use a dataset to center the image') self._datasetpospanel = ControlEmptyWidget('Datasets for the image position', enabled=True) ################################################################ self.formset = [ '_toolbox', '_exportdir', '_apply', '_progress' ] self.load_order = [ '_contourspanel','_userotup', '_userotdown', '_exportdir','_usemaskimg','_usemaskdilate','_usemaskellipse','_usemaskellipse', '_usemaskcircular', '_maskcircularsize', '_usemaskrect', '_margin', '_imagesize', '_usestretch', '_eventslst', '_usefixedangle', '_fixedangle', '_usedatasetangle', '_datasetanglepanel', '_useposdataset', '_datasetpospanel', '_usecut', '_cuty', '_cutx' ] #datasets painel self.datasets_dialog = DatasetsDialog(self) self.datasets_dialog.datasets_filter = lambda x: isinstance(x, Contours ) self._contourspanel.value = self.datasets_dialog self.posdatasets_dialog = DatasetsDialog(self) self.posdatasets_dialog.datasets_filter = lambda x: isinstance(x, (Contours,Path) ) self._datasetpospanel.value = self.posdatasets_dialog self.orientdatasets_dialog = DatasetsDialog(self) self.orientdatasets_dialog.datasets_filter = lambda x: isinstance(x, Contours ) self.orientdatasets_dialog.interval_visible = False self._datasetanglepanel.value = self.orientdatasets_dialog self._apply.value = self.__apply_event self._apply.icon = conf.ANNOTATOR_ICON_PATH self._imagesize.changed_event = self.__image_size_changed_evt self._toolbox.value = [ ('Extract from contours',( self.datasets_dialog, )), ('Mask',( self._usemaskimg, (self._usemaskdilate,self._maskdilatesize), (self._usemaskcircular,self._maskcircularsize), (self._usemaskellipse,self._usemaskrect), )), ('Margin, image size and stretch image',( self._usestretch, self._margin, self._imagesize, self._usecut, self._cutx, self._cuty )), ('Rotate images',( (self._userotup, self._userotdown), (self._usefixedangle, self._fixedangle), self._usedatasetangle, self._datasetanglepanel )), ('Center images',( self._useposdataset, self._datasetpospanel, )), ('Export images per events',( self._reloadevts, self._eventslst, )), ] self.__reload_events_btn_evt() self.__image_size_changed_evt()