Esempio n. 1
0
 def start_si_clicked():
     if self.__acquisition_running:
         self.MultiEELS.cancel()
     else:
         self.stem_controller = Registry.get_component(
             'stem_controller')
         self.superscan = self.stem_controller.scan_controller
         self.MultiEELS.stem_controller = self.stem_controller
         self.MultiEELS.camera = self.camera_choice_combo_box.current_item
         self.MultiEELS.superscan = self.superscan
         self.result_data_items = {}
         self.__new_data_ready_event_listener = self.MultiEELS.new_data_ready_event.listen(
             self.add_to_display_queue)
         self.__data_processed_event.clear()
         self.__display_thread = threading.Thread(
             target=self.process_display_queue)
         self.__display_thread.start()
         self.__acquisision_thread = threading.Thread(
             target=self.MultiEELS.acquire_multi_eels_spectrum_image,
             daemon=True)
         self.__acquisision_thread.start()
Esempio n. 2
0
        def start_clicked():
            if self.__acquisition_running:
                self.MultiEELS.cancel()
            else:
                self.stem_controller = Registry.get_component(
                    'stem_controller')
                self.MultiEELS.stem_controller = self.stem_controller
                self.MultiEELS.camera = self.camera_choice_combo_box.current_item

                def run_multi_eels():
                    data_dict = self.MultiEELS.acquire_multi_eels_spectrum()

                    def create_and_display_data_item():
                        self.create_result_data_item(data_dict)

                    document_controller.queue_task(create_and_display_data_item
                                                   )  # must occur on UI thread

                self.__acquisision_thread = threading.Thread(
                    target=run_multi_eels, daemon=True)
                self.__acquisision_thread.start()
Esempio n. 3
0
    def __init__(self,
                 *,
                 is_eels: bool = False,
                 camera_exposure: float = 0.025):
        super().__init__()

        # HardwareSource.run()
        # camera_base.run(configuration_location)
        # scan_base.run()
        # video_base.run()
        # CameraControlPanel.run()
        # ScanControlPanel.run()
        # MultipleShiftEELSAcquire.run()
        # VideoControlPanel.run()

        HardwareSource.run()
        instrument = self.setup_stem_controller()
        ScanDevice.run(typing.cast(InstrumentDevice.Instrument, instrument))
        scan_base.run()
        scan_hardware_source = Registry.get_component("scan_hardware_source")
        camera_hardware_source = self.setup_camera_hardware_source(
            instrument, camera_exposure, is_eels)
        HardwareSource.HardwareSourceManager().hardware_sources = []
        HardwareSource.HardwareSourceManager(
        ).hardware_source_added_event = Event.Event()
        HardwareSource.HardwareSourceManager(
        ).hardware_source_removed_event = Event.Event()
        self.instrument = instrument
        self.scan_hardware_source = scan_hardware_source
        self.camera_hardware_source = camera_hardware_source
        HardwareSource.HardwareSourceManager().register_hardware_source(
            self.camera_hardware_source)
        HardwareSource.HardwareSourceManager().register_hardware_source(
            self.scan_hardware_source)
        self.document_controller = self.create_document_controller(
            auto_close=False)
        self.document_model = self.document_controller.document_model
        stem_controller.register_event_loop(
            self.document_controller.event_loop)
        self.__exit_stack: typing.List[typing.Any] = list()
