예제 #1
0
    def __init__(self, title, topicArr, tmpArr, cmdBtnArr, spacers, btnSpacers):
        super(RobotWidget, self).__init__()

        self.setObjectName('robotWidget') # CSS object name
        self.robotName = title          # The name of the robot to be used as the title of the widget
        self.plotWidArr = []            # Array of PlotWidgets
        self.gotNewData = False         # FIXME: Should this be a int???
        self.gotNewAppData = False
        self.cmdBtnArr = cmdBtnArr      # Commands which can be sent to a robot
        self.topicArr = topicArr        # The custom buttons on a robot + default telemetry fields
        self.defaultTopicArr = tmpArr   # The default telemetry fields which every robot has
        self.cmdTupArr = []             # Array of tuples (QPushButton, Publisher)
        self.msgRingBuf = []            # Ring buffer of Telemetry msgs
        self.msgAppRingBuf = []
        self.msgRingMutex = QtCore.QMutex() # Mutex for the ring buffer
        self.msgAppRingMutex = QtCore.QMutex()
        self.btnLay = QtGui.QGridLayout() # Layout for the UI buttons
        self.isOddNumBtn = True         # Flag for formatting buttons
        self.outerLayout = QtGui.QGridLayout() # Base layout for the RobotWidget

        rospy.Subscriber('/' + self.robotName + '/telemetry', Telemetry, self.callback)  # Subscriber for this robot
        rospy.Subscriber('/' + self.robotName + '/phonereply', PhoneReply, self.app_callback)

        for topic in self.topicArr:
            if topic in self.defaultTopicArr:
                curvesNum = 2
            else:
                curvesNum = 1

            self.addPlot(title, topic, curvesNum)

        for i in range(spacers):
            space = QtGui.QSpacerItem(25, 100, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
            self.outerLayout.addItem(space, len(self.plotWidArr) + 1 + i, 0,
                                     QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)

        #TODO:
        """
        for cmd in cmdBtnArr:
            self.addButton(cmd)
        """

        for i in range(btnSpacers):
            self.btnLay.setRowMinimumHeight((len(self.cmdTupArr) + i) / 2, 35)  # FIXME???

        self.outerLayout.setRowStretch(len(self.plotWidArr) + 1 + spacers, 1)
        self.outerLayout.addLayout(self.btnLay, len(self.plotWidArr) + 1 + spacers, 0,
                                   QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom)
        self.setLayout(self.outerLayout)
예제 #2
0
    def __init__(self, device, priority=None, parent=None):
        """device: timedcapture.Device"""
        super().__init__(parent=parent)
        self._device = device
        self._has_trigger = False
        try:
            self._device.triggered = True
            self._has_trigger = True
        except RuntimeError:
            _debug(
                "failed to run in the triggered mode; use free-running mode")
        self._acquisition = QtCore.QMutex()
        self._triggered = QtCore.QWaitCondition()  # used with _acquisition
        self._captured = QtCore.QWaitCondition()  # used with _acquisition
        self._toquit = False  # used with _acquisition
        self._priority = DEFAULT_PRIORITY if priority is None else priority

        self._evaluator = no_evaluator
        self._output = no_output
        self._metadata = {}
예제 #3
0
    def __init__(self, interval_ms, acquisition, parent=None):
        super().__init__(parent=parent)
        self._thread = QtCore.QThread()
        self.moveToThread(self._thread)
        self._interval = interval_ms / 1000
        self._target = _now()
        self._continue = False
        self.wait = self._thread.wait
        self.quit = self._thread.quit
        self._timing = QtCore.QMutex()
        self._waitAcq = acquisition.triggerAndWait

        acquisition.setStaticMetadata(
            "interval", dict(mode="busy-wait", target_ms=interval_ms))
        acquisition.acquisitionStarting.connect(self._thread.start)
        acquisition.acquisitionEnding.connect(self.signal,
                                              QtCore.Qt.DirectConnection)
        self._thread.started.connect(self.run, QtCore.Qt.DirectConnection)
        self._thread.started.connect(self.raisePriority)
        self.timeout.connect(acquisition.trigger_capture,
                             QtCore.Qt.QueuedConnection)
예제 #4
0
vb_gray.addItem(img_gray)
vb_gray.autoRange()

vb_dist.addItem(img_dist)
vb_dist.autoRange()

vb_ambient.addItem(img_ambient)
vb_ambient.autoRange()

# mutex for exchange frame_data
frame_data = bytearray(320 * 240 * 4 * 4)
f_dist = None
f_gray = None
dev = None
f_mutex = QtCore.QMutex()

# -----------  dmcam data sampler ------------


def on_cap_err(dev, errnumber, errarg):
    print("caperr: %s" % dmcam.error_name(errnumber))
    if errnumber == dmcam.DMCAM_ERR_CAP_FRAME_DISCARD:
        print("   %d frame discarded" % int(errarg))
    # if return false, the capture process will be stopped
    return True


# init the lib with default log file
dmcam.init(None)
# init with specified log file
예제 #5
0
    def __init__(self, *args, **kwargs):
        super(SensorApplication, self).__init__(*args, **kwargs)

        # logger properties setup
        self.folder_name = "logs/"
        traces_name = self.folder_name + dt.datetime.now().strftime(
            "%d-%m-%Y %Hh%Mm%Ss")
        self.cvs_name = traces_name + ".csv"
        self.logfile_name = traces_name + ".txt"
        os.makedirs(os.path.dirname(self.logfile_name), exist_ok=True)
        logging.basicConfig(filename=self.logfile_name,
                            level=logging.DEBUG,
                            datefmt="%H:%M:%S",
                            format=LOG_FORMAT)
        self.logger1 = logging.getLogger('RawData')
        self.logger2 = logging.getLogger('ProgFlow')

        # Thread poll for getting serial line
        self.thread_pool = QtCore.QThreadPool()
        self.thread_pool.setMaxThreadCount(20)
        self.logger2.info("Multithreading with maximum %d threads" %
                          self.thread_pool.maxThreadCount())

        # Serial properties setup
        self.serial_dev = serial.Serial()
        self.serial_dev.port = 'COM4'
        self.serial_dev.baudrate = 115200
        self.serial_dev.timeout = 2

        # graphic properties setup
        self.win = QtGui.QMainWindow()
        self.area = DockArea()
        self.win.setCentralWidget(self.area)
        self.win.resize(1200, 650)
        self.win.setWindowTitle('IMU signal viewer')
        # Note that size arguments are only a suggestion; docks will still have to
        # fill the entire dock area and obey the limits of their internal widgets
        self.d1 = Dock("Accelerometer", size=(400, 400))
        self.d2 = Dock("Magnetometer", size=(400, 400))
        self.d3 = Dock("Gyroscope", size=(400, 400))
        self.d4 = Dock("LinearAcc", size=(800, 250))
        self.d5 = Dock("Position", size=(800, 400))
        self.d6 = Dock("Euler", size=(800, 250))
        self.d7 = Dock("Menu", size=(50, 50))
        self.d8 = Dock("Calibration", size=(400, 400))
        self.d9 = Dock("Graph", size=(CANVAS_LENGTH, CANVAS_HEIGHT))
        self.d10 = Dock("Word", size=(800, 250))
        self.d11 = Dock("Clasification", size=(400, 400))
        self.area.addDock(
            self.d4, 'left')  # place self.d6 at left edge of dock self.area
        self.area.addDock(self.d10, 'above', self.d4)
        self.area.addDock(self.d6, 'above', self.d10)
        self.area.addDock(self.d5, 'bottom',
                          self.d6)  # place self.d9 bottom edge of self.d6
        self.area.addDock(self.d9, 'above', self.d5)
        self.area.addDock(self.d1, 'right')
        self.area.addDock(self.d3, 'bottom', self.d1)
        self.area.addDock(self.d8, 'bottom', self.d3)
        self.area.addDock(self.d11, 'above', self.d8)
        self.area.addDock(self.d2, 'above', self.d11)
        self.area.addDock(self.d7, 'bottom', self.d2)
        plot_acc = pg.PlotWidget(title="Accelerometer m/s^2")
        plot_acc.addLegend()
        plot_acc.setLabel('bottom', 'Time', units='s')
        plot_acc.setYRange(-60, 60)
        self.acc_x = plot_acc.plot(pen=pg.mkPen('r', width=2), name='x')
        self.acc_y = plot_acc.plot(pen=pg.mkPen('b', width=2), name='y')
        self.acc_z = plot_acc.plot(pen=pg.mkPen('g', width=2), name='z')
        self.d1.addWidget(plot_acc)
        plot_mag = pg.PlotWidget(title="Magnetometer uT")
        plot_mag.addLegend()
        plot_mag.setLabel('bottom', 'Time', units='s')
        plot_mag.setYRange(-90, 90)
        self.mag_x = plot_mag.plot(pen=pg.mkPen('r', width=2), name='x')
        self.mag_y = plot_mag.plot(pen=pg.mkPen('b', width=2), name='y')
        self.mag_z = plot_mag.plot(pen=pg.mkPen('g', width=2), name='z')
        self.d2.addWidget(plot_mag)
        plot_gyr = pg.PlotWidget(title="Gyroscope rad/s")
        plot_gyr.addLegend()
        plot_gyr.setLabel('bottom', 'Time', units='s')
        plot_gyr.setYRange(-1500, 1500)
        self.gyr_x = plot_gyr.plot(pen=pg.mkPen('r', width=2), name='x')
        self.gyr_y = plot_gyr.plot(pen=pg.mkPen('b', width=2), name='y')
        self.gyr_z = plot_gyr.plot(pen=pg.mkPen('g', width=2), name='z')
        self.d3.addWidget(plot_gyr)
        plot_lin = pg.PlotWidget(title="Linear Accelerometer m/s^2")
        plot_lin.addLegend()
        plot_lin.setLabel('bottom', 'Time', units='s')
        plot_lin.setYRange(-60, 60)
        self.lin_x = plot_lin.plot(pen=pg.mkPen('r', width=2), name='x')
        self.lin_y = plot_lin.plot(pen=pg.mkPen('b', width=2), name='y')
        self.lin_z = plot_lin.plot(pen=pg.mkPen('g', width=2), name='z')
        self.d4.addWidget(plot_lin)
        plot_eul = pg.PlotWidget(title="Euler degrees")
        plot_eul.addLegend()
        plot_eul.setLabel('bottom', 'Time', units='s')
        plot_eul.setYRange(-200, 200)
        self.eul_x = plot_eul.plot(pen=pg.mkPen('r', width=2), name='x')
        self.eul_y = plot_eul.plot(pen=pg.mkPen('b', width=2), name='y')
        self.eul_z = plot_eul.plot(pen=pg.mkPen('g', width=2), name='z')
        self.d6.addWidget(plot_eul)

        # canvas dock
        self.label = QtWidgets.QLabel()
        self.canvas = QtGui.QPixmap(800, 400)
        self.canvas.fill(QtCore.Qt.white)
        self.label.setPixmap(self.canvas)
        self.d9.addWidget(self.label)
        self.last_x, self.last_y = CANVAS_LENGTH / 2, CANVAS_HEIGHT / 2
        self.last_ang_x, self.last_ang_y = 0.0, 0.0

        # display word dock
        layout_word = pg.LayoutWidget()
        self.label_word = QtGui.QLabel()
        layout_word.addWidget(self.label_word, row=0, col=0)
        self.d10.addWidget(layout_word)

        # plot position dock
        self.plot_position_wg = pg.PlotWidget(title="Character Display")
        self.plot_position_wg.setYRange(-0.50, 0.50)
        self.plot_position_wg.setXRange(-0.50, 0.50)
        self.plot_position_wg.addLegend()
        self.position_coord = self.plot_position_wg.plot(
            pen=pg.mkPen('r', width=5))
        self.d5.addWidget(self.plot_position_wg)

        # calibration window dock
        layout_calibration = pg.LayoutWidget()
        label_calib = QtGui.QLabel("Calibration:")
        self.label_calib_acc = QtGui.QLabel("ACC: 0")
        self.label_calib_gyr = QtGui.QLabel("GYR: 0")
        self.label_calib_mag = QtGui.QLabel("MAG: 0")
        self.label_calib_sys = QtGui.QLabel("SYS: 0")
        label_quat = QtGui.QLabel("Quaternion:")
        label_eul = QtGui.QLabel("Euler:")
        self.label_quaternion = QtGui.QLabel("W: 0.0\tX: 0.0\tY: 0.0\tZ: 0.0")
        self.label_euler = QtGui.QLabel("X: 0.0\tY: 0.0\tZ: 0.0")
        layout_calibration.addWidget(label_calib, row=0, col=0)
        layout_calibration.addWidget(self.label_calib_acc, row=1, col=0)
        layout_calibration.addWidget(self.label_calib_gyr, row=2, col=0)
        layout_calibration.addWidget(self.label_calib_mag, row=3, col=0)
        layout_calibration.addWidget(self.label_calib_sys, row=4, col=0)
        layout_calibration.addWidget(label_quat, row=5, col=0)
        layout_calibration.addWidget(self.label_quaternion, row=5, col=1)
        layout_calibration.addWidget(label_eul, row=6, col=0)
        layout_calibration.addWidget(self.label_euler, row=6, col=1)
        self.d8.addWidget(layout_calibration)

        # classification window dock
        layout_letter = pg.LayoutWidget()
        self.label_letter = QtGui.QLabel("")
        self.label_letter.setFont(QtGui.QFont('Arial', 50))
        layout_letter.addWidget(self.label_letter, row=0, col=0)
        self.d11.addWidget(layout_letter)

        # Menu window dock
        layout_buttons = pg.LayoutWidget()
        connect_b = QtGui.QPushButton(
            "Connect")  # To start listening to Serial port
        self.record_b = QtGui.QPushButton("Record")  # To start Recording data
        self.stop_b = QtGui.QPushButton("Stop")  # To start Recording data
        self.disconnect_b = QtGui.QPushButton(
            "Disconnect Device")  # To start Recording data
        self.change_name_b = QtGui.QPushButton(
            "Set log name")  # To start Recording data
        recenter_b = QtGui.QPushButton(
            "Re-Center")  # Re-center pointer position
        self.textbox = QtGui.QLineEdit()
        label_1 = QtGui.QLabel("""Orientation Mode: """)
        self.mode_box = QtGui.QComboBox()
        self.mode_box.addItems(
            ["complementary_filter", "Madgwick", "sensor_ahrs"])
        label_2 = QtGui.QLabel("""Word Mode: """)
        self.word_box = QtGui.QComboBox()
        self.word_box.addItems(["OFF", "ON"])
        label_3 = QtGui.QLabel("""Word command: """)
        self.start_b = QtGui.QPushButton(
            "Start")  # To start listening to Serial port
        self.next_b = QtGui.QPushButton("Next")  # To start Recording data
        self.end_b = QtGui.QPushButton("End")  # To start Recording data
        layout_buttons.addWidget(connect_b, row=0, col=0)
        layout_buttons.addWidget(self.record_b, row=0, col=1)
        layout_buttons.addWidget(self.stop_b, row=0, col=2)
        layout_buttons.addWidget(self.disconnect_b, row=0, col=3)
        layout_buttons.addWidget(self.change_name_b, row=1, col=0)
        layout_buttons.addWidget(self.textbox, row=1, col=1, colspan=3)
        layout_buttons.addWidget(label_1, row=2, col=0)
        layout_buttons.addWidget(self.mode_box, row=2, col=1, colspan=2)
        layout_buttons.addWidget(recenter_b, row=2, col=3)
        layout_buttons.addWidget(label_2, row=3, col=0)
        layout_buttons.addWidget(self.word_box, row=3, col=1, colspan=2)
        layout_buttons.addWidget(label_3, row=4, col=0)
        layout_buttons.addWidget(self.start_b, row=4, col=1)
        layout_buttons.addWidget(self.next_b, row=4, col=2)
        layout_buttons.addWidget(self.end_b, row=4, col=3)
        connect_b.pressed.connect(self.listen)
        self.record_b.pressed.connect(self.record)
        self.stop_b.pressed.connect(self.stop_recording)
        self.disconnect_b.pressed.connect(self.disconnect)
        self.change_name_b.pressed.connect(self.change_name)
        self.start_b.pressed.connect(self.start_letter)
        self.next_b.pressed.connect(self.next_letter)
        self.end_b.pressed.connect(self.end_letter)
        recenter_b.pressed.connect(self.recenter_pointer)
        self.mode_box.currentIndexChanged.connect(self.mode_change)
        self.word_box.currentIndexChanged.connect(self.word_mode_change)
        self.start_b.setEnabled(False)
        self.next_b.setEnabled(False)
        self.end_b.setEnabled(False)
        self.d7.addWidget(layout_buttons)

        self.mutex = QtCore.QMutex()  # mutex to control raw_data access
        self.mutex_line = QtCore.QMutex()  # mutex to control raw_line access
        self.raw_line = []  # This list will keep the incoming lines to process
        self.imu_struct = {
            "TIME": [],
            "ELAPSED_SECONDS": [],
            "PSTATE": [],
            "acc_x": [],
            "acc_y": [],
            "acc_z": [],
            "mag_x": [],
            "mag_y": [],
            "mag_z": [],
            "gyr_x": [],
            "gyr_y": [],
            "gyr_z": [],
            "lin_x": [],
            "lin_y": [],
            "lin_z": [],
            "eul_x": [],
            "eul_y": [],
            "eul_z": [],
            "qua_w": [],
            "qua_x": [],
            "qua_y": [],
            "qua_z": []
        }
        # Prettier and better solution would be to include this values to
        # imu_struct but that would imply REFACTORING the code to calculate
        # the x & y position in the fill table thread instead of the plotting thread
        self.empty_xy_points = {"x": [], "y": []}
        self.canvas_xy_points = copy.deepcopy(self.empty_xy_points)
        ##########################################################################################
        #  The rate of receiving RAW data depends on how much data is being transmitted
        # ########################################################################################
        #  Data received            |   Possible Calculation Methods    |   speed
        #  --------------------------------------------------------------------------------
        #  acc + gyr + quat         |   comp. filter                    |   Hz = 33  period = 30ms
        ##########################################################################################
        #  Orientation Modes:
        #   complementary_filter    Not working correctlty, can be improved or removed
        #   Madgwick                Using Madgwick's Sensor Fusion Algorithm
        #   sensor_ahrs             Using the Orientation provided by the sensor
        ##########################################################################################
        self.mode = "sensor_ahrs"
        self.period = 0.035  # The period depends on the transmission rate from the finger wearable
        self.rate = 1 / self.period
        # this is the structure where the las 50 samples are stored for displaying on the real-time
        # plots on screen.
        self.raw_data = copy.deepcopy(self.imu_struct)
        # empty structure, must be keep that way
        self.data_struct = copy.deepcopy(self.imu_struct)
        # This is the structure where the data is stored for storing the online data after completing
        # the finger-movement.
        self.to_save_data = copy.deepcopy(self.raw_data)

        # Display the GUI
        self.win.show()

        # Calibration from BNO055 IMU sensor
        self.accel_calibration = 0
        self.gyro_calibration = 0
        self.magnet_calibration = 0
        self.system_calibration = 0

        # PyQt timer
        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.update_graph)

        #flags to control de state machine (see Thesis Document chapter 3.4)
        self.first_angle_measure = True
        self.first_line = True
        self.first_update = True
        self.first_graph_update = True
        self.stop_threads = False
        self.init_time = 0
        self.recording = False
        self.word_mode = False
        self.recording_word = False
        self.word_letter_number = 0
        # Madgwick variable
        # By Increasing the value of Beta(magnetic & acc correction to gyro) is faster but more unstable
        self.madgwick_ahrs = skin.imus.Madgwick(rate=self.rate, Beta=0.10)
        self.prediction_model = None
        self.load_model()
        self.word_prediction = ""
