Пример #1
0
def wait_for_roughness(target_roughness, time_limit=None):
    ## connect to publisher
    monitor_socket = connect_to('spectrometer')

    # Stay at temperature until roughness drops
    buff = []
    start = time.monotonic()
    while True:
        _, data = monitor_socket.blocking_read()
        roughness = data['rough']['surf']
        if roughness is None:
            print('OceanFX is down!')
            break

        roughness = ufloat(*roughness)
        print(f'\rRoughness: {display(roughness)} nm', end='')

        # Keep rolling buffer
        if roughness.n > 0:
            buff.append(roughness.n)
            buff = buff[-32:]

        if np.mean(buff) < target_roughness:
            print()
            break

        if time_limit is not None and time.monotonic() - start > time_limit:
            print()
            print('Time limit exceeded.')
            break
    monitor_socket.socket.close()
Пример #2
0
    def music_scan(self, amplitude=1):
        self.client_socket = connect_to('scope')
        self.client_socket.make_connection()
        self.model = MirrorModel()

        input('Press enter once on pulse tube beat')

        while True:
            random.shuffle(songs)
            for song in songs:
                self.play_song(song, amplitude=amplitude)

                # Sleep for one measure
                time.sleep(SECONDS_PER_SIXTEENTH * 16)
Пример #3
0
def calibrate(
    name,
    time_limit=60,
    show_plot=False,
):
    print(f'Calibrating OceanFX {name} for {time_limit} seconds...')

    # connect to publisher
    monitor_socket = connect_to('spectrometer')

    samples = []
    start_time = time.monotonic()
    for i in itertools.count():
        _, data = monitor_socket.blocking_read()
        print(f'\rSample {Style.BRIGHT}{i+1}{Style.RESET_ALL}', end='')
        wavelengths = data['wavelengths']
        spectrum = data['intensities']
        samples.append(uarray(spectrum['nom'], spectrum['std']))

        if time.monotonic() - start_time > time_limit: break
    monitor_socket.socket.close()

    spectrum = sum(samples) / len(samples)
    print()

    if show_plot:
        print('Plotting...')
        plot(wavelengths, spectrum, continuous=True)
        plt.xlim(300, 900)
        plt.xlabel('Wavelength (nm)')
        plt.ylabel('Intensity (%)')
        plt.title(name)
        plt.show()

    print(f'Saving {name} OceanFX calibration...')
    np.savetxt(f'calibration/{name}.txt', [nom(spectrum), std(spectrum)])
    print('Done.')
Пример #4
0
plume_size = 200

print('Initializing cameras...')

if 'plume' in SHOW_CAMERAS:
    plume_camera = Camera(0)
    plume_camera.init()
    plume_camera.start()

if 'cbs' in SHOW_CAMERAS:
    plt.ion()
    fig = plt.figure()

## connect
print('Connecting to publisher...')
fringe_socket = connect_to('camera')
cbs_socket = connect_to('cbs-camera')
webcam_socket = connect_to('webcam')


def from_png(buff, color=False):
    png = np.frombuffer(buff, dtype=np.uint8)
    return cv2.imdecode(png, int(color))


print('Starting.')
start = time.monotonic()
while True:
    timestamp = f'[{time.monotonic() - start:.3f}]'

    if 'fringe' in SHOW_CAMERAS:
Пример #5
0
from uncertainties import ufloat

from headers.oceanfx import OceanFX, roughness_model
from headers.zmq_client_socket import connect_to

from headers.util import plot, uarray, nom


## SETTINGS ##
PLOT_TRANSMISSION = False
LOG_SCALE = True


## connect to publisher (spectrometer data)
monitor_socket = connect_to('spectrometer')

spec = OceanFX()

# Liveplot
plt.ion()
fig = plt.figure()
while True:
    # Get data
    _, data = monitor_socket.grab_json_data()

    if data is not None:
        # Unpack + convert data
        wavelengths = np.array(data['wavelengths'])
        intensities = data['intensities']
Пример #6
0
from headers.zmq_client_socket import connect_to


ROOT_DIR = Path('~/Desktop/edm_data/logs/system_logs/').expanduser()
if not ROOT_DIR.exists(): ROOT_DIR.mkdir(parents=True, exist_ok=True)

continuous_log_file = ROOT_DIR / 'continuous.txt'


def log_file():
    """Return the current log file. Will change at midnight."""
    return ROOT_DIR / (time.strftime('%Y-%m-%d') + '.txt')


## connect
monitor_socket = connect_to('edm-monitor')



## for tracking neon usage
last_neon = None
def update_neon_remaining(data):
    global last_neon

    # Subtract offset and scale by calibration factors
    buffer_flow = (data['flows']['cell'][0] - 0.02) * 1.46/1.39
    neon_flow = (data['flows']['neon'][0] - 0.005) * 1.46

    # Prevent drift
    if buffer_flow < 0.2: buffer_flow = 0
    if neon_flow < 0.2: neon_flow = 0
