Пример #1
0
def initialize(micromirror_parameters):
    camera_parameters = {
        'trigger': "external trigger/software exposure control",
        'exposure_time_microseconds': 6700,
    }
    camera = pco.Edge()
    camera.apply_settings(**camera_parameters)
    camera.arm()
    micromirrors = dmd.Micromirror_Subprocess(**micromirror_parameters)
    laser_shutters = shutters.Laser_Shutters(colors=['405', '488'])
    filter_wheel = wheel.Filter_Wheel(initial_position='f3')
    return camera, micromirrors, laser_shutters, filter_wheel
Пример #2
0
def pco_edge_camera_child_process(
        data_buffers,
        buffer_shape,
        input_queue,
        output_queue,
        commands,
        pco_edge_type='4.2'  #Change this if you're using a 5.5
):
    """For use with image_data_pipeline.py

    https://github.com/AndrewGYork/tools/blob/master/image_data_pipeline.py
    Debugged for the 4.2, but might work for the 5.5, with some TLC...
    """
    from image_data_pipeline import info, Q, sleep, clock
    try:
        import pco
    except ImportError:
        info("Failed to import pco.py; go get it from github:")
        info("https://github.com/AndrewGYork/tools/blob/master/pco.py")
        raise
    buffer_size = np.prod(buffer_shape)
    info("Initializing...")
    camera = pco.Edge(pco_edge_type=pco_edge_type, verbose=False)
    camera.apply_settings(trigger='auto_trigger')
    camera.arm(num_buffers=3)
    info("Done initializing")
    preframes = 3
    first_trigger_timeout_seconds = 0
    status = 'Normal'
    while True:
        if commands.poll():
            cmd, args = commands.recv()
            info("Command received: " + cmd)
            if cmd == 'apply_settings':
                result = camera.apply_settings(**args)
                camera.arm(num_buffers=3)
                commands.send(result)
            elif cmd == 'get_setting':
                setting = getattr(camera, args['setting'],
                                  'unrecognized_setting')
                commands.send(setting)
            elif cmd == 'set_buffer_shape':
                buffer_shape = args['shape']
                buffer_size = np.prod(buffer_shape)
                commands.send(buffer_shape)
            elif cmd == 'get_status':
                commands.send(status)
            elif cmd == 'reset_status':
                status = 'Normal'
                commands.send(status)
            elif cmd == 'get_preframes':
                commands.send(preframes)
            elif cmd == 'set_preframes':
                preframes = args['preframes']
                commands.send(preframes)
            elif cmd == 'get_first_trigger_timeout_seconds':
                commands.send(first_trigger_timeout_seconds)
            elif cmd == 'set_first_trigger_timeout_seconds':
                first_trigger_timeout_seconds = args[
                    'first_trigger_timeout_seconds']
                commands.send(first_trigger_timeout_seconds)
            elif cmd == 'force_trigger':
                result = camera._force_trigger()
                commands.send(result)
            else:
                info("Unrecognized command: " + cmd)
                commands.send("unrecognized_command")
                continue
        try:
            permission_slip = input_queue.get_nowait()
        except Q.Empty:
            sleep(0.001)  #Non-deterministic sleep time :(
            continue
        if permission_slip is None:  #This is how we signal "shut down"
            output_queue.put(permission_slip)
            break  #We're done
        else:
            # Fill the data buffer with images from the camera
            time_received = clock()
            process_me = permission_slip['which_buffer']
            ## Trust IDP to request a legal num_slices
            num_slices = permission_slip.get('num_slices', buffer_shape[0])
            info("start buffer %i, acquiring %i frames and %i preframes" %
                 (process_me, num_slices, preframes))
            with data_buffers[process_me].get_lock():
                a = np.frombuffer(data_buffers[process_me].get_obj(),
                                  dtype=np.uint16)[:buffer_size].reshape(
                                      buffer_shape)[:num_slices, :, :]
                try:
                    camera.record_to_memory(num_images=a.shape[0] + preframes,
                                            preframes=preframes,
                                            out=a,
                                            first_trigger_timeout_seconds=(
                                                first_trigger_timeout_seconds))
                except pco.TimeoutError as e:
                    info('TimeoutError: %s' % (e.value))
                    status = 'TimeoutError'
                    #FIXME: we can do better, probably. Keep trying?
                    #Should we zero the remainder of 'a'?
                except pco.DMAError:
                    info('DMAError')
                    status = 'DMAError'
                else:
                    status = 'Normal'
            info("end buffer %i, %06f seconds elapsed" %
                 (process_me, clock() - time_received))
            output_queue.put(permission_slip)
    camera.close()
    return None