예제 #6
0
 def __init__(self, parent=None):
     QtCore.QThread.__init__(self, parent)
     self.lock = QtCore.QMutex()
예제 #7
0
    def __init__(self):
        super(MyWidget, self).__init__()
        #  用来表示点阵的区域
        w = pg.GraphicsLayoutWidget(show=True)
        self.__SetPlotWidget(w)
        #   标签
        title = QtWidgets.QLabel(self)
        title.setText("聚类算法")
        title.setAlignment(QtCore.Qt.AlignCenter)
        lb1 = QtWidgets.QLabel(self)
        lb1.setText("文件名:")
        lb2 = QtWidgets.QLabel(self)
        lb2.setText("聚类方法:")
        lb3 = QtWidgets.QLabel(self)
        lb3.setText("参数:")
        lb4 = QtWidgets.QLabel(self)
        lb4.setText("反馈:")
        lb5 = QtWidgets.QLabel(self)
        lb5.setText("准确率:")
        lb6 = QtWidgets.QLabel(self)
        lb6.setText("用时:")
        lb7 = QtWidgets.QLabel(self)
        lb7.setText("描点大小:")
        #  参数控制
        self.para = [QtWidgets.QLabel(self) for i in range(3)]
        self.para_value = [QtWidgets.QLineEdit() for i in range(3)]
        for i in range(3):
            self.para[i].setText("--:")
            self.para_value[i].setText("")
        #  函数选择
        self.func_text = QtWidgets.QComboBox()
        self.func_text.addItems(["--"] + list(AlgorithmList.keys()))
        self.func_text.activated.connect(self.changefunc)
        #  特殊选项勾选
        self.ifbest = QtWidgets.QCheckBox("最佳模式", self)
        self.ifbest.stateChanged.connect(self.changeifbest)

        self.auto_retry = QtWidgets.QCheckBox("自动刷新", self)
        self.auto_retry.stateChanged.connect(self.changeAutoRetry)
        self.retry_thread = QtCore.QThread()
        self.retry_thread.started.connect(self.__autoretry)
        self.qtlock = QtCore.QMutex()
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.timeOut)
        self.threadd = Runthread(self._threadRetry)
        self.sin.connect(self.threadd.stop)
        #  编写文件名
        self.file_name = QtWidgets.QLineEdit()
        self.file_name.setText(self.file)
        self.file_name.editingFinished.connect(self.changefile)
        self.load_data(self.file)
        #  修改点大小
        self.sizeEdit = QtWidgets.QLineEdit()
        self.sizeEdit.setText(f"{self.point_size}")
        self.sizeEdit.editingFinished.connect(self.changesize)
        #  准确率显示
        self.Accuracy = QtWidgets.QLabel(self)
        self.Accuracy.setText("--")
        #  用时显示
        self.Time = QtWidgets.QLabel(self)
        self.Time.setText("--")

        # 按钮组
        self.btn1 = QtWidgets.QPushButton('Retry', self)
        self.btn1.clicked.connect(self.button_Retry)

        self.btn2 = QtWidgets.QPushButton('Check', self)
        self.btn2.clicked.connect(self.button_Check)
        self.info = QtWidgets.QTextEdit()

        ## 创建一个栅格Grid布局作为窗口的布局
        layout = QtWidgets.QGridLayout()
        self.setLayout(layout)
        ## 细节的控制每个区域所属的格子
        layout.addWidget(w, 0, 0, 0,
                         1)  # plot goes on right side, spanning all rows
        layout.addWidget(title, 0, 1, 1, 2)
        layout.addWidget(lb1, 1, 1)
        layout.addWidget(self.file_name, 1, 2)
        layout.addWidget(lb2, 2, 1)
        layout.addWidget(self.func_text, 2, 2)
        layout.addWidget(lb3, 3, 1)
        for i in range(3):
            layout.addWidget(self.para[i], 4 + i, 1)
            layout.addWidget(self.para_value[i], 4 + i, 2)

        layout.addWidget(self.btn1, 7, 1)  # button goes in upper-left
        layout.addWidget(self.btn2, 7, 2)  # button goes in upper-left
        layout.addWidget(lb4, 8, 1)
        layout.addWidget(self.info, 9, 1, 1,
                         2)  # list widget goes in bottom-left
        layout.addWidget(lb7, 10, 1)
        layout.addWidget(self.sizeEdit, 10, 2)
        layout.addWidget(lb5, 11, 1)
        layout.addWidget(self.Accuracy, 11, 2)
        layout.addWidget(lb6, 12, 1)
        layout.addWidget(self.Time, 12, 2)
        layout.addWidget(self.ifbest, 13, 1)
        layout.addWidget(self.auto_retry, 13, 2)
