示例#1
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """
        self._wavelength_data = []

        self.stopRequested = False

        self._wavemeter_device = self.get_connector('wavemeter1')
        #        print("Counting device is", self._counting_device)

        self._save_logic = self.get_connector('savelogic')
        self._counter_logic = self.get_connector('counterlogic')

        # create a new x axis from xmin to xmax with bins points
        self.histogram_axis = np.arange(self._xmin, self._xmax,
                                        (self._xmax - self._xmin) / self._bins)
        self.histogram = np.zeros(self.histogram_axis.shape)
        self.envelope_histogram = np.zeros(self.histogram_axis.shape)

        self.sig_update_histogram_next.connect(
            self._attach_counts_to_wavelength, QtCore.Qt.QueuedConnection)

        # create an indepentent thread for the hardware communication
        self.hardware_thread = QtCore.QThread()

        # create an object for the hardware communication and let it live on the new thread
        self._hardware_pull = HardwarePull(self)
        self._hardware_pull.moveToThread(self.hardware_thread)

        # connect the signals in and out of the threaded object
        self.sig_handle_timer.connect(self._hardware_pull.handle_timer)

        # start the event loop for the hardware
        self.hardware_thread.start()
        self.last_point_time = time.time()
示例#2
0
    def __init__(self, parent, run, finished=None):
        super(Threaded, self).__init__(parent)

        # Create thread/objects
        self.thread = QtCore.QThread()
        worker = Worker(run)
        worker.moveToThread(self.thread)
        Threaded.add_to_pool(self)

        # Connect error reporting
        worker.error[str].connect(self.errorString)

        # Start up
        self.thread.started.connect(worker.process)

        # Clean up
        worker.finished.connect(self.thread.quit)
        worker.finished.connect(worker.deleteLater)
        worker.error.connect(self.thread.quit)
        worker.error.connect(worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        if finished is not None:
            worker.finished.connect(finished)

        def remove_ref():
            Threaded.remove_from_pool(self)

        self.thread.finished.connect(remove_ref)

        # Need to keep ref so they stay in mem
        self.worker = worker
    def __init__(self, config=None):
        super().__init__()
        self.DELIM = b"<IDS|MSG>"
        # namespaces
        self.user_global_ns = globals()
        self.user_ns = self.user_global_ns

        self.exiting = False
        self.engine_id = str(uuid.uuid4())

        if config is not None:
            self.config = config
        else:
            logging.info("Starting simple_kernel with default args...")
            self.config = {
                'control_port': 0,
                'hb_port': 0,
                'iopub_port': 0,
                'ip': '127.0.0.1',
                'key': str(uuid.uuid4()),
                'shell_port': 0,
                'signature_scheme': 'hmac-sha256',
                'stdin_port': 0,
                'transport': 'tcp'
            }

        self.hb_thread = QtCore.QThread()
        self.hb_thread.setObjectName(self.engine_id)
        self.connection = config["transport"] + "://" + config["ip"]
        self.secure_key = config["key"].encode('ascii')
        self.signature_schemes = {"hmac-sha256": hashlib.sha256}
        self.auth = hmac.HMAC(
            self.secure_key,
            digestmod=self.signature_schemes[self.config["signature_scheme"]])
        logging.info('New Kernel {}'.format(self.engine_id))
示例#4
0
 def threadWrapperTearDown(self):
     self._thread.wait()
     self._thread = QtCore.QThread(self)
     self._worker.signals.started.disconnect(self.start_slot)
     self._worker.signals.finished.disconnect(self.end_slot)
     self._worker.signals.finished.disconnect(self.threadWrapperTearDown)
     self._worker.signals.error.disconnect(self.warning)
     self.start_slot = lambda: 0
     self.end_slot = lambda: 0
    def on_activate(self):
        #############################################
        # Initialisation to access external DLL
        #############################################
        try:
            # imports the spectrometer specific function from dll
            self._wavemeterdll = ctypes.windll.LoadLibrary('wlmData.dll')

        except:
            self.log.critical(
                'There is no Wavemeter installed on this '
                'Computer.\nPlease install a High Finesse Wavemeter and '
                'try again.')

        # define the use of the GetWavelength function of the wavemeter
#        self._GetWavelength2 = self._wavemeterdll.GetWavelength2
# return data type of the GetWavelength function of the wavemeter
        self._wavemeterdll.GetWavelength2.restype = ctypes.c_double
        # parameter data type of the GetWavelength function of the wavemeter
        self._wavemeterdll.GetWavelength2.argtypes = [ctypes.c_double]

        # define the use of the GetWavelength function of the wavemeter
        #        self._GetWavelength = self._wavemeterdll.GetWavelength
        # return data type of the GetWavelength function of the wavemeter
        self._wavemeterdll.GetWavelength.restype = ctypes.c_double
        # parameter data type of the GetWavelength function of the wavemeter
        self._wavemeterdll.GetWavelength.argtypes = [ctypes.c_double]

        # define the use of the ConvertUnit function of the wavemeter
        #        self._ConvertUnit = self._wavemeterdll.ConvertUnit
        # return data type of the ConvertUnit function of the wavemeter
        self._wavemeterdll.ConvertUnit.restype = ctypes.c_double
        # parameter data type of the ConvertUnit function of the wavemeter
        self._wavemeterdll.ConvertUnit.argtypes = [
            ctypes.c_double, ctypes.c_long, ctypes.c_long
        ]

        # manipulate perdefined operations with simple flags
        #        self._Operation = self._wavemeterdll.Operation
        # return data type of the Operation function of the wavemeter
        self._wavemeterdll.Operation.restype = ctypes.c_long
        # parameter data type of the Operation function of the wavemeter
        self._wavemeterdll.Operation.argtypes = [ctypes.c_ushort]

        # create an indepentent thread for the hardware communication
        self.hardware_thread = QtCore.QThread()

        # create an object for the hardware communication and let it live on the new thread
        self._hardware_pull = HardwarePull(self)
        self._hardware_pull.moveToThread(self.hardware_thread)

        # connect the signals in and out of the threaded object
        self.sig_handle_timer.connect(self._hardware_pull.handle_timer)
        self._hardware_pull.sig_wavelength.connect(self.handle_wavelength)

        # start the event loop for the hardware
        self.hardware_thread.start()
    def __init__(self, name):
        """ Create a ThreadItwm object

          @param str name: unique name of the thread
        """
        super().__init__()
        self.thread = QtCore.QThread()
        self.thread.setObjectName(name)
        self.name = name
        self.thread.finished.connect(self.myThreadHasQuit)
示例#7
0
    def package_filter_change(self):
        try:
            if self.comboBox.currentText() == "已安装":
                self.package_filter_default()
            elif self.comboBox.currentText() == "可更新":
                # self.package_filter_update()
                self.writing_thread = QtCore.QThread()
                self.package_filter_update.moveToThread(self.writing_thread)

        except BaseException:
            pass
示例#8
0
    def __init__(self, parent=None):
        super(AndorWindow, self).__init__(parent)

        self.worker = QtCore.QThread()
        self.cam = AndorObject()
        self.cam.moveToThread(self.worker)

        self.cam.status_changed.connect(self.onCameraStatus)

        self.worker.start()

        self.setupUi(self)
示例#9
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.optimizationlogic = OptimizationLogic()

        # Handle Thread for the optimization
        self.thread_optimization = QtCore.QThread(self)
        self.optimizationlogic.moveToThread(self.thread_optimization)
        self.thread_optimization.start()

        self.handle_ui_elements()
        self._mw.closeEvent = self.closeEvent
示例#10
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.optimizationlogic = OptimizationLogic()

        # Handle Thread for the optimization
        self.thread_optimization = QtCore.QThread(self)
        self.optimizationlogic.moveToThread(self.thread_optimization)
        self.thread_optimization.start()

        self.handle_ui_elements()
        self._mw.closeEvent = self.closeEvent
        # Activate the start button for testing
        self._mw.start_optimization_button.setEnabled(True)
示例#11
0
    def on_activate(self, e):

        # create an indepentent thread for the hardware communication
        self.hardware_thread = QtCore.QThread()

        # create an object for the hardware communication and let it live on the new thread
        self._hardware_pull = HardwarePull(self)
        self._hardware_pull.moveToThread(self.hardware_thread)

        # connect the signals in and out of the threaded object
        self.sig_handle_timer.connect(self._hardware_pull.handle_timer)

        # start the event loop for the hardware
        self.hardware_thread.start()
示例#12
0
    def __init__(self, model):
        super(ThreadModel, self).__init__()
        self.model = model

        # The ThreadModelWorker wrapping the code to be executed
        self._worker = ThreadModelWorker(self.model)
        # The QThread instance on which the execution of the code will be performed
        self._thread = QtCore.QThread(self)

        # callbacks for the .started() and .finished() signals of the worker
        self.start_slot = lambda: 0
        self.end_slot = lambda: 0
        self._exception_callback = self._default_exception_callback

        self.check_model_has_correct_attributes()
示例#13
0
 def start(self):
     sys.stdin = self
     stdout_fileno = sys.stdout.fileno()
     stderr_fileno = sys.stderr.fileno()
     stderr_save = os.dup(stderr_fileno)
     stdout_save = os.dup(stdout_fileno)
     stdout_pipe = os.pipe()
     os.dup2(stdout_pipe[1], stdout_fileno)
     os.dup2(stdout_pipe[1], stderr_fileno)
     os.close(stdout_pipe[1])
     self.receiver = Receiver(stdout_pipe[0])
     self.receiver.received.connect(self.append_text)
     self.stdoutThread = QtCore.QThread()
     self.receiver.moveToThread(self.stdoutThread)
     self.stdoutThread.started.connect(self.receiver.run)
     self.stdoutThread.start()
示例#14
0
    def toggleStart(self):
        if self.start_button.isChecked():
            self.start_button.setText('Starting...')

            if self.mode == GageMode.TRAD:
                self.sample_length = self.length_input.value()
                for config in channel_config:
                    config.segments = []

                self._worker = GageTradWorker(self.run_widget)

            elif self.mode == GageMode.SEG:
                self.sample_length = 0
                for config in channel_config:
                    cw = self.channel_widgets[config.id]
                    config.segments = cw.get_segments()

                    seg_ends = [seg[2] for seg in config.segments]
                    if len(seg_ends) > 0:
                        self.sample_length = max(self.sample_length, max(seg_ends))

                self._worker = GageSegWorker(self.run_widget, self.triggers)

            self.sample_depth = int(sample_clk * self.sample_length / 1e3)

            for cid, cw in self.channel_widgets.items():
                cw._pw.setXRange(0, self.sample_length * 1e-3)

            log('Starting acquisition for {:.1f} ms ({:d} samples)'.format(self.sample_length, self.sample_depth))
            self._gage_configure()

            self._thread = QtCore.QThread()
            self._worker.moveToThread(self._thread)
            self.capture_acquired.connect(self._worker.process_capture)
            self._worker.plot_capture.connect(self._plot_capture)

            self._thread.started.connect(self._worker.started)
            self._thread.finished.connect(self._thread_finished)

            self._thread.start()

            self._acquiring = True
            self.gage.Start()  # Arm acquisition
            self.state = GageState.ACQUIRE
        else:
            self._stop_acquisition()
示例#15
0
    def __init__(self, long_job_gen):
        super(ProgressingWindow, self).__init__()
        qbtn = qtw.QDialogButtonBox.Ok | qtw.QDialogButtonBox.Cancel
        self.buttonbox = qtw.QDialogButtonBox(qbtn)
        self.buttonbox.accepted.connect(self.accept)
        self.buttonbox.rejected.connect(self.reject)

        self.long_job_gen = long_job_gen
        form = qtw.QWidget()
        self.setWindowTitle("Background Running Jobs")
        layout = qtw.QFormLayout()
        form.setLayout(layout)

        self.run_btn = qtw.QPushButton('Clear Contents',
                                       clicked=self.clear_running)
        self.run_btn.animateClick()
        self.progress_bar = qtw.QProgressBar(self)

        self.results = qtw.QTableWidget(0, 2)
        self.results.setHorizontalHeaderLabels(['percentage', 'content'])
        self.results.horizontalHeader().setSectionResizeMode(
            qtw.QHeaderView.Stretch)
        self.results.setSizePolicy(qtw.QSizePolicy.Expanding,
                                   qtw.QSizePolicy.Expanding)

        layout.addRow(qtw.QLabel("Job running status"))
        layout.addRow(self.progress_bar)
        layout.addRow('Clear button', self.run_btn)
        layout.addRow(self.results)
        layout.addRow(self.buttonbox)

        self.runner = Runner(self.long_job_gen)
        self.runner_thread = qtc.QThread()
        self.runner.running.connect(self.add_job_to_table)
        self.runner.running.connect(self.progress_bar.setValue)
        self.running_submitted.connect(self.runner.run)

        self.runner.moveToThread(self.runner_thread)
        self.runner_thread.start(priority=qtc.QThread.IdlePriority)

        self.setLayout(layout)

        self.show()
示例#16
0
文件: feed.py 项目: osgirl/mercurygui
    def start_worker(self):
        """
        Start a thread to periodically update readings.
        """
        if self.worker and self.thread:
            self.worker.running = True
        else:
            self.dialog = SensorDialog(self.mercury.modules)
            self.dialog.accepted.connect(self.update_modules)

            # start data collection thread
            self.thread = QtCore.QThread()
            self.worker = DataCollectionWorker(self.refresh, self.mercury,
                                               self.dialog.modNumbers)
            self.worker.moveToThread(self.thread)
            self.worker.readings_signal.connect(self._get_data)
            self.worker.connected_signal.connect(self.connected_signal.emit)
            self.thread.started.connect(self.worker.run)
            self.update_modules(self.dialog.modNumbers)
            self.thread.start()
示例#17
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self._settings = QtCore.QSettings(QtCore.QSettings.NativeFormat,
                                       QtCore.QSettings.UserScope,
                                       'HF_AIO', 'MemoryUsageMonitor')
     self._pid = None
     self._ct = ''
     self._dq = collections.deque(maxlen=self._settings.value('dq_maxlen', 120, type=int))
     self._progress = QtWidgets.QProgressDialog(self)
     self._progress.setCancelButton(None)
     self._progress.setWindowTitle(__app_tittle__)
     self._progress.setWindowModality(QtCore.Qt.WindowModal)
     self._progress.setMinimumWidth(300)
     self._progress.reset()
     self._worker_thread = QtCore.QThread()
     self._worker_thread.start()
     self._log_parse_runnable = None  # type: Union[None, QtCore.QObject]
     self._timer = QtCore.QTimer()
     self._timer.timeout.connect(self._on_timer)
     self._init_ui()
     self._setup_shortcuts()
示例#18
0
def newWorkerThread(workerClass, *args, **kwargs):
    worker = workerClass(*args, **kwargs)
    thread = QtCore.QThread()
    worker.moveToThread(thread)
    # all workers started using this function must implement work() func
    thread.started.connect(worker.work)
    thread.finished.connect(thread.deleteLater)

    # connect dict from calling object to worker signals
    worker_connections = kwargs.get("workerConnect", None)
    if worker_connections:
        [
            getattr(worker, key).connect(val)
            for key, val in worker_connections.items()
        ]
    # optionally, can supply onfinish callable when thread finishes
    if kwargs.get("onfinish", None):
        thread.finished.connect(kwargs.get("onfinish"))
    if kwargs.get("start", False) is True:
        thread.start()  # usually need to connect stuff before starting
    return worker, thread
示例#19
0
    def __init__(self,
                 worker,
                 *args,
                 label='',
                 canceled_callback=None,
                 finished_callback=None,
                 **kwargs):

        super().__init__(*args, **kwargs)

        self.setLabel(QtWidgets.QLabel(label))
        self.worker = worker
        self.worker.progress.connect(self.setValue)
        if canceled_callback:
            self.canceled.connect(canceled_callback)
        if finished_callback:
            self.worker.finished.connect(finished_callback)

        self.thread = QtCore.QThread()
        self.worker = worker
        self.worker.moveToThread(self.thread)

        self.thread.started.connect(self.worker.run)
示例#20
0
    def on_activate(self):
        """ Initialisation performed during activation of the module.
        """
        self._wavelength_data = []

        self.stopRequested = False

        self._wavemeter_device = self.get_connector('wavemeter1')
        #        print("Counting device is", self._counting_device)

        self._save_logic = self.get_connector('savelogic')
        self._counter_logic = self.get_connector('counterlogic')

        self._fit_logic = self.get_connector('fitlogic')
        self.fc = self._fit_logic.make_fit_container('Wavemeter counts', '1d')
        self.fc.set_units(['Hz', 'c/s'])

        if 'fits' in self._statusVariables and isinstance(
                self._statusVariables['fits'], dict):
            self.fc.load_from_dict(self._statusVariables['fits'])
        else:
            d1 = OrderedDict()
            d1['Lorentzian peak'] = {
                'fit_function': 'lorentzian',
                'estimator': 'peak'
            }
            d1['Two Lorentzian peaks'] = {
                'fit_function': 'lorentziandouble',
                'estimator': 'peak'
            }
            d1['Two Gaussian peaks'] = {
                'fit_function': 'gaussiandouble',
                'estimator': 'peak'
            }
            default_fits = OrderedDict()
            default_fits['1d'] = d1
            self.fc.load_from_dict(default_fits)

        # create a new x axis from xmin to xmax with bins points
        self.histogram_axis = np.arange(self._xmin, self._xmax,
                                        (self._xmax - self._xmin) / self._bins)
        self.histogram = np.zeros(self.histogram_axis.shape)
        self.envelope_histogram = np.zeros(self.histogram_axis.shape)

        self.sig_update_histogram_next.connect(
            self._attach_counts_to_wavelength, QtCore.Qt.QueuedConnection)

        # fit data
        self.wlog_fit_x = np.linspace(self._xmin, self._xmax, self._bins * 5)
        self.wlog_fit_y = np.zeros(self.wlog_fit_x.shape)

        # create an indepentent thread for the hardware communication
        self.hardware_thread = QtCore.QThread()

        # create an object for the hardware communication and let it live on the new thread
        self._hardware_pull = HardwarePull(self)
        self._hardware_pull.moveToThread(self.hardware_thread)

        # connect the signals in and out of the threaded object
        self.sig_handle_timer.connect(self._hardware_pull.handle_timer)

        # start the event loop for the hardware
        self.hardware_thread.start()
        self.last_point_time = time.time()
示例#21
0
    def __init__(self,
                 frames,
                 traps=None,
                 labels=None,
                 active_labels=None,
                 box_dimensions=None,
                 mode='standard'):

        QtWidgets.QWidget.__init__(self)

        #be aware that for a lazy design effort some of the properties of the instance of this class, which is possessed by the main 'AnalyserGUI' panel, are set by direct variable assignment within methods of the 'AnalyserGUI' class.
        #This is a manifestation of the ability of python class instance properties to be accessed and changed by external functions. This is not consistently used. Some 'get' and 'set' functions have been written.

        #store frames as a dictionary

        #this function checks if the input traps and labels are spread over many videos or just one. It sets the structure of the trap position and trap label data stores accordingly and returns either True or False depending on whether there are several videos or just one

        self.multividflag = self.checkformultiness(frames, traps, labels,
                                                   active_labels)

        self.box_dimensions = box_dimensions
        self.centres = None
        #need to set length of video

        self.t0 = 0
        self.tmax = 1000

        self.mythread = QtCore.QThread()
        #   initialize single vesicle video as none type

        self.vesiclelife = None

        # Add deposits for the plotting data for every labelled trap.

        self.ydataI = None
        self.ydataA = None

        #Add deposits for comparing the data to check two different methods of extracting intensity and the area

        self.compare_ydataI = None
        self.compare_ydataA = None

        #Add dictionaries to be passed to the plot function

        self.ydata = {}
        self.xdata = {}
        self.params = {}

        self.compare_xdata = {}
        self.compare_ydata = {}
        self.compare_labels = {}
        #Standard message box which prompts user to accept or reject and queued operation

        self.interact_display = StandardDialog()
        self.proceed_to_directional_query = StandardDialog()

        #Add vesicle delete button

        self.delete = QtWidgets.QPushButton('Delete Vesicle')

        #Add plotting buttons
        self.plot_label_btn = QtWidgets.QPushButton('Plot Single Trap')

        self.plot_label_btn.clicked.connect(self.plot_now)

        #add button to generate heatplot

        self.make_heat = QtWidgets.QPushButton('Generate Heat Plot')

        self.make_heat.clicked.connect(self.check_then_gen_heat)

        #Add button to generate directional heat map. Unless 'directional' mode is turned on this button is not displayed to the user.

        self.gen_directional_heatmap_btn = QtWidgets.QPushButton(
            'Check Exp Directionality')
        self.gen_directional_heatmap_btn.clicked.connect(
            self.check_ready_to_record_times)

        #switch control for displaying thresholded or unprocessed image inside trap
        #abstract switch
        self.threshold_on = False

        #actual graphic switch
        self.threshold_control = QtWidgets.QPushButton(
            'Show Thresholded Image')
        self.threshold_control.clicked.connect(self.show_thresholded_frame)

        #Layout

        self.lyt = QtWidgets.QGridLayout()

        self.mode_directional_on(mode)
        # Widgets
        self.label_select_lbl = QtWidgets.QLabel('Select Trap to view')

        self.label_select = QtWidgets.QComboBox()
        self.video_select = QtWidgets.QComboBox()

        #create a subwidget which will be positioned in the layout. Initially for the single video analysis case this will seem redundant as it will just contain a single widget itself. But for the multi video case
        #this will also contain a combobox to select which video the vesicle is in
        self.combo_container = QtWidgets.QWidget()
        container_layout = QtWidgets.QHBoxLayout()
        container_layout.addWidget(self.label_select)
        self.combo_container.setLayout(container_layout)

        if self.labels is not None:
            self.label_select.addItems(np.array(self.activelabels).astype(str))

        # video viewer
        self.one_ves_view = livestream(qnd, images=None, annotations_on=False)

        self.go = QtWidgets.QPushButton('Display Trap')

        self.warning_box = QtWidgets.QMessageBox()

        self.plotter_with_border = PlotBox()

        self.go.clicked.connect(self.thread_display_generation)

        self.reload_with_centres = QtWidgets.QPushButton(
            'Display with \n Detected Centres')

        self.reload_with_centres.clicked.connect(self.include_centres)

        #include button for saving heat data

        self.save_heat = QtWidgets.QPushButton('Save Heat Plot Data')

        self.lyt.addWidget(self.label_select_lbl, 2, 0)
        self.lyt.addWidget(self.combo_container, 3, 0)
        self.lyt.addWidget(self.one_ves_view, 0, 1)
        self.lyt.addWidget(self.threshold_control, 1, 1)
        self.lyt.addWidget(self.go, 4, 0)
        self.lyt.addWidget(self.reload_with_centres, 2, 1)
        self.lyt.addWidget(self.plotter_with_border, 0, 0)
        self.lyt.addWidget(self.plot_label_btn, 1, 0)
        self.lyt.addWidget(self.make_heat, 4, 1)
        self.lyt.addWidget(self.save_heat, 5, 1)

        self.lyt.addWidget(self.delete, 3, 1)

        self.setLayout(self.lyt)

        if self.multividflag:
            self.addVideoSelector(self.labels_by_vid)
示例#22
0
    def __init__(self,
                 labelled_traps,
                 intensities,
                 firstintensities,
                 filtered_intensities,
                 first_filtered_intensities,
                 areas,
                 firstareas,
                 filtered_areas,
                 first_filtered_areas,
                 centres,
                 firstcentres,
                 rffitrace,
                 rffatrace,
                 t0,
                 tmax,
                 save_directory,
                 vid_id=None,
                 auto=False):

        QWidget.__init__(self)
        #Create thread for saving

        self.save_thread = QtCore.QThread()
        self.auto_save_thread = QtCore.QThread()
        #save directory to save files to

        self.sd = save_directory

        #when autosaving we save the files with an id which matches it to the video file which was analysed to produce the data

        self.vid_id = None

        #include warning box for errors
        self.warning_box = QtWidgets.QMessageBox()

        self.labelled_traps = labelled_traps
        self.intensities = intensities
        self.firstintensities = firstintensities

        self.fintensities = filtered_intensities
        self.ffintensities = first_filtered_intensities
        self.rffitrace = rffitrace

        self.areas = areas
        self.firstareas = firstareas
        self.fareas = filtered_areas
        self.ffareas = first_filtered_areas
        self.rffatrace = rffatrace

        self.centres = centres
        self.firstcentres = centres

        self.bookends = np.array([t0, tmax])

        self.worker = myworker(self.go_on_and_save)
        self.autoworker = myworker(self.autosave)

        self.save_thread.started.connect(self.worker.run)
        self.auto_save_thread.started.connect(self.autoworker.run)

        self.worker.sig1.connect(self.save_thread.exit)
        self.worker.sig1.connect(self.close)
        self.autoworker.sig1.connect(self.auto_save_thread.exit)
        self.autoworker.sig1.connect(self.close)

        #in order to save as csv file we must make all the numpy arrays the same length
        self.save_Date = QtWidgets.QLineEdit('Enter Date, NOT WITH "/"! ')

        self.save_Time = QtWidgets.QLineEdit('Enter Time')

        self.save_btn = QtWidgets.QPushButton('Save')

        self.layout = QtWidgets.QVBoxLayout()

        self.layout.addWidget(self.save_Date)

        self.layout.addWidget(self.save_Time)

        self.setLayout(self.layout)

        self.save_Time.returnPressed.connect(self.start_thread)

        self.save_btn.clicked.connect(self.start_thread)

        self.auto_sig.connect(self.start_auto_thread)

        self.vid_id = vid_id

        if auto:

            self.auto_sig.emit()
示例#23
0
    def _start_session(self, path=""):
        """
        Starts a session.
        """
        if self.running:
            raise RuntimeError("Must stop session before starting.")
        now = datetime.datetime.now()
        if not path:
            self.output_dir = str(self.ui.lineEdit_output_path.text())
        else:
            self.output_dir = path
            self.ui.lineEdit_output_path.setText(path)
        if self.output_dir[-3:] == ".h5":
            self.output_dir = self.output_dir[:-3]
        if self.ui.checkBox_timestamp.isChecked():
            self.output_dir += now.strftime('%y%m%d%H%M%S')
        basedir = os.path.dirname(self.output_dir)
        try:
            os.makedirs(basedir)
        except:
            pass
        device = str(self.ui.comboBox_device.currentText())

        data_bits = int(self.ui.lineEdit_data_bits.text())
        freq = float(str(self.ui.lineEdit_pulse_freq.text()))

        #add in analog recording?
        analog_on = self.ui.checkBox_analog_channels.isChecked()
        analog_channels = eval(str(self.ui.lineEdit_analog_channels.text()))
        analog_sample_rate = float(str(self.ui.comboBox_analog_freq.currentText()))
        analog_dtype = int(str(self.ui.comboBox_dtype.currentText()))

        #add in counter input?
        counter_input_on = self.ui.checkBox_ci.isChecked()
        counter_input_terminal = str(self.ui.comboBox_ci.currentText())

        # #create Sync object
        params = {
            'device': device,
            'output_dir': self.output_dir,
            'event_bits': data_bits,
            'freq': freq,
            'labels': self.digital_labels,
            'analog_on': analog_on,
            'analog_channels': analog_channels,
            'analog_sample_rate': analog_sample_rate,
            'analog_dtype': analog_dtype,
            'analog_labels': self.analog_labels,
            'counter_input_on': counter_input_on,
            'counter_input_terminal': counter_input_terminal,
            }

        self.sync = SyncObject(params=params)
        if self.sync_thread:
            self.sync_thread.terminate()
        self.sync_thread = QtCore.QThread()
        self.sync.moveToThread(self.sync_thread)
        self.sync_thread.start()
        self.sync_thread.setPriority(QtCore.QThread.TimeCriticalPriority)

        QtCore.QTimer.singleShot(100, self.sync.start)

        self.write_text("***Starting session at \
            %s on %s ***" % (str(now), device))
        
        self.running = True
        self._disable_ui()

        self._set_visualizer_path(self.output_dir)

        self.ui.pushButton_start.setIcon(QtGui.QIcon("res/stop.png"))
示例#24
0
 def __init__(self, parent):
     QtCore.QObject.__init__(self, parent)
     self._validation_thread = QtCore.QThread(parent=self)
     self._validation_thread.start()
     self._validation_worker = None