def _initialize(self, ): assert len(self.input.params['shape']) == 2, 'Are you joking ?' self.sample_rate = sr = self.input.params['sample_rate'] self.nb_channel = self.input.params['shape'][1] buf_size = int(self.input.params['sample_rate'] * self.max_xsize) # channel names channel_info = self.inputs['signals'].params.get('channel_info', None) if channel_info is None: self.channel_names = [ 'ch{}'.format(c) for c in range(self.nb_channel) ] else: self.channel_names = [ch_info['name'] for ch_info in channel_info] # create proxy input to ensure sharedarray with time axis 1 if self.input.params['transfermode'] == 'sharedmem' and self.input.params['axisorder'] is not None \ and tuple(self.input.params['axisorder']) == (1,0): self.conv = None # TODO raise here else: # if input is not transfermode creat a proxy if self.local_workers: self.conv = StreamConverter() else: ng = self.nodegroup_friends[-1] self.conv = ng.create_node('StreamConverter') self.conv.ng_proxy = ng self.conv.configure() # the inputstream is not needed except for parameters input_spec = dict(self.input.params) self.conv.input.connect(input_spec) self.conv.output.configure( protocol='tcp', interface='127.0.0.1', port='*', dtype='float32', transfermode='sharedmem', streamtype='analogsignal', buffer_size=buf_size, axisorder=[1, 0], shape=(-1, self.nb_channel), double=True, fill=0, ) self.conv.initialize() self.workers = [] self.input_maps = [] #~ self.global_poller = ThreadPollInput(input_stream=self.input, return_data=None) # only valid when no conv self.global_poller = ThreadPollOutput(output_stream=self.conv.output, return_data=False) self.global_timer = QtCore.QTimer(interval=500) self.global_timer.timeout.connect(self.compute_maps) if not self.local_workers: self.map_pollers = [] for i in range(self.nb_channel): # create worker if self.local_workers: worker = TimeFreqWorker() else: ng = self.nodegroup_friends[i % max( len(self.nodegroup_friends) - 1, 1)] worker = ng.create_node('TimeFreqWorker') worker.ng_proxy = ng worker.configure(channel=i, local=self.local_workers) worker.input.connect(self.conv.output) if self.local_workers: protocol = 'inproc' else: protocol = 'tcp' worker.output.configure(protocol=protocol, transfermode='plaindata') worker.initialize() self.workers.append(worker) # socket stream for maps from worker input_map = InputStream() out_params = worker.output.params if not isinstance(out_params, dict): # worker is remote; request attribute from remote process. out_params = out_params._get_value() else: # copy to prevent modification out_params = dict(out_params) stream_spec = out_params input_map.connect(worker.output) self.input_maps.append(input_map) if self.local_workers: worker.wt_map_done.connect(self.on_new_map_local) else: poller = ThreadPollInput(input_stream=input_map, return_data=True) poller.new_data.connect(self.on_new_map_socket) poller.chan = i self.map_pollers.append(poller) # This is used to diffred heavy action whena changing params (setting plots, compute wavelet, ...) # this avoid overload on CPU if multiple changes occurs in a short time self.mutex_action = Mutex() self.actions = OrderedDict([ (self.create_grid, False), (self.initialize_time_freq, False), (self.initialize_plots, False), ]) self.timer_action = QtCore.QTimer(singleShot=True, interval=300) self.timer_action.timeout.connect(self.apply_actions) # Create parameters all = [] for i in range(self.nb_channel): by_chan_p = [{ 'name': 'label', 'type': 'str', 'value': self.channel_names[i], 'readonly': True }] + list(self._default_by_channel_params) all.append({ 'name': 'ch{}'.format(i), 'type': 'group', 'children': by_chan_p }) self.by_channel_params = pg.parametertree.Parameter.create( name='AnalogSignals', type='group', children=all) self.params = pg.parametertree.Parameter.create( name='Global options', type='group', children=self._default_params) self.all_params = pg.parametertree.Parameter.create( name='all param', type='group', children=[self.params, self.by_channel_params]) self.params.param('xsize').setLimits([16. / sr, self.max_xsize * .95]) self.all_params.sigTreeStateChanged.connect(self.on_param_change) if self.with_user_dialog: self.params_controller = TimeFreqController(parent=self, viewer=self) self.params_controller.setWindowFlags(QtCore.Qt.Window) else: self.params_controller = None self.create_grid() self.initialize_time_freq() self.initialize_plots()
def __init__(self): super(FractalWidget, self).__init__() self.xsize, self.ysize = 1024, 1024 self.xmin, self.xmax = -2, 1 self.ymin, self.ymax = -1.5, 1.5 self.maxit, self.col = 200, 200 self.moveSpeed = 6 self.zoomSpeed = 1.06667 # Array to hold iteration count for each pixel self.data = np.zeros(self.xsize * self.ysize, dtype=np.int32) # Add view box view = self.addViewBox(lockAspect=True, enableMouse=False, enableMenu=False, invertY=True) # Create image item self.ip = pg.ImageItem(border='w') lut = generate_lut(color_map=get_color_map( os.path.dirname(os.path.abspath(__file__)) + '/../viridis')) self.ip.setLookupTable(lut, update=False) self.createFractal() view.addItem(self.ip) # Create TextItem to display fps and coordinates self.ti = pg.TextItem() self.ti.setPos(10, self.ysize) view.addItem(self.ti) # Connect mouse click event to function mouseEvent self.scene().sigMouseClicked.connect(self.mouseEvent) # Dictionary with functions to call at keypress self.staticKeyList = {QtCore.Qt.Key_R: self.createFractal} # Functions which get continuously called at keypress self.movementKeyList = { QtCore.Qt.Key_E: self.zoomIn, QtCore.Qt.Key_Q: self.zoomOut, QtCore.Qt.Key_A: self.moveL, QtCore.Qt.Key_D: self.moveR, QtCore.Qt.Key_S: self.moveD, QtCore.Qt.Key_W: self.moveU } # A set of currently pressed keys self.pressedKeys = set() # Timer which calls update function at const framerate self.tickRate = 1000 / 30 self.timer = QtCore.QTimer() self.timer.start(self.tickRate) self.timer.timeout.connect(self.move) self.timer.timeout.connect(self.renderText) # Init fps counter self.fps = 1000 / self.tickRate self.lastTime = time() self.timer.timeout.connect(self.fpsCounter)
def animation(self): timer = QtCore.QTimer() timer.timeout.connect(self.update) timer.start() self.start()
def __init__(self): # --------------------------------------------------------------------- # # --------------------------------------------------------------------- QtGui.QMainWindow.__init__(self) self.setWindowTitle('Test application') # --------------------------------------------------------------------- # # --------------------------------------------------------------------- parentWidget = QtGui.QWidget() vbox_gr = QtGui.QGridLayout() vbox_ui = QtGui.QVBoxLayout() hbox = QtGui.QHBoxLayout() hbox.addLayout(vbox_ui) hbox.addLayout(vbox_gr) parentWidget.setLayout(hbox) self.setCentralWidget(parentWidget) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- logoGBox = QtGui.QGroupBox() logoGBoxLayout = QtGui.QGridLayout() logoGBox.setLayout(logoGBoxLayout) logoGBox.setMaximumWidth(MINIMUM_WIDTH) logoGBox.setMinimumWidth(MINIMUM_WIDTH) # --------------------------------------------------------------------- label = QtGui.QLabel() pixmap = QtGui.QPixmap('logo.png') label.setPixmap(pixmap) logoGBoxLayout.addWidget(label) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- infoGBox = QtGui.QGroupBox("General info") infoGBoxLayout = QtGui.QGridLayout() infoGBox.setLayout(infoGBoxLayout) infoGBox.setMinimumWidth(MINIMUM_WIDTH) infoGBox.setMaximumWidth(MINIMUM_WIDTH) # --------------------------------------------------------------------- self.val0_label = QtGui.QLabel("...") infoGBoxLayout.addWidget(QtGui.QLabel("Val0: "), 0, 0) infoGBoxLayout.addWidget(self.val0_label, 0, 1, 1, 7) # --------------------------------------------------------------------- self.val1_label = QtGui.QLabel("...") infoGBoxLayout.addWidget(QtGui.QLabel("Val1: "), 1, 0) infoGBoxLayout.addWidget(self.val1_label, 1, 1, 1, 7) # --------------------------------------------------------------------- self.val2_label = QtGui.QLabel("...") infoGBoxLayout.addWidget(QtGui.QLabel("Val2: "), 2, 0) infoGBoxLayout.addWidget(self.val2_label, 2, 1, 1, 7) # --------------------------------------------------------------------- resetGraphButton = QtGui.QPushButton("Reset graph") infoGBoxLayout.addWidget(resetGraphButton, 3, 0, 1, 8) resetGraphButton.clicked.connect(self.resetGraphButtonAction) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- valIncControlGBox = QtGui.QGroupBox("Value increment adjustment") valIncControlGBoxLayout = QtGui.QGridLayout() valIncControlGBox.setLayout(valIncControlGBoxLayout) valIncControlGBox.setMaximumWidth(MINIMUM_WIDTH) valIncControlGBox.setMinimumWidth(MINIMUM_WIDTH) # --------------------------------------------------------------------- self.valIncControl_val0 = QtGui.QDoubleSpinBox() self.valIncControl_val0.setRange(0, 100000000) self.valIncControl_val0.setSingleStep(1) self.valIncControl_val0.setValue(100) self.valIncControl_val0.setDecimals(0) self.valIncControl_val0.setKeyboardTracking(False) valIncControlGBoxLayout.addWidget(QtGui.QLabel("Val0 Increment: "), 0, 0) valIncControlGBoxLayout.addWidget(self.valIncControl_val0, 0, 1, 1, 6) # --------------------------------------------------------------------- self.valIncControl_val1 = QtGui.QDoubleSpinBox() self.valIncControl_val1.setRange(0, 100000000) self.valIncControl_val1.setSingleStep(1) self.valIncControl_val1.setValue(200) self.valIncControl_val1.setDecimals(0) self.valIncControl_val1.setKeyboardTracking(False) valIncControlGBoxLayout.addWidget(QtGui.QLabel("Val1 Increment: "), 1, 0) valIncControlGBoxLayout.addWidget(self.valIncControl_val1, 1, 1, 1, 6) # --------------------------------------------------------------------- self.valIncControl_val2 = QtGui.QDoubleSpinBox() self.valIncControl_val2.setRange(0, 100000000) self.valIncControl_val2.setSingleStep(1) self.valIncControl_val2.setValue(300) self.valIncControl_val2.setDecimals(0) self.valIncControl_val2.setKeyboardTracking(False) valIncControlGBoxLayout.addWidget(QtGui.QLabel("Val2 Increment: "), 2, 0) valIncControlGBoxLayout.addWidget(self.valIncControl_val2, 2, 1, 1, 6) # --------------------------------------------------------------------- self.valIncControl_val0.valueChanged.connect(self.updateValIncrements) self.valIncControl_val1.valueChanged.connect(self.updateValIncrements) self.valIncControl_val2.valueChanged.connect(self.updateValIncrements) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- vbox_ui.addWidget(logoGBox) vbox_ui.addWidget(infoGBox) vbox_ui.addWidget(valIncControlGBox) vbox_ui.addStretch(1) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- self.plot1 = pg.PlotWidget() self.plot2 = pg.PlotWidget() self.plot3 = pg.PlotWidget() self.plot4 = pg.PlotWidget() # --------------------------------------------------------------------- self.plot1.setLabel('bottom', 'time(sec)') self.plot2.setLabel('bottom', 'time(sec)') self.plot3.setLabel('bottom', 'time(sec)') self.plot4.setLabel('bottom', 'time(sec)') self.plot1.setLabel('left', '...') self.plot2.setLabel('left', '...') self.plot3.setLabel('left', '...') self.plot4.setLabel('left', '...') # --------------------------------------------------------------------- self.plot1.setTitle("Test Value 0") self.plot2.setTitle("Test Value 1") self.plot3.setTitle("Test Value 2") self.plot4.setTitle("Test Values Combined") # --------------------------------------------------------------------- # # --------------------------------------------------------------------- vbox_gr.addWidget(self.plot1, 0, 0) vbox_gr.addWidget(self.plot2, 0, 1) vbox_gr.addWidget(self.plot3, 1, 0) vbox_gr.addWidget(self.plot4, 1, 1) # --------------------------------------------------------------------- self.plot1_curve1 = pg.PlotCurveItem(pen=(1, 1)) self.plot1.addItem(self.plot1_curve1) # --------------------------------------------------------------------- self.plot2_curve1 = pg.PlotCurveItem(pen=(1, 2)) self.plot2.addItem(self.plot2_curve1) # --------------------------------------------------------------------- self.plot3_curve1 = pg.PlotCurveItem(pen=(1, 3)) self.plot3.addItem(self.plot3_curve1) # --------------------------------------------------------------------- self.plot4_curve1 = pg.PlotCurveItem(pen=(1, 1)) self.plot4_curve2 = pg.PlotCurveItem(pen=(1, 2)) self.plot4_curve3 = pg.PlotCurveItem(pen=(1, 3)) self.plot4.addItem(self.plot4_curve1) self.plot4.addItem(self.plot4_curve2) self.plot4.addItem(self.plot4_curve3) # --------------------------------------------------------------------- pg.setConfigOptions(antialias=True) # --------------------------------------------------------------------- # # --------------------------------------------------------------------- self.timer = QtCore.QTimer() self.timer.timeout.connect(self.PeriodicFunc) self.timer.start(33)
def animation(self): timer = QtCore.QTimer() timer.timeout.connect(self.update) timer.start(10) QtGui.QApplication.instance().exec_()
def __init__(self): self.width = 1000 self.high = 1000 self.console_high = 150 self.plot_high = self.high - self.console_high self.console_size = (self.width, self.console_high) self.plot_size = (self.width, self.plot_high) self.app = QtGui.QApplication([]) self.win = QtGui.QMainWindow() self.area = DockArea() self.win.setCentralWidget(self.area) self.win.resize(self.width, self.high) self.win.setWindowTitle('Gimbal Monitor') self.timer_dt = 50 pg.setConfigOptions(antialias=True) pg.setConfigOption('background', [0, 0, 0]) pg.setConfigOption('foreground', [255, 255, 255, 100]) # Dock self.d_console = self.dock4console('Console') self.d_controller_state = self.dock4plot('Controller State') self.d_motors_state = self.dock4plot('Motors State') self.d_controller_config = self.dock4plot('Controller Config') self.d_motors_config = self.dock4plot('Motor Config') self.d_imu_attitude = Dock('IMU Attitude', size=(1000, self.plot_high), closable=True) #self.d_imu_attitude.show() self.area.addDock(self.d_console, 'bottom') self.area.addDock(self.d_controller_state, 'top') self.area.addDock(self.d_motors_state, 'top') self.area.addDock(self.d_controller_config, 'top') self.area.addDock(self.d_motors_config, 'top') self.area.addDock(self.d_imu_attitude, 'top') self.area.moveDock(self.d_motors_state, 'above', self.d_controller_state) self.area.moveDock(self.d_controller_config, 'above', self.d_motors_state) self.area.moveDock(self.d_motors_config, 'above', self.d_controller_config) self.area.moveDock(self.d_imu_attitude, 'right', self.d_controller_state) # Controller State Layout self.pen_width = 2 self.fill_beta = 70 self.pen_red = pg.mkPen('F00', width=self.pen_width) self.pen_green = pg.mkPen('0F0', width=self.pen_width) self.pen_blue = pg.mkPen('0AF', width=self.pen_width) self.fill_red = [255, 0, 0, self.fill_beta] self.fill_green = [0, 255, 0, self.fill_beta] self.fill_blue = [0, 200, 255, self.fill_beta] self.imu_angle_time_len = 200 self.imu_angle_data = np.zeros((3, self.imu_angle_time_len)) self.imu_angle_v_data = np.zeros((3, self.imu_angle_time_len)) self.w_controller_state = pg.LayoutWidget() self.p_attitude = pg.PlotWidget(title="Camera Attitude") self.p_angle_v = pg.PlotWidget(title="Angle Velocity") self.p_attitude.showGrid(x=True, y=True) self.p_angle_v.showGrid(x=True, y=True) self.curve_roll = self.p_attitude.plot(self.imu_angle_data[0], pen=self.pen_red, fillLevel=0, brush=self.fill_red) self.curve_pitch = self.p_attitude.plot(self.imu_angle_data[1], pen=self.pen_green, fillLevel=0, brush=self.fill_green) self.curve_yaw = self.p_attitude.plot(self.imu_angle_data[2], pen=self.pen_blue, fillLevel=0, brush=self.fill_blue) self.curve_roll_v = self.p_angle_v.plot(self.imu_angle_v_data[0], pen=self.pen_red, fillLevel=0, brush=self.fill_red) self.curve_pitch_v = self.p_angle_v.plot(self.imu_angle_v_data[1], pen=self.pen_green, fillLevel=0, brush=self.fill_green) self.curve_yaw_v = self.p_angle_v.plot(self.imu_angle_v_data[2], pen=self.pen_blue, fillLevel=0, brush=self.fill_blue) self.time_remain = 6 self.angle_max = 100 self.angle_v_max = 1000 self.text_interval = self.angle_max * 0.12 self.text_interval_v = self.angle_v_max * 0.12 self.angle_text_max_y = self.angle_max * 1.12 self.angle_v_text_max_y = self.angle_v_max * 1.12 self.p_attitude.setXRange(0 - self.time_remain, self.imu_angle_time_len + self.time_remain) self.p_attitude.setYRange(-100, 100) self.p_angle_v.setXRange(0 - self.time_remain, self.imu_angle_time_len + self.time_remain) self.p_angle_v.setYRange(-1000, 1000) self.t_roll_angle = pg.TextItem() self.t_roll_angle.setText('roll: %0.1f' % (0), [255, 0, 0, 200]) self.t_roll_angle.setPos(0, self.angle_text_max_y) self.p_attitude.addItem(self.t_roll_angle) self.t_pitch_angle = pg.TextItem() self.t_pitch_angle.setText('pitch: %0.1f' % (0), [0, 255, 0, 200]) self.t_pitch_angle.setPos(0, self.angle_text_max_y - self.text_interval) self.p_attitude.addItem(self.t_pitch_angle) self.t_yaw_angle = pg.TextItem() self.t_yaw_angle.setText('yaw: %0.1f' % (0), [0, 200, 255, 230]) self.t_yaw_angle.setPos(0, self.angle_text_max_y - 2 * self.text_interval) self.p_attitude.addItem(self.t_yaw_angle) self.t_roll_angle_v = pg.TextItem() self.t_roll_angle_v.setText('roll: %0.1f' % (0), [255, 0, 0, 200]) self.t_roll_angle_v.setPos(0, self.angle_v_text_max_y) self.p_angle_v.addItem(self.t_roll_angle_v) self.t_pitch_angle_v = pg.TextItem() self.t_pitch_angle_v.setText('pitch: %0.1f' % (0), [0, 255, 0, 200]) self.t_pitch_angle_v.setPos( 0, self.angle_v_text_max_y - self.text_interval_v) self.p_angle_v.addItem(self.t_pitch_angle_v) self.t_yaw_angle_v = pg.TextItem() self.t_yaw_angle_v.setText('yaw: %0.1f' % (0), [0, 200, 255, 230]) self.t_yaw_angle_v.setPos( 0, self.angle_v_text_max_y - 2 * self.text_interval_v) self.p_angle_v.addItem(self.t_yaw_angle_v) self.w_controller_state.addWidget(self.p_attitude, row=0, col=0) self.w_controller_state.addWidget(self.p_angle_v, row=1, col=0) self.d_controller_state.addWidget(self.w_controller_state, row=0, col=1) self.timer_controller_state = QtCore.QTimer() self.timer_controller_state.timeout.connect( self.controller_state_update) # Motors State Layout self.motors_state_time_len = 200 self.ntc_tempre_data = np.zeros((3, self.motors_state_time_len)) self.input_current_data = np.zeros((3, self.motors_state_time_len)) self.motor_current_data = np.zeros((3, self.motors_state_time_len)) self.input_v_data = np.zeros((3, self.motors_state_time_len)) self.duty_cycle_now_data = np.zeros((3, self.motors_state_time_len)) self.rpm_data = np.zeros((3, self.motors_state_time_len)) self.tacho_data = np.zeros((3, self.motors_state_time_len)) self.tacho_abs_data = np.zeros((3, self.motors_state_time_len)) self.w_motors_state = pg.LayoutWidget() self.p_ntc_tempre = pg.PlotWidget() self.p_current = pg.PlotWidget() self.p_input_v = pg.PlotWidget() self.p_duty_cycle_now = pg.PlotWidget() self.p_rpm = pg.PlotWidget() self.p_tacho = pg.PlotWidget() self.p_tach_abs = pg.PlotWidget() self.p_ntc_tempre.showGrid(True) self.p_current.showGrid(True) self.p_input_v.showGrid(True) self.p_duty_cycle_now.showGrid(True) self.p_rpm.showGrid(True) self.p_tacho.showGrid(True) self.p_tach_abs.showGrid(True) self.curve_ntc_tempre = self.p_ntc_tempre.plot(self.ntc_tempre_data[0], pen=self.pen_blue, fillLevel=0, brush=self.fill_blue) self.curve_input_current = self.p_current.plot( self.input_current_data[0], pen=self.pen_) # IMU Attitude OpenGL Layout self.vr_layout = pg.LayoutWidget() self.w_vr = gl.GLViewWidget() glEnable(GL_LINE_SMOOTH) glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_ALPHA) self.light() glMatrixMode(GL_PROJECTION) glMatrixMode(GL_MODELVIEW) gluPerspective(40., 1., 1., 40.) self.w_vr.opts['distance'] = 40 self.w_vr.opts['azimuth'] = -10 print(self.w_vr.opts) self.w_vr.setWindowTitle('IMU Attitude') #self.w_vr.setCameraPosition(pos=[0, 0, 50],) self.w_vr.show() self.vr_ground = gl.GLGridItem() self.vr_ground.scale(10, 10, 1) self.w_vr.addItem(self.vr_ground) self.cube_width = 20 self.cube_high = self.cube_width * (1 - 0.618) self.verts = np.array([ [self.cube_width / 2, self.cube_width / 2, self.cube_high / 2], [-self.cube_width / 2, self.cube_width / 2, self.cube_high / 2], [-self.cube_width / 2, -self.cube_width / 2, self.cube_high / 2], [self.cube_width / 2, -self.cube_width / 2, self.cube_high / 2], [self.cube_width / 2, self.cube_width / 2, -self.cube_high / 2], [-self.cube_width / 2, self.cube_width / 2, -self.cube_high / 2], [-self.cube_width / 2, -self.cube_width / 2, -self.cube_high / 2], [self.cube_width / 2, -self.cube_width / 2, -self.cube_high / 2], ]) self.face = np.array([ [0, 1, 2], # up [0, 2, 3], [4, 6, 5], # down [4, 7, 6], [0, 3, 7], # front [0, 7, 4], [1, 6, 2], # back [1, 5, 6], [0, 4, 5], # left [0, 5, 1], [2, 6, 7], # right [2, 7, 3], ]) self.alpha = 1 self.c_red = [1, 0, 0, self.alpha] self.c_greed = [0, 1, 0, self.alpha] self.c_blue = [0, 0, 1, self.alpha] self.gray_scale = 0.8 self.c_gray = [ self.gray_scale, self.gray_scale, self.gray_scale, self.alpha ] self.colors = np.array([ self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, self.c_gray, ]) self.cube = gl.GLMeshItem(vertexes=self.verts, faces=self.face, faceColors=self.colors, shader='shaded', drawEdges=True, edgeColor=(1, 1, 1, 1), smooth=False) self.cube.translate(0, 0, 3) self.cube_quat = QQuaternion(1.0, 0.0, 0.0, 0.0) self.cube_mat = self.cube_quat.toRotationMatrix() self.cube_mat_data = self.cube_mat.data() self.cube_transform = pg.Transform3D( self.cube_mat_data[0], self.cube_mat_data[1], self.cube_mat_data[2], 0, self.cube_mat_data[3], self.cube_mat_data[4], self.cube_mat_data[5], 0, self.cube_mat_data[6], self.cube_mat_data[7], self.cube_mat_data[8], 0, 0, 0, 0, 1) self.cube.setTransform(self.cube_transform) self.w_vr.addItem(self.cube) self.d_imu_attitude.addWidget(self.w_vr)
def __init__(self): TemplateBaseClass.__init__(self) # Create the main window self.ui = WindowTemplate() self.ui.setupUi(self) self.ui.runButton.clicked.connect(self.dostartstop) self.ui.actionRecord.triggered.connect(self.record) self.ui.verticalSlider.valueChanged.connect(self.triggerlevelchanged) self.ui.verticalSlider2.valueChanged.connect(self.triggerlevel2changed) self.ui.thresh2Check.clicked.connect(self.thresh2) self.ui.horizontalSlider.valueChanged.connect(self.triggerposchanged) self.ui.rollingButton.clicked.connect(self.rolling) self.ui.singleButton.clicked.connect(self.single) self.ui.timeslowButton.clicked.connect(self.timeslow) self.ui.timefastButton.clicked.connect(self.timefast) self.ui.risingedgeCheck.stateChanged.connect(self.risingfalling) self.ui.exttrigCheck.stateChanged.connect(self.exttrig) self.ui.totBox.valueChanged.connect(self.tot) self.ui.coinBox.valueChanged.connect(self.coin) self.ui.cointimeBox.valueChanged.connect(self.cointime) self.ui.autorearmCheck.stateChanged.connect(self.autorearm) self.ui.noselftrigCheck.stateChanged.connect(self.noselftrig) self.ui.avgCheck.stateChanged.connect(self.avg) self.ui.logicCheck.stateChanged.connect(self.logic) self.ui.highresCheck.stateChanged.connect(self.highres) self.ui.usb2Check.stateChanged.connect(self.usb2) self.ui.gridCheck.stateChanged.connect(self.grid) self.ui.markerCheck.stateChanged.connect(self.marker) self.ui.resampBox.valueChanged.connect(self.resamp) self.ui.upposButton.clicked.connect(self.uppos) self.ui.downposButton.clicked.connect(self.downpos) self.ui.chanBox.valueChanged.connect(self.selectchannel) self.ui.dacBox.valueChanged.connect(self.setlevel) self.ui.minidisplayCheck.stateChanged.connect(self.minidisplay) self.ui.acdcCheck.stateChanged.connect(self.acdc) self.ui.gainCheck.stateChanged.connect(self.gain) self.ui.supergainCheck.stateChanged.connect(self.supergain) self.ui.actionRead_from_file.triggered.connect( self.actionRead_from_file) self.ui.actionStore_to_file.triggered.connect(self.actionStore_to_file) self.ui.actionOutput_clk_left.triggered.connect( self.actionOutput_clk_left) self.ui.actionAllow_same_chan_coin.triggered.connect( self.actionAllow_same_chan_coin) self.ui.actionDo_autocalibration.triggered.connect( self.actionDo_autocalibration) self.ui.chanonCheck.stateChanged.connect(self.chanon) self.ui.slowchanonCheck.stateChanged.connect(self.slowchanon) self.ui.trigchanonCheck.stateChanged.connect(self.trigchanon) self.ui.oversampCheck.clicked.connect(self.oversamp) self.ui.overoversampCheck.clicked.connect(self.overoversamp) self.ui.decodeCheck.clicked.connect(self.decode) self.ui.fftCheck.clicked.connect(self.fft) self.ui.persistCheck.clicked.connect(self.persist) self.ui.drawingCheck.clicked.connect(self.drawing) self.db = False self.lastTime = time.time() self.fps = None self.lines = [] self.otherlines = [] self.savetofile = False # save scope data to file self.doh5 = True # use the h5 binary file format self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updateplot) self.timer2 = QtCore.QTimer() self.timer2.timeout.connect(self.drawtext) self.selectchannel() self.ui.statusBar.showMessage("Hello!") self.ui.plot.setBackground('w') self.show()
def setTimer(self): self._timer = QtCore.QTimer() self._timer.timeout.connect(self.update) self._timer.start(200) # fps 15
def setTimer(self): self._timer = QtCore.QTimer() self._timer.timeout.connect(self.update) self._timer.start(60) # call plot update func every 60ms
app.setQuitOnLastWindowClosed(False) print('before physics') rospy.init_node("simulator") max_range = 200.0 rospy.set_param("/carbon/maxrange", str(max_range)) psim = physics_sim() signal.signal(signal.SIGINT, psim.ctrl_c_reset) thread_physics = Thread(target=psim.start, args=(Tsample_physics, quadcopterId, qcc)) # start the thread: thread_physics.start() #print('after physics') # the graphics window is updated every Tsample_window seconds # using a timer function from the Qt GUI part of pyqtgraph # this also runs in the background, but at a much lower speed than # the physics and control updates. #print('a') timer_window = QtCore.QTimer() #print('b') timer_window.timeout.connect(update_window) #print('c') timer_window.start() #print('d') # END # Tips for using: print('qcc errorpos', qcc.error_pos, ' dk ', qcc.z_ctrl.Kp) #qcc.ref_pos = np.array([0,0,1]) QtGui.QApplication.instance().exec_()
p6 = win.addPlot(title="Updating plot") curve = p6.plot(pen='y') ptr = 0 count = 0 data = conn.recv(1024) otr = 0 def update(): global curve, data, ptr if len(data) != 0: data = struct.unpack( '>200h', data ) # '>200' is for recieveing 200 short signed point in big-endian form source:https://docs.python.org/3.0/library/struct.html curve.setData(data) data = conn.recv(1024) print(ptr) ptr += 1 timer1 = QtCore.QTimer() timer1.timeout.connect(update) timer1.start(10) # you can change this refreshment time if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') pg.setConfigOptions(antialias=True) uic.loadUi(pkg_resources.resource_filename(__name__, "sysmonitor.ui"), self) self.len_data = 60 self.cpu_curve = [] self.mem_curve = [] self.gpu_curve = [] self.net_curve = [] self.disk_curve = [] self.ti = [] self.ti_net = [] self.ti_disk = [] self.wait_time_ms = 1000 self.s = sysinfo() self.meminfo = np.zeros([self.len_data, 2]) self.netinfo = np.zeros([self.len_data, 2, self.s.amount_net_adater]) self.diskinfo = np.zeros([self.len_data, 2, self.s.amount_disks]) self.cpuinfo = np.zeros([self.len_data, self.s.cpu_core_count + 1]) self.x = np.linspace(-self.len_data * self.wait_time_ms / 1000, 0, num=self.len_data, endpoint=True) self.label_8.setText(self.s.cpu_model_name) self.plot_meminfo() self.plot_cpuinfo() self.plot_netinfo() self.plot_diskinfo() self.headertitle = ('USER', 'PID', 'CPU [%]', 'MEM [%]', 'START', 'TIME', 'COMMAND') self.tableWidget.verticalHeader().setVisible(False) self.tableWidget.horizontalHeader().setHighlightSections(False) header = self.tableWidget.horizontalHeader() header.setResizeMode(QtGui.QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setResizeMode(False) self.tableWidget.setSelectionBehavior( QtGui.QAbstractItemView.SelectRows) self.tableWidget.setShowGrid(False) self.update_running_processes() self.timer_4 = QtCore.QTimer() self.timer_4.timeout.connect(self.update_running_processes) self.timer_4.start(self.wait_time_ms) if self.s.nvidia_installed == 1: self.gpu_widgets = [] self.gpuinfo = np.zeros([self.len_data, 4, self.s.gpu_num]) for gpu_ind in range(self.s.gpu_num): tab_widgets = [] # first set vertical alignment of tab tab = QtWidgets.QWidget() self.tabWidget.addTab(tab, self.s.gpu_name[gpu_ind]) vbox = QtGui.QVBoxLayout(tab) # then add widgets in horizontal layout widget_1 = QtWidgets.QWidget() widget_2 = QtWidgets.QWidget() widget_3 = QtWidgets.QWidget() widget_4 = QtWidgets.QWidget() widget_5 = QtWidgets.QWidget() vbox.addWidget(widget_1) vbox.addWidget(widget_2) vbox.addWidget(widget_3) vbox.addWidget(widget_4) vbox.addWidget(widget_5) hbox_1 = QtGui.QGridLayout(widget_1) hbox_2 = QtGui.QGridLayout(widget_2) hbox_3 = QtGui.QGridLayout(widget_3) hbox_4 = QtGui.QGridLayout(widget_4) hbox_5 = QtGui.QGridLayout(widget_5) label_1 = QtGui.QLabel("Gpu:") label_1_sub = QtGui.QLabel("% over 60 seconds") label_1_sub.setFont(QtGui.QFont('Ubuntu', 7)) label_2 = QtGui.QLabel("Memory:") label_2_sub = QtGui.QLabel("% over 60 seconds") label_2_sub.setFont(QtGui.QFont('Ubuntu', 7)) label_3 = QtGui.QLabel("Encoder:") label_3_sub = QtGui.QLabel("% over 60 seconds") label_3_sub.setFont(QtGui.QFont('Ubuntu', 7)) label_4 = QtGui.QLabel("Decoder:") label_4_sub = QtGui.QLabel("% over 60 seconds") label_4_sub.setFont(QtGui.QFont('Ubuntu', 7)) label_5 = QtGui.QLabel("Gpu clock:") label_6 = QtGui.QLabel("Memory clock:") hbox_1.addWidget(label_1, 1, 1) hbox_1.addWidget(label_2, 1, 2) hbox_1.addWidget(label_1_sub, 2, 1) hbox_1.addWidget(label_2_sub, 2, 2) hbox_3.addWidget(label_3, 1, 1) hbox_3.addWidget(label_4, 1, 2) hbox_3.addWidget(label_3_sub, 2, 1) hbox_3.addWidget(label_4_sub, 2, 2) hbox_5.addWidget(label_5, 1, 1) hbox_5.addWidget(label_6, 1, 2) graph_w_1 = pg.GraphicsLayoutWidget() graph_w_2 = pg.GraphicsLayoutWidget() graph_w_3 = pg.GraphicsLayoutWidget() graph_w_4 = pg.GraphicsLayoutWidget() hbox_2.addWidget(graph_w_1, 1, 1) hbox_2.addWidget(graph_w_2, 1, 2) hbox_4.addWidget(graph_w_3, 1, 1) hbox_4.addWidget(graph_w_4, 1, 2) # Append for later access tab_widgets.append(tab) tab_widgets.append(vbox) tab_widgets.append(widget_1) tab_widgets.append(widget_2) tab_widgets.append(widget_3) tab_widgets.append(widget_4) tab_widgets.append(widget_5) tab_widgets.append(hbox_1) tab_widgets.append(hbox_2) tab_widgets.append(hbox_3) tab_widgets.append(hbox_4) tab_widgets.append(hbox_5) tab_widgets.append(label_1) tab_widgets.append(label_2) tab_widgets.append(label_3) tab_widgets.append(label_4) tab_widgets.append(label_5) tab_widgets.append(label_6) tab_widgets.append(graph_w_1) tab_widgets.append(graph_w_2) tab_widgets.append(graph_w_3) tab_widgets.append(graph_w_4) self.gpu_widgets.append(tab_widgets) self.plot_gpuinfo() self.update_gpuinfo() self.timer_3 = QtCore.QTimer() self.timer_3.timeout.connect(self.update_gpuinfo) self.timer_3.start(self.wait_time_ms)
def plot_cpuinfo(self, ): counter = 0 p = [] self.cpuinfo[-1, :] = self.s.refresh_stat() * 100 for cpu in range(self.s.cpu_core_count): p.append(self.widget_2.addPlot()) p[-1].setXRange(-self.len_data * self.wait_time_ms / 1000, 0, padding=0) p[-1].setYRange(0, 100, padding=0) p[-1].enableAutoRange('xy', False) p[-1].showAxis('top', show=True) p[-1].showAxis('right', show=True) p[-1].axes['bottom']['item'].setStyle(showValues=False) p[-1].axes['top']['item'].setStyle(showValues=False) p[-1].axes['left']['item'].setStyle(showValues=False) p[-1].axes['right']['item'].setStyle(showValues=False) p[-1].axes['right']['item'].setGrid(100) p[-1].axes['top']['item'].setGrid(100) p[-1].setMouseEnabled(x=False, y=False) p[-1].hideButtons() p[-1].setMenuEnabled(False) self.ti.append(pg.TextItem('', anchor=(0, 0))) self.ti[-1].setPos(-self.len_data * self.wait_time_ms / 1000, 100) p[-1].addItem(self.ti[-1]) self.ti.append(pg.TextItem('', anchor=(1, 0))) self.ti[-1].setPos(0, 100) p[-1].addItem(self.ti[-1]) self.cpu_curve.append(p[-1].plot(pen=pg.mkPen('b', width=1), fillLevel=-0.3, brush=(50, 50, 200, 50))) if counter == 3: self.widget_2.nextRow() counter = 0 else: counter += 1 p.append(self.widget_5.addPlot()) p[-1].setXRange(-self.len_data * self.wait_time_ms / 1000, 0, padding=0) p[-1].setYRange(0, 100, padding=0) p[-1].enableAutoRange('xy', False) p[-1].showAxis('top', show=True) p[-1].showAxis('right', show=True) p[-1].axes['bottom']['item'].setStyle(showValues=True) p[-1].axes['top']['item'].setStyle(showValues=False) p[-1].axes['left']['item'].setStyle(showValues=False) p[-1].axes['right']['item'].setStyle(showValues=True) p[-1].axes['right']['item'].setGrid(100) p[-1].axes['top']['item'].setGrid(100) p[-1].setLabel('right', "[%]") p[-1].setLabel('bottom', "Seconds") p[-1].setMouseEnabled(x=False, y=False) p[-1].hideButtons() p[-1].setMenuEnabled(False) self.cpu_curve.append(p[-1].plot(pen=pg.mkPen('b', width=1), fillLevel=-0.3, brush=(50, 50, 200, 50))) self.update_cpuinfo() self.timer_2 = QtCore.QTimer() self.timer_2.timeout.connect(self.update_cpuinfo) self.timer_2.start(self.wait_time_ms)
def __init__(self): #Initialisation de la GUI, des connections actionneurs/fonctions et des modules supplémentaires non supportés par QtCreator os.chdir("/home/pi/Desktop/Résultats Capsula") #dossier de travail super(self.__class__, self).__init__() self.setupUi(self) #initialisation de la GUI Capsula #Ajout des Widgets non proposés par QtDesigner #Graphe intensité du laser self.graphicsViewLaserBeamProfile = PlotWidget(self.tabWidgetLaserControl) self.graphicsViewLaserBeamProfile.setGeometry(QtCore.QRect(310, 60, 475, 300)) self.graphicsViewLaserBeamProfile.setXRange(0,480) self.graphicsViewLaserBeamProfile.setYRange(0,255) self.graphicsViewLaserBeamProfile.setObjectName("graphicsViewLaserBeamProfile") #Graphe détection self.graphicsViewRealPlot = PlotWidget(self.tabWidgetDetection) self.graphicsViewRealPlot.setGeometry(QtCore.QRect(10, 10, 550, 310)) self.graphicsViewRealPlot.setXRange(0,400) self.graphicsViewRealPlot.setYRange(0,1) self.graphicsViewRealPlot.setObjectName("graphicsViewRealPlot") #Message "Making reference, please wait" self.messageBoxBlank = QtGui.QProgressDialog("Making reference, please wait...", "Cancel",0, 100, self.tabWidgetDetection) self.messageBoxBlank.setWindowTitle("Wait...") #Initialisation des threads self.thread1 = thread.LoadingBar(self.messageBoxBlank) self.thread2 = thread.MakeBlank(self.messageBoxBlank) #Connexion boutons/méthodes self.checkBoxLaser532nm.clicked.connect(lambda: las.togglelaser532nm(self.checkBoxLaser532nm.isChecked())) self.checkBoxLaser635nm.clicked.connect(lambda: las.togglelaser635nm(self.checkBoxLaser635nm.isChecked())) self.pushButtonDutyCycleM.clicked.connect(lambda: mot.dutyCycleM(int(self.lcdNumberDutyCycleM.value()))) self.pushButtonBlank.clicked.connect(self.makeBlank) self.pushButtonClear.clicked.connect(self.on_init) self.pushButtonChangeDirectionM.clicked.connect(mot.changeDirectionM) self.pushButtonRunAndGoBackM.clicked.connect(mot.runAndGoBackM) self.pushButtonSeeCamera.clicked.connect(lambda: las.cameraStart(self.graphicsViewLaserBeamProfile, self.labelBeamImage, self.labelHHWValue, int(self.lineEditExposureTime.displayText()))) self.pushButtonStart.clicked.connect(self.startAcquisition) self.pushButtonStartMotor.clicked.connect(mot.startM) self.pushButtonStop.clicked.connect(self.stopAcquisition) self.pushButtonStopMotor.clicked.connect(mot.stopM) self.radioButtonContinu.clicked.connect(self.continuousDisplay) self.radioButtonSegmente.clicked.connect(self.segmentedDisplay) #Connexion actions/méthodes self.actionOpen_detection_configuration.triggered.connect(self.openDetectionConfiguration) self.actionOpen_pump_configuration.triggered.connect(self.openPumpConfiguration) self.actionOpen_motor_configuration.triggered.connect(self.openMotorConfiguration) self.actionPause.triggered.connect(self.pauseAcquisition) self.actionQuit.triggered.connect(self.closeEvent) self.actionSave_detection_configuration.triggered.connect(self.saveDetectionConfiguration) self.actionSave_pump_configuration.triggered.connect(self.savePumpConfiguration) self.actionSave_motor_configuration.triggered.connect(self.saveMotorConfiguration) self.actionStart_Aquisition.triggered.connect(self.startAcquisition) self.actionStop_Aquisition.triggered.connect(self.stopAcquisition) #Initialisation timer self.timer = QtCore.QTimer() self.pasDeTemps = float(self.lineEditSamplingPeriod.displayText()) #vitesse d'affichage self.timer.setInterval(self.pasDeTemps) self.timer.timeout.connect(self.update) #connexion timer out/update data #Initialisation graphe self.on_init() #Initialisation lasers GPIO.output(22, True) GPIO.output(32, True) #Déclaration variables self.blankDone = False self.inCaps = False self.noFloatDetected = True self.oldLineEdit = "" self.pause = False self.start = False self.stop = False self.withlVid = False self.withrVid = False #Connexion Rpi/Arduino via USB self.ser = serial.Serial('/dev/ttyACM0', 250000) #Onglet Lasers """voir laser.py""" #Onglet Fluidics """rien pour l'instant"""
class ScanCore(QtCore.QObject): ''' Core of a scanobject params: prebody: (waittime [ms], function(step) ) ''' result = QtCore.Signal(object) result_and_step = QtCore.Signal(object) finished = QtCore.Signal(object) timer = QtCore.QTimer() def __init__(self, body=None, steps=None, iterer=None, prebody=None, onfinished=None, name='scan', estimate=0): super().__init__() self.name = name self.steps = steps self.iterer = iterer self.paused = False self.body = body self.prebody = prebody self.onfinished = onfinished self._ready = False self.ready_time = None self.start_time = None self._estimate = estimate def __repr__(self): return '{}: estimated duration {}s'.format(self.name, self.estimate) def reset(self): '''Reset status such that rerun is posible''' self.iterer = None self.ready = False self.start_time = None @property def estimate(self): if self.start_time and not self.ready and self.count > 0: return (len(self.steps) - self.count)/self.count * \ (0.0001+(time.time() - self.start_time)) else: return self._estimate @property def ready(self): return self._ready @ready.setter def ready(self, status): if status: self._ready = True self.ready_time = time.time() self._estimate = self.ready_time - self.start_time self.finished.emit(status) else: self._ready = status def start(self, steps=None): if self.ready: raise RuntimeError('Scan has run already, reset first') self.cont = True if not self.paused: if not steps is None: self.steps = steps self.iterer = self.steps.__iter__() if self.iterer is None: self.iterer = self.steps.__iter__() self.start_time = time.time() self.count = 0 def internal(): try: if self.cont: step = self.iterer.__next__() self.count += 1 def measureandcontinue(): #connect to saver @Slot(object) def add_step_and_emit(measurement): self.result_and_step.emit((step, measurement)) self.result.connect(add_step_and_emit) self.body(self.result, step) self.result.disconnect(add_step_and_emit) self.timer.singleShot(1, internal) if self.prebody: self.prebody[1](step) self.timer.singleShot(self.prebody[0], measureandcontinue) else: measureandcontinue() except StopIteration: if self.onfinished: ret = self.onfinished(self) else: ret = True self.ready = ret try: cam.disarm() except AttributeError: pass self._internal = internal try: cam.arm() except AttributeError: pass self.timer.singleShot(0, internal) def pause(self): self.cont = False def resume(self): self.cont = True self.timer.singleShot(0, self._internal) def stop(self): self.cont = False
#Update input and output #Only executes when the graph is still being filled out (hasn't reached end of graph) if iteration < dataSize: #Read in next sample/input value (INPUT) data[iteration] = dw.getEyeblinkAmplitude() #Controls output of tone/airpuff (OUTPUT) manageOutputs() #End of iteration iteration += 1 #Create timer to run sample update function (start is called on the timer in createGraph function above) sampleTimer = QtCore.QTimer() sampleTimer.setTimerType(0) #0 = precise timer (default = 1 = coarse timer) sampleTimer.timeout.connect(sampleUpdate) #Updates the display def displayUpdate(): #Variables that need to be survive across multiple calls to update function global iteration, dataSize, curve, data, bars, barHeights, playing #Pause functionality if not playing: return #Update stimulus graph curve.setData(data)
class ScanManagerMonitor(QtGui.QTableWidget): """Create a window that shows all the current set scans""" timer = QtCore.QTimer() def __init__(self, QueueManager): super(self.__class__, self).__init__() self.finished_rows = 0 self.qm = QueueManager self.setupUI() self.populate() self.show() self.timer.timeout.connect(self.populate) self.timer.start(200) def setupUI(self): self.setWindowTitle('ScanManager Monitor') #self.setDisabled(True) self.setColumnCount(3) self.setHorizontalHeaderLabels(['Name', 'Duration (s)', 'Endtime']) #@Slot(object) def populate(self, obj=None): tasks = self.qm.scans rows = len(tasks) + 1 self.setRowCount(rows) for row, task in zip(range(rows), tasks): item = QtGui.QTableWidgetItem(task.name) self.setItem(row, 0, item) duration = max(task.estimate, 1e-10) self.setItem(row, 1, QtGui.QTableWidgetItem('{:.1f}'.format(duration))) if task.start_time: if task.ready: endtime = task.ready_time else: endtime = time.time() + duration endtime = time.strftime('%H:%M:%S', time.localtime(endtime)) else: endtime = '' self.setItem(row, 2, QtGui.QTableWidgetItem(str(endtime))) if task.ready: self.colorRow(row, 'lightblue') else: self.colorRow(row, 'white') self.setItem(rows - 1, 1, QtGui.QTableWidgetItem('End time')) #st = self.qm.start_time if self.qm.start_time else time.time() st = time.time() endtime = time.strftime('%H:%M:%S', time.localtime(self.qm.estimate() + st)) self.setItem(rows - 1, 2, QtGui.QTableWidgetItem(endtime)) self.setVerticalHeaderLabels([str(i) for i in range(self.rowCount())]) #self.resize(myGetQTableWidgetSize(self)) def finish(self): self.colorRow(self.finished_rows, 'lightblue') self.finished_rows += 1 def colorRow(self, rownumber, color): for col in range(self.columnCount()): try: self.item(rownumber, col).setBackgroundColor(QtGui.QColor(color)) except AttributeError: pass
def pyqt_cort(subj, mesh_dir, subcort_dir, elecs_dir, Grid, depths, Faces, Edge): # for white background pg.setConfigOption('background', 'w') # set up shader shader = gl.shaders.ShaderProgram('my_shader', [ gl.shaders.VertexShader(""" varying vec3 normal; void main() { // compute here for use in fragment shader normal = normalize(gl_NormalMatrix * gl_Normal * 0.5); gl_FrontColor = gl_Color; gl_BackColor = gl_Color; gl_Position = ftransform(); } """), gl.shaders.FragmentShader(""" varying vec3 normal; void main() { float p = dot(normal, normalize(vec3(1.0, -4.0, -4.0))); p = p < 0. ? p * -0.8 : p * 0.8; vec4 color = gl_Color; color.x = color.x * (0.3 + p); color.y = color.y * (0.3 + p); color.z = color.z * (0.3 + p); gl_FragColor = color; } """) ]) #define subjects mesh dir os.chdir(mesh_dir) #nave to mesh and loat it lh_tri = io.loadmat('lh_tri') lh_faces = lh_tri.get('tri') lh_faces = lh_faces - 1 lh_vert = io.loadmat('lh_vert') lh_verts = lh_vert.get('vert') #nave to mesh and loat it rh_tri = io.loadmat('rh_tri') rh_faces = rh_tri.get('tri') rh_faces = rh_faces - 1 rh_vert = io.loadmat('rh_vert') rh_verts = rh_vert.get('vert') # go to subcort dir os.chdir(subcort_dir) # set up hippocampus mesh lHipp_tri = io.loadmat('subcort_lHipp_tri') lHipp_faces = lHipp_tri.get('tri') lHipp_faces = lHipp_faces - 1 lHipp_vert = io.loadmat('subcort_lHipp_vert') lHipp_verts = lHipp_vert.get('vert') # set up amgd mesh lAmgd_tri = io.loadmat('subcort_lAmgd_tri') lAmgd_faces = lAmgd_tri.get('tri') lAmgd_faces = lAmgd_faces - 1 lAmgd_vert = io.loadmat('subcort_lAmgd_vert') lAmgd_verts = lAmgd_vert.get('vert') # set up GP mesh lGP_tri = io.loadmat('subcort_lGP_tri') lGP_faces = lGP_tri.get('tri') lGP_faces = lGP_faces - 1 lGP_vert = io.loadmat('subcort_lGP_vert') lGP_verts = lAmgd_vert.get('vert') # set up Caud mesh lCaud_tri = io.loadmat('subcort_lCaud_tri') lCaud_faces = lCaud_tri.get('tri') lCaud_faces = lCaud_faces - 1 lCaud_vert = io.loadmat('subcort_lCaud_vert') lCaud_verts = lCaud_vert.get('vert') # set up Put mesh lPut_tri = io.loadmat('subcort_lPut_tri') lPut_faces = lPut_tri.get('tri') lPut_faces = lPut_faces - 1 lPut_vert = io.loadmat('subcort_lPut_vert') lPut_verts = lPut_vert.get('vert') # set up Thal mesh lThal_tri = io.loadmat('subcort_lThal_tri') lThal_faces = lThal_tri.get('tri') lThal_faces = lThal_faces - 1 lThal_vert = io.loadmat('subcort_lThal_vert') lThal_verts = lThal_vert.get('vert') # set up hippocampus mesh rHipp_tri = io.loadmat('subcort_rHipp_tri') rHipp_faces = rHipp_tri.get('tri') rHipp_faces = rHipp_faces - 1 rHipp_vert = io.loadmat('subcort_rHipp_vert') rHipp_verts = rHipp_vert.get('vert') # set up amgd mesh rAmgd_tri = io.loadmat('subcort_rAmgd_tri') rAmgd_faces = rAmgd_tri.get('tri') rAmgd_faces = rAmgd_faces - 1 rAmgd_vert = io.loadmat('subcort_rAmgd_vert') rAmgd_verts = rAmgd_vert.get('vert') # set up GP mesh rGP_tri = io.loadmat('subcort_rGP_tri') rGP_faces = rGP_tri.get('tri') rGP_faces = rGP_faces - 1 rGP_vert = io.loadmat('subcort_rGP_vert') rGP_verts = rGP_vert.get('vert') # set up Caud mesh rCaud_tri = io.loadmat('subcort_rCaud_tri') rCaud_faces = rCaud_tri.get('tri') rCaud_faces = rCaud_faces - 1 rCaud_vert = io.loadmat('subcort_rCaud_vert') rCaud_verts = rCaud_vert.get('vert') # set up Put mesh rPut_tri = io.loadmat('subcort_rPut_tri') rPut_faces = rPut_tri.get('tri') rPut_faces = rPut_faces - 1 rPut_vert = io.loadmat('subcort_rPut_vert') rPut_verts = rPut_vert.get('vert') # set up Thal mesh rThal_tri = io.loadmat('subcort_rThal_tri') rThal_faces = rThal_tri.get('tri') rThal_faces = rThal_faces - 1 rThal_vert = io.loadmat('subcort_rThal_vert') rThal_verts = rThal_vert.get('vert') # go to fiber mesh dir #subj_fiberMesh_dir = '/Users/Zach/Desktop/Data/MR_data/EC69/DTI_HARDI_55_dirs/dti55trilin/fiberMeshes/lARC'; #os.chdir(subj_fiberMesh_dir); # set up fiber mesh #lARC_tri = io.loadmat('lARC_fiber_1'); #lARC_faces = lARC_tri.get('fiberMesh'); #lARC_faces = lARC_faces -1; # launch opengl app app = QtGui.QApplication([]) w = gl.GLViewWidget() w.show() w.setWindowTitle(('Patient Pial Surface and Depths for: ' + subj)) w.setCameraPosition(distance=750) # set grid on g = gl.GLGridItem() g.scale(100, 100, 50) #w.addItem(g) # add electrodes as spheres os.chdir(elecs_dir) grid = io.loadmat('depth_probes.mat') grid = grid.get('elecmatrix') m1 = gl.GLScatterPlotItem(pos=grid, size=15., color=(1, 0, 0, 1), pxMode=True) m1.translate(5, 5, 0) m1.setDepthValue(1) m1.setGLOptions('additive') #grid grid = io.loadmat('hd_grid.mat') grid = grid.get('elecmatrix') m4 = gl.GLScatterPlotItem(pos=grid, size=15., color=(1, 0, 0, 1), pxMode=True) m4.translate(5, 5, 0) m4.setDepthValue(1) m4.setGLOptions('translucent') phase = 0. #load in ecog data #subj_data_dir = '/Users/Zach/Desktop/Data/MR_data/EC69/ECoG'; #os.chdir(subj_data_dir); #data = io.loadmat('hg_listen_avg.mat'); #avg_trial = data.get('avg_trial'); #d2 = (grid**2).sum(axis=1)**0.5; # add depths and grid to plot w.addItem(m1) if Grid == True: w.addItem(m4) #z = avg_trial; #p4 = gl.GLSurfacePlotItem(x=grid[:,0], y = grid[:,1], shader='heightColor', computeNormals=False, smooth=False); # #p4.shader()['colorMap'] = np.array([0.2, 2, 0.5, 0.2, 1, 1, 0.2, 0, 2]); #avg_trial[:,0]; #p4.translate(10, 10, 0) #w.addItem(p4) # An alternative to the custom shader is to invert the mesh normals: #meshdata = gl.MeshData(vertexes=faces); #norms = meshdata.faceNormals(); #cd norms *= - 1; # set up lh mesh if Faces == True: edgeColor = (0, 0, 0, 1) else: edgeColor = (1, 1, 1, 0.2) colors1 = np.random.random(size=(lh_verts.shape[0], 3, 4)) m2 = gl.GLMeshItem(vertexes=lh_verts, faces=lh_faces, drawFaces=Faces, drawEdges=Edge, faceColor=(1, 0, 0, 0), edgeColor=edgeColor, smooth=True, shader='my_shader') m2.translate(5, 5, 0) m2.setGLOptions('translucent') #m2.setGLOptions('additive') m2.setDepthValue(0.5) w.addItem(m2) # add rh mesh colors2 = np.random.random(size=(rh_verts.shape[0], 3, 4)) m3 = gl.GLMeshItem(vertexes=rh_verts, faces=rh_faces, drawFaces=Faces, drawEdges=Edge, faceColor=(1, 0, 0, 0), edgeColor=edgeColor, smooth=True, shader='my_shader') m3.translate(5, 5, 0) m3.setGLOptions('translucent') #m2.setGLOptions('additive') m3.setDepthValue(0.5) w.addItem(m3) # add the hippocampus lHipp = gl.GLMeshItem(vertexes=lHipp_verts, faces=lHipp_faces, drawFaces=False, drawEdges=True, faceColor=(1, 0, 1, 0.4), edgeColor=(1, 0, 0.5, 0.2), smooth=True, shader='my_shader') lHipp.translate(5, 5, 0) lHipp.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lHipp) # add the Amygdala lAmgd = gl.GLMeshItem(vertexes=lAmgd_verts, faces=lAmgd_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.4, 0, 0.2), smooth=True, shader='my_shader') lAmgd.translate(5, 5, 0) lAmgd.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lAmgd) # add the Globus Pallidus lGP = gl.GLMeshItem(vertexes=lGP_verts, faces=lGP_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.8, 0.2, 0.2), smooth=True, shader='my_shader') lGP.translate(5, 5, 0) lGP.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lGP) # add the Caudate lCaud = gl.GLMeshItem(vertexes=lCaud_verts, faces=lCaud_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.2, 0.2, 0.2), smooth=True, shader='my_shader') lCaud.translate(5, 5, 0) lCaud.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lCaud) # add the Putamen lPut = gl.GLMeshItem(vertexes=lPut_verts, faces=lPut_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(0.2, 0.3, 0.5, 0.2), smooth=True, shader='my_shader') lPut.translate(5, 5, 0) lPut.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lPut) # add the Thalimus lThal = gl.GLMeshItem(vertexes=lThal_verts, faces=lThal_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(0.1, 0.7, 0.4, 0.2), smooth=True, shader='my_shader') lThal.translate(5, 5, 0) lThal.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(lThal) # add the Thalimus #lARC = gl.GLMeshItem(faces=lARC_faces, drawFaces=False, drawEdges=True, faceColor=(1,0.4,0.4,0.4),edgeColor=(1,0.7,0.4,0.2), smooth=True, shader='my_shader'); #lARC.translate(5, 5, 0) #lARC.setGLOptions('translucent');#m2.setGLOptions('additive') #w.addItem(lARC); # add the hippocampus rHipp = gl.GLMeshItem(vertexes=rHipp_verts, faces=rHipp_faces, drawFaces=False, drawEdges=True, faceColor=(1, 0, 1, 0.4), edgeColor=(1, 0, 0.5, 0.2), smooth=True, shader='my_shader') rHipp.translate(5, 5, 0) rHipp.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rHipp) # add the Amygdala rAmgd = gl.GLMeshItem(vertexes=rAmgd_verts, faces=rAmgd_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.4, 0, 0.2), smooth=True, shader='my_shader') rAmgd.translate(5, 5, 0) rAmgd.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rAmgd) # add the Globus Pallidus rGP = gl.GLMeshItem(vertexes=rGP_verts, faces=rGP_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.8, 0.2, 0.2), smooth=True, shader='my_shader') rGP.translate(5, 5, 0) rGP.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rGP) # add the Caudate rCaud = gl.GLMeshItem(vertexes=rCaud_verts, faces=rCaud_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(1, 0.2, 0.2, 0.2), smooth=True, shader='my_shader') rCaud.translate(5, 5, 0) rCaud.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rCaud) # add the Putamen rPut = gl.GLMeshItem(vertexes=rPut_verts, faces=rPut_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(0.2, 0.3, 0.5, 0.2), smooth=True, shader='my_shader') rPut.translate(5, 5, 0) rPut.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rPut) # add the Thalimus rThal = gl.GLMeshItem(vertexes=rThal_verts, faces=rThal_faces, drawFaces=False, drawEdges=True, faceColor=(0, 0.4, 0.4, 0.4), edgeColor=(0.1, 0.7, 0.4, 0.2), smooth=True, shader='my_shader') rThal.translate(5, 5, 0) rThal.setGLOptions('translucent') #m2.setGLOptions('additive') w.addItem(rThal) # add the Thalimus #lARC = gl.GLMeshItem(faces=lARC_faces, drawFaces=False, drawEdges=True, faceColor=(1,0.4,0.4,0.4),edgeColor=(1,0.7,0.4,0.2), smooth=True, shader='my_shader'); #lARC.translate(5, 5, 0) #lARC.setGLOptions('translucent');#m2.setGLOptions('additive') #w.addItem(lARC); # update over 50 iterations the color value plotted at each electrode index = 0 def update(): ## update volume colors global m1, m4, d2, index m1.rotate(1, 0, 0, 1) m2.rotate(1, 0, 0, 1) m3.rotate(1, 0, 0, 1) if Grid == True: m4.rotate(1, 0, 0, 1) index -= 1 #p4.setData(z=z[:,index%z.shape[1]]); #g.rotate(1,0,0,1); lHipp.rotate(1, 0, 0, 1) lAmgd.rotate(1, 0, 0, 1) lGP.rotate(1, 0, 0, 1) lCaud.rotate(1, 0, 0, 1) lPut.rotate(1, 0, 0, 1) lThal.rotate(1, 0, 0, 1) rHipp.rotate(1, 0, 0, 1) rAmgd.rotate(1, 0, 0, 1) rGP.rotate(1, 0, 0, 1) rCaud.rotate(1, 0, 0, 1) rPut.rotate(1, 0, 0, 1) rThal.rotate(1, 0, 0, 1) #lARC.rotate(1,0,0,1); w.setCameraPosition(distance=750 + index) if (750 + index) <= 220: w.setCameraPosition(distance=220) index = index + 1 t = QtCore.QTimer() t.timeout.connect(update) t.start(50) # launch mesh plot import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def _initialize(self): self.head = 0 self.timer = QtCore.QTimer(singleShot=False, interval=int(self.chunksize * self.sample_interval * 1000)) self.timer.timeout.connect(self.send_data)
accerFastV = 0.1 accerSlowV = 0.01 accerFastI = 1e-6 accerSlowI = 1e-8 scanTime = 50 #ms rate = accerSlowV ui.gpibAddrInputBox.setText(str(gpibAddress)) ui.accerFast.setText(str(accerFastV)) ui.accerSlow.setText(str(accerSlowV)) ui.slowSelect.setChecked(True) # set timer MeasTimer = QtCore.QTimer() ScanTimer = QtCore.QTimer() filename = '20.dat' def deviceInit(): global gpibAddress, filename global K2400 K2400 = Keithley_2400(gpibAddress) sourStats = K2400.getSourMode() gpibAddress = int(ui.gpibAddrInputBox.text()) filename = "{:d}.dat".format(gpibAddress) if sourStats == 'VOLT': ui.sourVolt.setChecked(True) elif sourStats == 'CURR':
data = np.random.random(n) data[int(n * 0.1):int(n * 0.13)] += .5 data[int(n * 0.18)] += 2 data[int(n * 0.1):int(n * 0.13)] *= 5 data[int(n * 0.18)] *= 20 data *= 1e-12 return data, np.arange(n, n + len(data)) / float(n) def updateData(): yd, xd = rand(10000) p1.setData(y=yd, x=xd) ## Start a timer to rapidly update the plot in pw t = QtCore.QTimer() t.timeout.connect(updateData) t.start(50) #updateData() ## Multiple parameterized plots--we can autogenerate averages for these. for i in range(0, 5): for j in range(0, 3): yd, xd = rand(10000) pw2.plot(y=yd * (j + 1), x=xd, params={'iter': i, 'val': j}) ## Test large numbers curve = pw3.plot(np.random.normal(size=100) * 1e0, clickable=True) curve.curve.setClickable(True) curve.setPen('w') ## white pen curve.setShadowPen(pg.mkPen((70, 70, 30), width=6, cosmetic=True))
def __init__(self, parent=None, name="ImageView", view=None, imageItem=None, *args): """ By default, this class creates an :class:`ImageItem <pyqtgraph.ImageItem>` to display image data and a :class:`ViewBox <pyqtgraph.ViewBox>` to contain the ImageItem. ============= ========================================================= **Arguments** parent (QWidget) Specifies the parent widget to which this ImageView will belong. If None, then the ImageView is created with no parent. name (str) The name used to register both the internal ViewBox and the PlotItem used to display ROI data. See the *name* argument to :func:`ViewBox.__init__() <pyqtgraph.ViewBox.__init__>`. view (ViewBox or PlotItem) If specified, this will be used as the display area that contains the displayed image. Any :class:`ViewBox <pyqtgraph.ViewBox>`, :class:`PlotItem <pyqtgraph.PlotItem>`, or other compatible object is acceptable. imageItem (ImageItem) If specified, this object will be used to display the image. Must be an instance of ImageItem or other compatible object. ============= ========================================================= Note: to display axis ticks inside the ImageView, instantiate it with a PlotItem instance as its view:: pg.ImageView(view=pg.PlotItem()) """ QtGui.QWidget.__init__(self, parent, *args) self.markerRadius = 50 #circle radius marking single points/rois self.clicked = [] self.image_Designation = None self.levelMax = 4096 self.levelMin = 0 self.name = name self.image = None self.axes = {} self.imageDisp = None self.ui = Ui_Form() #pyqtgraph.imageview.ImageViewTemplate_pyqt self.ui.setupUi(self) self.scene = self.ui.graphicsView.scene() self.ignoreTimeLine = False self.ignoreZLine = False if view is None: self.view = ViewBox() else: self.view = view self.ui.graphicsView.setCentralItem(self.view) self.view.setAspectLocked(True) self.view.invertY() if imageItem is None: self.imageItem = ImageItem() else: self.imageItem = imageItem self.imageview = self.view.addItem(self.imageItem) self.currentTime = 0 self.currentLayer = 0 #layer in z axis #relay x y coordinates within image self.view.scene().sigMouseMoved.connect(self.mouseMoved) self.view.scene().sigMouseClicked.connect(self.mouseClicked) #self.view.scene().mouseReleaseEvent(self.releaseEvent) #self.view.scene().mouseReleaseEvent(self.mouseReleased) #pdb.set_trace() #generate roi list self.croi = [] #holdes x,y,z points for roi self.ccroi = [] #hold pg roi for croi self.aroi = {} #place to store all rois, each roi is passed as dictionary with each index = currentLayer self.aaroi = [] #place to store pg of arois in self.currentLayer self.button1 = 'off' self.ui.histogram.setImageItem(self.imageItem) self.menu = None self.ui.normGroup.hide() self.roi = PlotROI(10) self.roi.setZValue(20) self.view.addItem(self.roi) self.roi.hide() self.normRoi = PlotROI(10) self.normRoi.setPen('y') self.normRoi.setZValue(20) self.view.addItem(self.normRoi) self.normRoi.hide() self.roiCurve = self.ui.roiPlot.plot() self.timeLine = InfiniteLine(0, movable=True) self.timeLine.setPen((255, 255, 0, 200)) #self.timeLine.setPen((255, 255, 200, 0)) self.timeLine.setZValue(1) self.ui.roiPlot.addItem(self.timeLine) self.ui.splitter.setSizes([self.height()-35, 35]) self.ui.roiPlot.hideAxis('left') self.ui.splitter.setSizes([self.height(), 10]) self.ui.zPlot.plot() self.zLine = InfiniteLine(0, movable=True, angle = 0) #self.zLine.setBounds([0, 42]) self.zLine.setPen((255, 255, 0, 200)) self.zLine.setZValue(self.currentLayer ) self.ui.ztext.setText(str(self.currentLayer)) self.ui.zPlot.addItem(self.zLine) self.ui.zPlot.hideAxis('bottom') self.keysPressed = {} self.playTimer = QtCore.QTimer() self.playRate = 0 self.lastPlayTime = 0 self.normRgn = LinearRegionItem() self.normRgn.setZValue(0) self.ui.roiPlot.addItem(self.normRgn) self.normRgn.hide() ## wrap functions from view box for fn in ['addItem', 'removeItem']: setattr(self, fn, getattr(self.view, fn)) ## wrap functions from histogram for fn in ['setHistogramRange', 'autoHistogramRange', 'getLookupTable', 'getLevels']: setattr(self, fn, getattr(self.ui.histogram, fn)) self.timeLine.sigPositionChanged.connect(self.timeLineChanged) self.zLine.sigPositionChanged.connect(self.zLineChanged) self.ui.roiBtn.clicked.connect(self.roiClicked) self.roi.sigRegionChanged.connect(self.roiChanged) #self.ui.normBtn.toggled.connect(self.normToggled) self.ui.menuBtn.clicked.connect(self.menuClicked) self.ui.normDivideRadio.clicked.connect(self.normRadioChanged) self.ui.normSubtractRadio.clicked.connect(self.normRadioChanged) self.ui.normOffRadio.clicked.connect(self.normRadioChanged) self.ui.normROICheck.clicked.connect(self.updateNorm) self.ui.normFrameCheck.clicked.connect(self.updateNorm) self.ui.normTimeRangeCheck.clicked.connect(self.updateNorm) #radio button for navigation and roi selection self.ui.navRadio.clicked.connect(self.NavigationStatus) self.ui.radioSinglePoint.clicked.connect(self.radioSinglePoint) self.ui.radioAreaROI.clicked.connect(self.radioAreaROI) self.ui.radioPolygon.clicked.connect(self.radioPolygon) self.ui.radioEdit.clicked.connect(self.radioEdit) self.playTimer.timeout.connect(self.timeout) self.normProxy = SignalProxy(self.normRgn.sigRegionChanged, slot=self.updateNorm) self.normRoi.sigRegionChangeFinished.connect(self.updateNorm) self.ui.roiPlot.registerPlot(self.name + '_ROI') self.view.register(self.name) self.noRepeatKeys = [QtCore.Qt.Key_Right, QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Down, QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown] self.roiClicked() ## initialize roi plot to correct shape / visibility
w2.setXRange(Frelist[0], Frelist[-1]) BtnStart.setChecked(False) StartODMR() #Finish the Rabi task print('Finished a measurement') Data.finished = False #Prepare for next task Plotting.stop() def OnTimeSettingChange(): #############Setting########### global Contime, Intetime, Power, startfre, endfre, step #Cooling[3]=SpinBoxCooling.value()*unit.ms startfre = SpinBoxstartfr.value() * unit.MHz endfre = SpinBoxendfr.value() * unit.MHz step = SpinBoxstep.value() * unit.MHz Contime = SpinBoxconstanttime.value() * unit.ms Intetime = SpinBoxIntegraltime.value() * unit.s Power = SpinBoxpower.value() * unit.dBm Plotting = QtCore.QTimer() Plotting.timeout.connect(update) i = 0 if __name__ == "__main__": win.show() app.exec_() print("Exit")
def __init__(self, device, *args, **kwargs): # agregue device super().__init__(*args, **kwargs) self.nidaq = device # esto tiene que ir imageWidget = pg.GraphicsLayoutWidget() self.vb = imageWidget.addViewBox(row=1, col=1) # imageWidget2 = pg.GraphicsLayoutWidget() # self.vb2 = imageWidget2.addViewBox(row=1, col=1) # Parameters for smooth moving (to no shake hard the piezo) self.moveTime = 0.1 # total time to move(s) self.moveSamples = 1000 # samples to move self.moveRate = self.moveSamples / self.moveTime self.activeChannels = ["x", "y", "z"] self.AOchans = [0, 1, 2] # LiveView Button self.liveviewButton = QtGui.QPushButton('confocal LIVEVIEW') self.liveviewButton.setCheckable(True) self.liveviewButton.clicked.connect(self.liveview) # self.liveviewButton.clicked.connect(self.channelsOpen) # save image Button self.saveimageButton = QtGui.QPushButton('Scan and Save') self.saveimageButton.setCheckable(True) self.saveimageButton.clicked.connect(self.saveimage) self.saveimageButton.setStyleSheet( "QPushButton { background-color: gray; }" "QPushButton:pressed { background-color: blue; }") # Defino el tipo de Scan que quiero self.scanMode = QtGui.QComboBox() self.scanModes = ['step scan', 'otro scan', 'tempesta scan'] self.scanMode.addItems(self.scanModes) # self.scanMode.currentIndexChanged.connect( # lambda: self.setScanMode(self.scanMode.currentText())) # def setScanMode(self, mode): ## self.stageScan.setScanMode(mode) # self.scanParameterChanged('scanMode') self.stepcheck = QtGui.QCheckBox('Scan Barckward') self.stepcheck.clicked.connect(self.steptype) self.step = False self.canales = False # Scanning parameters self.initialPositionLabel = QtGui.QLabel('Initial Pos [x0 y0 z0] (µm)') self.initialPositionEdit = QtGui.QLineEdit('0 0 1') self.scanRangeLabel = QtGui.QLabel('Scan range (µm)') self.scanRangeEdit = QtGui.QLineEdit('10') self.pixelTimeLabel = QtGui.QLabel('Pixel time (ms)') self.pixelTimeEdit = QtGui.QLineEdit('1') self.numberofPixelsLabel = QtGui.QLabel('Number of pixels') self.numberofPixelsEdit = QtGui.QLineEdit('100') self.pixelSizeLabel = QtGui.QLabel('Pixel size (nm)') self.pixelSizeValue = QtGui.QLabel('') self.timeTotalLabel = QtGui.QLabel('tiempo total del escaneo (s)') self.timeTotalValue = QtGui.QLabel('') self.numberofPixelsEdit.textChanged.connect(self.paramChanged) self.scanRangeEdit.textChanged.connect(self.paramChanged) self.pixelTimeEdit.textChanged.connect(self.paramChanged) self.initialPositionEdit.textChanged.connect(self.paramChanged) self.paramChanged() self.paramWidget = QtGui.QWidget() grid = QtGui.QGridLayout() self.setLayout(grid) grid.addWidget(imageWidget, 0, 0) grid.addWidget(self.paramWidget, 0, 1) # grid.addWidget(imageWidget2, 0, 2) subgrid = QtGui.QGridLayout() self.paramWidget.setLayout(subgrid) subgrid.addWidget(self.liveviewButton, 10, 1) subgrid.addWidget(self.initialPositionLabel, 0, 1) subgrid.addWidget(self.initialPositionEdit, 1, 1) subgrid.addWidget(self.scanRangeLabel, 2, 1) subgrid.addWidget(self.scanRangeEdit, 3, 1) subgrid.addWidget(self.pixelTimeLabel, 4, 1) subgrid.addWidget(self.pixelTimeEdit, 5, 1) subgrid.addWidget(self.numberofPixelsLabel, 6, 1) subgrid.addWidget(self.numberofPixelsEdit, 7, 1) subgrid.addWidget(self.pixelSizeLabel, 8, 1) subgrid.addWidget(self.pixelSizeValue, 9, 1) subgrid.addWidget(self.timeTotalLabel, 13, 1) subgrid.addWidget(self.timeTotalValue, 14, 1) subgrid.addWidget(self.stepcheck, 11, 2) # subgrid.addWidget(self.scanMode, 12, 1) subgrid.addWidget(self.saveimageButton, 15, 1) # self.paramWidget.setFixedHeight(400) self.vb.setMouseMode(pg.ViewBox.RectMode) # self.vb2.setMouseMode(pg.ViewBox.RectMode) self.img = pg.ImageItem() self.img.translate(-0.5, -0.5) self.vb.addItem(self.img) self.vb.setAspectLocked(True) # self.vb2.addItem(self.img) # self.vb2.setAspectLocked(True) imageWidget.setAspectLocked(True) # imageWidget2.setAspectLocked(True) self.hist = pg.HistogramLUTItem(image=self.img) self.hist.gradient.loadPreset('thermal') self.hist.vb.setLimits(yMin=0, yMax=66000) # self.hist.vb2.setLimits(yMin=0, yMax=66000) # self.cubehelixCM = pg.ColorMap(np.arange(0, 1, 1/256), # guitools.cubehelix().astype(int)) # self.hist.gradient.setColorMap(self.cubehelixCM) for tick in self.hist.gradient.ticks: tick.hide() imageWidget.addItem(self.hist, row=1, col=2) # imageWidget2.addItem(self.hist, row=1, col=2) # self.ROI = guitools.ROI((0, 0), self.vb, (0, 0), handlePos=(1, 0), # handleCenter=(0, 1), color='y', scaleSnap=True, # translateSnap=True) self.viewtimer = QtCore.QTimer() self.viewtimer.timeout.connect(self.updateView)
x = 0 # variável contendo o índice def update(): global tensao, curva, x leitura_arduino = comport.readline() # Lendo o valor da arduino if leitura_arduino != b'\r\n' and leitura_arduino != b'\n': # Checkando se o valor é válido tensao_ecg = float(leitura_arduino) / 100.0 - 1.65 # tensao_ecg = float(leitura_arduino)/100.0 - 1.65 tensao.append(tensao_ecg) # Inserindo o valor lido ao vetor 'tensao' tensao.pop(0) # deletando o valor mais antigo do vetor 'tensao' tensaonp = np.array( tensao[-500:], dtype='float' ) # Convertendo o vetor 'tensao' do tipo array para numpy array curva.setData(tensaonp) # Passando os valores do vetor para a curva x += 1 # Atualizando o índice da leitura curva.setPos(x, 0) # Valor do eixo x e seu deslocamento verticalmente plot.setLabel('bottom', "Tensão [V]: " + "{0:.2f}".format(tensaonp.item(499))) app.processEvents() # Atualizando a interface (janela do gráfico) timer = QtCore.QTimer() # Temporizador da biblioteca timer.timeout.connect(update) timer.start(0) if __name__ == '__main__': # Função iniciando a execução da janela import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
def visualize_time_travel_data(path=None, automatically_rotate=True): """ This function visualizes data from the Time Travel Task in 3D. :param path: the path to a data file to visualize :param automatically_rotate: If True, the figure will automatically rotate in an Abs(Sin(x)) function shape, otherwise the user can interact with the figure. :return: Nothing """ # noinspection PyGlobalUndefined global path_line, idx, timer, iterations, click_scatter, click_pos, click_color, click_size, window, meta, \ reconstruction_items, num_points_to_update, line_color, line_color_state, auto_rotate auto_rotate = automatically_rotate #################################################################################################################### # Setup #################################################################################################################### # Get Log File Path and Load File local_directory = os.path.dirname(os.path.realpath(__file__)) # The directory of this script # filename = '001_1_1_1_2016-08-29_10-26-03.dat' # The relative path to the data file (CHANGE ME) # path = os.path.join(local_directory, filename) if path is None: path = easygui.fileopenbox() if path is '': logging.info('No file selected. Closing.') exit() if not os.path.exists(path): logging.error('File not found. Closing.') exit() meta = None # noinspection PyBroadException try: meta = get_filename_meta_data(os.path.basename(path)) # The meta filename information for convenience except: logging.error('There was an error reading the filename meta-information. Please confirm this is a valid log ' 'file.') exit() logging.info("Parsing file (" + str(path) + ")...") # First we populate a list of each iteration's data # This section of code contains some custom binary parser data which won't be explained here iterations = read_binary_file(path) # Output the iterations count for debugging purposes logging.info("Plotting " + str(len(iterations)) + " iterations.") # Generate UI Window and Set Camera Settings app = QtGui.QApplication([]) window = gl.GLViewWidget() window.opts['center'] = pg.Qt.QtGui.QVector3D(0, 0, 30) window.opts['distance'] = 200 window.setWindowTitle('Timeline Visualizer' + ' - Subject {0}, Trial {1}, Phase {2}'.format(meta['subID'], meta['trial'], phase_num_to_str(int(meta['phase'])))) #################################################################################################################### # Generate static graphical items #################################################################################################################### # Make Grid grid_items = [] def make_grid_item(loc, rot, scale): g = gl.GLGridItem() g.scale(scale[0], scale[1], scale[2]) g.rotate(rot[0], rot[1], rot[2], rot[3]) g.translate(loc[0], loc[1], loc[2]) return g if meta['phase'] == '0' or meta['phase'] == '3' or meta['phase'] == '6': g0 = make_grid_item((-19, 0, 15), (90, 0, 1, 0), (1.5, 1.9, 1.9)) g1 = make_grid_item((0, -19, 15), (90, 1, 0, 0), (1.9, 1.5, 1.9)) grid_items.append(g0) grid_items.append(g1) window.addItem(g0) window.addItem(g1) else: g0 = make_grid_item((-19, 0, 15), (90, 0, 1, 0), (1.5, 1.9, 1.9)) g1 = make_grid_item((-19, 0, 45), (90, 0, 1, 0), (1.5, 1.9, 1.9)) g2 = make_grid_item((0, -19, 15), (90, 1, 0, 0), (1.9, 1.5, 1.9)) g3 = make_grid_item((0, -19, 45), (90, 1, 0, 0), (1.9, 1.5, 1.9)) grid_items.append(g0) grid_items.append(g1) grid_items.append(g2) grid_items.append(g3) window.addItem(g0) window.addItem(g1) window.addItem(g2) window.addItem(g3) gn = make_grid_item((0, 0, 0), (0, 0, 0, 0), (1.9, 1.9, 1.9)) grid_items.append(gn) window.addItem(gn) # Make Image Base # Determine the background image according to meta phase img_location = './media/time_travel_task/' bg_path = 'studyBG.png' if meta['phase'] == '0' or meta['phase'] == '3': bg_path = 'practiceBG.png' elif meta['phase'] == '6': bg_path = 'practiceBG.png' elif meta['phase'] == '7' or meta['phase'] == '8': bg_path = 'studyBG.png' img = imread(os.path.abspath(os.path.join(img_location, bg_path))) image_scale = (19.0 * 2.0) / float(img.shape[0]) tex1 = pg.makeRGBA(img)[0] base_image = gl.GLImageItem(tex1) base_image.translate(-19, -19, 0) base_image.rotate(270, 0, 0, 1) base_image.scale(image_scale, image_scale, image_scale) window.addItem(base_image) # Make Timeline Colored Bars color_bars = [] def make_color_bar(rgb, p, r, s): v = gl.GLImageItem(np.array([[rgb + (255,)]])) v.translate(p[0], p[1], p[2]) v.scale(s[0], s[1], s[2]) v.rotate(r[0], r[1], r[2], r[3]) return v color_bar_length = 15 if meta['phase'] == '0' or meta['phase'] == '3' or meta['phase'] == '6': times = [0, 7.5, 15, 22.5] color_bar_length = 7.5 else: times = [0, 15, 30, 45] if meta['inverse'] == '1': times.reverse() v0 = make_color_bar((255, 255, 0), (19, times[0], 19), (90, 1, 0, 0), (5, color_bar_length, 0)) v1 = make_color_bar((255, 0, 0), (19, times[1], 19), (90, 1, 0, 0), (5, color_bar_length, 0)) v2 = make_color_bar((0, 255, 0), (19, times[2], 19), (90, 1, 0, 0), (5, color_bar_length, 0)) v3 = make_color_bar((0, 0, 255), (19, times[3], 19), (90, 1, 0, 0), (5, color_bar_length, 0)) color_bars.append(v0) color_bars.append(v1) color_bars.append(v2) color_bars.append(v3) window.addItem(v0) window.addItem(v1) window.addItem(v2) window.addItem(v3) # Generate Path Line forwardColor = (255, 255, 255, 255) backwardColor = (255, 0, 255, 255) line_color = np.empty((len(iterations), 4)) line_color_state = np.empty((len(iterations), 4)) x = [] y = [] z = [] for idx, i in enumerate(iterations): x.append(float(i['x'])) y.append(float(i['z'])) z.append(float(i['time_val'])) c = forwardColor if i['timescale'] <= 0: c = backwardColor line_color[idx] = pg.glColor(c) line_color_state[idx] = pg.glColor((0, 0, 0, 0)) pts = np.vstack([x, y, z]).transpose() path_line = gl.GLLinePlotItem(pos=pts, color=line_color_state, mode='line_strip', antialias=True) window.addItem(path_line) # Generate Item Lines (ground truth) # noinspection PyUnusedLocal items, times, directions = get_items_solutions(meta) if meta['phase'] == '0' or meta['phase'] == '3' or meta['phase'] == '6': times = [2, 12, 18, 25] directions = [2, 1, 2, 1] # Fall = 2, Fly = 1, Stay = 0 if meta['inverse'] == '1': times.reverse() directions.reverse() items = [{'direction': directions[0], 'pos': (2, -12, times[0]), 'color': (255, 255, 0)}, {'direction': directions[1], 'pos': (2, 13, times[1]), 'color': (255, 0, 0)}, {'direction': directions[2], 'pos': (-13, 2, times[2]), 'color': (0, 255, 0)}, {'direction': directions[3], 'pos': (-12, -17, times[3]), 'color': (0, 0, 255)}, {'direction': 0, 'pos': (13, 5, 0), 'color': (128, 0, 128)}] # elif meta['phase'] == '7' or meta['phase'] == '8': # times = [2, 8, 17, 23] # directions = [2, 1, 1, 2] # Fall = 2, Fly = 1, Stay = 0 # if meta['inverse'] == '1': # times.reverse() # directions.reverse() # items = [{'direction': directions[0], 'pos': (16, -14, times[0]), 'color': (255, 255, 0)}, # {'direction': directions[1], 'pos': (-10, -2, times[1]), 'color': (255, 0, 0)}, # {'direction': directions[2], 'pos': (15, -8, times[2]), 'color': (0, 255, 0)}, # {'direction': directions[3], 'pos': (-15, -15, times[3]), 'color': (0, 0, 255)}, # {'direction': 0, 'pos': (-2, 10, 0), 'color': (128, 0, 128)}] else: times = [4, 10, 16, 25, 34, 40, 46, 51] directions = [2, 1, 1, 2, 2, 1, 2, 1] # Fall = 2, Fly = 1, Stay = 0 if meta['inverse'] == '1': times.reverse() directions.reverse() items = [{'direction': directions[0], 'pos': (18, -13, times[0]), 'color': (255, 255, 0)}, {'direction': directions[1], 'pos': (-13, 9, times[1]), 'color': (255, 255, 0)}, {'direction': directions[2], 'pos': (-10, -2, times[2]), 'color': (255, 0, 0)}, {'direction': directions[3], 'pos': (6, -2, times[3]), 'color': (255, 0, 0)}, {'direction': directions[4], 'pos': (17, -8, times[4]), 'color': (0, 255, 0)}, {'direction': directions[5], 'pos': (-2, -7, times[5]), 'color': (0, 255, 0)}, {'direction': directions[6], 'pos': (-15, -15, times[6]), 'color': (0, 0, 255)}, {'direction': directions[7], 'pos': (6, 18, times[7]), 'color': (0, 0, 255)}, {'direction': 0, 'pos': (14, 6, 0), 'color': (128, 0, 128)}, {'direction': 0, 'pos': (-2, 10, 0), 'color': (128, 0, 128)}] item_lines = [] pos = np.empty((len(items), 3)) size = np.empty((len(items))) color = np.empty((len(items), 4)) end_time = 60 if meta['phase'] == '0' or meta['phase'] == '3' or meta['phase'] == '6': end_time = 30 for idx, i in enumerate(items): pos[idx] = i['pos'] size[idx] = 2 if i['direction'] == 0: size[idx] = 0 color[idx] = (i['color'][0] / 255, i['color'][1] / 255, i['color'][2] / 255, 1) idx += 1 end = i['pos'] if i['direction'] == 1: end = (end[0], end[1], 0) elif i['direction'] == 2 or i['direction'] == 0: end = (end[0], end[1], end_time) line = gl.GLLinePlotItem(pos=np.vstack([[i['pos'][0], end[0]], [i['pos'][1], end[1]], [i['pos'][2], end[2]]]).transpose(), color=pg.glColor(i['color']), width=3, antialias=True) item_lines.append(line) window.addItem(line) item_scatter_plot = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False) window.addItem(item_scatter_plot) #################################################################################################################### # Generate data graphical items #################################################################################################################### # If Study/Practice, label click events '''click_pos = np.empty((len(items), 3)) click_size = np.zeros((len(iterations), len(items))) click_color = np.empty((len(items), 4)) if meta['phase'] == '0' or meta['phase'] == '1' or meta['phase'] == '3' or meta['phase'] == '4' \ or meta['phase'] == '6' or meta['phase'] == '7': for idx, i in enumerate(iterations): if idx + 1 < len(iterations): for idxx, (i1, i2) in enumerate(zip(i['itemsclicked'], iterations[idx + 1]['itemsclicked'])): if i['itemsclicked'][idxx]: click_size[idx][idxx] = 0.5 if not i1 == i2: click_pos[idxx] = (i['x'], i['z'], i['time_val']) click_color[idxx] = (128, 128, 128, 255) else: for idxx, i1 in enumerate(i['itemsclicked']): if i['itemsclicked'][idxx]: click_size[idx][idxx] = 0.5 ''' click_pos, _, click_size, click_color = get_click_locations_and_indicies(iterations, items, meta) click_scatter = gl.GLScatterPlotItem(pos=click_pos, size=click_size[0], color=click_color, pxMode=False) window.addItem(click_scatter) # If Test, Generate Reconstruction Items event_state_labels, item_number_label, item_label_filename, cols = get_item_details() # if meta['phase'] == '7' or meta['phase'] == '8': # item_number_label = ['bottle', 'clover', 'boot', 'bandana', 'guitar'] # item_label_filename = ['bottle.jpg', 'clover.jpg', 'boot.jpg', 'bandana.jpg', 'guitar.jpg'] # cols = [(255, 255, pastel_factor), (255, pastel_factor, pastel_factor), (pastel_factor, 255, pastel_factor), # (pastel_factor, pastel_factor, 255), (128, pastel_factor / 2, 128)] reconstruction_item_scatter_plot = None reconstruction_item_lines = [] if meta['phase'] == '2' or meta['phase'] == '5' or meta['phase'] == '8': reconstruction_items, order = parse_test_items(iterations, cols, item_number_label, event_state_labels) pos = np.empty((len(reconstruction_items), 3)) size = np.empty((len(reconstruction_items))) color = np.empty((len(reconstruction_items), 4)) # Iterate through the reconstruction items and visualize them for idx, i in enumerate(reconstruction_items): pos[idx] = i['pos'] size[idx] = 2 if i['direction'] == 0: size[idx] = 0 color[idx] = (i['color'][0] / 255, i['color'][1] / 255, i['color'][2] / 255, 1) end = pos[idx] if i['direction'] == 1: end = (end[0], end[1], 0) elif i['direction'] == 2 or i['direction'] == 0: end = (end[0], end[1], end_time) line = gl.GLLinePlotItem(pos=np.vstack([[pos[idx][0], end[0]], [pos[idx][1], end[1]], [pos[idx][2], end[2]]]).transpose(), color=pg.glColor(i['color']), width=3, antialias=True) reconstruction_item_lines.append(line) window.addItem(line) img_path = item_label_filename[idx] img = imread(os.path.join(local_directory, img_path)) expected_size = 2.0 image_scale = expected_size / float(img.shape[0]) offset_param = 0.0 - image_scale / 2 - expected_size / 2 tex = pg.makeRGBA(img)[0] label_image = gl.GLImageItem(tex) t = pos[idx][2] if i['direction'] == 0: t = end_time label_image.translate(pos[idx][0] + offset_param, pos[idx][1] + offset_param, t) label_image.scale(image_scale, image_scale, image_scale) window.addItem(label_image) billboard_item_labels.append(label_image) reconstruction_item_scatter_plot = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False) window.addItem(reconstruction_item_scatter_plot) #################################################################################################################### # Show UI #################################################################################################################### window.show() logging.info("Showing plot. Close plot to exit program.") #################################################################################################################### # Custom Keyboard Controls #################################################################################################################### # These variables are modified by the keyboard controls idx = 0 num_points_to_update = 5 saved_points_to_update = 0 paused = False # GUI Callbacks def speed_up(): global num_points_to_update, paused if not paused: num_points_to_update += 5 logging.info("Setting speed to " + str(num_points_to_update) + " points per tick.") def speed_down(): global num_points_to_update, paused if not paused: num_points_to_update -= 5 logging.info("Setting speed to " + str(num_points_to_update) + " points per tick.") def pause(): global num_points_to_update, saved_points_to_update, paused if not paused: logging.info("Paused.") saved_points_to_update = num_points_to_update num_points_to_update = 0 paused = True else: logging.info("Unpaused.") num_points_to_update = saved_points_to_update saved_points_to_update = -0.5 paused = False def reset(): global idx, line_color_state logging.info("Resetting to time zero.") idx = 0 for index in range(0, len(line_color_state) - 1): line_color_state[index] = (0, 0, 0, 0) def go_to_end(): global idx, line_color_state, line_color logging.info("Going to end.") idx = len(line_color_state) - 1 for index in range(0, len(line_color_state) - 1): line_color_state[index] = line_color[index] def close_all(): global timer, app logging.info("User Shutdown Via Button Press") timer.stop() app.closeAllWindows() # Visibility Variables grid_visible = True base_visible = True color_bars_visible = True items_visible = True path_line_visible = True reconstruction_item_lines_visible = True billboard_item_labels_visible = True def toggle_grid_visible(): global grid_visible if grid_visible: for g in grid_items: g.hide() grid_visible = False else: for g in grid_items: g.show() grid_visible = True def toggle_base_visible(): global base_visible if base_visible: base_image.hide() base_visible = False else: base_image.show() base_visible = True def toggle_color_bars_visible(): global color_bars_visible if color_bars_visible: for bar in color_bars: bar.hide() color_bars_visible = False else: for bar in color_bars: bar.show() color_bars_visible = True def toggle_items_visible(): global items_visible if items_visible: item_scatter_plot.hide() for il in item_lines: il.hide() items_visible = False else: item_scatter_plot.show() for il in item_lines: il.show() items_visible = True def toggle_path_line_visible(): global path_line_visible if path_line_visible: path_line.hide() click_scatter.hide() path_line_visible = False else: path_line.show() click_scatter.show() path_line_visible = True def toggle_reconstruction_item_lines_visible(): global reconstruction_item_lines_visible if reconstruction_item_lines_visible: if reconstruction_item_scatter_plot is not None: reconstruction_item_scatter_plot.hide() for ril in reconstruction_item_lines: ril.hide() reconstruction_item_lines_visible = False else: if reconstruction_item_scatter_plot is not None: reconstruction_item_scatter_plot.show() for ril in reconstruction_item_lines: ril.show() reconstruction_item_lines_visible = True def toggle_billboard_item_labels_visible(): global billboard_item_labels_visible if billboard_item_labels_visible: for il in billboard_item_labels: il.hide() billboard_item_labels_visible = False else: for il in billboard_item_labels: il.show() billboard_item_labels_visible = True # GUI Initialization sh = QtGui.QShortcut(QtGui.QKeySequence("+"), window, speed_up) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("-"), window, speed_down) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence(" "), window, pause) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("R"), window, reset) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("E"), window, go_to_end) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("Escape"), window, close_all) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("1"), window, toggle_grid_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("2"), window, toggle_base_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("3"), window, toggle_color_bars_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("4"), window, toggle_items_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("5"), window, toggle_path_line_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("6"), window, toggle_reconstruction_item_lines_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) sh = QtGui.QShortcut(QtGui.QKeySequence("7"), window, toggle_billboard_item_labels_visible) sh.setContext(QtCore.Qt.ApplicationShortcut) #################################################################################################################### # Animation Loop #################################################################################################################### timer = QtCore.QTimer() # noinspection PyUnresolvedReferences timer.timeout.connect(update) timer.start(1) #################################################################################################################### # PyQtGraph Initialization #################################################################################################################### if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): # noinspection PyArgumentList QtGui.QApplication.instance().exec_()
return 0 # print(test_re.datalines) for i, line_data in enumerate(test_re.datalines): test_re.getStockData(line_data["name"]) print(line_data["name"]) print(line_data["price"]) exec("curve{}.setData(line_data['price'])".format(i)) #stockline 1 ,2 save the data set exec("stockline{} = line_data['price']".format(i)) # stock_curve0.setData(line_data["price"]) # stock_curve1.setData(old_line["price"]) # old_line = line_data timer = QtCore.QTimer() timer.timeout.connect(update) # interval 29 sec to update the plotting timer.start(29000) # region.sigRegionChanged.connect(update) # def updateRegion(window, viewRange): rgn = viewRange[0] region.setRegion(rgn) p1.sigRangeChanged.connect(updateRegion) region.setRegion([1000, 2000])
def __init__(self, capture, cam='cam'): self.punched = QtCore.Signal(object) self.timer = QtCore.QTimer()
def __init__(self,*args,**kwargs): super(QuadrotorWidget,self).__init__(*args,**kwargs) self.object = 0 self.lastPos = QtCore.QPoint() self.trolltechGreen = QtGui.QColor.fromCmykF(0.40,0.0,1.0,0.0) self.trolltechPurple = QtGui.QColor.fromCmykF(0.39,0.39,0.0,0.0) # window parameters self.window = 0 ## window size in pixels. width and height self.window_size = (800,800) self.window_size_minimum = (400,400) ## perspective self.fovy = 60 self.near = 0.01 self.far = 2000 # axes parameters self.tip = 0 self.ORG = [0,0,0] self.AXES = [[2,0,0],[0,2,0],[0,0,2]] self.AXES_NORM = [[-1,0,0],[0,-1,0],[0,0,-1]] self.mat_diffuse = (1.0,0.0,0.0,0.0) # material and light parameters self.mat_specular = (0.2,0.2,0.2,0.2) self.mat_shininess = 0.2 self.light_position = (10.0,10.0,10.0,0.0) self.white_light = (1.0,1.0,1.0,1.0) self.lmodel_ambient = (0.1,0.1,0.1,1.0) # load model self.drone_base = WFObject() self.drone_base.loadFile(get_source_name("models/drone_base.obj")) self.drone_propeller1 = WFObject() self.drone_propeller1.loadFile(get_source_name("models/drone_propeller1.obj")) self.drone_propeller2 = WFObject() self.drone_propeller2.loadFile(get_source_name("models/drone_propeller2.obj")) self.drone_propeller3 = WFObject() self.drone_propeller3.loadFile(get_source_name("models/drone_propeller3.obj")) self.drone_propeller4 = WFObject() self.drone_propeller4.loadFile(get_source_name("models/drone_propeller4.obj")) # Base Plane Size self.floor_size = (-100,100) self.floor_grid_num = 60 self.floor_color = (0.3,0.3,0.3) # rotation vector self.vector_radius = 0.4 self.vector_radius_color = [0.8,0.0,0.0] # quadrotor state set self.drone_position = [0,0,0] ## 312 yaw-roll-pitch self.drone_angles = [0,0,0] ## drone_motor_speed self.drone_motors_speed = [100.0,200.0,250.0,10.0] # info screen self.info_screen = None self.info_screen_size = (150,200) ## gap between the left border/top border and info screen self.info_screen_gap = (10,10) ## view size self.info_screen_L = 10 ## char size self.char_height = 4 self.char_gap = 2 # interaction parameters self.mouse_state = {'button':None,'position':[0,0]} self.scene_movement = [0,0] self.movement_ratio = 0.1 self.rotation_ratio = 0.1 self.scale_ratio = 0.01 self.camera_azimuth = 45 self.camera_attitude = 45 ## distance between eye and origin self.eye_R = 180 self.camera_view_center = [0,0,0] self.follow = True self.trace_visible = False self.vector_visible = False self.drone_position_history = [] ## drone trace color self.drone_trace_color = [1,0,0] # GUI glutInit() self.animationTimer = QtCore.QTimer() self.animationTimer.setSingleShot(False) self.animationTimer.timeout.connect(self.animate) self.animationTimer.start(25)
def start(self): self.campoGrafico.show() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.audio) self.timer.start(5)