예제 #8
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._numQueuedImages = 0
     self._numQueuedImagesMutex = QtCore.QMutex()
예제 #9
0
    def __init__(self):
        
# Load an instance of the Digitizer control object
         
        
# Load the ui file for GUI
         QtGui.QMainWindow.__init__(self)
         Ui_MainWindow.__init__(self)
         self.setupUi(self)
         self.mutex = QtCore.QMutex()

         
# Window for real time streaming
         pg.setConfigOption('background','w')
         pg.setConfigOption('foreground','k')
         self.pen=pg.mkPen(color=(0,0,0))
         self.pen2=pg.mkPen(color=(255,0,0))
         #self.pen=pg.mkPen(1)
         #self.streamwindow=pg.LayoutWidget()
         self.plotchannels = pg.GraphicsLayoutWidget()
         self.StreamWindow.addWidget(self.plotchannels,row=0,col=0,rowspan=1,colspan=1)
         
         
         self.plt_chA =self.plotchannels.addPlot(row=0,col=0)
         self.plt_chA.setLabel(axis='left',text='Signal')
         self.plt_chA.setLabel(axis='bottom',text='Tof (x0.5ns)')
         self.plt_chA.showGrid(1,1,alpha=0.5)
         self.plt_datachA=pg.PlotDataItem(np.arange(2000),np.zeros((2000)))
         self.plt_chA.addItem(self.plt_datachA)
         
         
         self.roiA = pg.LinearRegionItem(values=(500,1000),bounds=(-30000,30000)) # first vector =[x0,y0], second vector =[lx,ly]
         self.plt_chA.addItem(self.roiA)
         self.roiA.setZValue(10)  # make sure ROI is drawn above image
         #self.roiA.sigRegionChanged.connect(self.UpdatePlot)
         
         self.plt_intchA =self.plotchannels.addPlot(row=1,col=0)
         self.plt_intchA.setLabel(axis='left',text='Integrated Signal')
         self.plt_intchA.setLabel(axis='bottom',text='real time (ms)')
         self.plt_intchA.showGrid(1,1,alpha=0.5)
         
        
         self.ROIRate_button.display(0)
         
         
         self.plotchannelsSCTDC = pg.GraphicsLayoutWidget()
         self.StreamWindow_SCTDC.addWidget(self.plotchannelsSCTDC,row=0,col=0,rowspan=1,colspan=1)
         self.plotScan=self.plotchannelsSCTDC.addPlot(row=0,col=0)
         self.imgSCTDC = pg.ImageItem()
         self.plotScan.addItem(self.imgSCTDC)
         
         
         self.hist = pg.HistogramLUTItem()
         self.hist.setImageItem(self.imgSCTDC)
         self.plotchannelsSCTDC.addItem(self.hist,row=0,col=1)
         
         self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g')
         self.hist.vb.addItem(self.isoLine)
         self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier
         self.isoLine.setValue(0.8)
         self.isoLine.setZValue(1000) # bring iso line above contrast controls
         