Пример #3
0
def camera_child_process(
    data_buffers,
    buffer_shape,
    input_queue,
    output_queue,
    commands,
):
    """
    This version's suitable for the pco.edge camera.
    """
    buffer_size = np.prod(buffer_shape)
    import pco
    camera = pco.Edge(pco_edge_type='4.2')  #Change this if you're using a 5.5
    camera.apply_settings(trigger='auto trigger')
    camera.get_shutter_mode()
    camera.get_settings(verbose=False)
    camera.arm(num_buffers=3)
    camera._prepare_to_record_to_memory()
    preframes = 3
    status = 'Normal'
    timeout = 0
    while True:
        if commands.poll():
            cmd, args = commands.recv()
            if cmd == 'set_buffer_shape':
                buffer_shape = args['shape']
                buffer_size = np.prod(buffer_shape)
                commands.send(buffer_shape)
            elif cmd == 'apply_settings':
                settings = camera.apply_settings(**args)
                camera.arm()
                camera._prepare_to_record_to_memory()
                commands.send(settings)
            elif cmd == 'get_settings':
                commands.send(camera.get_settings(**args))
            elif cmd == 'get_status':
                commands.send(status)
            elif cmd == 'reset_status':
                status = 'Normal'
                commands.send(None)
            elif cmd == 'get_preframes':
                commands.send(preframes)
            elif cmd == 'set_preframes':
                preframes = args['preframes']
                commands.send(preframes)
            elif cmd == 'get_timeout':
                commands.send(timeout)
            elif cmd == 'set_timeout':
                timeout = args['timeout']
                commands.send(timeout)
            continue  #ignore commands we don't recognize. Bad idea?
        try:
            permission_slip = input_queue.get_nowait()
        except Queue.Empty:
            time.sleep(0.001)
            continue
        if permission_slip is None:
            break  #We're done
        else:
            time_received = clock()
            """Fill the buffer with something"""
            process_me = permission_slip['which_buffer']
            info("start buffer %i" % (process_me))
            with data_buffers[process_me].get_lock():
                a = np.frombuffer(
                    data_buffers[process_me].get_obj(),
                    dtype=np.uint16)[:buffer_size].reshape(buffer_shape)
                while True:
                    info('Start acquiring:%06f' % clock())
                    try:
                        camera.record_to_memory(num_images=a.shape[0] +
                                                preframes,
                                                preframes=preframes,
                                                out=a)
                    except pco.TimeoutError as e:
                        info('TimeoutError, %i acquired' % (e.num_acquired))
                        status = 'TimeoutError'
                        time_elapsed = clock() - time_received
                        if time_elapsed > timeout:
                            raise UserWarning(
                                "No trigger received, timeout exceeded")
                    except pco.DMAError:
                        info('DMAError')
                        status = 'DMAError'
                        break
                    else:
                        info('Done acquiring:%06f' % clock())
                        status = 'Normal'
                        break
            info("end buffer %i" % (process_me))
            output_queue.put(permission_slip)
    camera.close()
    return None
