Ejemplo n.º 1
0
def test_seabreeze_any_backend_available(backend_name):
    """requests one backend and allows fallback"""
    import seabreeze

    seabreeze.use(backend_name, force=False)
    from seabreeze.backends import get_backend

    get_backend()
Ejemplo n.º 2
0
def connect():
    ''' Try to connect to the spectrometer
    '''
    import seabreeze
    seabreeze.use("pyseabreeze")

    import seabreeze.spectrometers as sb
    spec = sb.Spectrometer.from_serial_number()
    spec.integration_time_micros(20000)
    spec.wavelengths()
Ejemplo n.º 3
0
    def connect(self, exp_dependencie=False):
        """
        This function is to connect the Spectrometer.

        Parameters:
            exp_dependencie : This is a boolean value that tells the user if
            the user wants to update the experiment window
        """

        # This function is to open a window if you have more than one device
        # connected. This function is still untested. How it works is that it
        # creates a window that will ask you to select one device to be
        # connected.
        def device_popup(items=None):
            device = PopUp(values=items).mainloop()
            device = device.value
            return device

        # Uses of Seabreeze to connect the device and retain it's information
        # in memory.
        import seabreeze
        seabreeze.use('cseabreeze')
        import seabreeze.spectrometers as sb
        devices = sb.list_devices()
        if type(devices) == list and devices:
            if len(devices) > 1:
                device = device_popup(value=devices, lib_=sb)
            else:
                device = devices[0]
        else:
            messagebox.showinfo(
                title='Error',
                message='It seems like no devices are connected')
            return
        print(device)
        self.spectro = sb.Spectrometer(device)
        self.adjust_wavelength_range()
        # Set basic integration time
        self.spectro.integration_time_micros(1000)
        # Display message of successful connection
        messagebox.showinfo(title='Spectrometer',
                            message='Spectrometer is connected.')
        # Update of the Experimental window
        if self.mainf:
            experiments = self.mainf.Frame[4].experiment_dict
            for experiment in experiments:
                experiments[experiment].update_options('Spectrometer')

        if exp_dependencie:
            experiments = self.mainf.Frame[4].experiment_dict
            for experiment in experiments:
                experiments[experiment].update_options('Spectrometer')
    def ini_detector(self, controller=None):
         """
         init hardware

         """
         self.status.update(edict(initialized=False, info="", x_axis=None, y_axis=None, controller=None))
         import usb.core
         import seabreeze
         seabreeze.use("pyseabreeze")
         import seabreeze.spectrometers as sb
         time.sleep(5)
         device = sb.list_devices()
         time.sleep(5)
         self.controller = sb.Spectrometer(device[0])
         self.controller.integration_time_micros(3000)
         # %%%%%%% init axes from hardware: do xaxis if 1D viewer do both if 2D viewer
         self.x_axis = self.get_xaxis()
         self.status.initialized = True
         self.statubs.controller = self.controller
         self.emit_status(ThreadCommand('close_splash'))
         return self.status
Ejemplo n.º 5
0
1B  Ti          15
2B  Mo          16
3B  Ti          1
4B  Mo          2
5A  In          11
5B  CuGa        12
6A  CIG         13
6B  CIG         14

