Example #1
0
 def ok(self):
     if self.first_cross:
         self.label[
             'text'] = 'Align rectangle with first apartment, then press Finish'
         self.btn['text'] = 'Finish'
         self.first_cross = False
         self.first_point = pos.current(self.mmc, axis='xy')
     else:
         self.second_point = pos.current(self.mmc, axis='xy')
         self.delete()
Example #2
0
 def ok(self):
     if self.first_cross:
         self.label[
             'text'] = 'Align same point on chip with new cross, then press Finish'
         self.btn['text'] = 'Finish'
         self.first_cross = False
         self.first_point = pos.current(self.mmc, axis='xy')
     else:
         self.second_point = pos.current(self.mmc, axis='xy')
         self.delete()
Example #3
0
 def ok(self):
     if self.first_cross:
         self.label[
             'text'] = 'Align same point on chip with new cross, then press Finish'
         self.btn['text'] = 'Finish'
         self.first_cross = False
         self.first_point = pos.current(mmc)
Example #4
0
def get_center(mmc, center, frame_to_pixel_ratio, camera_pixel_width,
               camera_pixel_height):
    cur_position = pos.current(mmc)
    x_change = (center[0] -
                (float(camera_pixel_width) / 2)) * frame_to_pixel_ratio
    y_change = (center[1] -
                (float(camera_pixel_height) / 2)) * frame_to_pixel_ratio
    new_x = cur_position.x - x_change
    new_y = cur_position.y - y_change
    return pos.StagePosition(x=new_x, y=new_y)
Example #5
0
def focus_point(mmc, focus_model, delta_z=10, total_z=250, exposure=1):
    cur_z = pos.current(mmc).z
    if total_z == 0:
        return cur_z
    z = get_z_list(cur_z, delta_z, total_z)
    cam = sc_utils.start_cam()

    preds = []
    for curr_z in z:
        pos.set_pos(mmc, z=curr_z)
        frame = sc_utils.get_live_frame(cam, exposure)
        preds.append(focus_model.score(sc_utils.bytescale(frame, high=65535)))
    # find the index of the min focus prediction
    best_focus_index = np.argmin(preds)
    # append to the PositionList 
    last_z = z[best_focus_index]

    sc_utils.close_cam(cam)
    return last_z
Example #6
0
def focus_from_image_stack(xy_points, mmc, delta_z=5, total_z=150, exposure=1):
    ''' Brute force focus algorthim 
    
    args: 
        xy_points: a PositionList() of the locations to 
            focus at
        mmc: Micromanger instance
        delta_z: distacne between images (um)
        total_z: total imaging distance (all focused points on 
            chip should be in this range)
    
    returns:
        focused PositionList()
    '''
    # Get focus model
    focus_model = miq.get_classifier()
    pos_list = pos.PositionList()
    # make z position array
    cur_pos = pos.current(mmc)
    z = get_z_list(cur_pos.z, delta_z, total_z)
    cam = sc_utils.start_cam()
    for posit in xy_points:
        # Go to the x,y position 
        pos.set_pos(mmc, x=posit.x, y=posit.y)
        preds = []
        for curr_z in z:
            mmc.setPosition(curr_z)
            mmc.waitForSystem()
            frame = cam.get_frame(exp_time=exposure).reshape(cam.sensor_size[::-1])
            preds.append(focus_model.score(sc_utils.bytescale(frame, high=65535)))
        # find the index of the min focus prediction
        best_focus_index = np.argmin(preds)
        # append to the PositionList 
        sp = pos.StagePosition(x=posit.x, y=posit.y,
                               z=z[best_focus_index])
        pos_list.append(sp)
    
    sc_utils.close_cam(cam)
    return pos_list
Example #7
0
def extended_search(stage_controller):
    center = pos.current(stage_controller)
    keep_searching = True
    while keep_searching:
        pos.set_pos()