#Digitizer stream parameters

         self.StartStream_button.clicked.connect(self.StartStream)
         self.StopStream_button.clicked.connect(self.StopStream)
         self.SignalThresh_button.valueChanged.connect(self.setAcquisitionParameters)
         self.TOFT0_button.valueChanged.connect(self.setAcquisitionParameters)
         #self.ChA_broadcast_button.stateChanged.connect(self.
         


# Digitizer record parameters
        
         self.RecSS_button.clicked.connect(self.setAcquisitionParameters)
         self.RecAvg_button.clicked.connect(self.setAcquisitionParameters)
         self.progress=0.0

         self.Nsamples_button.valueChanged.connect(self.setAcquisitionParameters)
         self.Nseconds_button.valueChanged.connect(self.setAcquisitionParameters)
         self.Reprate_button.activated.connect(self.setAcquisitionParameters)
         
         self.PretriggerVal_button.valueChanged.connect(self.setAcquisitionParameters)
         self.HoldoffVal_button.valueChanged.connect(self.setAcquisitionParameters)
         
         self.RecRef_button.clicked.connect(self.SaveTrace)
         

# Metadata record parameters
         # Voltages
         self.Vtofmcpf_button.valueChanged.connect(self.setMetadata)
         self.Vgrid_button.valueChanged.connect(self.setMetadata)
         self.Vtofdtube_button.valueChanged.connect(self.setMetadata)
         self.Vrep_button.valueChanged.connect(self.setMetadata)
         self.Vext_button.valueChanged.connect(self.setMetadata)
         self.Vcorr_button.valueChanged.connect(self.setMetadata)
         self.Vvmimcpf_button.valueChanged.connect(self.setMetadata)
         self.Vvmimcpb_button.valueChanged.connect(self.setMetadata)
         self.Vph_button.valueChanged.connect(self.setMetadata)
         
         # Channels labels
         #self.ChAlabel_button.textChanged.connect(self.setMetadata)
         #self.ChBlabel_button.textChanged.connect(self.setMetadata)
         
         #delay value for single tof (no dscan)
         self.Singledelay_button.valueChanged.connect(self.setMetadata)
         
         # Comments on the scan
         self.Comments_button.textChanged.connect(self.setMetadata)
         