'''
import ctypes, time, os, csv, matplotlib, subprocess, sys, re
import sqlite3 as sq
import pylab as plt
import easygui as eg
import seabreeze
seabreeze.use('pyseabreeze')
import seabreeze.spectrometers as sb
from datetime import datetime
from scipy import integrate
import pylab as plt
import matplotlib.dates as mdates
sys.path.append("Y:/Nate/git/nuvosun-python-lib/")
import nuvosunlib as nsl


# connect to sqlite DB and get cursor

plotOESfile = 'C:/OESdata/plot OES 3.1.py'
autoBackupfile = 'C:/OESdata/auto backup files, read schedule and start measurements.py'
MPMdriverPath = 'Y:/Nate/Wayne/'
Ejemplo n.º 6
0
	spectrometer in idle mode when no spectrum is requested.
    
    
.. codeauthor:: Kevin A.G. Smet (ksmet1977 at gmail.com)
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tkinter
from tkinter import messagebox
from scipy.signal import savgol_filter
import time
import os

import seabreeze
seabreeze.use("pyseabreeze")
import seabreeze.spectrometers as sb

__all__ = [
    'dvc_open', 'get_spd', 'create_dark_model', 'estimate_dark_from_model',
    'plot_spd'
]

# Init default parameters
_INT_TIME_SEC = 0.5  # default integration time
_CORRECT_DARK_COUNTS = False  # automatic dark count correction supported by some spectrometers
_CORRECT_NONLINEARITY = False  # automatic non-linearity correction
_TARGET_MAX_CNTS_RATIO = 0.8  # aim for 80% of max number of counts
_IT_RATIO_INCREASE = 1.2  # first stage: increase int_time by this fraction
_MAX_NUMBER_OF_RATIO_INCREASES = 4  # number of times to apply ration increase before estimating using lin. regr.
_DARK_MODEL_INT_TIMES = np.linspace(
Ejemplo n.º 7
0
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
# from scipy.signal import savgol_filter

# manually fix pyUSB installation for import of Ocean Optics Spectometer
# DO NOT CHANGE THE ORDER OF THE FOLLOWING LINES OR DEVICE WILL NOT BE FOUND
import usb.backend.libusb1
# THIS LINE MUST POINT TO APPROPRIATE DLL LIBRARY FILE 'libusb-1.0.dll'
backend = usb.backend.libusb1.get_backend(
    find_library=lambda x: 'libusb-1.0.dll')
dev = usb.core.find(backend=backend)
import seabreeze
seabreeze.use('pyseabreeze')
import seabreeze.spectrometers as sb
fontsize = 12


def initialize_spectrometer(spec_dict):
    # connect to Ocean Optics USB4000 spectrometer
    sm = sb.Spectrometer(sb.list_devices()[0])
    # print(sm.pixels)
    return sm


def spec_checked(spec_dict):
    # run this when spectrometer checkbox on GUI is checked or unchecked
    # open spectrometer
    if spec_dict['spec_on'].isChecked():
Ejemplo n.º 8
0
"""
Manages communication with the spectrometer through the SeaBreeze library.
"""
import time as sleep_timers

import seabreeze
seabreeze.use('cseabreeze')
import seabreeze.spectrometers


class Spectrometer():
	"""Class for interacting with the spectrometer through seabreeze."""
	
	def __init__(self):
		# 0 = standby, 1 = integrating, 2 = disconnected
		self.states_spectrometer = 2
		self.spec = self._setupSpectrometer()
		self.data = []
		self.data2 = []
		self.data3 = []
		self.data_external = []
	


	def _setupSpectrometer(self):
		devices = seabreeze.spectrometers.list_devices()
		print("\nSpectrometers Connected to USB: {}\n".format(devices))
		if devices != []:
			self.states_spectrometer = 0                                    # Standby state
			self.spec = seabreeze.spectrometers.Spectrometer(devices[0])
			print("You have connected {}\n".format(self.spec))
Ejemplo n.º 9
0
    # Init Stage: Stage is deactivated as default situation
    # =============================================================================

    #import serial as sl
    #from MyStage import MyStage, MyAxis
    #MyLab.n_xips = 1
    #MyLab.Stage = MyStage(os, sl, MyLab.n_xips)
    #MyLab.Axes_init()
    #MyLab.Stage.Axis2.step_out = [5, 5, 5]

    # =============================================================================
    # Search for and initialise Spectrometers
    # =============================================================================

    import seabreeze as sb
    sb.use('cseabreeze')
    import seabreeze.spectrometers as sbs

    ### invoke and initialize MyLabOptica instance
    MyLab = MyOpticsLab(os, sl=None, sbs=sbs)

    #import matplotlib.animation as animation

    if len(MyLab.devices) > 0:
        # Setup Spectrometers
        from MySpectrometer import MySpectrometer
        #MyLab.NonlinCorrect = False
        #MyLab.DarkCurrentCorrect = False
        OO = {}
        # Create ViewPort for live plot of intensities
        ViewPort = CustomGraphicsWindow(title="Spectrometer LiveStream")
Ejemplo n.º 10
0
import pytest

try:
    import seabreeze.pyseabreeze as psb
except ImportError:
    psb = None

try:
    import seabreeze.cseabreeze as csb
except ImportError:
    csb = None

# skip all tests in this module if no backends can be imported
if csb is not None or psb is not None:
    import seabreeze
    seabreeze.use('cseabreeze', force=False)
    from seabreeze.spectrometers import list_devices, Spectrometer
else:
    pytestmark = pytest.mark.skip("No backend available!")


def _retr():
    """retrieves a list of all connected spectrometers for all backends"""
    params, ids = [], []
    csb_serials, psb_serials = set(), set()
    for serials, backend in [(csb_serials, csb), (psb_serials, psb)]:
        if backend is None:
            continue
        api = backend.SeaBreezeAPI()
        try:
            serials.update(
Ejemplo n.º 11
0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from time import sleep
import seabreeze
seabreeze.use('pyseabreeze')  # using the python/usb lib not cseabreeze
import seabreeze.spectrometers as sb

devices = sb.list_devices()

sleep(1)
devices
spec = sb.Spectrometer(devices[0])

wl = spec.wavelengths()

spec.integration_time_micros(1e5)
wl = spec.wavelengths()

fig = plt.figure(figsize=[8,6])
ax = plt.subplot(1,1,1)
plt.ion()
#plt.xlim(400, 900)
#fig.show()
#fig.canvas.draw()

hot_pixels = [1235, 1303, 681, 589]
def hot_pixel_avg(intensity, hot_pixels=[]):
    if hot_pixel_list:
        for pixel in hot_pixel_list:
            pix = int(pixel)
Ejemplo n.º 12
0
def test_seabreeze_wrong_backend_requested():
    """requests a nonexistent backend"""
    import seabreeze

    with pytest.raises(ValueError):
        seabreeze.use("i-do-not-exist")
Ejemplo n.º 13
0
    * We are using list_devices() to setup spectrometer instead of from_first_available(), this can be swapped out if needed
    * Also, we should see if the spectrometer only blinks once for everytime the spectrometer integrates in especially in multiple_integrate()
    * For backend function calls with 'f', see https://python-seabreeze.readthedocs.io/en/latest/_modules/seabreeze/spectrometers.html
    * As a final side note, this program is also rather flexible, so you can just straight up use seabreeze commands instead of using the given functions
    * As a final final side note, pyseabreeze seems to have a pretty bad backend from messing around with things before even testing, so I'd advise using the cseabreeze wrapper

Sources:
    * https://python-seabreeze.readthedocs.io/en/latest/index.html
"""
import time as sleep_timers

import seabreeze.pyseabreeze
import seabreeze.cseabreeze
import seabreeze
import seabreeze.spectrometers
seabreeze.use(
    "cseabreeze")  # Used for backend function calls, like in initialize()

#import usb.core        # Not sure if pyusb is called already in the backend for pyseabreeze
#import usb.util


class Spectrometer():
    def __init__(self):
        self.spec = None
        self.connect()
        self.states_spectrometer = 0

    def connect(self):
        """
            This function is meant to connect our spectrometer and allow for us to send it commands
        """
try:
    import seabreeze.pyseabreeze as psb
except ImportError:
    psb = None

try:
    import seabreeze.cseabreeze as csb
except ImportError:
    csb = None

# skip all tests in this module if no backends can be imported
if csb is not None or psb is not None:
    import seabreeze

    seabreeze.use("cseabreeze", force=False)
    from seabreeze.spectrometers import list_devices, Spectrometer
else:
    pytestmark = pytest.mark.skip("No backend available!")


def _retr():
    """retrieves a list of all connected spectrometers for all backends"""
    params, ids = [], []
    if not _running_on_ci():
        csb_serials, psb_serials = set(), set()
        for serials, backend in [(csb_serials, csb), (psb_serials, psb)]:
            if backend is None:
                continue
            api = backend.SeaBreezeAPI()
            try:
Ejemplo n.º 15
0
"""
import struct
import pathlib
import readline
import threading
from argparse import ArgumentParser
import time
import pickle
import platform
import serial
import binascii
import math

import seabreeze

seabreeze.use('cseabreeze')  # Select the cseabreeze backend for consistency
from seabreeze.spectrometers import Spectrometer
from seabreeze.cseabreeze._wrapper import SeaBreezeError

if platform.system() == "Linux":
    import Adafruit_BBIO.GPIO as GPIO
else:
    from gpio_spoof import DummyGPIO as GPIO  # This is for debugging purposes

from ujlaser.lasercontrol import Laser, LaserCommandError

running = True
verbose = False
spectrometer = None
laser = None
devices = []