scope.property_changer("SOLA","White_Enable",1)

## basic settings
run_number=3
interval= 300 # set to 15 minutes (in seconds)
timepoints= 864


## less changed settings
save_dir=r"E:\Folks\Nate\20160425_%s" % run_number
pos_record=r"E:\Folks\Nate\20160425_%s\PositionHistory.csv" % run_number

                               
#### Getting stage locations
positions_file=u'C:/Users/Administrator/Desktop/MicroscopeControl/MicroscopeControl/HalfChipPointsList.pos'
positions=StagePositions.positionList_parser(open(positions_file).read())
order=sorted(positions.keys(),key= lambda x: int(x[3:]))


### running everything

#setting up path
if os.path.exists(save_dir) is False: os.mkdir(save_dir)

fout=open(pos_record,"w")
header="%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % ("Pos",
                                                                "Time",
                                                                "x_set",
                                                                "y_set",
                                                                "z_set",
                                                                "afc_set",
def multi_point_timelapse(
    scope, save_dir, positions_file, illumination_pattern_object, n_timepoints, frequency, file_name_prefix="Timelapse"
):
    """
    args:
        scope -- initalized scope object -- see Microscopes.Microscope
        
    
    """
    #####################################################
    ### Pre Imaging                                   ###
    #####################################################
    #### Getting stage locations

    positions = StagePositions.positionList_parser(open(positions_file).read())
    pos_order = sorted(positions.keys(), key=lambda x: int(x[3:]))  # numerical order
    #### Getting the channels that will be taken

    # channels=illumination_pattern_object.channels
    # channels=["BF","qGFP","qmCherry"]
    channels = ["qDIC", "qGFP", "qCherry"]
    #### Set up the to save images in a structured set of directories

    if os.path.exists(save_dir) is False:
        os.mkdir(save_dir)
    for pos_label in pos_order:
        pos_dir = os.path.join(save_dir, pos_label)
        if os.path.exists(pos_dir) is False:
            os.mkdir(pos_dir)
        for channel_name in channels:
            channel_dir = os.path.join(pos_dir, channel_name)
            if os.path.exists(channel_dir) is False:
                os.mkdir(channel_dir)

    #### Set up the log file

    pos_stats_file_path = os.path.join(save_dir, "Position_Stats.tsv")
    fout = open(pos_stats_file_path, "w")
    pos_record_values = [
        "Pos",
        "Time",
        "x_set",
        "y_set",
        "z_set",
        "afc_set",
        "x_1",
        "y_1",
        "z_1",
        "afc_1",
        "x_2",
        "y_2",
        "z_2",
        "afc_2",
        "channels",
    ]
    header = "\t".join(pos_record_values) + "\n"
    fout.write(header)
    fout.close()

    #####################################################
    ### Imaging Loop                                  ###
    #####################################################
    try:
        ### interate over timepoints
        for t in range(0, n_timepoints):
            print ["init", "init", "move", "foc ", "imag", "save", "stats"]
            acquisition_start_time = time.time()
            for pos_label in pos_order:
                t1 = time.time()
                ## lookup where to go
                pos = positions[pos_label]
                x = pos.get_x()
                y = pos.get_y()
                z = pos.get_z()
                afc = pos.get_afc_offset()
                print "Locations settings: %s\t%s x\t%s y\t%s z\t%s offset" % (pos_label, x, y, z, afc)
                ## move scope to x,y
                t2 = time.time()
                scope.move_XYstage(x, y)
                ## see where the scope is
                x1, y1, z1, afc1 = scope.get_stage_loc()
                ## focus the scope using afc offset
                t3 = time.time()
                scope.move_to_offset(afc, post_focus_delay=0.1, attempt_delay=0.1)
                ## see where the scope is now
                x2, y2, z2, afc2 = scope.get_stage_loc()
                ## figure out the channels to image
                # c_to_image=conditional_illuminations.get_channels(pos_label,t)
                # c_stack_settings=conditional_illuminations.get_stack_settings(pos_label,t)
                c_to_image = [Illuminations.BF2, Illuminations.dimGREEN, Illuminations.dimRED]
                # c_to_image=["qDIC","qGFP","qCherry"]
                c_stack_settings = {"qDIC": [5, 1]}
                ## take the images
                t4 = time.time()
                images, metadata = scope.multichannel_zstack(c_to_image, z_params=c_stack_settings, timed=True)
                ## save the images
                t5 = time.time()
                for c in range(0, len(c_to_image)):
                    stack = images[c]
                    md_stack = metadata[c]
                    try:
                        channel_name = c_to_image[c].name
                    except:
                        channel_name = c_to_image[c]
                    full_save_dir = os.path.join(save_dir, pos_label, channel_name)
                    full_file_name = "%s_%s_c%s%s_t%s" % (file_name_prefix, pos_label, c, channel_name, t)
                    FileOut.stack_writer(full_save_dir, full_file_name, stack, md_stack[len(md_stack) / 2])
                t6 = time.time()

                ###log some stats
                channels_aqcuired_string = ""  # this is in progress
                # for c in c_to_image:
                #    name=c.name
                #    intensity=c.SOLA_intensity
                #    length=c.exposure
                #    if name in c_stack_settings:
                #        z=c_stack_settings[name][0]/c_stack_settings[name][1]+1
                #    else: z=1
                #    channel_string=""
                pos_record_stats = (
                    pos_label,
                    t,
                    x,
                    y,
                    z,
                    afc,
                    x1,
                    y1,
                    z1,
                    afc1,
                    x2,
                    y2,
                    z2,
                    afc2,
                    channels_aqcuired_string,
                )
                pos_record_stats = [str(i) for i in pos_record_stats]
                pos_record_stats = "\t".join(pos_record_stats)
                pos_record_stats += "\n"
                fout = open(pos_stats_file_path, "a")
                fout.write(pos_record_stats)
                fout.close()
                t7 = time.time()
                times = [t1, t2, t3, t4, t5, t6, t7]
                times = ["%.2f" % (i - times[0]) for i in times]
                times_lab = ["Start", "Find Where to Go", "Move Stage", "Focused", "Imaged", "Saved", "Saved_Stats"]
                for i in range(0, len(times)):
                    print times[i], times_lab[i]
            ##return the to first location
            scope.move_to_offset(afc)
            xnext = positions[pos_order[0]].get_x()
            ynext = positions[pos_order[0]].get_y()
            scope.move_XYstage(xnext, ynext)
            scope.mmc.enableContinuousFocus(False)
            ### wait for the start of the next acquisition
            acquisition_finish_time = time.time()
            until_next = frequency - (acquisition_finish_time - acquisition_start_time)
            verbose_sleeper(until_next)
        print "Timelapse completed"
        results = "Scan Completed"

    except:
        print "UH OH!"
        tb = StringIO.StringIO()
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback, file=tb)
        results = (
            "There was some sort of error, "
            "your scan most likely did not finish."
            "The error was \n\n %s" % tb.getvalue()
        )

    return results