# Path for file saving
         self.FilePath_button.textChanged.connect(self.setAcquisitionParameters)
         self.FilePath='//sb1files.epfl.ch/lsu/LSU_DATA/Wetlab/Data/Photoelectrons/20180809'
         self.FilePathBrowser_button.clicked.connect(self.setDir)
#         
         self.DscanMode_button.stateChanged.connect(self.setAcquisitionParameters)
         self.DscanStart_button.valueChanged.connect(self.setAcquisitionParameters)
         self.DscanStop_button.valueChanged.connect(self.setAcquisitionParameters)
         self.DscanStep_button.valueChanged.connect(self.setAcquisitionParameters)
         
         #self.FilePath_button.textChanged.connect(self.setAcquisitionParameters)
         self.Delayfile=[]
         self.DelayfilePath=''
         self.DelayfileBrowser_button.clicked.connect(self.setDelayfile)

# Start/Stop
         
         
         
         self.data_chA = np.zeros((self.Nsamples_button.value()),dtype=np.int64)
         self.RecData_chA=np.zeros((self.Nsamples_button.value()*2),dtype=np.int64)
         
         self.diff_data=0
         self.prev_data=0
         
         self.rolling_dataA = np.zeros((500,2)) # rolling array for integrated signal in real time from CHA
         self.rolling_count = 0
         self.t0 = 0 # first timeStamp recording

         self.SavedData_chA = np.zeros((self.Nsamples_button.value()),dtype=np.int64)
         
         self.StartAcq_button.clicked.connect(self.StartAcquisition)
         self.StopAcq_button.clicked.connect(self.StopAcquisition)
         self.AcqStart=0
         
         print 'GUI loaded'
         f.write('GUI loaded')
         
         self.timer=QtCore.QTimer()        
         self.timer.timeout.connect(self.UpdateRecording)
         
         self.MetadataDict=[]
         self.thread=[]
         self.SCTDCthread=[]
         self.TDCthread=[]
         self.broadcastthread=[]
         
         
         self.DAQ=DAQ()
         self.SCTDC=[]
         self.Dstage=DelayStage()
         
         
         
         self.KineticEnergy=np.zeros((self.Nsamples_button.value()))
         self.delaylist=np.zeros((1))
         
         f.write('init digitizer done')
         print 'init digitizer done'
