Exemplo n.º 1
0
        def add_line_profile(
                data_item: DataItem.DataItem,
                document_controller: DocumentController.DocumentController,
                display_panel_id: str,
                midpoint: float = 0.5,
                integration_width: float = 0.25) -> None:
            logging.debug("midpoint: {:.4f}".format(midpoint))
            logging.debug("width: {:.4f}".format(integration_width))

            # next, line profile through center of crop
            # please don't copy this bad example code!
            crop_region = Graphics.RectangleGraphic()
            crop_region.center = Geometry.FloatPoint(midpoint, 0.5)
            crop_region.size = Geometry.FloatSize(integration_width, 1)
            crop_region.is_bounds_constrained = True
            display_item = document_controller.document_model.get_display_item_for_data_item(
                data_item)
            assert display_item
            display_item.add_graphic(crop_region)
            display_data_item = display_item.data_item
            assert display_data_item
            eels_data_item = document_controller.document_model.get_projection_new(
                display_item, display_data_item, crop_region)
            if eels_data_item:
                eels_data_item.title = _("EELS Summed")
                eels_display_item = document_controller.document_model.get_display_item_for_data_item(
                    eels_data_item)
                assert eels_display_item
                document_controller.show_display_item(eels_display_item)
            else:
                eels_display_item = None

            workspace_controller = document_controller.workspace_controller
            if workspace_controller and eels_display_item:
                workspace_controller.display_display_item_in_display_panel(
                    eels_display_item, display_panel_id)
Exemplo n.º 2
0
    async def grab(self,
                   document_controller: DocumentController.DocumentController,
                   hardware_source: scan_base.ScanHardwareSource,
                   do_acquire: bool) -> None:
        # this is an async method meaning that it will execute until it calls await, at which time
        # it will let other parts of the software run until the awaited function finishes. in this
        # case, waiting for acquired data and grabbing the last frames are run in a thread.

        assert document_controller
        assert hardware_source

        event_loop = document_controller.event_loop

        self.cancel_event.clear()

        self.state.value = "running"
        self.progress_model.value = 0
        frame_count = self.frame_count_model.value or 0
        was_playing = hardware_source.is_playing

        success_ref = [True]

        xdata_group_list: typing.List[typing.Sequence[typing.Optional[
            DataAndMetadata.DataAndMetadata]]] = list()

        def exec_acquire() -> None:
            # this will execute in a thread; the enclosing async routine will continue when it finishes
            try:
                start_time = time.time()
                max_wait_time = max(
                    hardware_source.get_current_frame_time() * 1.5, 3)
                while not hardware_source.is_playing:
                    if time.time() - start_time > max_wait_time:
                        success_ref[0] = False
                        return
                    time.sleep(0.01)
                hardware_source.get_next_xdatas_to_start(
                    max_wait_time * 2)  # wait for frame + next frame
                for i in range(frame_count):
                    self.progress_model.value = int(100 * i / frame_count)
                    if self.cancel_event.is_set():
                        success_ref[0] = False
                        break
                    hardware_source.get_next_xdatas_to_finish(max_wait_time *
                                                              2)
            except Exception as e:
                import traceback
                traceback.print_exc()
                success_ref[0] = False

        if do_acquire:
            print("AR: start playing")
            hardware_source.start_playing()
            print("AR: wait for acquire")
            await event_loop.run_in_executor(None, exec_acquire)
            print("AR: acquire finished")

        def exec_grab() -> None:
            # this will execute in a thread; the enclosing async routine will continue when it finishes
            try:
                start_time = time.time()
                max_wait_time = max(
                    hardware_source.get_current_frame_time() * 1.5, 3)
                while hardware_source.is_playing:
                    if time.time() - start_time > max_wait_time:
                        success_ref[0] = False
                        return
                    time.sleep(0.01)
                data_element_groups = hardware_source.get_buffer_data(
                    -frame_count, frame_count)
                for data_element_group in data_element_groups:
                    if self.cancel_event.is_set():
                        success_ref[0] = False
                        break
                    xdata_group = list()
                    for data_element in data_element_group:
                        xdata = ImportExportManager.convert_data_element_to_data_and_metadata(
                            data_element)
                        xdata_group.append(xdata)
                    xdata_group_list.append(xdata_group)
                self.progress_model.value = 100
            except Exception as e:
                import traceback
                traceback.print_exc()
                success_ref[0] = False

        if success_ref[0]:
            print("AR: stop playing")
            hardware_source.stop_playing()
            print("AR: grabbing data")
            await event_loop.run_in_executor(None, exec_grab)
            print("AR: grab finished")

        xdata_group = None

        if success_ref[0]:
            if len(xdata_group_list) > 1:
                print("AR: making xdata")
                valid_count = 0
                examplar_xdata_group = xdata_group_list[-1]
                shapes = [
                    xdata._data_ex.shape for xdata in examplar_xdata_group
                    if xdata
                ]
                dtypes = [
                    xdata._data_ex.dtype for xdata in examplar_xdata_group
                    if xdata
                ]
                for xdata_group in reversed(xdata_group_list):
                    shapes_i = [
                        xdata._data_ex.shape for xdata in xdata_group if xdata
                    ]
                    dtypes_i = [
                        xdata._data_ex.dtype for xdata in xdata_group if xdata
                    ]
                    if shapes_i == shapes and dtypes_i == dtypes:
                        valid_count += 1
                xdata_group = list()
                for i, xdata in enumerate(examplar_xdata_group):
                    if xdata:
                        intensity_calibration = xdata.intensity_calibration
                        dimensional_calibrations = [
                            Calibration.Calibration()
                        ] + list(xdata.dimensional_calibrations)
                        data_descriptor = DataAndMetadata.DataDescriptor(
                            True,
                            xdata.data_descriptor.collection_dimension_count,
                            xdata.data_descriptor.datum_dimension_count)
                        # TODO: ugly typing.
                        data: numpy.typing.NDArray[typing.Any] = numpy.vstack(
                            list(
                                typing.cast(DataAndMetadata.DataAndMetadata,
                                            xdata_group[i])._data_ex
                                for xdata_group in
                                xdata_group_list[-valid_count:])).reshape(
                                    valid_count, *shapes[i])
                        xdata = DataAndMetadata.new_data_and_metadata(
                            data,
                            intensity_calibration=intensity_calibration,
                            dimensional_calibrations=dimensional_calibrations,
                            data_descriptor=data_descriptor,
                            metadata=xdata.metadata)
                        xdata_group.append(xdata)
            elif len(xdata_group_list) == 1:
                xdata_group = xdata_group_list[0]

        if xdata_group:
            print("AR: making data item")
            for xdata in xdata_group:
                if xdata:
                    data_item = DataItem.DataItem(large_format=True)
                    data_item.ensure_data_source()
                    data_item.set_xdata(xdata)
                    channel_name = xdata.metadata.get(
                        "hardware_source", dict()).get("channel_name")
                    channel_ext = (" (" + channel_name +
                                   ")") if channel_name else ""
                    data_item.title = _(
                        "Recording of "
                    ) + hardware_source.display_name + channel_ext
                    document_controller.document_model.append_data_item(
                        data_item)
                    display_item = document_controller.document_model.get_display_item_for_data_item(
                        data_item)
                    if display_item:
                        document_controller.show_display_item(display_item)

        if was_playing:
            print("AR: restarting")
            hardware_source.start_playing()
        self.state.value = "idle"
        self.progress_model.value = 0
        print("AR: done")