###        know what you are doing!                    ###
###                                                    ###
##########################################################

scan_visibility=False
import PlateScan
import EmailFromNTHAYER
import StringIO
import StagePositions
import traceback
import sys



pos_string=open(pos_file).read()
positions=StagePositions.positionList_parser(pos_string)
try:
    scope=scopeConfig.DGLab_Leica2()
    scope.mmc.setProperty("XYStage","Speed",str(stageSpeed))
except:
    tb=StringIO.StringIO()
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print "Could not initialize scope. Try restarting python and/or scope"
    traceback.print_exception(exc_type,
                            exc_value,
                            exc_traceback,
                            file=tb)
    print tb.getvalue()
    raise 
try:
    scan_results=PlateScan.plateScan(scope,
示例#4
0
def legacy():
    """
    This is the code that I had originall wrote to do this.
    This code was really messy, but worked, so I am leaving it here.
    It has been rewritten in the above functions, but could be useful to look
    at.
    """
    ## initialize the scope    
    scope=DGLab_Leica2.DGLab_Leica2()
    
    ## set up the 
    rows=string.ascii_uppercase[1:7]
    columns=range(2,12)
    sites=range(0,225)
    pos_string=open("PositionList_96well_15x15sites.pos").read()
    positions=StagePositions.positionList_parser(pos_string)
    scope.mmc.enableContinuousFocus(True)
    scope.set_illumination(Illuminations.Cy5)
    #start_time=time.asctime().replace(" ","_").replace(":","_")
    start_time="Thu_Aug_13_14_38_51_2015"
    done_list={}
    well_counter={}
    ## if this is a continuation of an old scan, this will add on to the 
    ## existing log file. 
    if os.path.exists("Scan_%s.txt" % start_time):
        completed_fin=open("Scan_%s.txt" % start_time,"r")
        for line in completed_fin:
            site=line.split(";")[0]
            try:
                if "No cells of interest" not in line.split(";")[1]:
                    well=site.split("-")
                    if well not in well_counter:
                        well_counter[well]=0
                    well_counter+=1
            except:
                pass
        completed_fin.close()
        status_out=open("Scan_%s.txt" % start_time,"r")
        status_string=status_out.read()
        status_out.close()
        status_out=open("Scan_%s.txt" % start_time,"w")
        status_out.write(status_string)
    else:
        status_out=open("Scan_%s.txt" % start_time,"w")    

    data_dir="Scan_%s" % start_time
    if os.path.isdir(data_dir) is False:
        os.mkdir(data_dir)
    order=-1
    for row in rows:
            ## flip the order that the columns are gone through
            order=order*-1
            for column in columns[::order]:
                well="%s%s" % (row,column)
                if well not in well_counter:well_counter[well]=0
                if well_counter[well]<15:
                ## reset the well count for this new well. 
                    well_count=well_counter[well]
                    ## iterate through the site in this well. 
                    for site in sites: ## Test case
                        if "%s%s-Site_%s" % (row,column,site) not in done_list.keys():
                            done_list["%s%s-Site_%s" % (row,column,site)]=True
                            print ">Looking at %s%s-Site_%s" % (row,column,site)
                            x,y=positions["%s%s-Site_%s" % (row,column,site)].get_xy()
                            ## take an image to use for a trigger
                            scope.set_illumination(Illuminations.qCy5)
                            scope.mmc.setXYPosition("XYStage",x,y)
                            scope.mmc.snapImage()
                            img=scope.mmc.getImage()
                            ## show image
                            plt.imshow(img)
                            plt.draw()
                            ## analyze this image
                            cois=Threshold.coi_finder(img,
                                                        threshold=1000,
                                                        min_area=100,
                                                        max_area=1000)
                            if cois:
                                do_stack=True
                                progress_line=">%s%s-Site_%s;cois=%s\n" % (row,column,site,cois)
                            else:
                                do_stack=False
                                progress_line=">%s%s-Site_%s;No cells of interest\n" % (row,column,site)
                            status_out.write(progress_line)
                            ## run the stack if there was a COI found
                            if do_stack:
                                print ">Stack at %s%s-Site_%s" % (row,column,site)
                                well_count+=1
                                well_counter[well]+=1
                                channels=[Illuminations.DIC,
                                            Illuminations.GFP,
                                            Illuminations.qCy5,
                                            Illuminations.DAPI]
                                scope.mmc.enableContinuousFocus(False)
                                mda,md=scope.multi_channel_acquisition(channels)
                                FileOut.mda_save(out_dir=data_dir,
                                                prefix="%s%s-Site_%s" % (row,column,site),
                                                mda=mda,
                                                md=md,
                                                channels=channels) 
                                print "Stack taken at %s%s-Site_%s" % (row,column,site)                   
                            ## turn AFC back on
                            scope.mmc.enableContinuousFocus(True)
                            ## move onto the next well if we have acquired enough
                            if well_count > 15:
                                break
                            ## break out of the well if you can't focus
                            if scope.mmc.isContinuousFocusLocked() is False:
                                time.sleep(5)
                                if scope.mmc.isContinuousFocusLocked() is False:
                                    print "Couldnt focus 3"
                                    break
                ## break out of the column if you still cant focus
                if scope.mmc.isContinuousFocusLocked() is False:
                    time.sleep(5)
                    if scope.mmc.isContinuousFocusLocked() is False:
                        print "Couldnt focus 2"
                        break
            ## break out of the row if you STILL cant focus. 
            if scope.mmc.isContinuousFocusLocked() is False:
                time.sleep(5)
                if scope.mmc.isContinuousFocusLocked() is False:
                    print "Couldnt focus 1"
                    break                     
    status_out.close()