예제 #10
0
    def __init__(self):
        #TemplateBaseClass.__init__(self)
        
        # Initialize Camera
        tlFactory = pylon.TlFactory.GetInstance()
        devices=tlFactory.EnumerateDevices
        print devices()[1].GetModelName()
        self.VMIcrtl = pylon.InstantCamera(tlFactory.CreateDevice(devices()[1]))
        #self.VMIcrtl.open()
        
        
        ## initialize camera acquisition settings
        self.NbAcq=10
        self.NbAcquired=0
        self.Threshold=0
        
        
        #self.VMIcrtl=VMIcrtl_ext.VMIcrtl();
        #Init semaphore
        self.mutex = QtCore.QMutex()


        #Initialize window

        self.win =pg.LayoutWidget()  # Main layout
        self.win.setWindowTitle('VMI GUI')

#Loadfile button
        self.loadbutton=QtGui.QPushButton('Load Data')
        self.loadbutton.clicked.connect(self.OpenFile)
#Take reference button
        self.refbutton=QtGui.QPushButton('Save Reference')
        self.refbutton.clicked.connect(self.SaveReference)
        
        self.Prevbutton=QtGui.QPushButton('Preview')
        self.Prevbutton.clicked.connect(self.PrevAcq)
        self.FlatBGbutton=QtGui.QPushButton('Flat Corr')
        self.FlatBGbutton.clicked.connect(self.LoadFlatCorrection)
        self.Startbutton=QtGui.QPushButton('Start')
        self.Startbutton.clicked.connect(self.StartAcq)
        self.Stopbutton=QtGui.QPushButton('Stop')
        self.Stopbutton.clicked.connect(self.StopAcq)
#Checkboxes

        self.checkbox0=QtGui.QCheckBox('Reference') #View the data feeded by the digitizer
        self.checkbox0.clicked.connect(self.updatePlot)

        self.checkbox1=QtGui.QCheckBox('Refresh Viewer') #View the data feeded by the digitizer
        self.checkbox1.clicked.connect(self.StreamOnOff)
        self.checkbox1.setEnabled(False)
        
        self.checkbox2=QtGui.QCheckBox('Norm Radial Distribution')
        self.checkbox2.clicked.connect(self.NormalizeDscan)
        self.checkbox3=QtGui.QCheckBox('Norm TOF')
        self.checkbox3.clicked.connect(self.NormalizeTOF)

# Center control buttons
        self.cxlabel=QtGui.QLabel('Center X pos')
        self.spinbox1=QtGui.QDoubleSpinBox()
        self.spinbox1.valueChanged.connect(self.updateROI)
        self.spinbox1.setMaximum(1000.0)
        self.spinbox1.setMinimum(0.0)
        self.spinbox1.setValue(204.0)
        self.cylabel=QtGui.QLabel('Center Y pos')
        self.spinbox2=QtGui.QDoubleSpinBox()
        self.spinbox2.valueChanged.connect(self.updateROI)
        self.spinbox2.setMaximum(1000.0)
        self.spinbox2.setMinimum(0.0)
        self.spinbox2.setValue(197.0)

