Esempio n. 1
0
    def _on_fine_align(self, event):
        """
        Called when the "Fine alignment" button is clicked
        """
        self._pause()
        main_data = self._main_data_model
        main_data.is_acquiring.value = True

        logging.debug("Starting overlay procedure")
        f = align.FindOverlay(self.OVRL_REPETITION,
                              main_data.fineAlignDwellTime.value,
                              self.OVRL_MAX_DIFF,
                              main_data.ebeam,
                              main_data.ccd,
                              main_data.sed,
                              skew=True)
        logging.debug("Overlay procedure is running...")
        self._acq_future = f
        # Transform Fine alignment button into cancel
        self._tab_panel.btn_fine_align.Bind(wx.EVT_BUTTON, self._on_cancel)
        self._tab_panel.btn_fine_align.Label = "Cancel"

        # Set up progress bar
        self._tab_panel.lbl_fine_align.Hide()
        self._tab_panel.gauge_fine_align.Show()
        self._sizer.Layout()
        self._faf_connector = ProgressiveFutureConnector(
            f, self._tab_panel.gauge_fine_align)

        f.add_done_callback(self._on_fa_done)
Esempio n. 2
0
    def test_find_overlay(self):
        """
        Test FindOverlay
        """
        escan = self.ebeam
        detector = self.sed
        ccd = self.ccd

        f = align.FindOverlay((7, 7), 0.1, 1e-06, escan, ccd, detector)

        t, md = f.result()
Esempio n. 3
0
    def test_find_overlay_failure(self):
        """
        Test FindOverlay failure due to low maximum allowed difference
        """
        escan = self.ebeam
        detector = self.sed
        ccd = self.ccd

        f = align.FindOverlay((9, 9), 1e-06, 1e-08, escan, ccd, detector)

        with self.assertRaises(ValueError):
            f.result()
Esempio n. 4
0
    def acquire(self):
        """
        Runs the find overlay procedure
        returns Future that will have as a result an empty DataArray with
        the correction metadata
        """
        # Just calls the FindOverlay function and return its future
        ovrl_future = align.FindOverlay(self.repetition.value,
                                        self.dwellTime.value, OVRL_MAX_DIFF,
                                        self._emitter, self._ccd,
                                        self._detector)

        return _FutureOverlayWrapper(ovrl_future)
Esempio n. 5
0
    def test_find_overlay_failure(self):
        """
        Test FindOverlay failure due to low maximum allowed difference
        """
        f = align.FindOverlay((6, 6),
                              1e-6,
                              1e-08,
                              self.ebeam,
                              self.ccd,
                              self.sed,
                              skew=True)

        with self.assertRaises(ValueError):
            f.result()
Esempio n. 6
0
    def test_find_overlay(self):
        """
        Test FindOverlay
        """
        f = align.FindOverlay((4, 4),
                              0.1,
                              10e-06,
                              self.ebeam,
                              self.ccd,
                              self.sed,
                              skew=True)

        t, (opt_md, sem_md) = f.result()
        self.assertEqual(len(t), 5)
        self.assertIn(model.MD_PIXEL_SIZE_COR, opt_md)
        self.assertIn(model.MD_SHEAR_COR, sem_md)
Esempio n. 7
0
    def test_find_overlay_cancelled(self):
        """
        Test FindOverlay cancellation
        """
        escan = self.ebeam
        detector = self.sed
        ccd = self.ccd

        f = align.FindOverlay((9, 9), 1e-06, 1e-07, escan, ccd, detector)
        time.sleep(0.04)  # Cancel almost after the half grid is scanned

        f.cancel()
        self.assertTrue(f.cancelled())
        self.assertTrue(f.done())
        with self.assertRaises(futures.CancelledError):
            f.result()
Esempio n. 8
0
    def test_find_overlay_cancelled(self):
        """
        Test FindOverlay cancellation
        """
        f = align.FindOverlay((6, 6),
                              10e-06,
                              1e-07,
                              self.ebeam,
                              self.ccd,
                              self.sed,
                              skew=True)
        time.sleep(0.04)  # Cancel almost after the half grid is scanned

        f.cancel()
        self.assertTrue(f.cancelled())
        self.assertTrue(f.done())
        with self.assertRaises(futures.CancelledError):
            f.result()
Esempio n. 9
0
    def test_bad_mag(self):
        self._prepare_hardware(ccd_img="overlay_4_4_test_1.tiff")

        # original mag was 35 (SEM pxs size = 432e-9 m), which was incorrect by x2
        for mag in (30, 40, 70, 1000):
            self.ebeam.magnification.value = mag

            f = align.FindOverlay((4, 4),
                                  0.001,
                                  10e-06,
                                  self.ebeam,
                                  self.ccd,
                                  self.sed,
                                  skew=True)

            t, (opt_md, sem_md) = f.result()
            self.assertEqual(len(t), 5)
            self.assertIn(model.MD_PIXEL_SIZE_COR, opt_md)
            self.assertIn(model.MD_SHEAR_COR, sem_md)
Esempio n. 10
0
    def test_ratio_3_4(self):
        """
        Try also (unsual) 3:4
        """
        ebeam_kwargs = {
            "max_res": [3072, 4096],
            "hfw_nomag": 0.132,
        }
        # SEM mag = 150x  ~ SEM pxs size = 288e-9 m
        self._prepare_hardware(ebeam_kwargs, 150, "overlay_4_4_test_2.tiff")

        f = align.FindOverlay((4, 4),
                              0.001,
                              10e-06,
                              self.ebeam,
                              self.ccd,
                              self.sed,
                              skew=True)

        t, (opt_md, sem_md) = f.result()
        self.assertEqual(len(t), 5)
        self.assertIn(model.MD_PIXEL_SIZE_COR, opt_md)
        self.assertIn(model.MD_SHEAR_COR, sem_md)
Esempio n. 11
0
    def test_ratio_4_3(self):
        """
        Test FindOverlay when the SEM image ratio is not 1:1 (but 4:3)
        """
        ebeam_kwargs = {
            "max_res": [4096, 3072],
            "hfw_nomag": 0.177,
        }
        # SEM mag = 150x  ~ SEM pxs size = 288e-9 m
        self._prepare_hardware(ebeam_kwargs, 150, "overlay_4_4_test_2.tiff")

        f = align.FindOverlay((4, 4),
                              0.001,
                              10e-06,
                              self.ebeam,
                              self.ccd,
                              self.sed,
                              skew=True)

        t, (opt_md, sem_md) = f.result()
        self.assertEqual(len(t), 5)
        self.assertIn(model.MD_PIXEL_SIZE_COR, opt_md)
        self.assertIn(model.MD_SHEAR_COR, sem_md)