Example #8
0
    def image(self):
        # Delete Live Camera
        if self.live_class is not None:
            self.live_class.delete()

        save_dir = (self.saving_params['Folder'].entry.get() + '/' +
                    self.experiment_params['Start Date'].entry.get() + '-' +
                    self.experiment_params['Chip'].entry.get() + '-' +
                    self.experiment_params['Cell'].entry.get() + '-' +
                    self.experiment_params['Drug'].entry.get() + '/' +
                    self.experiment_params['Concentration'].entry.get() + '-' +
                    self.experiment_params['Drug'].entry.get() + '/' +
                    self.experiment_params['Chip Index'].entry.get() +
                    '/').replace(' ', '-')

        saved_focus = False
        # use the directories in save_dir to determine the number of times this
        # chip has been imaged
        if not os.path.isdir(save_dir):
            time_point = 't00'
        else:
            points = len(next(os.walk(save_dir))[1])
            time_point = "t{0:0=2d}".format(points)
            saved_focus = True
        positions_dir = save_dir + 't00'
        save_dir = save_dir + time_point
        sc_utils.print_info("Set saving directory to " + save_dir)
        os.makedirs(save_dir, exist_ok=True)

        if saved_focus == True:
            saved_focus = start_popup()
        print("Saved Focus", saved_focus)

        # Write info file
        self.write_info_file(save_dir)

        for chip in self.config_yaml_data['chips']:
            if chip['name'] == self.experiment_params["Chip"].entry.get():
                cur_chip = chip

        sc_utils.print_info("Using chip: " + str(cur_chip))

        # Check if number of focus points is too low for interpolation
        if int(self.focus_params['Focus Points X'].entry.get()) < 4:
            focus_points_x = 4
            sc_utils.print_info(
                'Focus Points X cannot be less than 4, using 4 instead.')
        else:
            focus_points_x = int(
                self.focus_params['Focus Points X'].entry.get())
        if int(self.focus_params['Focus Points Y'].entry.get()) < 4:
            focus_points_y = 4
            sc_utils.print_info(
                'Focus Points Y cannot be less than 4, using 4 instead.')
        else:
            focus_points_y = int(
                self.focus_params['Focus Points Y'].entry.get())

        sc_utils.before_imaging()

        first_through = True
        original_point = pos.current(self.mmc)
        for val, check in self.exposure_checkboxes.items():
            if check.get() and first_through and not saved_focus == True:
                if not val == 'BFF':
                    sc_utils.print_error(
                        'Must image in BFF first when aligning and focusing')
                    return
                sc_utils.set_led_and_shutter(self.mmc,
                                             read_yaml(LED_YAML_PATH)[val][0])
                run.auto_image_chip(
                    cur_chip, self.mmc, save_dir,
                    self.experiment_params['Chip Index'].entry.get(),
                    self.system_params['Alignment Model'].entry.get(),
                    os.path.splitext(
                        self.system_params['Focus Model'].entry.get())[0], val,
                    float(self.focus_params['Step Size (um)'].entry.get()),
                    int(self.focus_params['Initial Focus Range (um)'].entry.
                        get()),
                    int(self.focus_params['Focus Range (um)'].entry.get()),
                    focus_points_x, focus_points_y,
                    int(self.focus_params['Focus Exposure'].entry.get()),
                    int(self.system_params['Image Rotation (degrees)'].entry.
                        get()),
                    float(self.calibration_params['Frame to Pixel Ratio'].
                          entry.get()), sc_utils.get_frame_size(),
                    int(self.exposure_params[val].entry.get()), [
                        float(self.calibration_params['First Position X'].
                              entry.get()),
                        float(self.calibration_params['First Position Y'].
                              entry.get())
                    ],
                    int(self.system_params['Apartments in Image X'].entry.get(
                    )),
                    int(self.system_params['Apartments in Image Y'].entry.get(
                    )), [
                        int(self.saving_params['Output Image Pixel Width'].
                            entry.get()),
                        int(self.saving_params['Output Image Pixel Height'].
                            entry.get())
                    ])

                first_through = False

            elif check.get():
                sc_utils.set_led_and_shutter(self.mmc,
                                             read_yaml(LED_YAML_PATH)[val][0])
                run.image_from_saved_positions(
                    cur_chip, positions_dir, save_dir, self.mmc, val,
                    int(self.system_params['Image Rotation (degrees)'].entry.
                        get()), int(self.exposure_params[val].entry.get()), [
                            float(self.calibration_params['First Position X'].
                                  entry.get()),
                            float(self.calibration_params['First Position Y'].
                                  entry.get())
                        ],
                    int(self.system_params['Apartments in Image X'].entry.get(
                    )),
                    int(self.system_params['Apartments in Image Y'].entry.get(
                    )), [
                        int(self.saving_params['Output Image Pixel Width'].
                            entry.get()),
                        int(self.saving_params['Output Image Pixel Height'].
                            entry.get())
                    ])
            sc_utils.in_between_channels()
        pos.set_pos(self.mmc,
                    x=original_point.x,
                    y=original_point.y,
                    z=original_point.z)

        sc_utils.after_imaging()