Пример #4
0
def z_t_series(colors=[('488', 'f3')],
               z_positions=[None],
               time_delays=[None],
               file_basename=None,
               save_path=None,
               preframes=3,
               pattern='sim',
               repetition_period_microseconds='4500',
               illumination_microseconds=None):
    """Take a sequence of SIM or widefield frames while moving the piezo"""
    if file_basename is None or save_path is None:
        save_path, file_basename = get_save_file()

    print "Preframes to be discarded:", preframes

    available_exposures = {
        '4500': {
            'pt': 4500,
            'it': 2200,
            'et': 2200
        },
        '9000': {
            'pt': 9000,
            'it': 6800,
            'et': 6700
        },
        '15000': {
            'pt': 15000,
            'it': 12600,
            'et': 12600
        },
        '25000': {
            'pt': 25000,
            'it': 22600,
            'et': 22600
        },
        '50000': {
            'pt': 50000,
            'it': 47600,
            'et': 47600
        },
        '100000': {
            'pt': 100000,
            'it': 97500,
            'et': 97500
        },
    }
    try:
        exposure = available_exposures[repetition_period_microseconds]
    except KeyError:
        print "Requested exposure time not recognized."
        print "Available repetition times (microseconds):"
        for k in sorted([int(k) for k in available_exposures.keys()]):
            print k
        raise

    if illumination_microseconds is not None:
        illumination_microseconds = int(illumination_microseconds)
        if exposure['it'] > illumination_microseconds:
            exposure['it'] = illumination_microseconds
        else:
            print "Max illumination time:", exposure['it'], 'microseconds.'
            print "Requested illumination time:", illumination_microseconds
            raise UserWarning('Pick a shorter exposure time')

    micromirror_parameters = {
        'delay': 0.04,
        'illuminate_time': exposure['it'],
        'picture_time': exposure['pt'],
    }
    if pattern == 'sim':
        micromirror_parameters[
            'illumination_filename'] = 'illumination_pattern.raw'
    elif pattern == 'widefield':
        micromirror_parameters[
            'illumination_filename'] = 'widefield_pattern.raw'
        print "Using widefield pattern"
    else:
        raise UserWarning("'pattern' must be 'sim' or 'widefield'")
    micromirrors = dmd.Micromirror_Subprocess(**micromirror_parameters)

    laser_shutters = shutters.Laser_Shutters(
        colors=[c[0] for c in colors], pause_after_open=0.75
    )  ##Seconds we wait after shutter opens (vibration)

    aotf = gooch.AOTF()

    filter_wheel = wheel.Filter_Wheel(initial_position=colors[0][1])

    if z_positions[0] is not None:
        piezo = stage.Z()

    camera = pco.Edge()
    camera_parameters = {
        'trigger': "external trigger/software exposure control",
        'exposure_time_microseconds': exposure['et'],
    }
    camera.apply_settings(**camera_parameters)
    camera.arm()
    basename, ext = os.path.splitext(file_basename)
    filenames, c_points, z_points, t_points = [], [], [], []
    try:  #Don't worry, we re-raise exceptions in here!
        if len(colors) == 1:
            filter_wheel.move(colors[0][1])
            laser_shutters.open(colors[0][0])
        if len(time_delays) > 1:
            time_delays = [0] + time_delays
        for j, delay in enumerate(time_delays):
            if delay is not None:
                print "\nPausing for %0.3f seconds..." % (delay)
                if delay > 0:
                    for c in colors:
                        laser_shutters.shut(c[0])
                    time.sleep(delay)
                    print "Done pausing."
                t_index = '_t%04i' % (j)
            else:
                t_index = ''
            for c in colors:
                if len(colors) > 1 or delay > 0:
                    filter_wheel.move(c[1])
                    laser_shutters.open(c[0])
                for i, z in enumerate(z_positions):
                    if z is not None:
                        piezo.move(float(z))
                        z_index = '_z%04i' % (i)
                    else:
                        z_index = ''
                    file_name = (basename + '_c' + c[0] + '_' + c[1] +
                                 t_index + z_index + ext)
                    print file_name
                    for tries in range(4):
                        print "Triggering micromirrors..."
                        micromirrors.display_pattern()
                        try:
                            camera.record_to_file(
                                num_images=micromirrors.num_images,
                                preframes=preframes,
                                file_name=file_name,
                                save_path=save_path)
                        except Exception as exc:
                            laser_shutters.shut(c[0])
                            print "\n Recording failed"
                            print "Retrying...\n"
                            print "Micromirrors postmortem:"
                            micromirrors.close()
                            print "Reopening micromirrors..."
                            micromirrors = dmd.Micromirror_Subprocess(
                                **micromirror_parameters)
                            print "Closing and reopening camera..."
                            camera.close()
                            camera = pco.Edge()
                            camera.apply_settings(**camera_parameters)
                            camera.arm()
                            filter_wheel.move(c[1])
                            laser_shutters.open(c[0])
                        else:  #It worked!
                            break
                    else:  #We failed a bunch of times
                        raise exc

                    filenames.append(file_name)
                    z_points.append(z)
                    t_points.append(time.clock())
                    c_points.append(c)
                    print "DMD subprocess report:"
                    micromirrors.readout()
                if len(colors) > 1:
                    laser_shutters.shut(c[0])
    except:
        print "Something went wrong, better close the shutters..."
        raise
    finally:
        laser_shutters.close()
        aotf.close()
        filter_wheel.close()
        camera.close()
        micromirrors.close()
        if z_positions[0] is not None:
            piezo.close()
        if z_positions[0] is not None or time_delays[0] is not None:
            index = open(os.path.join(save_path, basename + '_index.txt'),
                         'wb')
            for i, fn in enumerate(filenames):
                z = z_points[i]
                if z is None:
                    z = 0
                t = t_points[i]
                c = c_points[i]
                index.write(fn + ': c= %s' % (c[0]) + ', f= %s' % (c[1]) +
                            ', z= %+0.3f microns' % (z * 0.1) +
                            ', t= %0.4f seconds\r\n' % (t))
            index.close()
        data_filename_pattern = (basename + '_c???_f?' +
                                 re.sub('[%s]' % string.digits, '?', t_index) +
                                 re.sub('[%s]' % string.digits, '?', z_index) +
                                 ext)  #Hard-coded ???? lengths...
        print "\nFilename pattern:", data_filename_pattern
        max_proj_stack(data_filenames_list=[
            os.path.join(save_path, f) for f in filenames
        ],
                       data_filename_pattern=data_filename_pattern,
                       data_dimensions=(480,
                                        480))  #Hard-coded dimensions, too...
    return filenames, t_points, z_points