Esempio n. 12
0
def _DoDelphiCalibration(future, main_data, overview_pressure, vacuum_pressure,
                         vented_pressure):
    """
    It performs all the calibration steps for Delphi including the lens alignment,
    the conversion metadata update and the fine alignment.
    future (model.ProgressiveFuture): Progressive future provided by the wrapper
    main_data (odemis.gui.model.MainGUIData)
    overview_pressure (float): NavCam pressure value
    vacuum_pressure (float): Pressure under vacuum
    vented_pressure (float): Pressure when vented
    returns (tuple of floats): Hole top
            (tuple of floats): Hole bottom
            (tuple of floats): Stage translation
            (tuple of floats): Stage scale
            (tuple of floats): Stage rotation
            (tuple of floats): Image scale
            (tuple of floats): Image rotation
            (tuple of floats): Resolution-related shift slope
            (tuple of floats): Resolution-related shift intercept
            (tuple of floats): HFW-related shift slope
            (tuple of floats): Spot shift percentage
    raises:
        CancelledError() if cancelled
    """
    logging.debug("Delphi calibration...")

    try:
        if future._delphi_calib_state == CANCELLED:
            raise CancelledError()

        try:
            # Move to the overview position first
            f = main_data.chamber.moveAbs({"pressure": overview_pressure})
            f.result()

            # Clear all the previous calibration
            logging.debug("Clear all the previous calibration...")
            main_data.stage.updateMetadata({
                model.MD_POS_COR: (0, 0),
                model.MD_PIXEL_SIZE_COR: (1, 1),
                model.MD_ROTATION_COR: 0
            })

            # We need access to the separate sem and optical stages, which form
            # the "stage". They are not found in the model, but we can find them
            # as children of stage (on the DELPHI), and distinguish them by
            # their role.
            sem_stage = None
            opt_stage = None
            logging.debug("Find SEM and optical stages...")
            for c in main_data.stage.children.value:
                if c.role == "sem-stage":
                    sem_stage = c
                elif c.role == "align":
                    opt_stage = c

            if not sem_stage or not opt_stage:
                raise KeyError("Failed to find SEM and optical stages")

            # Reference the (optical) stage
            logging.debug("Reference the (optical) stage...")
            f = opt_stage.reference({"x", "y"})
            f.result()

            logging.debug("Reference the focus...")
            f = main_data.focus.reference({"z"})
            f.result()

            # SEM stage to (0,0)
            logging.debug("Move to the center of SEM stage...")
            f = sem_stage.moveAbs({"x": 0, "y": 0})
            f.result()

            # Calculate offset approximation
            try:
                logging.debug("Starting lens alignment...")
                f = aligndelphi.LensAlignment(main_data.overview_ccd,
                                              sem_stage)
                position = f.result()
                logging.debug("SEM position after lens alignment: %s",
                              position)
            except Exception:
                raise IOError("Lens alignment failed.")

            # Update progress of the future
            future.set_end_time(time.time() + 14 * 60)

            # Just to check if move makes sense
            f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
            f.result()

            # Move to SEM
            f = main_data.chamber.moveAbs({"pressure": vacuum_pressure})
            f.result()

            # Lens to a good optical focus position
            logging.debug("Move focus to a good initial level...")
            f = main_data.focus.moveAbs({"z": DELPHI_OPT_GOOD_FOCUS})
            f.result()

            # Update progress of the future
            logging.debug("Try to update the remaining time...")
            future.set_end_time(time.time() + 12.5 * 60)

            # Compute stage calibration values
            try:
                logging.debug("Starting conversion update...")
                f = aligndelphi.UpdateConversion(main_data.ccd,
                                                 main_data.bsd,
                                                 main_data.ebeam,
                                                 sem_stage,
                                                 opt_stage,
                                                 main_data.ebeam_focus,
                                                 main_data.focus,
                                                 main_data.stage,
                                                 first_insertion=True,
                                                 sem_position=position)
                htop, hbot, hole_focus, strans, srot, sscale, resa, resb, hfwa, spotshift = f.result(
                )
            except Exception:
                raise IOError("Conversion update failed.")
            # Update progress of the future
            logging.debug("Try to update the remaining time...")
            future.set_end_time(time.time() + 60)

            # Run the optical fine alignment
            # TODO: reuse the exposure time
            f = align.FindOverlay(
                (4, 4),
                0.5,  # s, dwell time
                10e-06,  # m, maximum difference allowed
                main_data.ebeam,
                main_data.ccd,
                main_data.bsd)
            trans_val, cor_md = f.result()
            iscale = cor_md[model.MD_PIXEL_SIZE_COR]
            irot = cor_md[model.MD_ROTATION_COR]
            return htop, hbot, strans, sscale, srot, iscale, irot, resa, resb, hfwa, spotshift
        except Exception:
            raise IOError("Delphi calibration failed.")
    finally:
        with future._delphi_calib_lock:
            if future._delphi_calib_state == CANCELLED:
                raise CancelledError()
            future._delphi_calib_state = FINISHED