Example #9
0
    def image(self):
        # Delete Live Camera
        if self.live_class is not None:
            self.live_class.delete()

        chip_type = self.general_options[0].entry.get()
        objective = self.general_options[1].entry.get()
        drug = self.general_options[2].entry.get()
        cell = self.general_options[3].entry.get()
        origin = self.general_options[4].entry.get()
        folder = self.entries[0].get()
        date = self.entries[1].get()
        concentration = self.entries[2].get()
        index = self.entries[3].get()
        bff = int(self.entries[4].get())
        dap = int(self.entries[5].get())
        gfp = int(self.entries[6].get())
        txr = int(self.entries[7].get())
        cy5 = int(self.entries[8].get())
        focus_step = int(self.entries[9].get())
        focus_total_range = int(self.entries[10].get())
        focus_point_range = int(self.entries[11].get())
        focus_x = int(self.entries[12].get())
        focus_y = int(self.entries[13].get())
        save_jpg = self.entries[14].get()
        alignment_model = self.entries[15].get()
        image_rotation = int(self.entries[16].get())
        apart_per_img_x = self.entries[17].get()
        apart_per_img_y = self.entries[18].get()
        frame_width = self.entries[19].get()
        frame_height = self.entries[20].get()
        camera_pixel_width = self.entries[21].get()
        camera_pixel_height = self.entries[22].get()

        save_dir = (folder + '/' + date + '/' + concentration + '-' +
                    self.unit_string.get() + '-' + drug + '/' + 'Chip' +
                    index + '/')
        # use the directories in save_dir to determine the number of times this
        # chip has been imaged
        if not os.path.isdir(save_dir):
            time_point = 't00'
        else:
            points = len(next(os.walk(save_dir))[1])
            time_point = "t{0:0=2d}".format(points)
        save_dir = save_dir + time_point

        os.makedirs(save_dir, exist_ok=True)

        # Write info file
        self.write_info_file(save_dir)

        if chip_type == 'ML Chip':
            curr_chip = chip.ML_Chip()
        elif chip_type == 'KL Chip':
            curr_chip = chip.KL_Chip()

        if save_jpg == 'y' or save_jpg == 'Y':
            save_jpg = True
        else:
            save_jpg = False

        exp_names = ['BFF', 'DAP', 'GFP', 'TXR', 'CY5']
        exposures = []
        if self.bff_check.get():
            exposures.append(int(bff))
        else:
            exposures.append(False)
        if self.dap_check.get():
            exposures.append(int(dap))
        else:
            exposures.append(False)
        if self.gfp_check.get():
            exposures.append(int(gfp))
        else:
            exposures.append(False)
        if self.txr_check.get():
            exposures.append(int(txr))
        else:
            exposures.append(False)
        if self.cy5_check.get():
            exposures.append(int(cy5))
        else:
            exposures.append(False)

        first_through = True
        original_point = pos.current(self.mmc)
        for i, exp in enumerate(exposures):

            if exp is not False and first_through:
                run.auto_image_chip_focus_first(
                    curr_chip,
                    self.mmc,
                    save_dir,
                    index,
                    alignment_model_name=alignment_model,
                    naming_scheme=exp_names[i],
                    focus_delta_z=focus_step,
                    focus_total_z=focus_total_range,
                    focus_next_point_range=focus_point_range,
                    number_of_focus_points_x=focus_x,
                    number_of_focus_points_y=focus_y,
                    save_jpg=save_jpg,
                    image_rotation=image_rotation,
                    frame_width=frame_width,
                    frame_height=frame_height,
                    camera_pixel_width=camera_pixel_width,
                    camera_pixel_height=camera_pixel_height,
                    exposure=exp)
                first_through = False

            elif exp is not False:
                input("Press Enter to continue...")
                run.image_from_saved_positions(
                    curr_chip,
                    index,
                    save_dir,
                    self.mmc,
                    realign=False,
                    alignment_model_name=alignment_model,
                    naming_scheme=exp_names[i],
                    save_jpg=save_jpg,
                    image_rotation=image_rotation,
                    frame_width=frame_width,
                    frame_height=frame_height,
                    camera_pixel_width=camera_pixel_width,
                    camera_pixel_height=camera_pixel_height,
                    exposure=exp)
        pos.set_pos(self.mmc,
                    x=original_point.x,
                    y=original_point.y,
                    z=original_point.z)