Esempio n. 4
0
 def acquire(self, number_frames: int, energy_offset: float,
             sleep_time: int, dark_ref_choice: bool,
             dark_file: pathlib.Path, cross_cor_choice: bool) -> None:
     if number_frames <= 0:
         return
     # Function to set up and start acquisition
     eels_camera = typing.cast(
         typing.Optional[camera_base.CameraHardwareSource],
         self.__eels_camera_choice.hardware_source)
     if eels_camera:
         # setup the workspace layout
         workspace_controller = self.document_controller.workspace_controller
         assert workspace_controller
         self.__configure_start_workspace(workspace_controller,
                                          eels_camera.hardware_source_id)
         # start the EELS acquisition
         eels_camera.start_playing()
         stem_controller = typing.cast(
             typing.Optional[STEMController.STEMController],
             Registry.get_component("stem_controller"))
         assert stem_controller
         if dark_ref_choice is False:
             # Dark reference is undesired
             dark_ref_data = None
         else:
             # Dark reference is desired: import from the file given, if
             # the import does not succeed (file does not exist or no path
             # was given), then set dark_ref_data to None
             dark_ref_import = ImportExportManager.ImportExportManager(
             ).read_data_items(dark_file)
             if dark_ref_import:
                 dark_ref_data = dark_ref_import[0].data
             else:
                 dark_ref_data = None
         AcquireController().start_threaded_acquire_and_sum(
             stem_controller, eels_camera, number_frames, energy_offset,
             sleep_time, dark_ref_choice, dark_ref_data, cross_cor_choice,
             self.document_controller,
             functools.partial(self.set_final_layout))
    def acquire_series(self, abr_coeff, abr_range, nsteps):
        # name of aberration coefficient to vary
        self.abr_coeff = abr_coeff
        # total range of aberration in m
        self.abr_range = abr_range
        # number of steps to change the aberration coefficients.
        self.nsteps = nsteps

        # initialize list for aberration and image.
        value_list = [(i - self.nsteps // 2) * self.abr_range / self.nsteps
                      for i in range(self.nsteps)]
        self.image_stack = []
        # Connect to stem controller to setup aberration
        stem_controller = Registry.get_component("stem_controller")
        success, initial_val = stem_controller.TryGetVal(abr_coeff)
        print(str(success) + str(initial_val))
        ronchigram = stem_controller.ronchigram_camera
        # start acquisition for each aberration value in the list, in a separate thread.
        for i in value_list:
            for _ in range(self.rep):
                if stem_controller.SetVal(self.abr_coeff, i):
                    threading.Thread(
                        target=self.acquire_frame(ronchigram)).start()
                    print(self.abr_coeff + ' ' + str(i))
        # After acquisition, set the value back to the default number.
        stem_controller.SetVal(self.abr_coeff, initial_val)

        # save the acquired image stack.
        image_stack_array = np.asarray(self.image_stack)
        filename = self.abr_coeff + '_' + str(abr_range) + 'm_' + str(
            self.nsteps) + 'steps_' + str(self.exposure_ms) + 'ms_bin' + str(
                self.binning) + '_repx' + str(self.rep) + 'maxFOV.npy'
        print(self.path + filename)
        np.save(self.path + filename, image_stack_array)
        del image_stack_array
        return
def get_context():
    executor = Registry.get_component('libertem_executor')
    return api.Context(executor=executor.ensure_sync())
Esempio n. 7
0
    x1 = (x_start + x_center) / 2
    x2 = (x_center + x_end) / 2
    A = numpy.exp((numpy.log(geo_mean_1) - (x1 / x2) * numpy.log(geo_mean_2)) /
                  (1 - x1 / x2))
    tau = -x2 / (numpy.log(geo_mean_2) - numpy.log(A))
    return A, tau


def exponential_func(x: numpy.ndarray, A: numpy.ndarray,
                     tau: numpy.ndarray) -> numpy.ndarray:
    return A * numpy.exp(-x / tau)


# register background models with the registry.
Registry.register_component(
    PolynomialBackgroundModel("constant_background_model",
                              0,
                              title=_("Constant")), {"background-model"})

Registry.register_component(
    PolynomialBackgroundModel("linear_background_model", 1, title=_("Linear")),
    {"background-model"})

Registry.register_component(
    PolynomialBackgroundModel("power_law_background_model",
                              1,
                              transform=numpy.log,
                              untransform=numpy.exp,
                              title=_("Power Law")), {"background-model"})

Registry.register_component(
    PolynomialBackgroundModel("poly2_background_model",
Esempio n. 8
0
            },
        ]
        self.is_mappable = True
        self.is_scalar = True
        self.attributes["connection_type"] = "map"

    def process(
        self, *, src: DataItem.DataSource, **kwargs
    ) -> typing.Union[DataAndMetadata.DataAndMetadata,
                      DataAndMetadata.ScalarAndMetadata]:
        filtered_xdata = src.filtered_xdata
        return DataAndMetadata.ScalarAndMetadata.from_value(
            numpy.average(filtered_xdata),
            filtered_xdata.intensity_calibration)


# Registry.register_component(ProcessingFFT(), {"processing-component"})
# Registry.register_component(ProcessingIFFT(), {"processing-component"})
Registry.register_component(ProcessingGaussianWindow(),
                            {"processing-component"})
Registry.register_component(ProcessingHammingWindow(),
                            {"processing-component"})
Registry.register_component(ProcessingHannWindow(), {"processing-component"})
Registry.register_component(ProcessingMappedSum(), {"processing-component"})
Registry.register_component(ProcessingMappedAverage(),
                            {"processing-component"})


def init():
    pass
 def stop_playing(self):
     stem_controller = Registry.get_component("stem_controller")
     ronchigram = stem_controller.ronchigram_camera
     ronchigram.stop_playing()
     return
Esempio n. 10
0
 def remove_hardware_source(self, hardware_source):
     hardware_source.abort_playing()
     component = hardware_source.video_device
     Registry.unregister_component(component)
     self.__save()
Esempio n. 11
0
            drink = Activity.Activity("drink", "Drink")
            Activity.append_activity(drink)

            await asyncio.sleep(3.0)
            eat = XActivity("Eat")
            Activity.append_activity(eat)

            await asyncio.sleep(3.0)
            Activity.activity_finished(eat)

            await asyncio.sleep(3.0)
            Activity.activity_finished(drink)

        document_controller.event_loop.create_task(later())
"""
"""
class XActivity(Activity.Activity):
    def __init__(self, title: str) -> None:
        super().__init__("x-activity", title)


class XActivityHandler(Declarative.HandlerLike):
    # Declarative component handler for a section in a multiple acquire method component.

    def __init__(self, activity: Activity.Activity) -> None:
        assert isinstance(activity, XActivity)
        self.activity = activity
        u = Declarative.DeclarativeUI()
        self.ui_view = u.create_row(
            u.create_label(text="X"),
            u.create_label(text="@binding(activity.title)"),
Esempio n. 12
0
 def setup_stem_controller(self) -> stem_controller.STEMController:
     instrument = InstrumentDevice.Instrument("usim_stem_controller")
     Registry.register_component(instrument, {"stem_controller"})
     return instrument
Esempio n. 13
0
 def scan_controller(self) -> HardwareSource.HardwareSource:
     if self.__scan_controller:
         return self.__scan_controller
     return Registry.get_component("scan_hardware_source")
Esempio n. 14
0
 def eels_camera(self) -> HardwareSource.HardwareSource:
     if self.__eels_camera:
         return self.__eels_camera
     return Registry.get_component("eels_camera_hardware_source")
Esempio n. 15
0
 def ronchigram_camera(self) -> HardwareSource.HardwareSource:
     if self.__ronchigram_camera:
         return self.__ronchigram_camera
     return Registry.get_component("ronchigram_camera_hardware_source")
Esempio n. 16
0
    def __init__(self, ui, set_global=True, resources_path=None):
        super().__init__(ui)
        self.__class__.count += 1

        # reset these values for tests. otherwise tests run slower after app.start is called in any previous test.
        DocumentModel.DocumentModel.computation_min_period = 0.0
        DocumentModel.DocumentModel.computation_min_factor = 0.0

        logging.getLogger("migration").setLevel(logging.ERROR)
        logging.getLogger("loader").setLevel(logging.ERROR)

        global app

        ui.set_application_info("Nion Swift", "Nion", "nion.com")

        self.ui.persistence_root = "3"  # sets of preferences
        self.__resources_path = resources_path
        self.version_str = "0.15.2"

        self.document_model_available_event = Event.Event()

        if True or set_global:
            app = self  # hack to get the single instance set. hmm. better way?

        self.__profile = None
        self.__document_model = None

        self.__menu_handlers = []

        Registry.register_component(
            Inspector.DeclarativeImageChooserConstructor(self),
            {"declarative_constructor"})
        Registry.register_component(
            Inspector.DeclarativeDataSourceChooserConstructor(self),
            {"declarative_constructor"})

        workspace_manager = Workspace.WorkspaceManager()
        workspace_manager.register_panel(SessionPanel.SessionPanel,
                                         "session-panel", _("Session"),
                                         ["left", "right"], "right", {
                                             "min-width": 320,
                                             "height": 80
                                         })
        workspace_manager.register_panel(ProjectPanel.CollectionsPanel,
                                         "collections-panel", _("Collections"),
                                         ["left", "right"], "left", {
                                             "min-width": 320,
                                             "min-height": 200
                                         })
        workspace_manager.register_panel(DataPanel.DataPanel, "data-panel",
                                         _("Data Panel"), ["left", "right"],
                                         "left", {
                                             "min-width": 320,
                                             "min-height": 320
                                         })
        workspace_manager.register_panel(HistogramPanel.HistogramPanel,
                                         "histogram-panel", _("Histogram"),
                                         ["left", "right"], "right", {
                                             "min-width": 320,
                                             "height": 140
                                         })
        workspace_manager.register_panel(InfoPanel.InfoPanel, "info-panel",
                                         _("Info"), ["left", "right"], "right",
                                         {
                                             "min-width": 320,
                                             "height": 60
                                         })
        workspace_manager.register_panel(Inspector.InspectorPanel,
                                         "inspector-panel", _("Inspector"),
                                         ["left", "right"], "right",
                                         {"min-width": 320})
        workspace_manager.register_panel(Task.TaskPanel, "task-panel",
                                         _("Task Panel"), ["left", "right"],
                                         "right", {"min-width": 320})
        workspace_manager.register_panel(Panel.OutputPanel, "output-panel",
                                         _("Output"), ["bottom"], "bottom", {
                                             "min-width": 480,
                                             "min-height": 200
                                         })
        workspace_manager.register_panel(ToolbarPanel.ToolbarPanel,
                                         "toolbar-panel", _("Toolbar"),
                                         ["top"], "top", {"height": 30})
        workspace_manager.register_panel(MetadataPanel.MetadataPanel,
                                         "metadata-panel", _("Metadata"),
                                         ["left", "right"], "right", {
                                             "width": 320,
                                             "height": 8
                                         })
        workspace_manager.register_filter_panel(FilterPanel.FilterPanel)
    def create_panel_widget(
            self, ui: Facade.UserInterface,
            document_controller: Facade.DocumentWindow) -> Facade.ColumnWidget:
        stem_controller_ = typing.cast(
            stem_controller.STEMController,
            Registry.get_component("stem_controller"))

        self.__scan_hardware_source_choice_model = ui._ui.create_persistent_string_model(
            "scan_acquisition_hardware_source_id")
        self.__scan_hardware_source_choice = HardwareSourceChoice.HardwareSourceChoice(
            self.__scan_hardware_source_choice_model,
            lambda hardware_source: hardware_source.features.get(
                "is_scanning", False))
        self.__camera_hardware_source_choice_model = ui._ui.create_persistent_string_model(
            "scan_acquisition_camera_hardware_source_id")
        self.__camera_hardware_source_choice = HardwareSourceChoice.HardwareSourceChoice(
            self.__camera_hardware_source_choice_model,
            lambda hardware_source: hardware_source.features.get(
                "is_camera", False))

        self.__scan_hardware_source_stream = HardwareSourceChoice.HardwareSourceChoiceStream(
            self.__scan_hardware_source_choice).add_ref()
        self.__camera_hardware_source_stream = HardwareSourceChoice.HardwareSourceChoiceStream(
            self.__camera_hardware_source_choice).add_ref()

        def clear_scan_context_fields() -> None:
            self.__roi_description.text = _("Scan context not active")
            self.__scan_label_widget.text = None
            self.__scan_specifier.scan_context = stem_controller.ScanContext()
            self.__scan_specifier.scan_count = 1
            self.__scan_specifier.size = None
            self.__scan_specifier.drift_interval_lines = 0
            self.__scan_specifier.drift_interval_scans = 0
            self.__acquire_button._widget.enabled = self.__acquisition_state == SequenceState.scanning  # focus will be on the SI data, so enable if scanning
            self.__scan_pixels = 0

        def update_context() -> None:
            assert self.__scan_hardware_source_choice
            scan_hardware_source = typing.cast(
                scan_base.ScanHardwareSource,
                self.__scan_hardware_source_choice.hardware_source)
            if not scan_hardware_source:
                clear_scan_context_fields()
                return

            scan_context = scan_hardware_source.scan_context

            scan_context_size = scan_context.size
            exposure_ms = self.__exposure_time_ms_value_model.value or 0.0 if self.__exposure_time_ms_value_model else 0.0
            if scan_context.is_valid and scan_hardware_source.line_scan_enabled and scan_hardware_source.line_scan_vector:
                assert scan_context_size
                calibration = scan_context.calibration
                start = Geometry.FloatPoint.make(
                    scan_hardware_source.line_scan_vector[0])
                end = Geometry.FloatPoint.make(
                    scan_hardware_source.line_scan_vector[1])
                length = int(
                    Geometry.distance(start, end) * scan_context_size.height)
                max_dim = max(scan_context_size.width,
                              scan_context_size.height)
                length_str = calibration.convert_to_calibrated_size_str(
                    length, value_range=(0, max_dim), samples=max_dim)
                line_str = _("Line Scan")
                self.__roi_description.text = f"{line_str} {length_str} ({length} px)"
                scan_str = _("Scan (1D)")
                scan_length = max(self.__scan_width, 1)
                self.__scan_label_widget.text = f"{scan_str} {scan_length} px"
                self.__scan_pixels = scan_length
                self.__scan_specifier.scan_context = copy.deepcopy(
                    scan_context)
                self.__scan_specifier.scan_count = max(self.__scan_count, 1)
                self.__scan_specifier.size = 1, scan_length
                self.__scan_specifier.drift_interval_lines = 0
                self.__scan_specifier.drift_interval_scans = 0
                self.__acquire_button._widget.enabled = True
            elif scan_context.is_valid and scan_hardware_source.subscan_enabled and scan_hardware_source.subscan_region:
                assert scan_context_size
                calibration = scan_context.calibration
                width = scan_hardware_source.subscan_region.width * scan_context_size.width
                height = scan_hardware_source.subscan_region.height * scan_context_size.height
                width_str = calibration.convert_to_calibrated_size_str(
                    width,
                    value_range=(0, scan_context_size.width),
                    samples=scan_context_size.width)
                height_str = calibration.convert_to_calibrated_size_str(
                    height,
                    value_range=(0, scan_context_size.height),
                    samples=scan_context_size.height)
                rect_str = _("Subscan")
                self.__roi_description.text = f"{rect_str} {width_str} x {height_str} ({int(width)} px x {int(height)} px)"
                scan_str = _("Scan (2D)")
                scan_width = self.__scan_width
                scan_height = int(self.__scan_width * height / width)
                drift_lines = scan_hardware_source.calculate_drift_lines(
                    scan_width, exposure_ms /
                    1000) if scan_hardware_source else 0
                drift_str = f" / Drift {drift_lines} lines" if drift_lines > 0 else str(
                )
                drift_scans = scan_hardware_source.calculate_drift_scans()
                drift_str = f" / Drift {drift_scans} scans" if drift_scans > 0 else drift_str
                self.__scan_label_widget.text = f"{scan_str} {scan_width} x {scan_height} px" + drift_str
                self.__scan_pixels = scan_width * scan_height
                self.__scan_specifier.scan_context = copy.deepcopy(
                    scan_context)
                self.__scan_specifier.scan_count = max(self.__scan_count, 1)
                self.__scan_specifier.size = scan_height, scan_width
                self.__scan_specifier.drift_interval_lines = drift_lines
                self.__scan_specifier.drift_interval_scans = drift_scans
                self.__acquire_button._widget.enabled = True
            elif scan_context.is_valid:
                assert scan_context_size
                calibration = scan_context.calibration
                width = scan_context_size.width
                height = scan_context_size.height
                width_str = calibration.convert_to_calibrated_size_str(
                    width,
                    value_range=(0, scan_context_size.width),
                    samples=scan_context_size.width)
                height_str = calibration.convert_to_calibrated_size_str(
                    height,
                    value_range=(0, scan_context_size.height),
                    samples=scan_context_size.height)
                data_str = _("Context Scan")
                self.__roi_description.text = f"{data_str} {width_str} x {height_str} ({int(width)} x {int(height)})"
                scan_str = _("Scan (2D)")
                scan_width = self.__scan_width
                scan_height = int(self.__scan_width * height / width)
                drift_lines = scan_hardware_source.calculate_drift_lines(
                    scan_width, exposure_ms /
                    1000) if scan_hardware_source else 0
                drift_str = f" / Drift {drift_lines} lines" if drift_lines > 0 else str(
                )
                drift_scans = scan_hardware_source.calculate_drift_scans()
                drift_str = f" / Drift {drift_scans} scans" if drift_scans > 0 else drift_str
                self.__scan_label_widget.text = f"{scan_str} {scan_width} x {scan_height} px" + drift_str
                self.__scan_pixels = scan_width * scan_height
                self.__scan_specifier.scan_context = copy.deepcopy(
                    scan_context)
                self.__scan_specifier.scan_count = max(self.__scan_count, 1)
                self.__scan_specifier.size = scan_height, scan_width
                self.__scan_specifier.drift_interval_lines = drift_lines
                self.__scan_specifier.drift_interval_scans = drift_scans
                self.__acquire_button._widget.enabled = True
            else:
                clear_scan_context_fields()

            self.__scan_count_widget.text = Converter.IntegerToStringConverter(
            ).convert(self.__scan_count)

            self.__scan_width_widget.text = Converter.IntegerToStringConverter(
            ).convert(self.__scan_width)

            self.__update_estimate()

        def stem_controller_property_changed(key: str) -> None:
            if key in ("subscan_state", "subscan_region", "subscan_rotation",
                       "line_scan_state", "line_scan_vector",
                       "drift_channel_id", "drift_region", "drift_settings"):
                document_controller._document_controller.event_loop.call_soon_threadsafe(
                    update_context)

        def scan_context_changed() -> None:
            # this can be triggered from a thread, so use call soon to transfer it to the UI thread.
            document_controller._document_controller.event_loop.call_soon_threadsafe(
                update_context)

        self.__stem_controller_property_listener = None
        self.__scan_context_changed_listener = None

        if stem_controller_:
            self.__stem_controller_property_listener = stem_controller_.property_changed_event.listen(
                stem_controller_property_changed)
            self.__scan_context_changed_listener = stem_controller_.scan_context_changed_event.listen(
                scan_context_changed)

        column = ui.create_column_widget()

        self.__styles_list_model = ListModel.ListModel[
            ScanAcquisitionProcessing](items=[
                ScanAcquisitionProcessing.SUM_PROJECT,
                ScanAcquisitionProcessing.NONE
            ])
        self.__styles_list_property_model = ListModel.ListPropertyModel(
            self.__styles_list_model)
        self.__style_combo_box = ui.create_combo_box_widget(
            self.__styles_list_property_model.value,
            item_text_getter=operator.attrgetter("value.display_name"))
        self.__style_combo_box._widget.set_property("min-width", 100)
        items_binding = Binding.PropertyBinding(
            self.__styles_list_property_model, "value")
        items_binding.source_setter = None
        typing.cast(UserInterfaceModule.ComboBoxWidget,
                    self.__style_combo_box._widget).bind_items(items_binding)
        self.__style_combo_box.current_index = 0

        self.__acquire_button = ui.create_push_button_widget(_("Acquire"))

        self.__progress_bar = ui.create_progress_bar_widget()
        # self.__progress_bar.enabled = False

        self.__roi_description = ui.create_label_widget()

        self.__scan_count_widget = ui.create_line_edit_widget()
        self.__scan_count_widget._widget.set_property("width", 72)

        self.__scan_processing_widget = ui.create_combo_box_widget(
            items=["Raw", "Sum", "Raw + Sum"])

        self.__scan_width_widget = ui.create_line_edit_widget()

        self.__exposure_time_widget = ui.create_line_edit_widget()

        self.__estimate_label_widget = ui.create_label_widget()

        self.__scan_label_widget = ui.create_label_widget()

        class ComboBoxWidget:
            def __init__(self,
                         widget: UserInterfaceModule.ComboBoxWidget) -> None:
                self.__combo_box_widget = widget

            @property
            def _widget(self) -> UserInterfaceModule.ComboBoxWidget:
                return self.__combo_box_widget

        camera_row = ui.create_row_widget()
        camera_row.add_spacing(12)
        camera_row.add(
            ComboBoxWidget(
                self.__camera_hardware_source_choice.create_combo_box(ui._ui)))
        camera_row.add_spacing(12)
        camera_row.add(self.__style_combo_box)
        camera_row.add_spacing(12)
        camera_row.add_stretch()

        scan_choice_row = ui.create_row_widget()
        scan_choice_row.add_spacing(12)
        scan_choice_row.add(
            ComboBoxWidget(
                self.__scan_hardware_source_choice.create_combo_box(ui._ui)))
        scan_choice_row.add_spacing(12)
        scan_choice_row.add_stretch()

        scan_count_row = ui.create_row_widget()
        scan_count_row.add_spacing(12)
        scan_count_row.add(ui.create_label_widget("Scan Count"))
        scan_count_row.add_spacing(12)
        scan_count_row.add(self.__scan_count_widget)
        scan_count_row.add_spacing(12)
        scan_count_row.add(self.__scan_processing_widget)
        scan_count_row.add_spacing(12)
        scan_count_row.add_stretch()

        roi_size_row = ui.create_row_widget()
        roi_size_row.add_spacing(12)
        roi_size_row.add(self.__roi_description)
        roi_size_row.add_spacing(12)
        roi_size_row.add_stretch()

        scan_spacing_pixels_row = ui.create_row_widget()
        scan_spacing_pixels_row.add_spacing(12)
        scan_spacing_pixels_row.add(
            ui.create_label_widget("Scan Width (pixels)"))
        scan_spacing_pixels_row.add_spacing(12)
        scan_spacing_pixels_row.add(self.__scan_width_widget)
        scan_spacing_pixels_row.add_spacing(12)
        scan_spacing_pixels_row.add_stretch()

        eels_exposure_row = ui.create_row_widget()
        eels_exposure_row.add_spacing(12)
        eels_exposure_row.add(
            ui.create_label_widget("Camera Exposure Time (ms)"))
        eels_exposure_row.add_spacing(12)
        eels_exposure_row.add(self.__exposure_time_widget)
        eels_exposure_row.add_spacing(12)
        eels_exposure_row.add_stretch()

        scan_row = ui.create_row_widget()
        scan_row.add_spacing(12)
        scan_row.add(self.__scan_label_widget)
        scan_row.add_stretch()

        estimate_row = ui.create_row_widget()
        estimate_row.add_spacing(12)
        estimate_row.add(self.__estimate_label_widget)
        estimate_row.add_stretch()

        acquire_sequence_button_row = ui.create_row_widget()
        acquire_sequence_button_row.add(self.__acquire_button)
        acquire_sequence_button_row.add_spacing(8)
        acquire_sequence_button_row.add(self.__progress_bar)
        acquire_sequence_button_row.add_spacing(8)

        if self.__scan_hardware_source_choice.hardware_source_count > 1:
            column.add_spacing(8)
            column.add(scan_choice_row)
        column.add_spacing(8)
        column.add(camera_row)
        column.add_spacing(8)
        column.add(scan_count_row)
        column.add_spacing(8)
        column.add(roi_size_row)
        column.add_spacing(8)
        column.add(scan_spacing_pixels_row)
        column.add_spacing(8)
        column.add(eels_exposure_row)
        column.add_spacing(8)
        column.add(scan_row)
        column.add_spacing(8)
        column.add(estimate_row)
        column.add_spacing(8)
        column.add(acquire_sequence_button_row)
        column.add_spacing(8)
        column.add_stretch()

        def camera_hardware_source_changed(
            hardware_source: typing.Optional[HardwareSource.HardwareSource]
        ) -> None:
            styles_list_model = self.__styles_list_model
            self.disconnect_camera_hardware_source()
            if hardware_source and styles_list_model:
                self.connect_camera_hardware_source(hardware_source)
                if hardware_source.features.get("has_masked_sum_option"):
                    styles_list_model.items = [
                        ScanAcquisitionProcessing.SUM_PROJECT,
                        ScanAcquisitionProcessing.NONE,
                        ScanAcquisitionProcessing.SUM_MASKED
                    ]
                else:
                    styles_list_model.items = [
                        ScanAcquisitionProcessing.SUM_PROJECT,
                        ScanAcquisitionProcessing.NONE
                    ]

        self.__camera_hardware_changed_event_listener = self.__camera_hardware_source_choice.hardware_source_changed_event.listen(
            camera_hardware_source_changed)
        camera_hardware_source_changed(
            self.__camera_hardware_source_choice.hardware_source)

        def style_current_item_changed(current_item: str) -> None:
            self.__update_estimate()

        self.__style_combo_box.on_current_item_changed = style_current_item_changed

        def scan_count_changed(text: str) -> None:
            scan_count = Converter.IntegerToStringConverter().convert_back(
                text) or 1
            scan_count = max(scan_count, 1)
            if scan_count != self.__scan_count:
                self.__scan_count = scan_count
                update_context()
            self.__scan_count_widget.request_refocus()

        self.__scan_count_widget.on_editing_finished = scan_count_changed

        def scan_width_changed(text: str) -> None:
            scan_width = Converter.IntegerToStringConverter().convert_back(
                text) or 1
            scan_width = max(scan_width, 1)
            if scan_width != self.__scan_width:
                self.__scan_width = scan_width
                update_context()
            self.__scan_width_widget.request_refocus()

        self.__scan_width_widget.on_editing_finished = scan_width_changed

        def acquisition_state_changed(
                acquisition_state: SequenceState) -> None:
            self.__acquisition_state = acquisition_state

            async def update_state(is_idle: bool) -> None:
                self.__acquire_button.text = _("Acquire") if is_idle else _(
                    "Cancel")
                # self.__progress_bar.enabled = not is_idle
                update_context()  # update the cancel button
                if is_idle and self.__progress_task:
                    self.__progress_task.cancel()
                    self.__progress_task = None
                    self.__progress_bar.value = 100
                if not is_idle and not self.__progress_task:

                    async def update_progress() -> None:
                        while True:
                            if self.__scan_acquisition_controller:
                                self.__progress_bar.value = int(
                                    100 *
                                    self.__scan_acquisition_controller.progress
                                )
                            await asyncio.sleep(0.25)

                    self.__progress_task = document_controller._document_window.event_loop.create_task(
                        update_progress())

            if acquisition_state == SequenceState.idle:
                self.__scan_acquisition_controller = None
                if self.__acquisition_state_changed_event_listener:
                    self.__acquisition_state_changed_event_listener.close()
                    self.__acquisition_state_changed_event_listener = None
                document_controller._document_window.event_loop.create_task(
                    update_state(True))
            else:
                document_controller._document_window.event_loop.create_task(
                    update_state(False))

        def acquire_sequence() -> None:
            if self.__scan_acquisition_controller:
                if self.__scan_acquisition_controller:
                    self.__scan_acquisition_controller.cancel()
            else:
                scan_hardware_source_choice = self.__scan_hardware_source_choice
                assert scan_hardware_source_choice
                if scan_hardware_source_choice.hardware_source:
                    scan_hardware_source = self.__api.get_hardware_source_by_id(
                        scan_hardware_source_choice.hardware_source.
                        hardware_source_id,
                        version="1.0")
                else:
                    scan_hardware_source = None

                camera_hardware_source_choice = self.__camera_hardware_source_choice
                assert camera_hardware_source_choice
                if camera_hardware_source_choice.hardware_source:
                    camera_hardware_source = self.__api.get_hardware_source_by_id(
                        camera_hardware_source_choice.hardware_source.
                        hardware_source_id,
                        version="1.0")
                else:
                    camera_hardware_source = None

                if scan_hardware_source and camera_hardware_source:
                    self.__scan_acquisition_controller = ScanAcquisitionController(
                        self.__api, document_controller, scan_hardware_source,
                        camera_hardware_source, self.__scan_specifier)
                    self.__acquisition_state_changed_event_listener = self.__scan_acquisition_controller.acquisition_state_changed_event.listen(
                        acquisition_state_changed)
                    scan_processing = ScanProcessing(
                        self.__scan_processing_widget.current_index in (0, 2),
                        self.__scan_processing_widget.current_index in (1, 2))
                    scan_acquisition_processing = self.__style_combo_box.current_item if self.__style_combo_box and self.__style_combo_box.current_item else ScanAcquisitionProcessing.NONE
                    self.__scan_acquisition_controller.start(
                        scan_acquisition_processing, scan_processing)

        self.__acquire_button.on_clicked = acquire_sequence

        self.__update_estimate()

        update_context()

        return column
Esempio n. 18
0
            fit[index] = self._perform_fit(yss[index], z)
        return fit

    def _perform_fit(self, ys: numpy.ndarray, z: int) -> numpy.ndarray:
        # ys will be an array of y-values with shape (L)
        # z is the index of the column of 0eV
        # return an ndarray of the fit with shape (L)
        # implement at least one of _perform_fits and _perform_fit
        return numpy.reshape(
            self._perform_fits(numpy.reshape(ys, (1, ) + ys.shape), z),
            ys.shape)


class SimpleZeroLossPeakModel(AbstractZeroLossPeakModel):
    def __init__(self, zero_loss_peak_model: str, title: str = None):
        super().__init__(zero_loss_peak_model, title)

    def _perform_fits(self, yss: numpy.ndarray, z: int) -> numpy.ndarray:
        left = max(0, z - 3)
        right = min(yss.shape[-1], z + 3)
        result = numpy.zeros(yss.shape)
        result[..., left:right] = yss[..., left:right]
        # print(f"{z=} {left=} {right=}")
        return result


# register models with the registry.
Registry.register_component(
    SimpleZeroLossPeakModel("simple_peak_model", title=_("Simple")),
    {"zlp-model"})
 def component_unregistered(component, component_types):
     if "camera_module" in component_types:
         camera_hardware_source = component.hardware_source
         Registry.unregister_component(camera_hardware_source)
         HardwareSource.HardwareSourceManager().unregister_hardware_source(
             camera_hardware_source)
Esempio n. 20
0
        self.__text = value
        self.notify_property_changed("text")

    def dismiss(self) -> None:
        self.dismiss_event.fire()


class NotificationSourceLike(typing.Protocol):
    notify_event: Event.Event
    notifications: typing.Sequence[Notification]


class NotificationSource(NotificationSourceLike):
    def __init__(self) -> None:
        self.notify_event = Event.Event()
        self.notifications: typing.List[Notification] = list()

    def notify(self, notification: Notification) -> None:
        self.notifications.append(notification)
        self.notify_event.fire(notification)


_notification_source = NotificationSource()


def notify(notification: Notification) -> None:
    _notification_source.notify(notification)


Registry.register_component(_notification_source, {"notification-source"})
Esempio n. 21
0
    def build(self, ui, event_loop=None, **kwargs):
        u = Declarative.DeclarativeUI()

        video_device_factories = list(Registry.get_components_by_type("video_device_factory"))

        class Handler:
            def __init__(self, ui_view, video_sources):
                self.ui_view = ui_view
                self.video_sources = video_sources
                self.video_source_type_index = Model.PropertyModel(0)

            def create_new_video_device(self, widget):
                video_base.video_configuration.create_hardware_source(video_device_factories[self.video_source_type_index.value])

            def create_handler(self, component_id: str, container=None, item=None, **kwargs):

                class SectionHandler:

                    def __init__(self, container, hardware_source):
                        self.container = container
                        self.hardware_source = hardware_source
                        self.settings = video_base.video_configuration.get_settings_model(hardware_source)
                        self.settings_original = copy.deepcopy(self.settings)
                        self.needs_saving_model = Model.PropertyModel(False)
                        self.property_changed_event = Event.Event()
                        self.apply_button = None
                        self.revert_button = None

                        def settings_changed(property_name):
                            self.needs_saving_model.value = True

                        self.__settings_changed_event_listener = self.settings.property_changed_event.listen(settings_changed)

                        def needs_saving_model_changed(property_name):
                            if self.apply_button:
                                self.apply_button.enabled = self.needs_saving_model.value
                            if self.revert_button:
                                self.revert_button.enabled = self.needs_saving_model.value

                        self.__needs_saving_changed_event_listener = self.needs_saving_model.property_changed_event.listen(needs_saving_model_changed)

                    def close(self):
                        self.__settings_changed_event_listener.close()
                        self.__settings_changed_event_listener = None

                    def init_handler(self):
                        self.apply_button.enabled = self.needs_saving_model.value
                        self.revert_button.enabled = self.needs_saving_model.value

                    def create_handler(self, component_id: str, container=None, item=None, **kwargs):
                        if component_id == "edit_group":
                            if self.__video_device_factory:
                                return self.__video_device_factory.create_editor_handler(self.settings)
                            else:
                                return self

                    @property
                    def resources(self):
                        if self.__video_device_factory:
                            content = self.__video_device_factory.get_editor_description()
                        else:
                            content = u.create_label(text=_("Not Available"))

                        component = u.define_component(content=content, component_id="edit_group")

                        return {"edit_group": component}

                    @property
                    def __video_device_factory(self):
                        for video_device_factory in video_device_factories:
                            if video_device_factory.factory_id == self.settings.driver:
                                return video_device_factory
                        return None

                    @property
                    def driver_display_name(self) -> str:
                        video_device_factory = self.__video_device_factory
                        return video_device_factory.display_name if video_device_factory else _("Unknown")

                    def apply(self, widget):
                        video_base.video_configuration.set_settings_model(self.hardware_source, self.settings)
                        self.needs_saving_model.value = False

                    def revert(self, widget):
                        self.settings.copy_from(self.settings_original)
                        self.needs_saving_model.value = False

                    def remove(self, widget):
                        video_base.video_configuration.remove_hardware_source(self.hardware_source)

                if component_id == "section":
                    return SectionHandler(container, item)

            @property
            def resources(self):
                u = Declarative.DeclarativeUI()

                driver_display_name_label = u.create_label(text="@binding(driver_display_name)")

                device_id_field = u.create_line_edit(text="@binding(settings.device_id)", width=180)

                display_name_field = u.create_line_edit(text="@binding(settings.name)", width=240)

                edit_group_content = u.create_component_instance("edit_group")

                edit_group = u.create_group(edit_group_content, margin=8)

                edit_row = u.create_row(edit_group, u.create_stretch())

                apply_button = u.create_push_button(name="apply_button", text=_("Apply"), on_clicked="apply")
                revert_button = u.create_push_button(name="revert_button", text=_("Revert"), on_clicked="revert")
                remove_button = u.create_push_button(text=_("Remove"), on_clicked="remove")
                remove_row = u.create_row(apply_button, revert_button, remove_button, u.create_stretch())

                label_column = u.create_column(u.create_label(text=_("Driver:")), u.create_label(text=_("Device ID:")), u.create_label(text=_("Display Name:")), spacing=4)
                field_column = u.create_column(driver_display_name_label, device_id_field, display_name_field, spacing=4)

                content_row = u.create_row(label_column, field_column, u.create_stretch(), spacing=12)

                content = u.create_column(content_row, edit_row, remove_row, spacing=8)

                component = u.define_component(content=content, component_id="section")

                return {"section": component}

        sources_column = u.create_column(items="video_sources.items", item_component_id="section", spacing=8)

        sources_content = u.create_scroll_area(u.create_column(sources_column, u.create_stretch()))

        video_source_types = [video_device_factory.display_name for video_device_factory in video_device_factories]

        video_source_type_combo = u.create_combo_box(items=video_source_types, current_index="@binding(video_source_type_index.value)")

        button_row = u.create_row(u.create_stretch(), video_source_type_combo, u.create_push_button(text=_("New"), on_clicked="create_new_video_device"), spacing=8)

        content = u.create_column(sources_content, button_row)

        return Declarative.DeclarativeWidget(ui, event_loop, Handler(content, self.__video_configuration.video_sources))
Esempio n. 22
0
 def stem_controller(self):
     if self._stem_controller is None:
         self._stem_controller = Registry.get_component('stem_controller')
     return self._stem_controller
Esempio n. 23
0
def acquire_multi_eels(interactive, api):
    # first grab the stem controller object by asking the Registry
    stem_controller = Registry.get_component("stem_controller")

    # establish the EELS camera object and stop it if it is playing
    eels_camera = stem_controller.eels_camera
    eels_camera.stop_playing()

    print(eels_camera.hardware_source_id)

    # this table represents the acquisitions to be performed
    # each entry is energy offset, exposure (milliseconds), and the number of frames to integrate
    table = [
        # energy offset, exposure(ms), N frames
        (0, 100, 2),
        (10, 100, 2),
        #(250, 1000, 10),
        #(0, 100, 5),
    ]

    # this is the list of integrated spectra that will be the result of this script
    spectra = list()

    # this algorithm handles dark subtraction specially - so dark subtraction and gain normalization should
    # be disabled in the camera settings; this algorithm will handle dark subtraction itself.
    do_dark = True
    do_gain = False

    print("start taking data")

    energy_offset_control = "EELS_MagneticShift_Offset"  # for hardware EELS
    # energy_offset_control = "EELS_MagneticShift_Offset"  # for simulator

    tolerance_factor_from_nominal = 1.0
    timeout_for_confirmation_ms = 3000

    for energy_offset_ev, exposure_ms, frame_count in table:
        # for each table entry, set the drift tube loss to the energy offset
        stem_controller.SetValAndConfirm(energy_offset_control,
                                         energy_offset_ev,
                                         tolerance_factor_from_nominal,
                                         timeout_for_confirmation_ms)

        # configure the camera to have the desired exposure
        frame_parameters = eels_camera.get_current_frame_parameters()
        frame_parameters["exposure_ms"] = exposure_ms
        eels_camera.set_current_frame_parameters(frame_parameters)

        # disable blanker
        stem_controller.SetValAndConfirm("C_Blank", 0,
                                         tolerance_factor_from_nominal,
                                         timeout_for_confirmation_ms)

        # acquire a sequence of images and discard it; this ensures a steady state
        eels_camera.grab_sequence_prepare(frame_count)
        eels_camera.grab_sequence(frame_count)

        # acquire a sequence of images again, but now integrate the acquired images into a single image
        eels_camera.grab_sequence_prepare(frame_count)
        xdata = eels_camera.grab_sequence(frame_count)[0]

        print(f"grabbed data of shape {xdata.data_shape}")

        # extract the calibration info
        counts_per_electron = xdata.metadata.get("hardware_source",
                                                 dict()).get(
                                                     "counts_per_electron", 1)
        exposure_ms = xdata.metadata.get("hardware_source",
                                         dict()).get("exposure", 1)
        intensity_scale = xdata.intensity_calibration.scale / counts_per_electron / xdata.dimensional_calibrations[
            -1].scale / exposure_ms / frame_count

        # now sum the data in the sequence/time dimension. use xd.sum to automatically handle metadata such as calibration.
        xdata = xd.sum(xdata, 0)

        # if dark subtraction is enabled, perform another similar acquisition with blanker enabled and subtract it
        if do_dark:
            # enable blanker
            stem_controller.SetValAndConfirm("C_Blank", 1,
                                             tolerance_factor_from_nominal,
                                             timeout_for_confirmation_ms)

            # acquire a sequence of images and discard it; this ensures a steady state
            eels_camera.grab_sequence_prepare(frame_count)
            eels_camera.grab_sequence(frame_count)

            # acquire a sequence of images again, but now integrate the acquired images into a single image
            eels_camera.grab_sequence_prepare(frame_count)
            dark_xdata = eels_camera.grab_sequence(frame_count)[0]

            # sum it and subtract it from xdata
            dark_xdata = xd.sum(dark_xdata, 0)
            xdata = xdata - dark_xdata

            print(f"subtracted dark data of shape {dark_xdata.data_shape}")
        if do_gain:
            # divide out the gain
            gain_uuid = uuid.uuid4(
            )  # fill this in with the actual gain image uuid
            gain = interactive.document_controller.document_model.get_data_item_by_uuid(
                gain_uuid)
            if gain is not None:
                xdata = xdata / gain.xdata

        # next sum the 2d data into a 1d spectrum by collapsing the y-axis (0th dimension)
        # also configure the intensity calibration and title.
        spectrum = xd.sum(xdata, 0)
        spectrum.data_metadata._set_intensity_calibration(
            Calibration.Calibration(scale=intensity_scale, units="e/eV/s"))
        spectrum.data_metadata._set_metadata({
            "title":
            f"{energy_offset_ev}eV {int(exposure_ms*1000)}ms [x{frame_count}]"
        })

        # add it to the list of spectra
        spectra.append(spectrum)

    # disable blanking and return drift tube loss to 0.0eV
    stem_controller.SetValAndConfirm("C_Blank", 0,
                                     tolerance_factor_from_nominal,
                                     timeout_for_confirmation_ms)
    stem_controller.SetValAndConfirm(energy_offset_control, 0,
                                     tolerance_factor_from_nominal,
                                     timeout_for_confirmation_ms)

    print("finished taking data")

    # when multi display is available, we can combine the spectra into a single line plot display without
    # padding the data; but for now, we need to use a single master data item where each row is the same length.

    if len(spectra) > 0:
        # define the padded spectra list
        padded_spectra = list()

        # extract calibration info
        ev_per_channel = spectra[0].dimensional_calibrations[-1].scale
        units = spectra[0].dimensional_calibrations[-1].units
        min_ev = min([
            spectrum.dimensional_calibrations[-1].convert_to_calibrated_value(
                0) for spectrum in spectra
        ])
        max_ev = max([
            spectrum.dimensional_calibrations[-1].convert_to_calibrated_value(
                spectrum.data_shape[-1]) for spectrum in spectra
        ])

        # calculate what the length of the padded data will be
        data_length = int((max_ev - min_ev) / ev_per_channel)

        # for each spectra, pad it out to the appropriate length, putting the actual data in the proper range
        for spectrum in spectra:
            energy_offset_ev = int(
                (spectrum.dimensional_calibrations[-1].
                 convert_to_calibrated_value(0) - min_ev) / ev_per_channel)
            calibration_factor = spectrum.intensity_calibration.scale / spectra[
                0].intensity_calibration.scale
            data = numpy.zeros((data_length, ))
            data[energy_offset_ev:energy_offset_ev +
                 spectrum.data_shape[-1]] = spectrum.data * calibration_factor
            padded_spectrum = DataAndMetadata.new_data_and_metadata(
                data, spectrum.intensity_calibration,
                [Calibration.Calibration(min_ev, ev_per_channel, units)])
            padded_spectra.append(padded_spectrum)

        # stack all of the padded data together for display
        master_xdata = xd.vstack(padded_spectra)

        # show the data
        window = api.application.document_windows[0]
        data_item = api.library.create_data_item_from_data_and_metadata(
            master_xdata)
        legends = [s.metadata["title"] for s in spectra]
        data_item.title = f"MultiEELS ({', '.join(legends)})"
        window.display_data_item(data_item)

    print("finished")
Esempio n. 24
0
    def create_panel_widget(self, ui, document_controller):
        self.ui = ui
        self.document_controller = document_controller

        def start_clicked():
            if self.__acquisition_running:
                self.multi_acquire_controller.cancel()
            else:
                self.multi_acquire_controller.stem_controller = self.stem_controller
                self.multi_acquire_controller.camera = self.camera_choice_combo_box.current_item

                def run_multi_eels():
                    data_dict = self.multi_acquire_controller.acquire_multi_eels_spectrum(
                    )

                    def create_and_display_data_item():
                        self.create_result_data_item(data_dict)

                    document_controller.queue_task(create_and_display_data_item
                                                   )  # must occur on UI thread

                self.__acquisition_thread = threading.Thread(
                    target=run_multi_eels, daemon=True)
                self.__acquisition_thread.start()

        def start_si_clicked():
            if self.__acquisition_running:
                self.multi_acquire_controller.cancel()
            else:
                self.multi_acquire_controller.stem_controller = self.stem_controller
                self.multi_acquire_controller.camera = self.camera_choice_combo_box.current_item
                self.multi_acquire_controller.superscan = self.superscan
                self.result_data_items = {}
                self.__new_data_ready_event_listener = self.multi_acquire_controller.new_data_ready_event.listen(
                    self.add_to_display_queue)
                self.__data_processed_event.clear()
                self.__display_thread = threading.Thread(
                    target=self.process_display_queue)
                self.__display_thread.start()
                self.__acquisition_thread = threading.Thread(
                    target=self.multi_acquire_controller.
                    acquire_multi_eels_spectrum_image,
                    daemon=True)
                self.__acquisition_thread.start()

        def settings_button_clicked():
            if not self.settings_window_open:
                self.settings_window_open = True
                self.show_config_box()

        def camera_changed(current_item):
            if current_item:
                self.multi_acquire_controller.settings[
                    'camera_hardware_source_id'] = current_item.hardware_source_id

        camera_choice_row = ui.create_row_widget()
        settings_button = ui.create_push_button_widget('Settings...')
        settings_button.on_clicked = settings_button_clicked
        self.camera_choice_combo_box = ui.create_combo_box_widget(
            item_text_getter=lambda camera: getattr(camera, 'display_name'))
        self.camera_choice_combo_box.on_current_item_changed = camera_changed
        camera_choice_row.add_spacing(5)
        camera_choice_row.add(ui.create_label_widget('Camera: '))
        camera_choice_row.add(self.camera_choice_combo_box)
        camera_choice_row.add_stretch()
        camera_choice_row.add_spacing(5)
        camera_choice_row.add(settings_button)
        camera_choice_row.add_spacing(5)
        self.update_camera_list()
        self.update_current_camera()
        self.__settings_changed_event_listener = self.multi_acquire_controller.settings.settings_changed_event.listen(
            self.update_current_camera)

        def component_changed(component, component_types):
            if 'camera_hardware_source' in component_types:
                self.update_camera_list()

        self.__component_registered_event_listener = Registry.listen_component_registered_event(
            component_changed)
        self.__component_unregistered_event_listener = Registry.listen_component_unregistered_event(
            component_changed)

        change_parameters_row = ui.create_row_widget()
        change_parameters_row.add_spacing(5)
        change_parameters_row.add(
            ui.create_label_widget('MultiAcquire parameters:'))
        change_parameters_row.add_stretch()
        change_parameters_row.add_spacing(20)

        parameter_description_row = ui.create_row_widget()
        parameter_description_row.add_spacing(5)
        parameter_description_row.add(ui.create_label_widget('#'))
        parameter_description_row.add_spacing(20)
        parameter_description_row.add(ui.create_label_widget('X Offset (eV)'))
        parameter_description_row.add_spacing(25)
        parameter_description_row.add_stretch()
        parameter_description_row.add(ui.create_label_widget('Exposure (ms)'))
        parameter_description_row.add_spacing(25)
        parameter_description_row.add_stretch()
        parameter_description_row.add(ui.create_label_widget('Frames'))
        parameter_description_row.add_spacing(5)
        parameter_description_row.add_stretch()

        add_remove_parameters_row = ui.create_row_widget()
        add_parameters_button = ui.create_push_button_widget('+')
        add_parameters_button._widget.set_property('width', 40)
        add_parameters_button.on_clicked = self.multi_acquire_controller.add_spectrum
        remove_parameters_button = ui.create_push_button_widget('-')
        remove_parameters_button._widget.set_property('width', 40)
        remove_parameters_button.on_clicked = self.multi_acquire_controller.remove_spectrum

        add_remove_parameters_row.add_spacing(5)
        add_remove_parameters_row.add(add_parameters_button)
        add_remove_parameters_row.add_spacing(5)
        add_remove_parameters_row.add(remove_parameters_button)
        add_remove_parameters_row.add_spacing(20)
        add_remove_parameters_row.add_stretch()

        progress_row = ui.create_row_widget()
        progress_row.add_spacing(180)
        self.progress_bar = ui.create_progress_bar_widget()
        progress_row.add(self.progress_bar)
        progress_row.add_spacing(5)

        time_estimate_row = ui.create_row_widget()
        time_estimate_row.add_spacing(6)
        self.time_estimate_label = ui.create_label_widget()
        time_estimate_row.add(self.time_estimate_label)
        time_estimate_row.add_spacing(5)
        time_estimate_row.add_stretch()
        self.si_time_estimate_label = ui.create_label_widget()
        time_estimate_row.add(self.si_time_estimate_label)
        time_estimate_row.add_spacing(6)
        self.multi_acquire_controller.stem_controller = self.stem_controller
        self.multi_acquire_controller.superscan = self.superscan

        def frame_parameters_changed(profile_index, frame_parameters):
            self.update_time_estimate()

        self.__superscan_frame_parameters_changed_event_listener = self.superscan.frame_parameters_changed_event.listen(
            frame_parameters_changed)
        self.update_camera_list()

        self.start_button = ui.create_push_button_widget('Start Multi-Acquire')
        self.start_button.on_clicked = start_clicked
        self.start_si_button = ui.create_push_button_widget(
            'Start Multi-Acquire spectrum image')
        self.start_si_button.on_clicked = start_si_clicked
        start_row = ui.create_row_widget()
        start_row.add_spacing(5)
        start_row.add(self.start_button)
        start_row.add_spacing(5)
        start_row.add_stretch()
        start_row.add(self.start_si_button)
        start_row.add_spacing(5)

        column = ui.create_column_widget()
        column.add_spacing(5)
        column.add(camera_choice_row)
        column.add_spacing(5)
        column.add(change_parameters_row)
        column.add_spacing(10)
        column.add(parameter_description_row)
        column.add_spacing(10)
        self.parameter_column = ui.create_column_widget()
        for spectrum_parameters in self.multi_acquire_controller.spectrum_parameters:
            line = self.create_parameter_line(spectrum_parameters)
            self.parameter_column.add(line)
        column.add(self.parameter_column)
        column.add_spacing(5)
        column.add(add_remove_parameters_row)
        column.add_spacing(5)
        column.add(progress_row)
        column.add_spacing(10)
        column.add(time_estimate_row)
        column.add_spacing(5)
        column.add(start_row)
        column.add_spacing(5)
        column.add_stretch()
        return column
Esempio n. 25
0
def run():
    scan_device = Device()
    component_types = {"scan_device"}  # the set of component types that this component represents
    Registry.register_component(scan_device, component_types)
Esempio n. 26
0
 def update_camera_list(self):
     cameras = list(
         Registry.get_components_by_type('camera_hardware_source'))
     self.camera_choice_combo_box.items = cameras
     self.update_current_camera()
Esempio n. 27
0
    def execute(self, src, map_regions):
        try:
            if hasattr(self.computation._computation,
                       'last_src_uuid') and hasattr(
                           self.computation._computation, 'last_map_regions'):
                map_regions_ = [
                    region.persistent_dict for region in map_regions
                ]
                if str(
                        src.uuid
                ) == self.computation._computation.last_src_uuid and map_regions_ == self.computation._computation.last_map_regions:
                    return
            metadata = copy.deepcopy(src.xdata.metadata)
            libertem_metadata = metadata.get('libertem-io')
            if libertem_metadata is None:
                return
            executor = Registry.get_component('libertem_executor')
            if executor is None:
                logging.error(
                    'No libertem executor could be retrieved from the Registry.'
                )
                return
            file_parameters = libertem_metadata['file_parameters']
            file_type = file_parameters.pop('type')
            shape = src.xdata.data_shape
            if map_regions:
                mask_data = np.zeros(shape, dtype=np.bool)
                for region in map_regions:
                    np.logical_or(mask_data,
                                  region.get_mask(shape),
                                  out=mask_data)
            else:
                mask_data = np.ones(shape, dtype=np.bool)

            ds = dataset.load(file_type, executor.ensure_sync(),
                              **file_parameters)
            udf = ApplyMasksUDF(mask_factories=[lambda: mask_data])
            dc = self.__api.application.document_controllers[
                0]._document_controller
            if hasattr(self.computation._computation, 'cancel_id'):
                print(
                    f'Cancelling task: {self.computation._computation.cancel_id}'
                )
                to_cancel = self.computation._computation.cancel_id
                self.__api.queue_task(lambda: self.__event_loop.create_task(
                    executor.cancel(to_cancel)))
                #self.computation._computation.cancel_id = None
            self.computation._computation.cancel_id = str(time.time())
            print(f'Creating task: {self.computation._computation.cancel_id}')
            dc.add_task(
                'libertem-map4d', lambda: self.__event_loop.create_task(
                    self.run_udf(udf,
                                 self.computation._computation.cancel_id,
                                 executor,
                                 dataset=ds)))
            self.computation._computation.last_src_uuid = str(src.uuid)
            self.computation._computation.last_map_regions = copy.deepcopy(
                [region.persistent_dict for region in map_regions])

        except Exception as e:
            print(str(e))
            import traceback
            traceback.print_exc()
Esempio n. 28
0
def subtract_background_from_signal(api, window):
    window._document_controller.event_loop.create_task(
        use_interval_as_background(api, window))


Symbolic.register_computation_type("eels.background_subtraction3",
                                   EELSBackgroundSubtraction)
Symbolic.register_computation_type("eels.mapping3", EELSMapping)

BackgroundModel = Schema.entity("background_model", None, None, {})


def component_registered(component, component_types):
    if "background-model" in component_types:
        # when a background model is registered, create an empty (for now) entity type, and register it with the data
        # structure so that an entity for use with the UI and computations can be created when the data structure loads.
        background_model_entity = Schema.entity(component.background_model_id,
                                                BackgroundModel, None, {})
        DataStructure.DataStructure.register_entity(
            background_model_entity,
            entity_name=component.title,
            entity_package_name=component.package_title)


_component_registered_listener = Registry.listen_component_registered_event(
    component_registered)

# handle any components that have already been registered.
for component in Registry.get_components_by_type("background-model"):
    component_registered(component, {"background-model"})
Esempio n. 29
0
    def _setup_hardware_source(
        self,
        initialize: bool = True,
        is_eels: bool = False
    ) -> (DocumentController.DocumentController, DocumentModel.DocumentModel,
          HardwareSource.HardwareSource,
          CameraControlPanel.CameraControlStateController):

        document_model = DocumentModel.DocumentModel()
        document_controller = DocumentController.DocumentController(
            self.app.ui, document_model, workspace_id="library")

        # this is simulator specific. replace this code but be sure to set up self.exposure and blanked and positioned
        # initial settings.
        self.exposure = 0.04

        instrument = InstrumentDevice.Instrument("usim_stem_controller")
        Registry.register_component(instrument, {"stem_controller"})

        camera_id = "usim_ronchigram_camera" if not is_eels else "usim_eels_camera"
        camera_type = "ronchigram" if not is_eels else "eels"
        camera_name = "uSim Camera"
        camera_settings = CameraDevice.CameraSettings(camera_id)
        camera_device = CameraDevice.Camera(camera_id, camera_type,
                                            camera_name, instrument)
        camera_hardware_source = camera_base.CameraHardwareSource(
            "usim_stem_controller", camera_device, camera_settings, None, None)
        if is_eels:
            camera_hardware_source.features["is_eels_camera"] = True
            camera_hardware_source.add_channel_processor(
                0, HardwareSource.SumProcessor(((0.25, 0.0), (0.5, 1.0))))
        camera_hardware_source.set_frame_parameters(
            0,
            camera_base.CameraFrameParameters({
                "exposure_ms": self.exposure * 1000,
                "binning": 2
            }))
        camera_hardware_source.set_frame_parameters(
            1,
            camera_base.CameraFrameParameters({
                "exposure_ms": self.exposure * 1000,
                "binning": 2
            }))
        camera_hardware_source.set_frame_parameters(
            2,
            camera_base.CameraFrameParameters({
                "exposure_ms":
                self.exposure * 1000 * 2,
                "binning":
                1
            }))
        camera_hardware_source.set_selected_profile_index(0)

        HardwareSource.HardwareSourceManager().register_hardware_source(
            camera_hardware_source)

        state_controller = CameraControlPanel.CameraControlStateController(
            camera_hardware_source, document_controller.queue_task,
            document_controller.document_model)
        if initialize:
            state_controller.initialize_state()

        return document_controller, document_model, camera_hardware_source, state_controller
Esempio n. 30
0
 def execute(self, eels_spectrum_data_item, background_model,
             fit_interval_graphics, **kwargs) -> None:
     try:
         spectrum_xdata = eels_spectrum_data_item.xdata
         assert spectrum_xdata.is_datum_1d
         assert spectrum_xdata.datum_dimensional_calibrations[
             0].units == "eV"
         eels_spectrum_xdata = spectrum_xdata
         # fit_interval_graphics.interval returns normalized coordinates. create calibrated intervals.
         fit_intervals = list()
         for fit_interval_graphic in fit_interval_graphics:
             fit_interval = Calibration.CalibratedInterval(
                 Calibration.Coordinate(
                     Calibration.CoordinateType.NORMALIZED,
                     fit_interval_graphic.interval[0]),
                 Calibration.Coordinate(
                     Calibration.CoordinateType.NORMALIZED,
                     fit_interval_graphic.interval[1]))
             fit_intervals.append(fit_interval)
         fit_minimum = min(
             [fit_interval.start.value for fit_interval in fit_intervals])
         signal_interval = Calibration.CalibratedInterval(
             Calibration.Coordinate(Calibration.CoordinateType.NORMALIZED,
                                    fit_minimum),
             Calibration.Coordinate(Calibration.CoordinateType.NORMALIZED,
                                    1.0))
         reference_frame = Calibration.ReferenceFrameAxis(
             eels_spectrum_xdata.datum_dimensional_calibrations[0],
             eels_spectrum_xdata.datum_dimension_shape[0])
         signal_xdata = Core.get_calibrated_interval_slice(
             eels_spectrum_xdata, reference_frame, signal_interval)
         background_xdata = None
         subtracted_xdata = None
         if background_model._data_structure.entity:
             entity_id = background_model._data_structure.entity.entity_type.entity_id
             for component in Registry.get_components_by_type(
                     "background-model"):
                 if entity_id == component.background_model_id:
                     fit_result = component.fit_background(
                         spectrum_xdata=spectrum_xdata,
                         fit_intervals=fit_intervals,
                         background_interval=signal_interval)
                     background_xdata = fit_result["background_model"]
                     # use 'or' to avoid doing subtraction if subtracted_spectrum already present
                     subtracted_xdata = fit_result.get(
                         "subtracted_spectrum",
                         None) or Core.calibrated_subtract_spectrum(
                             spectrum_xdata, background_xdata)
         if background_xdata is None:
             background_xdata = DataAndMetadata.new_data_and_metadata(
                 numpy.zeros_like(signal_xdata.data),
                 intensity_calibration=signal_xdata.intensity_calibration,
                 dimensional_calibrations=signal_xdata.
                 dimensional_calibrations)
         if subtracted_xdata is None:
             subtracted_xdata = DataAndMetadata.new_data_and_metadata(
                 signal_xdata.data,
                 intensity_calibration=signal_xdata.intensity_calibration,
                 dimensional_calibrations=signal_xdata.
                 dimensional_calibrations)
         self.__background_xdata = background_xdata
         self.__subtracted_xdata = subtracted_xdata
     except Exception as e:
         import traceback
         print(traceback.format_exc())
         print(e)
         raise