Esempio n. 13
0
def man_calib(logpath):
    escan = None
    detector = None
    ccd = None
    # find components by their role
    for c in model.getComponents():
        if c.role == "e-beam":
            escan = c
        elif c.role == "bs-detector":
            detector = c
        elif c.role == "ccd":
            ccd = c
        elif c.role == "sem-stage":
            sem_stage = c
        elif c.role == "align":
            opt_stage = c
        elif c.role == "ebeam-focus":
            ebeam_focus = c
        elif c.role == "overview-focus":
            navcam_focus = c
        elif c.role == "focus":
            focus = c
        elif c.role == "overview-ccd":
            overview_ccd = c
        elif c.role == "chamber":
            chamber = c
    if not all([escan, detector, ccd]):
        logging.error("Failed to find all the components")
        raise KeyError("Not all components found")

    hw_settings = aligndelphi.list_hw_settings(escan, ccd)

    try:
        # Get pressure values
        pressures = chamber.axes["pressure"].choices
        vacuum_pressure = min(pressures.keys())
        vented_pressure = max(pressures.keys())
        if overview_ccd:
            for p, pn in pressures.items():
                if pn == "overview":
                    overview_pressure = p
                    break
            else:
                raise IOError("Failed to find the overview pressure in %s" %
                              (pressures, ))

        calibconf = get_calib_conf()
        shid, sht = chamber.sampleHolder.value
        calib_values = calibconf.get_sh_calib(shid)
        if calib_values is None:
            first_hole = second_hole = offset = resa = resb = hfwa = scaleshift = (
                0, 0)
            scaling = iscale = iscale_xy = (1, 1)
            rotation = irot = ishear = 0
            hole_focus = aligndelphi.SEM_KNOWN_FOCUS
            opt_focus = aligndelphi.OPTICAL_KNOWN_FOCUS
            print "\033[1;31mCalibration values missing! All the steps will be performed anyway...\033[1;m"
            force_calib = True
        else:
            first_hole, second_hole, hole_focus, opt_focus, offset, scaling, rotation, iscale, irot, iscale_xy, ishear, resa, resb, hfwa, scaleshift = calib_values
            force_calib = False
        print "\033[1;36m"
        print "**Delphi Manual Calibration steps**"
        print "1.Sample holder hole detection"
        print "    Current values: 1st hole: " + str(first_hole)
        print "                    2st hole: " + str(second_hole)
        print "                    hole focus: " + str(hole_focus)
        print "2.Twin stage calibration"
        print "    Current values: offset: " + str(offset)
        print "                    scaling: " + str(scaling)
        print "                    rotation: " + str(rotation)
        print "                    optical focus: " + str(opt_focus)
        print "3.Fine alignment"
        print "    Current values: scale: " + str(iscale)
        print "                    rotation: " + str(irot)
        print "                    scale-xy: " + str(iscale_xy)
        print "                    shear: " + str(ishear)
        print "4.SEM image calibration"
        print "    Current values: resolution-a: " + str(resa)
        print "                    resolution-b: " + str(resb)
        print "                    hfw-a: " + str(hfwa)
        print "                    spot shift: " + str(scaleshift)
        print '\033[1;m'
        print "\033[1;33mNote that you should not perform any stage move during the process. \nInstead, you may zoom in/out while focusing.\033[1;m"
        print "\033[1;30mNow initializing, please wait...\033[1;m"

        # Move to the overview position first
        f = chamber.moveAbs({"pressure": overview_pressure})
        f.result()

        # Reference the (optical) stage
        f = opt_stage.reference({"x", "y"})
        f.result()

        f = focus.reference({"z"})
        f.result()

        # SEM stage to (0,0)
        f = sem_stage.moveAbs({"x": 0, "y": 0})
        f.result()

        # Calculate offset approximation
        try:
            f = aligndelphi.LensAlignment(overview_ccd, sem_stage, logpath)
            position = f.result()
        except IOError as ex:
            if not force_calib:
                position = (offset[0] * scaling[0], offset[1] * scaling[1])
            else:
                position = (0, 0)
            logging.warning(
                "Failed to locate the optical lens (%s), will used previous value %s",
                ex, position)

        # Just to check if move makes sense
        f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
        f.result()

        # Move to SEM
        f = chamber.moveAbs({"pressure": vacuum_pressure})
        f.result()

        # Set basic e-beam settings
        escan.spotSize.value = 2.7
        escan.accelVoltage.value = 5300  # V

        # Detect the holes/markers of the sample holder
        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                msg = "\033[1;35mDo you want to execute the sample holder hole detection? [Y/n]\033[1;m"
                ans = raw_input(msg)
            if ans in YES_CHARS:
                # Move Phenom sample stage next to expected hole position
                sem_stage.moveAbsSync(aligndelphi.SHIFT_DETECTION)
                ebeam_focus.moveAbsSync({"z": hole_focus})
                # Set the FoV to almost 2mm
                escan.horizontalFoV.value = escan.horizontalFoV.range[1]
                msg = "\033[1;34mPlease turn on the SEM stream and focus the SEM image. Then turn off the stream and press Enter ...\033[1;m"
                raw_input(msg)
                print "\033[1;30mTrying to detect the holes/markers, please wait...\033[1;m"
                try:
                    hole_detectionf = aligndelphi.HoleDetection(
                        detector,
                        escan,
                        sem_stage,
                        ebeam_focus,
                        manual=True,
                        logpath=logpath)
                    new_first_hole, new_second_hole, new_hole_focus = hole_detectionf.result(
                    )
                    print '\033[1;36m'
                    print "Values computed: 1st hole: " + str(new_first_hole)
                    print "                 2st hole: " + str(new_second_hole)
                    print "                 hole focus: " + str(new_hole_focus)
                    print '\033[1;m'
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        msg = "\033[1;35mDo you want to update the calibration file with these values? [Y/n]\033[1;m"
                        ans = raw_input(msg)
                    if ans in YES_CHARS:
                        first_hole, second_hole, hole_focus = new_first_hole, new_second_hole, new_hole_focus
                        calibconf.set_sh_calib(shid, first_hole, second_hole,
                                               hole_focus, opt_focus, offset,
                                               scaling, rotation, iscale, irot,
                                               iscale_xy, ishear, resa, resb,
                                               hfwa, scaleshift)
                    break
                except IOError:
                    print "\033[1;31mSample holder hole detection failed.\033[1;m"
            else:
                break

        f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
        f.result()

        f = opt_stage.moveAbs({"x": 0, "y": 0})
        f.result()

        if hole_focus is not None:
            good_focus = hole_focus - aligndelphi.GOOD_FOCUS_OFFSET
        else:
            good_focus = aligndelphi.SEM_KNOWN_FOCUS - aligndelphi.GOOD_FOCUS_OFFSET
        f = ebeam_focus.moveAbs({"z": good_focus})
        f.result()

        # Set min fov
        # We want to be as close as possible to the center when we are zoomed in
        escan.horizontalFoV.value = escan.horizontalFoV.range[0]
        pure_offset = None

        # Start with the best optical focus known so far
        f = focus.moveAbs({"z": opt_focus})
        f.result()

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                msg = "\033[1;35mDo you want to execute the twin stage calibration? [Y/n]\033[1;m"
                ans = raw_input(msg)
            if ans in YES_CHARS:
                # Configure CCD and e-beam to write CL spots
                ccd.binning.value = (1, 1)
                ccd.resolution.value = ccd.resolution.range[1]
                ccd.exposureTime.value = 900e-03
                escan.scale.value = (1, 1)
                escan.resolution.value = (1, 1)
                escan.translation.value = (0, 0)
                if not escan.rotation.readonly:
                    escan.rotation.value = 0
                escan.shift.value = (0, 0)
                escan.dwellTime.value = 5e-06
                detector.data.subscribe(_discard_data)
                print "\033[1;34mPlease turn on the Optical stream, set Power to 0 Watt and focus the image so you have a clearly visible spot.\033[1;m"
                print "\033[1;34mUse the up and down arrows or the mouse to move the optical focus and right and left arrows to move the SEM focus. Then turn off the stream and press Enter ...\033[1;m"
                if not force_calib:
                    print "\033[1;33mIf you cannot see the whole source background (bright circle) you may try to move to the already known offset position. \nTo do this press the R key at any moment.\033[1;m"
                    rollback_pos = (offset[0] * scaling[0],
                                    offset[1] * scaling[1])
                else:
                    rollback_pos = None
                ar = ArrowFocus(sem_stage, focus, ebeam_focus,
                                ccd.depthOfField.value,
                                escan.depthOfField.value)
                ar.focusByArrow(rollback_pos)
                detector.data.unsubscribe(_discard_data)
                print "\033[1;30mFine alignment in progress, please wait...\033[1;m"
                try:
                    # TODO: the first point (at 0,0) isn't different from the next 4 points,
                    # excepted it might be a little harder to focus.
                    # => use the same code for all of them
                    align_offsetf = aligndelphi.AlignAndOffset(
                        ccd, detector, escan, sem_stage, opt_stage, focus,
                        logpath)
                    align_offset = align_offsetf.result()
                    new_opt_focus = focus.position.value.get('z')

                    def ask_user_to_focus(n):
                        detector.data.subscribe(_discard_data)
                        msg = (
                            "\033[1;34mAbout to calculate rotation and scaling (%d/4). "
                            "Please turn on the Optical stream, "
                            "set Power to 0 Watt and focus the image using the mouse "
                            "so you have a clearly visible spot. \n"
                            "If you do not see a spot nor the source background, "
                            "move the sem-stage from the command line by steps of 200um "
                            "in x and y until you can see the source background at the center. \n"
                            "Then turn off the stream and press Enter ...\033[1;m"
                            % (n + 1, ))
                        raw_input(msg)  # TODO: use ArrowFocus() too?
                        print "\033[1;30mCalculating rotation and scaling (%d/4), please wait...\033[1;m" % (
                            n + 1, )
                        detector.data.unsubscribe(_discard_data)

                    f = aligndelphi.RotationAndScaling(
                        ccd,
                        detector,
                        escan,
                        sem_stage,
                        opt_stage,
                        focus,
                        align_offset,
                        manual=ask_user_to_focus,
                        logpath=logpath)
                    acc_offset, new_rotation, new_scaling = f.result()

                    # Offset is divided by scaling, since Convert Stage applies scaling
                    # also in the given offset
                    pure_offset = acc_offset
                    new_offset = ((acc_offset[0] / new_scaling[0]),
                                  (acc_offset[1] / new_scaling[1]))

                    print '\033[1;36m'
                    print "Values computed: offset: " + str(new_offset)
                    print "                 scaling: " + str(new_scaling)
                    print "                 rotation: " + str(new_rotation)
                    print "                 optical focus: " + str(
                        new_opt_focus)
                    print '\033[1;m'
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        msg = "\033[1;35mDo you want to update the calibration file with these values? [Y/n]\033[1;m"
                        ans = raw_input(msg)
                    if ans in YES_CHARS:
                        offset, scaling, rotation, opt_focus = new_offset, new_scaling, new_rotation, new_opt_focus
                        calibconf.set_sh_calib(shid, first_hole, second_hole,
                                               hole_focus, opt_focus, offset,
                                               scaling, rotation, iscale, irot,
                                               iscale_xy, ishear, resa, resb,
                                               hfwa, scaleshift)
                    break
                except IOError:
                    print "\033[1;31mTwin stage calibration failed.\033[1;m"
            else:
                break

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                msg = "\033[1;35mDo you want to execute the fine alignment? [Y/n]\033[1;m"
                ans = raw_input(msg)
            if ans in YES_CHARS:
                # Return to the center so fine alignment can be executed just after calibration
                f = opt_stage.moveAbs({"x": 0, "y": 0})
                f.result()
                if pure_offset is not None:
                    f = sem_stage.moveAbs({
                        "x": pure_offset[0],
                        "y": pure_offset[1]
                    })
                    f.result()
                elif offset is not None:
                    f = sem_stage.moveAbs({
                        "x": offset[0] * scaling[0],
                        "y": offset[1] * scaling[1]
                    })
                    f.result()
                else:
                    f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
                    f.result()

                f = focus.moveAbs({"z": opt_focus})
                f.result()
                f = ebeam_focus.moveAbs({"z": good_focus})
                f.result()

                # Run the optical fine alignment
                # TODO: reuse the exposure time
                # Configure e-beam to write CL spots
                escan.horizontalFoV.value = escan.horizontalFoV.range[0]
                escan.scale.value = (1, 1)
                escan.resolution.value = (1, 1)
                escan.translation.value = (0, 0)
                if not escan.rotation.readonly:
                    escan.rotation.value = 0
                escan.shift.value = (0, 0)
                escan.dwellTime.value = 5e-06
                detector.data.subscribe(_discard_data)
                print "\033[1;34mPlease turn on the Optical stream, set Power to 0 Watt and focus the image so you have a clearly visible spot.\033[1;m"
                print "\033[1;34mUse the up and down arrows or the mouse to move the optical focus and right and left arrows to move the SEM focus. Then turn off the stream and press Enter ...\033[1;m"
                ar = ArrowFocus(sem_stage, focus, ebeam_focus,
                                ccd.depthOfField.value,
                                escan.depthOfField.value)
                ar.focusByArrow()
                detector.data.unsubscribe(_discard_data)

                # restore CCD settings (as the GUI/user might have changed them)
                ccd.binning.value = (1, 1)
                ccd.resolution.value = ccd.resolution.range[1]
                ccd.exposureTime.value = 900e-03
                # Center (roughly) the spot on the CCD
                f = spot.CenterSpot(ccd, sem_stage, escan, spot.ROUGH_MOVE,
                                    spot.STAGE_MOVE, detector.data)
                dist, vect = f.result()
                if dist is None:
                    logging.warning(
                        "Failed to find a spot, twin stage calibration might have failed"
                    )

                print "\033[1;30mFine alignment in progress, please wait...\033[1;m"
                try:
                    escan.horizontalFoV.value = 80e-06
                    f = align.FindOverlay(
                        (4, 4),
                        0.5,  # s, dwell time
                        10e-06,  # m, maximum difference allowed
                        escan,
                        ccd,
                        detector,
                        skew=True,
                        bgsub=True)
                    trans_val, cor_md = f.result()
                    trans_md, skew_md = cor_md
                    new_iscale = trans_md[model.MD_PIXEL_SIZE_COR]
                    new_irot = -trans_md[model.MD_ROTATION_COR] % (2 * math.pi)
                    new_ishear = skew_md[model.MD_SHEAR_COR]
                    new_iscale_xy = skew_md[model.MD_PIXEL_SIZE_COR]
                    print '\033[1;36m'
                    print "Values computed: scale: " + str(new_iscale)
                    print "                 rotation: " + str(new_irot)
                    print "                 scale-xy: " + str(new_iscale_xy)
                    print "                 shear: " + str(new_ishear)
                    print '\033[1;m'
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        msg = "\033[1;35mDo you want to update the calibration file with these values? [Y/n]\033[1;m"
                        ans = raw_input(msg)
                    if ans in YES_CHARS:
                        iscale, irot, iscale_xy, ishear = new_iscale, new_irot, new_iscale_xy, new_ishear
                        calibconf.set_sh_calib(shid, first_hole, second_hole,
                                               hole_focus, opt_focus, offset,
                                               scaling, rotation, iscale, irot,
                                               iscale_xy, ishear, resa, resb,
                                               hfwa, scaleshift)
                    break
                except ValueError:
                    print "\033[1;31mFine alignment failed.\033[1;m"
            else:
                break

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                msg = "\033[1;35mDo you want to execute the SEM image calibration? [Y/n]\033[1;m"
                ans = raw_input(msg)
            if ans in YES_CHARS:
                # Resetting shift parameters, to not take them into account during calib
                blank_md = dict.fromkeys(aligndelphi.MD_CALIB_SEM, (0, 0))
                escan.updateMetadata(blank_md)

                # We measure the shift in the area just behind the hole where there
                # are always some features plus the edge of the sample carrier. For
                # that reason we use the focus measured in the hole detection step
                f = sem_stage.moveAbs(aligndelphi.SHIFT_DETECTION)
                f.result()

                f = ebeam_focus.moveAbs({"z": hole_focus})
                f.result()
                try:
                    # Compute spot shift percentage
                    print "\033[1;30mSpot shift measurement in progress, please wait...\033[1;m"
                    f = aligndelphi.ScaleShiftFactor(detector, escan, logpath)
                    new_scaleshift = f.result()

                    # Compute resolution-related values.
                    print "\033[1;30mCalculating resolution shift, please wait...\033[1;m"
                    resolution_shiftf = aligndelphi.ResolutionShiftFactor(
                        detector, escan, logpath)
                    new_resa, new_resb = resolution_shiftf.result()

                    # Compute HFW-related values
                    print "\033[1;30mCalculating HFW shift, please wait...\033[1;m"
                    hfw_shiftf = aligndelphi.HFWShiftFactor(
                        detector, escan, logpath)
                    new_hfwa = hfw_shiftf.result()

                    print '\033[1;36m'
                    print "Values computed: resolution-a: " + str(new_resa)
                    print "                 resolution-b: " + str(new_resb)
                    print "                 hfw-a: " + str(new_hfwa)
                    print "                 spot shift: " + str(new_scaleshift)
                    print '\033[1;m'
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        msg = "\033[1;35mDo you want to update the calibration file with these values? [Y/n]\033[1;m"
                        ans = raw_input(msg)
                    if ans in YES_CHARS:
                        resa, resb, hfwa, scaleshift = new_resa, new_resb, new_hfwa, new_scaleshift
                        calibconf.set_sh_calib(shid, first_hole, second_hole,
                                               hole_focus, opt_focus, offset,
                                               scaling, rotation, iscale, irot,
                                               iscale_xy, ishear, resa, resb,
                                               hfwa, scaleshift)
                    break
                except IOError:
                    print "\033[1;31mSEM image calibration failed.\033[1;m"
            else:
                break

        # Update calibration file
        print "\033[1;30mUpdating calibration file is done\033[1;m"

    finally:
        print "\033[1;30mCalibration ended, now ejecting sample, please wait...\033[1;m"
        # Eject the sample holder
        f = chamber.moveAbs({"pressure": vented_pressure})

        aligndelphi.restore_hw_settings(escan, ccd, hw_settings)

        # Store the final version of the calibration file
        try:
            shutil.copy(calibconf.file_path, logpath)
        except Exception:
            logging.info("Failed to log calibration file", exc_info=True)

        f.result()
