Skip to content

Focus Scan

focus_scan

Attributes

FWHM_X module-attribute

FWHM_X = FWHM(axis_x_x, gaussian(axis_x_x, *popt_x))

FWHM_Y module-attribute

FWHM_Y = FWHM(axis_x_y, gaussian(axis_x_y, *popt_y))

PV module-attribute

PV = PV

args module-attribute

args = parse_args()

axis_x_x module-attribute

axis_x_x = linspace(1, size_of_roi_x, size_of_roi_x)

axis_x_y module-attribute

axis_x_y = linspace(1, size_of_roi_y, size_of_roi_y)

fwhm_data module-attribute

fwhm_data = zeros((142, 3))

image module-attribute

image = get_roi(image, marker1X, marker1Y, marker2X, marker2Y)

lens_z module-attribute

lens_z = get_lens_z()

parser module-attribute

parser = ArgumentParser(prog='focus_scan', usage='%(prog)s [options] PV', add_help=False)

tfs_Z_stop module-attribute

tfs_Z_stop = 'MFX:TFS:MMS:21.STOP'

tfs_current_Z module-attribute

tfs_current_Z = 'MFX:TFS:MMS:21.RBV'

tfs_set_Z module-attribute

tfs_set_Z = 'MFX:TFS:MMS:21.VAL'

thread module-attribute

thread = Thread(target=autorun(sample='Focus_scan', run_length=153, record=True, runs=1, daq_num=daq_num))

wait module-attribute

wait = round((300 - lens_z) / 2, 1) + 3

Functions

FWHM

FWHM(x, y)
Source code in scripts/focus_scan.py
def FWHM(x, y):
    d = y - (max(y) / 2)
    indexes = np.where(d > 0)[0]
    try:
        fwhm = abs(x[indexes[-1]] - x[indexes[0]])
    except IndexError:
        fwhm = 0
    return fwhm

check_camviewer_config

check_camviewer_config(PV)
Source code in scripts/focus_scan.py
def check_camviewer_config(PV):
    hutch = str.lower(PV.split(':')[0])
    if hutch not in ['mfx', 'cxi', 'xcs']:
        print(" [!] Unsupported camera", PV + ".", "Exiting...", '\n')
        sys.exit(1)
    file = "/reg/g/pcds/pyps/config/" + hutch + "/camviewer.cfg"
    with open(file, 'r') as viewer_config:
        for line in viewer_config:
            if PV not in line:
                continue
            else:
                camconfig = (line.split(',')[1].split(';')[0].split(':')[3])
    if camconfig == 'IMAGE2':
        ArraySizeX_data = caget(PV + ':IMAGE1:ArraySize0_RBV')
        ArraySizeY_data = caget(PV + ':IMAGE1:ArraySize1_RBV')
        ArraySizeX_viewer = caget(PV + ':IMAGE2:ArraySize0_RBV')
        ArraySizeY_viewer = caget(PV + ':IMAGE2:ArraySize1_RBV')
        if ArraySizeX_data != ArraySizeX_viewer or \
           ArraySizeY_data != ArraySizeY_viewer:
            print('\n',
                  "[!] camViewer for",
                  PV, "is configured as", camconfig, '\n',
                  "[!] but data and viewer streams have different resolution",
                  '\n',
                  "[!] - data stream width is:", ArraySizeX_data, '\n',
                  "[!] - viewer stream width is:", ArraySizeX_viewer, '\n',
                  "[!] - data stream height is:", ArraySizeY_data, '\n',
                  "[!] - viewer stream height is:", ArraySizeY_viewer, '\n',
                  "[!] ROI defined with markers in camViewer won't make sense.", '\n',
                  "[!] Exiting...", '\n')
            sys.exit(1)

check_color_mode

check_color_mode(PV)
Source code in scripts/focus_scan.py
def check_color_mode(PV):
    color_mode = caget(PV + ':ColorMode_RBV')
    if color_mode != 0:
        print(" [!] Camera", PV, "is not in Mono color mode.",
              "Exiting...", '\n')
        sys.exit(1)

check_data_stream

check_data_stream(PV)
Source code in scripts/focus_scan.py
def check_data_stream(PV):
    data_stream = caget(PV + ':IMAGE1:EnableCallbacks_RBV')
    if data_stream != 1:
        print(" [!] Data stream is disabled for", PV + ".", "Exiting...", '\n')
        sys.exit(1)

fwhm_calc

fwhm_calc(PV, marker1X, marker1Y, marker2X, marker2Y, axis_x_x, axis_x_y)
Source code in scripts/focus_scan.py
def fwhm_calc(PV, marker1X, marker1Y, marker2X, marker2Y, axis_x_x, axis_x_y):
    image = get_image(PV)
    image_roi = get_roi(image, marker1X, marker1Y, marker2X, marker2Y)

    x_projection, y_projection = get_projections(image_roi)

    try:
        popt_x, pcov_x = curve_fit(gaussian, axis_x_x, x_projection)
        popt_y, pcov_y = curve_fit(gaussian, axis_x_y, y_projection)

    except RuntimeError:
        print('\n', "[!] Can't fit a Gaussian. Exiting...", '\n')
        sys.exit(1)

    gauss_fit_x = gaussian(axis_x_x, *popt_x)
    gauss_fit_y = gaussian(axis_x_y, *popt_y)

    FWHM_X = FWHM(axis_x_x, gauss_fit_x)
    FWHM_Y = FWHM(axis_x_y, gauss_fit_y)

    return(image_roi, x_projection, y_projection,
           gauss_fit_x, gauss_fit_y, FWHM_X, FWHM_Y)

