Example #1
0
 def updateFrame(self):
     image = self.device.image1.shaped_image.get()
     if image is not None and len(image):
         try:
             image = self.preprocess(image)
         except Exception as ex:
             pass
             # msg.logError(ex)
         self.getting_frame = True
         threads.invoke_in_main_thread(self._setFrame, image)
Example #2
0
    def load_element(self, element, candidate_infofile, plugin_info):
        """

        Parameters
        ----------
        element
        candidate_infofile
        plugin_info

        Returns
        -------
        bool
            True if the element matched a category, and will be accepted as a plugin

        """
        target_plugin_info = None
        for category_name in self.categories_interfaces:
            try:
                is_correct_subclass = issubclass(
                    element, self.categories_interfaces[category_name])
            except Exception:
                continue
            if is_correct_subclass and element is not self.categories_interfaces[
                    category_name]:
                current_category = category_name
                if candidate_infofile not in self._category_file_mapping[
                        current_category]:
                    # we found a new plugin: initialise it and search for the next one
                    try:

                        threads.invoke_in_main_thread(self.instanciatePlugin,
                                                      plugin_info, element,
                                                      current_category)

                    except Exception as ex:
                        exc_info = sys.exc_info()
                        msg.logError(ex)
                        msg.logMessage("Unable to create plugin object: %s" %
                                       plugin_info.path)
                        plugin_info.error = exc_info
                        # break  # If it didn't work once it wont again
                        msg.logError(
                            RuntimeError(
                                "An error occurred while loading plugin: %s" %
                                plugin_info.path))
                    else:
                        # plugin_info.categories.append(current_category)
                        # self.category_mapping[current_category].append(plugin_info)
                        self._category_file_mapping[current_category].append(
                            candidate_infofile)

                        return True
Example #3
0
    def __init__(self):
        # # Enforce global style within the console
        # with open('xicam/gui/style.stylesheet', 'r') as f:
        #     style = f.read()
        # style = (qdarkstyle.load_stylesheet() + style)

        # Setup the kernel
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        kernel = self.kernel_manager.kernel
        kernel.gui = 'qt'

        # Push Xi-cam variables into the kernel
        kernel.shell.push({
            plugin.name: plugin
            for plugin in pluginmanager.get_plugins_of_type("GUIPlugin") +
            pluginmanager.get_plugins_of_type("EZPlugin")
        })

        # Observe plugin changes
        pluginmanager.attach(self.pluginsChanged)

        # Continue kernel setuppluginmanager.getPluginsOfCategory("GUIPlugin")
        self.kernel_client = self.kernel_manager.client()
        threads.invoke_in_main_thread(self.kernel_client.start_channels)

        # Setup console widget
        def stop():
            self.kernel_client.stop_channels()
            self.kernel_manager.shutdown_kernel()

        control = RichJupyterWidget()
        control.kernel_manager = self.kernel_manager
        threads.invoke_in_main_thread(setattr, control, "kernel_client",
                                      self.kernel_client)
        control.exit_requested.connect(stop)
        # control.style_sheet = style
        control.syntax_style = u'monokai'
        control.set_default_style(colors='Linux')

        # Setup layout
        self.stages = {'Terminal': GUILayout(control)}

        # Save for later
        self.kernel = kernel

        super(IPythonPlugin, self).__init__()
Example #4
0
    def show_results(self):
        header_labels_set = False
        self.show_results_event.clear()
        t0 = time.monotonic()
        counter = 0

        try:
            msg.showBusy()
            while not self._new_uids_queue.empty():
                counter += 1
                row = []
                new_uid = self._new_uids_queue.get()
                try:
                    entry = self.get_run_by_uid(new_uid)
                    row_data = self.apply_search_result_row(entry)
                except SkipRow as e:
                    msg.showMessage(str(msg))
                    msg.logError(e)
                    continue
                if not header_labels_set:
                    # Set header labels just once.
                    threads.invoke_in_main_thread(
                        self.search_results_model.setHorizontalHeaderLabels,
                        list(row_data))
                    header_labels_set = True
                for value in row_data.values():
                    item = QStandardItem()
                    item.setData(value, Qt.DisplayRole)
                    item.setData(new_uid, Qt.UserRole)
                    row.append(item)
                if QThread.currentThread().isInterruptionRequested():
                    self.show_results_event.set()
                    msg.logMessage("Interrupt requested")
                    return
                threads.invoke_in_main_thread(
                    self.search_results_model.appendRow, row)
            if counter:
                self.sig_update_header.emit()
                duration = time.monotonic() - t0
                msg.showMessage("Displayed {} new results {}.".format(
                    counter, duration))
            self.show_results_event.set()
        except Exception as e:
            msg.showMessage("Error displaying runs")
            msg.logError(e)
        finally:
            msg.hideBusy()