Пример #7
0
async def run_publisher():
    print('Initializing devices...')
    pressure_gauge = FRG730()
    thermometers = [(CTC100(31415), ['saph', 'coll', 'bott hs',
                                     'cell'], ['heat saph', 'heat coll']),
                    (CTC100(31416),
                     ['srb4k', 'srb45k', '45k plate',
                      '4k plate'], ['srb45k out', 'srb4k out'])]
    labjack = Labjack('470022275')
    mfc = MFC(31417)
    wm = WM(
        publish=False
    )  #wavemeter class used for reading frequencies from high finesse wavemeter
    pt = PulseTube()

    camera = Camera(1)
    camera.init()
    try:
        camera.start()
    except:
        pass
    camera.GainAuto = 'Off'
    camera.Gain = 10
    camera.ExposureAuto = 'Off'
    camera_publisher = create_server('camera')

    turbo = TurboPump()

    pt_last_off = time.monotonic()
    heaters_last_safe = time.monotonic()

    try:
        cbs_cam = Ximea(exposure=1e6)
        cbs_cam.set_roi(500, 500, 700, 700)
    except:
        cbs_cam = None
        print(f'{Fore.RED}ERROR: Ximea camera is unplugged!{Style.RESET_ALL}')
    cbs_publisher = create_server('cbs-camera')

    spectrometer_monitor = connect_to('spectrometer')

    print('Starting publisher')
    publisher_start = time.monotonic()
    loop = asyncio.get_running_loop()
    run_async = lambda f: loop.run_in_executor(None, f)
    try:
        with create_server('edm-monitor') as publisher:
            rough = {}
            trans = {}

            for loop_iteration in itertools.count(1):
                loop_start = time.monotonic()
                async_getters = []

                times = {}

                ##### Read pressure gauge (Async) #####
                chamber_pressure = None

                def pressure_getter():
                    nonlocal chamber_pressure, times
                    with Timer('pressure', times):
                        chamber_pressure = pressure_gauge.pressure

                async_getters.append(run_async(pressure_getter))

                ##### Read CTC100 Temperatures + Heaters (Async) #####
                temperatures = {}
                heaters = {}

                async def CTC_getter(thermometer):
                    """Record data from the given thermometer."""
                    obj, temp_channels, heater_channels = thermometer

                    with Timer(f'CTC{obj._address[1]}', times):
                        for channel in temp_channels:
                            temperatures[channel] = await obj.async_read(
                                channel)

                        for channel in heater_channels:
                            heaters[channel] = await obj.async_read(channel)

                async_getters.extend(
                    [CTC_getter(thermometer) for thermometer in thermometers])

                ##### Read MFC Flows (Async) #####
                flows = {}

                async def flow_getter():
                    """Record the flow rates from the MFC."""
                    with Timer('MFC', times):
                        flows['cell'] = deconstruct(
                            await mfc.async_get_flow_rate_cell())
                        flows['neon'] = deconstruct(
                            await mfc.async_get_flow_rate_neon_line())

                async_getters.append(flow_getter())

                ##### Read wavemeter frequencies (Async) #####
                frequencies = {}

                async def frequency_getter():
                    """Record the frequencies from the wavemeter."""
                    with Timer('wavemeter', times):
                        frequencies['baf'] = await with_uncertainty(
                            lambda: wm.read_frequency(8))
                        frequencies['calcium'] = await with_uncertainty(
                            lambda: wm.read_frequency(6))

                async_getters.append(frequency_getter())

                ##### Read Camera (Async) #####
                center = {}
                refl = {}
                png = {}

                def camera_getter():
                    camera_samples = []

                    with Timer('camera', times):
                        exposure = camera.ExposureTime

                        image = None
                        while True:
                            capture_start = time.monotonic()
                            sample = camera.get_array()
                            capture_time = time.monotonic() - capture_start

                            camera_samples.append(fit_image(sample))
                            if image is None: image = sample

                            # Clear buffer (force new acquisition)
                            if capture_time > 20e-3: break

                        # Track fringes
                        fringe_model.update(image, exposure)
                        center_x, center_y, cam_refl, saturation = [
                            unweighted_mean(arr)
                            for arr in np.array(camera_samples).T
                        ]
                        cam_refl *= 1500 / exposure

                        # Downsample if 16-bit
                        if isinstance(image[0][0], np.uint16):
                            image = (image / 256 + 0.5).astype(np.uint8)

                        # Save images
                        png['raw'] = cv2.imencode('.png', image)[1].tobytes()
                        png['fringe'] = cv2.imencode(
                            '.png', fringe_model.scaled_pattern)[1].tobytes()
                        png['fringe-annotated'] = cv2.imencode(
                            '.png',
                            fringe_model.annotated_pattern)[1].tobytes()

                    # Store data
                    center['x'] = deconstruct(center_x)
                    center['y'] = deconstruct(center_y)
                    center['saturation'] = deconstruct(saturation)
                    center['exposure'] = exposure
                    refl['cam'] = deconstruct(2 * cam_refl)
                    refl['ai'] = deconstruct(fringe_model.reflection)

                    if saturation.n > 99: camera.ExposureTime = exposure // 2
                    if saturation.n < 30: camera.ExposureTime = exposure * 2

                async_getters.append(run_async(camera_getter))

                ##### Read turbo status (Async) #####
                pt_on = pt.is_on()
                running = {'pt': pt_on}

                async def turbo_getter():
                    """Record the operational status of the turbo pump."""
                    with Timer('turbo', times):
                        status = await turbo.async_operation_status()
                        running['turbo'] = (status == 'normal')

                async_getters.append(turbo_getter())

                ##### Read labjack (Async) #####
                intensities = {}

                def labjack_getter():
                    with Timer('labjack', times):
                        intensities['broadband'] = deconstruct(
                            labjack.read('AIN0'))
                        #                        intensities['hene'] = deconstruct(labjack.read('AIN1'))
                        intensities['LED'] = deconstruct(labjack.read('AIN2'))

                async_getters.append(run_async(labjack_getter))

                # Await all async data getters.
                # Tasks will run simultaneously.
                gather_task = asyncio.gather(*async_getters)
                try:
                    await asyncio.wait_for(gather_task, timeout=15)
                except:
                    raise ValueError(gather_task.exception())

                ##### Read CBS camera (Sync) #####
                cbs_png = None
                cbs_info = {'data': None, 'fit': None}

                with Timer('CBS Camera', times):
                    if cbs_cam is not None and cbs_cam.capture():
                        cbs_png = cv2.imencode('.png',
                                               cbs_cam.image)[1].tobytes()

                    try:
                        r, I, (peak, width,
                               background), chisq = fit_cbs(cbs_cam.image)

                        cbs_info['data'] = {
                            'radius': list(r),
                            'intensity': {
                                'nom': list(nom(I)),
                                'std': list(std(I)),
                            }
                        }

                        if max(width.s, peak.s) > 100 or min(width.n,
                                                             peak.n) < 0:
                            raise ValueError

                        cbs_info['fit'] = {
                            'peak': deconstruct(peak),
                            'width': deconstruct(width),
                            'background': deconstruct(background),
                            'chisq': chisq,
                        }
                    except:
                        pass

                # Read spectrometer thread.
                _, spec_data = spectrometer_monitor.grab_json_data()
                if spec_data is not None:
                    rough = spec_data['rough']
                    trans = spec_data['trans']
                    rough['hdr-chisq'] = spec_data['fit']['chisq']

                ### Update models ###
                saph_temp = temperatures['saph']

                growth_model.update(ufloat(*flows['neon']),
                                    ufloat(*flows['cell']), saph_temp)
                fringe_counter.update(refl['ai'][0],
                                      grow=(growth_model._growth_rate.n > 0))

                if saph_temp > 13: fringe_counter.reset()

                # Construct final data packet
                times['loop'] = round(1e3 * (time.monotonic() - loop_start))
                uptime = (time.monotonic() - publisher_start) / 3600

                data_dict = {
                    'pressure': deconstruct(chamber_pressure),
                    'flows': flows,
                    'temperatures': temperatures,
                    'heaters': heaters,
                    'center': center,
                    'cbs': cbs_info['fit'],
                    'rough': rough,
                    'trans': trans,
                    'refl': refl,
                    'fringe': {
                        'count': fringe_counter.fringe_count,
                        'ampl': fringe_counter.amplitude,
                    },
                    'model': {
                        'height': deconstruct(growth_model.height),
                    },
                    'freq': frequencies,
                    'intensities': intensities,
                    'running': running,
                    'debug': {
                        'times': times,
                        'uptime': uptime if loop_iteration > 1 else None,
                        'memory': memory_usage(),
                        'system-memory':
                        round(psutil.virtual_memory().used / 1024),
                        'cpu': psutil.cpu_percent(),
                    }
                }
                print_tree(data_dict)

                ### Limit publishing speed ###
                target_end = PUBLISH_INTERVAL * loop_iteration + publisher_start
                time.sleep(max(target_end - time.monotonic(), 0))

                publisher.send(data_dict)
                camera_publisher.send(png)
                if cbs_png is not None:
                    cbs_publisher.send({
                        'image': cbs_png,
                        **cbs_info,
                    })
                print()
                print()

                # Restart if pressure gauge cuts out
                if data_dict['pressure'] is None:
                    pressure_gauge.close()
                    pressure_gauge = FRG730()

    finally:
        print(
            f'{Fore.RED}{Style.BRIGHT}Crashed, cleaning up...{Style.RESET_ALL}'
        )
        tb = traceback.format_exc()
        print(tb)

        print('Stopping fringe camera...')
        camera.stop()
        camera.close()
        camera_publisher.close()

        print('Stopping CBS camera...')
        cbs_cam.close()
        cbs_publisher.close()

        print('Stopping miscellaneous equipment...')
        pressure_gauge.close()
        mfc.close()
        turbo.close()

        print('Done.')