#background removal buttons
        self.BGbutton=QtGui.QPushButton('Load XUV BG')
        self.BGbutton.clicked.connect(self.LoadBG)
        self.bglabel=QtGui.QLabel('BG removal amount')
        self.spinbox3=QtGui.QDoubleSpinBox()
        self.spinbox3.valueChanged.connect(self.updateBG)
        self.spinbox3.setMaximum(10.0)
        self.spinbox3.setMinimum(0.0)
        self.spinbox3.setValue(1.0)
        self.checkbox4=QtGui.QCheckBox('BG removed ON/OFF')
        self.checkbox4.clicked.connect(self.updateBG)

        self.checkbox5=QtGui.QCheckBox('pixels to energy')
        self.checkbox5.clicked.connect(self.updatePlot)
        self.EnCaliblabel=QtGui.QLabel('Energy Calibration coeff (x1e-6)')
        self.spinbox4=QtGui.QDoubleSpinBox()
        self.spinbox4.valueChanged.connect(self.updatePlot)
        self.spinbox4.setMaximum(10000.0)
        self.spinbox4.setMinimum(0.0)
        self.spinbox4.setValue(894.30)
        
        self.NAcqLabel=QtGui.QLabel('Number of acquisitions')
        self.spinbox5=QtGui.QSpinBox()
        self.spinbox5.valueChanged.connect(self.UpdateParameters)
        self.spinbox5.setMaximum(100000)
        self.spinbox5.setMinimum(0)
        self.spinbox5.setValue(50)
        
        self.checkbox6=QtGui.QCheckBox('Dscan')
        
        self.Dstart=QtGui.QLabel('Dstart')
        self.spinbox6=QtGui.QDoubleSpinBox()
        #self.spinbox6.valueChanged.connect(self.updatePlot)
        self.spinbox6.setMaximum(80.0)
        self.spinbox6.setMinimum(0.0)
        self.spinbox6.setValue(0.0)
        
        self.Dstop=QtGui.QLabel('Dstop')
        self.spinbox7=QtGui.QDoubleSpinBox()
        self.spinbox7.setMaximum(80.0)
        self.spinbox7.setMinimum(0.0)
        self.spinbox7.setValue(80.0)
        
        self.Dstep=QtGui.QLabel('Dstep')
        self.spinbox8=QtGui.QDoubleSpinBox()
        self.spinbox8.setMaximum(80.0)
        self.spinbox8.setMinimum(0.0)
        self.spinbox8.setValue(1.0)
        
        self.ThLabel=QtGui.QLabel('Threshold')
        self.spinbox9=QtGui.QSpinBox()
        self.spinbox9.valueChanged.connect(self.UpdateParameters)
        self.spinbox9.setMaximum(5000)
        self.spinbox9.setMinimum(1)
        self.spinbox9.setValue(1)
        
        self.checkbox7=QtGui.QCheckBox('Median Filter')
        self.checkbox7.clicked.connect(self.UpdateParameters)
        self.checkbox8=QtGui.QCheckBox('Single Shot rec')
        self.checkbox8.clicked.connect(self.UpdateParameters)
        
        ## Trigger mode
        
        self.checkbox10=QtGui.QCheckBox('Trigger ON/OFF')
        self.checkbox10.clicked.connect(self.setTriggerMode)
        
        self.ExpoLabel=QtGui.QLabel('    Exposure (us)')
        self.spinbox10=QtGui.QSpinBox()
        self.spinbox10.valueChanged.connect(self.UpdateParameters)
        self.spinbox10.setMaximum(990)
        self.spinbox10.setMinimum(100)
        self.spinbox10.setValue(500.0)


        
        ## save path
        
        self.Savepath='20161130_0000.dat'
        self.SaveLabel=QtGui.QLabel('Save path:')
        self.Savepathbutton=QtGui.QPushButton('...')
        self.Savepathedit=QtGui.QLineEdit(self.Savepath)
        self.Savepathedit.textChanged.connect(self.UpdateParameters)
        self.Savepathbutton.clicked.connect(self.setDir)
        
        ## Progress bars
        self.DprogressLabel=QtGui.QLabel('Dscan progress')
        self.Dprogressbar=QtGui.QProgressBar()
        self.Dprogressbar.setRange(0,100)
        self.progressLabel=QtGui.QLabel('Acq progress')
        self.progressbar=QtGui.QProgressBar()
        self.progressbar.setRange(0,100)
        
        
        
       
        self.infos=QtGui.QLabel('Center Position : X0= 0.0 / Y0= 0.0 ; ROI radius = 100.0 px')
        self.graph = pg.GraphicsLayoutWidget()

# GUI layout
        self.win.addWidget(self.loadbutton,row=0,col=0,colspan=1)
        self.win.addWidget(self.refbutton,row=1,col=0,colspan=1)
        self.win.addWidget(self.checkbox0,row=2,col=0,colspan=1)
        self.win.addWidget(self.checkbox1,row=3,col=0,colspan=1)
        self.win.addWidget(self.checkbox2,row=4,col=0,colspan=1)
        self.win.addWidget(self.checkbox3,row=5,col=0,colspan=1)

        self.win.addWidget(self.BGbutton,row=6,col=0)
        self.win.addWidget(self.checkbox4,row=7,col=0)
        self.win.addWidget(self.bglabel,row=8,col=0)
        self.win.addWidget(self.spinbox3,row=9,col=0)
        
        #self.win.addWidget(self.triggerlabel,row=11,col=2,colspan=1)
        self.win.addWidget(self.checkbox10,row=11,col=2,colspan=1)
        self.win.addWidget(self.ExpoLabel,row=12,col=2,colspan=1)
        self.win.addWidget(self.spinbox10,row=13,col=2,colspan=1)
        
        self.win.addWidget(self.cxlabel,row=10,col=0)
        self.win.addWidget(self.spinbox1,row=11,col=0)
        self.win.addWidget(self.cylabel,row=12,col=0)
        self.win.addWidget(self.spinbox2,row=13,col=0)
        
        self.win.addWidget(self.checkbox5,row=14,col=0)
        self.win.addWidget(self.EnCaliblabel,row=15,col=0)
        self.win.addWidget(self.spinbox4,row=16,col=0)
        
        self.win.addWidget(self.Prevbutton,row=0,col=1,colspan=1)
        self.win.addWidget(self.FlatBGbutton,row=0,col=2,colspan=1)
        self.win.addWidget(self.Startbutton,row=1,col=1,colspan=1)
        self.win.addWidget(self.Stopbutton,row=1,col=2,colspan=1)
        
        self.win.addWidget(self.NAcqLabel,row=2,col=1)
        self.win.addWidget(self.spinbox5,row=3,col=1,colspan=1)
        self.win.addWidget(self.checkbox7,row=4,col=1,colspan=1)
        self.win.addWidget(self.checkbox8,row=5,col=1,colspan=1)
        
        self.win.addWidget(self.ThLabel,row=2,col=2)
        self.win.addWidget(self.spinbox9,row=3,col=2,colspan=1)
        
        self.win.addWidget(self.checkbox6,row=4,col=2,colspan=1)
        self.win.addWidget(self.Dstart,row=5,col=2,colspan=1)
        self.win.addWidget(self.spinbox6,row=6,col=2,colspan=1)
        self.win.addWidget(self.Dstop,row=7,col=2,colspan=1)
        self.win.addWidget(self.spinbox7,row=8,col=2,colspan=1)
        self.win.addWidget(self.Dstep,row=9,col=2,colspan=1)
        self.win.addWidget(self.spinbox8,row=10,col=2,colspan=1)
        
        self.win.addWidget(self.SaveLabel,row=14,col=1,colspan=1)
        self.win.addWidget(self.Savepathbutton,row=14,col=2,colspan=1)
        self.win.addWidget(self.Savepathedit,row=15,col=1,colspan=2)
        
        
        self.win.addWidget(self.progressLabel,row=17,col=0,colspan=1)
        self.win.addWidget(self.progressbar,row=17,col=1,colspan=2)
        self.win.addWidget(self.DprogressLabel,row=18,col=0,colspan=1)
        self.win.addWidget(self.Dprogressbar,row=18,col=1,colspan=2)
        
        
        
        
        self.win.addWidget(self.infos,row=18,col=3)

        self.win.addWidget(self.graph,row=0,col=3,rowspan=18,colspan=6)
        self.win.resize(1500, 1000)
        #self.win.show()