Esempio n. 14
0
def man_calib(logpath):
    escan = None
    detector = None
    ccd = None
    # find components by their role
    for c in model.getComponents():
        if c.role == "e-beam":
            escan = c
        elif c.role == "bs-detector":
            detector = c
        elif c.role == "ccd":
            ccd = c
        elif c.role == "sem-stage":
            sem_stage = c
        elif c.role == "align":
            opt_stage = c
        elif c.role == "ebeam-focus":
            ebeam_focus = c
        elif c.role == "overview-focus":
            navcam_focus = c
        elif c.role == "focus":
            focus = c
        elif c.role == "overview-ccd":
            overview_ccd = c
        elif c.role == "chamber":
            chamber = c
    if not all([escan, detector, ccd]):
        logging.error("Failed to find all the components")
        raise KeyError("Not all components found")

    hw_settings = aligndelphi.list_hw_settings(escan, ccd)

    try:
        # Get pressure values
        pressures = chamber.axes["pressure"].choices
        vacuum_pressure = min(pressures.keys())
        vented_pressure = max(pressures.keys())
        if overview_ccd:
            for p, pn in pressures.items():
                if pn == "overview":
                    overview_pressure = p
                    break
            else:
                raise IOError("Failed to find the overview pressure in %s" % (pressures,))

        calibconf = get_calib_conf()
        shid, sht = chamber.sampleHolder.value
        calib_values = calibconf.get_sh_calib(shid)
        if calib_values is None:
            first_hole = second_hole = offset = resa = resb = hfwa = scaleshift = (0, 0)
            scaling = iscale = iscale_xy = (1, 1)
            rotation = irot = ishear = 0
            hole_focus = aligndelphi.SEM_KNOWN_FOCUS
            opt_focus = aligndelphi.OPTICAL_KNOWN_FOCUS
            print_col(ANSI_RED, "Calibration values missing! All the steps will be performed anyway...")
            force_calib = True
        else:
            first_hole, second_hole, hole_focus, opt_focus, offset, scaling, rotation, iscale, irot, iscale_xy, ishear, resa, resb, hfwa, scaleshift = calib_values
            force_calib = False
        print_col(ANSI_CYAN,
                  "**Delphi Manual Calibration steps**\n"
                  "1.Sample holder hole detection\n"
                  "    Current values: 1st hole: " + str(first_hole) + "\n"
                  "                    2st hole: " + str(second_hole) + "\n"
                  "                    hole focus: " + str(hole_focus) + "\n"
                  "2.SEM image calibration\n"
                  "    Current values: resolution-a: " + str(resa) + "\n"
                  "                    resolution-b: " + str(resb) + "\n"
                  "                    hfw-a: " + str(hfwa) + "\n"
                  "                    spot shift: " + str(scaleshift) + "\n"
                  "3.Twin stage calibration\n"
                  "    Current values: offset: " + str(offset) + "\n"
                  "                    scaling: " + str(scaling) + "\n"
                  "                    rotation: " + str(rotation) + "\n"
                  "                    optical focus: " + str(opt_focus) + "\n"
                  "4.Fine alignment\n"
                  "    Current values: scale: " + str(iscale) + "\n"
                  "                    rotation: " + str(irot) + "\n"
                  "                    scale-xy: " + str(iscale_xy) + "\n"
                  "                    shear: " + str(ishear))
        print_col(ANSI_YELLOW,
                  "Note that you should not perform any stage move during the process.\n"
                  "Instead, you may zoom in/out while focusing.")
        print_col(ANSI_BLACK, "Now initializing, please wait...")

        # Move to the overview position first
        f = chamber.moveAbs({"pressure": overview_pressure})
        f.result()

        # Reference the (optical) stage
        f = opt_stage.reference({"x", "y"})
        f.result()

        f = focus.reference({"z"})
        f.result()

        # SEM stage to (0,0)
        f = sem_stage.moveAbs({"x": 0, "y": 0})
        f.result()

        # Calculate offset approximation
        try:
            f = aligndelphi.LensAlignment(overview_ccd, sem_stage, logpath)
            position = f.result()
        except IOError as ex:
            if not force_calib:
                position = (offset[0] * scaling[0], offset[1] * scaling[1])
            else:
                position = (0, 0)
            logging.warning("Failed to locate the optical lens (%s), will used previous value %s",
                            ex, position)

        # Just to check if move makes sense
        f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
        f.result()

        # Move to SEM
        f = chamber.moveAbs({"pressure": vacuum_pressure})
        f.result()

        # Set basic e-beam settings
        escan.spotSize.value = 2.7
        escan.accelVoltage.value = 5300  # V
        # Without automatic blanker, the background subtraction doesn't work
        if (model.hasVA(escan, "blanker") and  # For simulator
            None in escan.blanker.choices and
            escan.blanker.value is not None):
            logging.warning("Blanker set back to automatic")
            escan.blanker.value = None

        # Detect the holes/markers of the sample holder
        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                ans = input_col(ANSI_MAGENTA,
                                "Do you want to execute the sample holder hole detection? [Y/n]")
            if ans in YES_CHARS:
                # Move Phenom sample stage next to expected hole position
                sem_stage.moveAbsSync(aligndelphi.SHIFT_DETECTION)
                ebeam_focus.moveAbsSync({"z": hole_focus})
                # Set the FoV to almost 2mm
                escan.horizontalFoV.value = escan.horizontalFoV.range[1]
                input_col(ANSI_BLUE,
                          "Please turn on the SEM stream and focus the SEM image. Then turn off the stream and press Enter...")
                print_col(ANSI_BLACK,"Trying to detect the holes/markers, please wait...")
                try:
                    hole_detectionf = aligndelphi.HoleDetection(detector, escan, sem_stage,
                                                                ebeam_focus, manual=True, logpath=logpath)
                    new_first_hole, new_second_hole, new_hole_focus = hole_detectionf.result()
                    print_col(ANSI_CYAN,
                              "Values computed: 1st hole: " + str(new_first_hole) + "\n"
                              "                 2st hole: " + str(new_second_hole) + "\n"
                              "                 hole focus: " + str(new_hole_focus))
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        ans = input_col(ANSI_MAGENTA,
                                        "Do you want to update the calibration file with these values? [Y/n]")
                    if ans in YES_CHARS:
                        first_hole, second_hole, hole_focus = new_first_hole, new_second_hole, new_hole_focus
                        calibconf.set_sh_calib(shid, first_hole, second_hole, hole_focus, opt_focus, offset,
                               scaling, rotation, iscale, irot, iscale_xy, ishear,
                               resa, resb, hfwa, scaleshift)
                        print_col(ANSI_BLACK, "Calibration file is updated.")
                    break
                except IOError:
                    print_col(ANSI_RED, "Sample holder hole detection failed.")
            else:
                break

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                ans = input_col(ANSI_MAGENTA,
                                "Do you want to execute the SEM image calibration? [Y/n]")
            if ans in YES_CHARS:
                # Resetting shift parameters, to not take them into account during calib
                blank_md = dict.fromkeys(aligndelphi.MD_CALIB_SEM, (0, 0))
                escan.updateMetadata(blank_md)

                # We measure the shift in the area just behind the hole where there
                # are always some features plus the edge of the sample carrier. For
                # that reason we use the focus measured in the hole detection step
                sem_stage.moveAbsSync(aligndelphi.SHIFT_DETECTION)

                ebeam_focus.moveAbsSync({"z": hole_focus})
                try:
                    # Compute spot shift percentage
                    print_col(ANSI_BLACK, "Spot shift measurement in progress, please wait...")
                    f = aligndelphi.ScaleShiftFactor(detector, escan, logpath)
                    new_scaleshift = f.result()

                    # Compute resolution-related values.
                    print_col(ANSI_BLACK, "Calculating resolution shift, please wait...")
                    resolution_shiftf = aligndelphi.ResolutionShiftFactor(detector, escan, logpath)
                    new_resa, new_resb = resolution_shiftf.result()

                    # Compute HFW-related values
                    print_col(ANSI_BLACK, "Calculating HFW shift, please wait...")
                    hfw_shiftf = aligndelphi.HFWShiftFactor(detector, escan, logpath)
                    new_hfwa = hfw_shiftf.result()

                    print_col(ANSI_CYAN,
                              "Values computed: resolution-a: " + str(new_resa) + "\n"
                              "                 resolution-b: " + str(new_resb) + "\n"
                              "                 hfw-a: " + str(new_hfwa) + "\n"
                              "                 spot shift: " + str(new_scaleshift))
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        ans = input_col(ANSI_MAGENTA,
                                        "Do you want to update the calibration file with these values? [Y/n]")
                    if ans in YES_CHARS:
                        resa, resb, hfwa, scaleshift = new_resa, new_resb, new_hfwa, new_scaleshift
                        calibconf.set_sh_calib(shid, first_hole, second_hole, hole_focus, opt_focus, offset,
                               scaling, rotation, iscale, irot, iscale_xy, ishear,
                               resa, resb, hfwa, scaleshift)
                        print_col(ANSI_BLACK, "Calibration file is updated.")
                    break
                except IOError:
                    print_col(ANSI_RED, "SEM image calibration failed.")
            else:
                break

        # Update the SEM metadata to have the spots already at corrected place
        escan.updateMetadata({
            model.MD_RESOLUTION_SLOPE: resa,
            model.MD_RESOLUTION_INTERCEPT: resb,
            model.MD_HFW_SLOPE: hfwa,
            model.MD_SPOT_SHIFT: scaleshift
        })

        f = sem_stage.moveAbs({"x": position[0], "y": position[1]})
        f.result()

        f = opt_stage.moveAbs({"x": 0, "y": 0})
        f.result()

        if hole_focus is not None:
            good_focus = hole_focus - aligndelphi.GOOD_FOCUS_OFFSET
        else:
            good_focus = aligndelphi.SEM_KNOWN_FOCUS - aligndelphi.GOOD_FOCUS_OFFSET
        f = ebeam_focus.moveAbs({"z": good_focus})
        f.result()

        # Set min fov
        # We want to be as close as possible to the center when we are zoomed in
        escan.horizontalFoV.value = escan.horizontalFoV.range[0]
        pure_offset = None

        # Start with the best optical focus known so far
        f = focus.moveAbs({"z": opt_focus})
        f.result()

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                ans = input_col(ANSI_MAGENTA,
                                "Do you want to execute the twin stage calibration? [Y/n]")
            if ans in YES_CHARS:
                # Configure CCD and e-beam to write CL spots
                ccd.binning.value = ccd.binning.clip((4, 4))
                ccd.resolution.value = ccd.resolution.range[1]
                ccd.exposureTime.value = 900e-03
                escan.scale.value = (1, 1)
                escan.resolution.value = (1, 1)
                escan.translation.value = (0, 0)
                if not escan.rotation.readonly:
                    escan.rotation.value = 0
                escan.shift.value = (0, 0)
                escan.dwellTime.value = 5e-06
                detector.data.subscribe(_discard_data)
                print_col(ANSI_BLUE,
                          "Please turn on the Optical stream, set Power to 0 Watt "
                          "and focus the image so you have a clearly visible spot.\n"
                          "Use the up and down arrows or the mouse to move the "
                          "optical focus and right and left arrows to move the SEM focus. "
                          "Then turn off the stream and press Enter...")
                if not force_calib:
                    print_col(ANSI_YELLOW,
                              "If you cannot see the whole source background (bright circle) "
                              "you may try to move to the already known offset position. \n"
                              "To do this press the R key at any moment and use I to go back "
                              "to the initial position.")
                    rollback_pos = (offset[0] * scaling[0], offset[1] * scaling[1])
                else:
                    rollback_pos = None
                ar = ArrowFocus(sem_stage, focus, ebeam_focus, ccd.depthOfField.value, 10e-6)
                ar.focusByArrow(rollback_pos)
                detector.data.unsubscribe(_discard_data)
                print_col(ANSI_BLACK, "Twin stage calibration starting, please wait...")
                try:
                    # TODO: the first point (at 0,0) isn't different from the next 4 points,
                    # excepted it might be a little harder to focus.
                    # => use the same code for all of them
                    align_offsetf = aligndelphi.AlignAndOffset(ccd, detector, escan, sem_stage,
                                                               opt_stage, focus, logpath)
                    align_offset = align_offsetf.result()
                    new_opt_focus = focus.position.value.get('z')

                    # If the offset is large, it can prevent the SEM stage to follow
                    # the optical stage. If it's really large (eg > 1mm) it will
                    # even prevent from going to the calibration locations.
                    # So warn about this, as soon as we detect it. It could be
                    # caused either due to a mistake in the offset detection, or
                    # because the reference switch of the optical axis is not
                    # centered (enough) on the axis. In such case, a technician
                    # should open the sample holder and move the reference switch.
                    # Alternatively, we could try to be more clever and support
                    # the range of the tmcm axes to be defined per sample
                    # holder, and set some asymmetric range (to reflect the fact
                    # that 0 is not at the center).
                    for a, trans in zip(("x", "y"), align_offset):
                        # SEM pos = Opt pos + offset
                        rng_sem = sem_stage.axes[a].range
                        rng_opt = opt_stage.axes[a].range
                        if (rng_opt[0] + trans < rng_sem[0] or
                            rng_opt[1] + trans > rng_sem[1]):
                            logging.info("Stage align offset = %s, which could cause "
                                         "moves on the SEM stage out of range (on axis %s)",
                                         align_offset, a)
                            input_col(ANSI_RED,
                                      "Twin stage offset on axis %s is %g mm, which could cause moves out of range.\n"
                                      "Check that the reference switch in the sample holder is properly at the center." %
                                      (a, trans * 1e3))

                    def ask_user_to_focus(n):
                        detector.data.subscribe(_discard_data)
                        input_col(ANSI_BLUE,
                                  "About to calculate rotation and scaling (%d/4). " % (n + 1,) +
                                  "Please turn on the Optical stream, "
                                  "set Power to 0 Watt and focus the image using the mouse "
                                  "so you have a clearly visible spot. \n"
                                  "If you do not see a spot nor the source background, "
                                  "move the sem-stage from the command line by steps of 200um "
                                  "in x and y until you can see the source background at the center. \n"
                                  "Then turn off the stream and press Enter...")
                        # TODO: use ArrowFocus() too?
                        print_col(ANSI_BLACK, "Calculating rotation and scaling (%d/4), please wait..." % (n + 1,))
                        detector.data.unsubscribe(_discard_data)

                    f = aligndelphi.RotationAndScaling(ccd, detector, escan, sem_stage,
                                                       opt_stage, focus, align_offset,
                                                       manual=ask_user_to_focus, logpath=logpath)
                    acc_offset, new_rotation, new_scaling = f.result()

                    # Offset is divided by scaling, since Convert Stage applies scaling
                    # also in the given offset
                    pure_offset = acc_offset
                    new_offset = ((acc_offset[0] / new_scaling[0]), (acc_offset[1] / new_scaling[1]))

                    print_col(ANSI_CYAN,
                              "Values computed: offset: " + str(new_offset) + "\n"
                              "                 scaling: " + str(new_scaling) + "\n"
                              "                 rotation: " + str(new_rotation) + "\n"
                              "                 optical focus: " + str(new_opt_focus))
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        ans = input_col(ANSI_MAGENTA,
                                        "Do you want to update the calibration file with these values? [Y/n]")
                    if ans in YES_CHARS:
                        offset, scaling, rotation, opt_focus = new_offset, new_scaling, new_rotation, new_opt_focus
                        calibconf.set_sh_calib(shid, first_hole, second_hole, hole_focus, opt_focus, offset,
                               scaling, rotation, iscale, irot, iscale_xy, ishear,
                               resa, resb, hfwa, scaleshift)
                        print_col(ANSI_BLACK, "Calibration file is updated.")
                    break
                except IOError:
                    print_col(ANSI_RED, "Twin stage calibration failed.")
            else:
                break

        while True:
            ans = "Y" if force_calib else None
            while ans not in YES_NO_CHARS:
                ans = input_col(ANSI_MAGENTA,
                                "Do you want to execute the fine alignment? [Y/n]")
            if ans in YES_CHARS:
                # Return to the center so fine alignment can be executed just after calibration
                f = opt_stage.moveAbs({"x": 0, "y": 0})
                f.result()
                if pure_offset is not None:
                    f = sem_stage.moveAbs({"x":pure_offset[0], "y":pure_offset[1]})
                    f.result()
                elif offset is not None:
                    f = sem_stage.moveAbs({"x":offset[0] * scaling[0], "y":offset[1] * scaling[1]})
                    f.result()
                else:
                    f = sem_stage.moveAbs({"x":position[0], "y":position[1]})
                    f.result()

                f = focus.moveAbs({"z": opt_focus})
                f.result()
                f = ebeam_focus.moveAbs({"z": good_focus})
                f.result()

                # Run the optical fine alignment
                # TODO: reuse the exposure time
                # Configure e-beam to write CL spots
                escan.horizontalFoV.value = escan.horizontalFoV.range[0]
                escan.scale.value = (1, 1)
                escan.resolution.value = (1, 1)
                escan.translation.value = (0, 0)
                if not escan.rotation.readonly:
                    escan.rotation.value = 0
                escan.shift.value = (0, 0)
                escan.dwellTime.value = 5e-06
                detector.data.subscribe(_discard_data)
                print_col(ANSI_BLUE,
                          "Please turn on the Optical stream, set Power to 0 Watt "
                          "and focus the image so you have a clearly visible spot.\n"
                          "Use the up and down arrows or the mouse to move the "
                          "optical focus and right and left arrows to move the SEM focus. "
                          "Then turn off the stream and press Enter...")
                ar = ArrowFocus(sem_stage, focus, ebeam_focus, ccd.depthOfField.value, 10e-6)
                ar.focusByArrow()
                detector.data.unsubscribe(_discard_data)

                print_col(ANSI_BLACK, "Fine alignment in progress, please wait...")

                # restore CCD settings (as the GUI/user might have changed them)
                ccd.binning.value = (1, 1)
                ccd.resolution.value = ccd.resolution.range[1]
                ccd.exposureTime.value = 900e-03
                # Center (roughly) the spot on the CCD
                f = spot.CenterSpot(ccd, sem_stage, escan, spot.ROUGH_MOVE, spot.STAGE_MOVE, detector.data)
                dist, vect = f.result()
                if dist is None:
                    logging.warning("Failed to find a spot, twin stage calibration might have failed")

                try:
                    escan.horizontalFoV.value = 80e-06
                    f = align.FindOverlay((4, 4),
                                          0.5,  # s, dwell time
                                          10e-06,  # m, maximum difference allowed
                                          escan,
                                          ccd,
                                          detector,
                                          skew=True,
                                          bgsub=True)
                    trans_val, cor_md = f.result()
                    trans_md, skew_md = cor_md
                    new_iscale = trans_md[model.MD_PIXEL_SIZE_COR]
                    new_irot = -trans_md[model.MD_ROTATION_COR] % (2 * math.pi)
                    new_ishear = skew_md[model.MD_SHEAR_COR]
                    new_iscale_xy = skew_md[model.MD_PIXEL_SIZE_COR]
                    print_col(ANSI_CYAN,
                              "Values computed: scale: " + str(new_iscale) + "\n"
                              "                 rotation: " + str(new_irot) + "\n"
                              "                 scale-xy: " + str(new_iscale_xy) + "\n"
                              "                 shear: " + str(new_ishear))
                    ans = "Y" if force_calib else None
                    while ans not in YES_NO_CHARS:
                        ans = input_col(ANSI_MAGENTA,
                                        "Do you want to update the calibration file with these values? [Y/n]")
                    if ans in YES_CHARS:
                        iscale, irot, iscale_xy, ishear = new_iscale, new_irot, new_iscale_xy, new_ishear
                        calibconf.set_sh_calib(shid, first_hole, second_hole, hole_focus, opt_focus, offset,
                               scaling, rotation, iscale, irot, iscale_xy, ishear,
                               resa, resb, hfwa, scaleshift)
                        print_col(ANSI_BLACK, "Calibration file is updated.")
                    break
                except ValueError:
                    print_col(ANSI_RED, "Fine alignment failed.")
            else:
                break
    except Exception:
        logging.exception("Unexpected failure during calibration")
    finally:
        print_col(ANSI_BLACK, "Calibration ended, now ejecting sample, please wait...")
        # Eject the sample holder
        f = chamber.moveAbs({"pressure": vented_pressure})

        aligndelphi.restore_hw_settings(escan, ccd, hw_settings)

        # Store the final version of the calibration file in the log folder
        try:
            shutil.copy(calibconf.file_path, logpath)
        except Exception:
            logging.info("Failed to log calibration file", exc_info=True)

        ans = input_col(ANSI_MAGENTA, "Press Enter to close")
        f.result()