Example #5
0
 def preview_catalog(self, catalog: BlueskyRun):
     threads.invoke_in_main_thread(self.setText, "LOADING...")
     try:
         stream, field = bluesky_utils.guess_stream_field(catalog)
         data = bluesky_utils.preview(catalog, stream, field)
         threads.invoke_in_main_thread(self.setImage, data)
     except Exception as ex:
         msg.logError(ex)
         threads.invoke_in_main_thread(self.imageitem.clear)
         threads.invoke_in_main_thread(self.setText, "UNKNOWN DATA FORMAT")
Example #6
0
 def preview_catalog(self, catalog: BlueskyRun):
     threads.invoke_in_main_thread(self.setText, "LOADING...")
     try:
         stream, field = self.guess_stream_field(catalog)
         data = getattr(catalog, stream).to_dask()[field].squeeze()
         for i in range(len(data.shape) - 2):
             data = data[0]
         threads.invoke_in_main_thread(self.setImage,
                                       np.asarray(data.compute()))
     except Exception as ex:
         msg.logError(ex)
         threads.invoke_in_main_thread(self.imageitem.clear)
         threads.invoke_in_main_thread(self.setText, "UNKNOWN DATA FORMAT")
Example #7
0
 def preview_header(self, header: NonDBHeader):
     try:
         data = header.meta_array()[0]
         threads.invoke_in_main_thread(self.setImage, data)
     except IndexError:
         threads.invoke_in_main_thread(self.imageitem.clear)
         threads.invoke_in_main_thread(self.setText, "UNKNOWN DATA FORMAT")
Example #8
0
    def _update_thread(self, update_action: Callable):
        while True:
            if self.cached_frame is not None:
                time.sleep(.01)
                continue

            t = time.time()
            max_period = 1 / self.maxfps
            current_elapsed = t - self._last_timestamp

            if current_elapsed < max_period:
                time.sleep(max_period - current_elapsed)

            if not self.passive.isChecked():
                break

            if self.visibleRegion().isEmpty():
                continue

            try:
                if not self.device.connected:
                    with msg.busyContext():
                        msg.showMessage('Connecting to device...')
                        self.device.wait_for_connection()

                update_action()
            except (RuntimeError, CaprotoTimeoutError, ConnectionTimeoutError,
                    TimeoutError) as ex:
                threads.invoke_in_main_thread(
                    self.error_text.setText,
                    'An error occurred communicating with this device.')
                msg.logError(ex)
            except Exception as e:
                threads.invoke_in_main_thread(
                    self.error_text.setText,
                    'Unknown error occurred when attempting to communicate with device.'
                )
                msg.logError(e)
Example #9
0
    def _update_thread(self, update_action:Callable):
        while True:
            if not self.passive.isChecked():
                break

            if self.visibleRegion().isEmpty():
                time.sleep(1 / self.maxfps)
                continue

            try:
                if not self.device.connected:
                    with msg.busyContext():
                        msg.showMessage('Connecting to device...')
                        self.device.wait_for_connection()

                update_action()
            except (RuntimeError, CaprotoTimeoutError, ConnectionTimeoutError, TimeoutError) as ex:
                threads.invoke_in_main_thread(self.error_text.setText,
                                              'An error occurred communicating with this device.')
                msg.logError(ex)
            except Exception as e:
                threads.invoke_in_main_thread(self.error_text.setText,
                                              'Unknown error occurred when attempting to communicate with device.')
                msg.logError(e)

            num_exposures_counter = self.device.cam.num_exposures_counter.get()
            num_exposures = self.device.cam.num_exposures.get()
            num_captured = self.device.hdf5.num_captured.get()
            num_capture = self.device.hdf5.num_capture.get()
            capturing = self.device.hdf5.capture.get()
            if capturing:
                current = num_exposures_counter + num_captured * num_exposures
                total = num_exposures * num_capture
            elif num_exposures == 1:  # Show 'busy' for just one exposure
                current = 0
                total = 0
            else:
                current = num_exposures_counter
                total = num_exposures
            threads.invoke_in_main_thread(self._update_progress, current, total)

            while self.getting_frame:
                time.sleep(.01)

            t = time.time()
            max_period = 1 / self.maxfps
            current_elapsed = t - self._last_timestamp

            if current_elapsed < max_period:
                time.sleep(max_period - current_elapsed)

            self._last_timestamp = time.time()
Example #10
0
 def call_entries_finished(self, run):
     invoke_in_main_thread(self._call_entries_result, run)
 def _showProgress(self, progress: int, maxprogress: int):
     threads.invoke_in_main_thread(msg.showProgress, progress, 0,
                                   maxprogress)
Example #12
0
 def _get_frame(self):
     self.cached_frame = self.device.image1.shaped_image.get()
     threads.invoke_in_main_thread(self.updateFrame)