# Graph layout for cartesian image

        self.p1 =self.graph.addPlot(row=0,col=0,rowspan=2)
        self.p1.setLabel(axis='left',text='Py (pixel)')
        self.p1.setLabel(axis='bottom',text='Py (pixel)')

# Item for displaying image data
        self.img = pg.ImageItem()
        self.p1.addItem(self.img)
        self.p1.setAspectLocked(True,ratio=1)

# Custom ROI for selecting an image region
        self.roi = pg.CircleROI([100, 100], [50, 50]) # first vector =[x0,y0], second vector =[lx,ly]
#        self.roi.addScaleHandle([0.5, 1], [0.5, 0.5])
#        self.roi.addScaleHandle([0, 0.5], [0.5, 0.5])
        self.p1.addItem(self.roi)
        self.roi.setZValue(10)  # make sure ROI is drawn above image
        self.roi.sigRegionChanged.connect(self.updatePlot)
        
        

# Isocurve drawing
        self.iso = pg.IsocurveItem(level=0.8, pen='g')
        self.iso.setParentItem(self.img)
        self.iso.setZValue(5)

# Contrast/color control
        self.hist = pg.HistogramLUTItem()
        self.hist.setImageItem(self.img)
        self.graph.addItem(self.hist,row=0,col=1,rowspan=2)

# Draggable line for setting isocurve level
        self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g')
        self.hist.vb.addItem(self.isoLine)
        self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier
        self.isoLine.setValue(0.8)
        self.isoLine.setZValue(1000) # bring iso line above contrast controls
        self.isoLine.sigDragged.connect(self.updateIsocurve)

# Another plot area for displaying ROI data
        self.graph.nextRow()
        self.p0 = self.graph.addPlot(row=0,col=3,colspan=2)
        self.p0.setLabel(axis='left',text='Radius (px)')
        self.p0.setLabel(axis='bottom',text='Angle (°)')
        self.imgpol = pg.ImageItem()
        self.p0.addItem(self.imgpol)
        self.histpol = pg.HistogramLUTItem()
        self.histpol.setImageItem(self.imgpol)
        self.graph.addItem(self.histpol,row=0,col=5)
        self.histpol.setMaximumWidth(100)
        

        self.graph.nextCol()
        self.p2 = self.graph.addPlot(row=1,col=3,colspan=2)
        self.p2.setLabel(axis='left',text='Signal (arb. u)')
        self.p2.setLabel(axis='bottom',text='Momentum (pixel)')
        
        self.graph.nextRow()
        self.p3 = self.graph.addPlot(row=3,col=0,colspan=5)
        self.p3.setLabel(axis='bottom',text='Delay (fs)')
        self.p3.setLabel(axis='left',text='Momentum (px)')
        self.Dscan = pg.ImageItem()
        self.p3.addItem(self.Dscan)
        self.histpol2 = pg.HistogramLUTItem()
        self.histpol2.setImageItem(self.Dscan)
        self.graph.addItem(self.histpol2,row=3,col=5)
        self.histpol2.setMaximumWidth(100)

        self.roipol = pg.ROI([50, 1], [30, 150]) # first vector =[x0,y0], second vector =[lx,ly]
        self.roipol.addScaleHandle([0.5, 1], [0.5, 0.5])
        self.roipol.addScaleHandle([0, 0.5], [0.5, 0.5])
        self.p0.addItem(self.roipol)
        self.roipol.setZValue(10)  # make sure ROI is drawn above image
        self.roipol.sigRegionChanged.connect(self.updatePlot)
        
#Initialize the image
        
        self.initimg = np.random.normal(size=(1000, 1000))
        self.initimg[380:420, 380:420] += 2.
        self.initimg = pg.gaussianFilter(self.initimg, (3, 3))
        self.initimg += np.random.normal(size=(1000, 1000)) * 0.1
        self.scan=VMITraceProcessing(self.initimg)
        self.activeimg=self.scan.imgcart_raw
        
        self.img.setImage(self.activeimg)
        self.img.scale(1,1)
        self.img.translate(0, 0)
        self.hist.setLevels(self.activeimg.min(), self.activeimg.max())
        self.p1.autoRange()
        
        
        #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0],self.roi.size())
        #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0])
        self.scan.DefineCenter([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0])
        self.scan.ImgCart2Pol(self.roi.size())
        
        
        
        print self.roi.size()[0], 'test'
        #self.scan.ImgCart2Pol([self.roi.size()[0]])
        
        self.imgpol.setImage(self.scan.imgpol)
        
        #self.imgDscan=np.zeros((1000,80))
        
# Infos from filedata
        self.pname=''
        self.pnameBG=''
        self.fname=''
        
        
        
        
# Initialise useful variables
        self.FlatCorrimg=np.zeros((1000,1000))
        self.BGimg=np.zeros((1000,1000))
        self.normDscan=[]
        self.normTOF=[]
        self.refRadialDist=[]
        self.refx0=[]
        self.refy0=[]
        self.cx=[]
        self.cy=[]
        
        
#Load previous config if available:
        
        isconfig=glob.glob('config.npz')
#        if isconfig!=[]:
#            
#            conf=np.load('config.npz')
#            self.Threshold=conf['Threshold']
#            self.NbAcq=conf['NbAcq']
#            self.FlatCorrimg=conf['Flatcorr']
#            self.SavePath=conf['Savepath']
            
#Instanciate acquisition Thread
            
        self.thread=[]
        
#Timer object for realtime data

        self.timer=QtCore.QTimer()        
        self.timer.timeout.connect(self.updatePlot)
#Update the gui
        self.win.show()
예제 #11
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.connected = False
     self.mutex = QtCore.QMutex()
     self.client = com.ClientSocket()