Example #10
0
def auto_image_chip(cur_chip, mmc, save_dir, chip_number, alignment_model_path,
                    focus_model_path, naming_scheme, focus_delta_z,
                    focus_total_z, focus_next_point_range,
                    number_of_focus_points_x, number_of_focus_points_y,
                    focus_exposure, image_rotation, frame_to_pixel_ratio,
                    camera_pixels, exposure, first_position,
                    number_of_apartments_in_frame_x,
                    number_of_apartments_in_frame_y, output_pixels):
    ''' Aligns, focuses, and images given chip

    args:
        chip: an instance of a Chip class (found in chip.py)
        mmc: Micro-Manager instance (can get from sc_utils.get_stage_controller())
        save_dir: directory to save images to 
        chip_number: string to identify chip
        alignment_model_name: name of the trained model for alignment
        alignment_model_path: path to the trained model for alignment
        naming_scheme: Beginning of image file names
        focus_delta_z: amount to change in the z direction between getting 
                       focus prediction
        focus_total_z: total z in each direction to look for an individual 
                       focus point or the first focus point in a set
        focus_next_point_range: total z in each direction to look for each 
                       focus point that directly follows a nearby point that 
                       we have already focused (this will need to be increased
                       for chips that are not relatively flat)
        number_of_focus_points_x: Number of positions to focus at in the x 
                       direction (must be greater than 3 for interpolation to 
                       work propertly)
        number_of_focus_points_y: Number of positions to focus at in the y 
                       direction (must be greater than 3 for interpolation to 
                       work propertly)
        save_jpg: Saves images as both tiff files and jpg files if True
    '''
    start = time.time()
    sc_utils.print_info("Starting: Alignment, Focus, and Imaging")

    model = alignment.get_inference_model(alignment_model_path)
    p1 = pos.current(mmc)
    p2 = pos.StagePosition(x=p1.x + cur_chip['chip_width'], y=p1.y)
    p3 = pos.StagePosition(x=p1.x + cur_chip['chip_width'],
                           y=p1.y - cur_chip['chip_height'])

    # Create a temporay chip for focusing
    temp_corners = pos.PositionList(positions=[p1, p2, p3])
    print('Corners: ', str(temp_corners))
    temp_chip = chip.Chip(temp_corners, first_position, cur_chip,
                          number_of_apartments_in_frame_x,
                          number_of_apartments_in_frame_y)

    focus_pl = temp_chip.get_focus_position_list(number_of_focus_points_x,
                                                 number_of_focus_points_y)
    print('Focus PL: ', str(focus_pl))
    # return
    focused_pl = focus.focus_from_last_point(
        focus_pl,
        mmc,
        focus_model_path,
        delta_z=focus_delta_z,
        total_z=focus_total_z,
        next_point_range=focus_next_point_range,
        exposure=focus_exposure)
    focused_pl.save('focused_pl', save_dir)

    p1.z = focus.predict_z_height(focused_pl, xy_location=(p1.x, p1.y))[0][0]
    p2.z = focus.predict_z_height(focused_pl, xy_location=(p2.x, p2.y))[0][0]
    p3.z = focus.predict_z_height(focused_pl, xy_location=(p3.x, p3.y))[0][0]

    print(p1)

    p1 = alignment.search_and_find_center(mmc, p1, model, exposure,
                                          frame_to_pixel_ratio,
                                          camera_pixels[0], camera_pixels[1])
    p2 = alignment.search_and_find_center(mmc, p2, model, exposure,
                                          frame_to_pixel_ratio,
                                          camera_pixels[0], camera_pixels[1])
    p3 = alignment.search_and_find_center(mmc, p3, model, exposure,
                                          frame_to_pixel_ratio,
                                          camera_pixels[0], camera_pixels[1])

    align_time = time.time()
    sc_utils.print_info('Time for alignment:' + str(align_time - start))

    # Create a Position List of the corners and save it
    corners = pos.PositionList(positions=[p1, p2, p3])
    corners.save('corners_pl', save_dir)
    # # Create a chip instance
    imaging_chip = chip.Chip(corners, first_position, cur_chip,
                             number_of_apartments_in_frame_x,
                             number_of_apartments_in_frame_y)
    imaging_pl = imaging_chip.get_position_list(focused_pl)
    imaging_pl.image(mmc,
                     save_dir,
                     naming_scheme,
                     rotation=image_rotation,
                     exposure=exposure,
                     output_pixels=output_pixels)

    end = time.time()
    sc_utils.print_info('Total time:' + str(end - start))