gaussian

gaussian(x, amplitude, mean, stddev)
Source code in scripts/focus_scan.py
def gaussian(x, amplitude, mean, stddev):
    return amplitude * np.exp(-((x - mean) / 4 / stddev)**2)

get_image

get_image(PV)
Source code in scripts/focus_scan.py
def get_image(PV):
    image = caget(PV + ':IMAGE1:ArrayData')
    if len(image) == 0:
        print(" [!] Can't read camera", PV + ".", "Exiting...", '\n')
        sys.exit(1)
    else:
        ArraySizeX = caget(PV + ':IMAGE1:ArraySize0_RBV')
        ArraySizeY = caget(PV + ':IMAGE1:ArraySize1_RBV')
        image = np.reshape(image, (ArraySizeY, ArraySizeX))
        # image = ndimage.gaussian_filter(image, 0.1) # test gaussian filter denoising
        # image = ndimage.median_filter(image, 1) # test median filter denoising
    return image

get_lens_z

get_lens_z()
Source code in scripts/focus_scan.py
def get_lens_z():
    return round(caget(tfs_current_Z), 0)

get_markers

get_markers(PV)
Source code in scripts/focus_scan.py
def get_markers(PV):
    marker1X = caget(PV + ':Cross1X')
    marker1Y = caget(PV + ':Cross1Y')
    marker2X = caget(PV + ':Cross2X')
    marker2Y = caget(PV + ':Cross2Y')
    return marker1X, marker1Y, marker2X, marker2Y

get_projections

get_projections(image)
Source code in scripts/focus_scan.py
def get_projections(image):
    x_projection = np.sum(image, axis=0)
    y_projection = np.sum(image, axis=1)

    x_projection -= x_projection.min()
    y_projection -= y_projection.min()

    return x_projection, y_projection

get_roi

get_roi(image, marker1X, marker1Y, marker2X, marker2Y)
Source code in scripts/focus_scan.py
def get_roi(image, marker1X, marker1Y, marker2X, marker2Y):
    image = image[marker1Y:marker2Y, marker1X:marker2X]
    return image

park_lens

park_lens()
Source code in scripts/focus_scan.py
def park_lens():
    lens_z = get_lens_z()

    if lens_z <= 150:
        lens_direction_bit = 0  # 0 for 0 to 299, 1 for 299 to 0
        try:
            print(" [*] Transfocator is at Z =", lens_z, "mm", '\n',
                    "[*] Sending transfocator to the nearest end (Z = 0 mm)")
            caput(tfs_set_Z, 0)
            wait = round((lens_z / 2), 1) + 3
            print(" [*] Waiting", wait, "sec...", '\n')
            time.sleep(wait)
        except KeyboardInterrupt:
            print('\n', "[*] Stopping transfocator Z motion and exiting...",'\n')
            caput(tfs_Z_stop, 1)
            sys.exit()

    else:
        lens_direction_bit = 1  # 0 for 0 to 299, 1 for 299 to 0
        try:
            print(" [*] Transfocator is at Z =", lens_z, "mm", '\n',
                "[*] Sending transfocator to the nearest end (Z = 299 mm)")
            caput(tfs_set_Z, 299)
            wait = round(((300 - lens_z) / 2), 1) + 3
            print(" [*] Waiting", wait, "sec...", '\n')
            time.sleep(wait)
        except KeyboardInterrupt:
            print('\n', "[*] Stopping transfocator Z motion and exiting...",'\n')
            caput(tfs_Z_stop, 1)
            sys.exit()

    return(lens_direction_bit)

plot_data

plot_data(scan_data)
Source code in scripts/focus_scan.py
def plot_data(scan_data):
    lens_z_position = scan_data[:, 0]
    fwhm_data_x = scan_data[:, 1]
    fwhm_data_y = scan_data[:, 2]

    fig, (ax1, ax2) = plt.subplots(2, 1)
    fig.subplots_adjust(hspace=0.5)
    fig.canvas.manager.set_window_title('FWHM scan results')

    ax1.plot(lens_z_position[:], fwhm_data_x)
    ax1.set_xlabel('Transfocator Z')
    ax1.set_ylabel('FWHM X')
    ax1.grid(True)

    ax2.plot(lens_z_position[:], fwhm_data_y)
    ax2.set_xlabel('Transfocator Z')
    ax2.set_ylabel('FWHM Y')
    ax2.grid(True)

    plt.show()
    return()

roi_size

roi_size(marker1X, marker1Y, marker2X, marker2Y)
Source code in scripts/focus_scan.py
def roi_size(marker1X, marker1Y, marker2X, marker2Y):
    size_of_roi_x = marker2X - marker1X
    size_of_roi_y = marker2Y - marker1Y
    if size_of_roi_x < 0 or size_of_roi_y < 0:
        print(" [!] ROI doesn't make sense. ", '\n',
              "[!] Set Orientation to 'None'," '\n',
              "[!] Marker 1 to the upper left corner,", '\n',
              "[!] Marker 2 to the bottom right corner of the desired ROI", '\n',
              "[!] and enable 'Use Global Markers' in the menu Markers/ROI.", '\n',
              "[!] Exiting..."
              '\n')
        sys.exit(1)
    else:
        return size_of_roi_x, size_of_roi_y