def connect_spectrometer(self): if self.spec is None: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.ui.status_textBrowser.append( "Ocean Optics Device Connected!\n\n Device:\n\n" + str(sb.list_devices()[0])) else: self.ui.status_textBrowser.append("Already Connected")
def find_spec(): for i in range(len(devices)): temp = sb.Spectrometer(devices[i]) print("DEVICE NAME IS @@@@@@@@@@@@@" + str(temp)) if temp.model == "USB2000PLUS": fspec = temp #usb.util.dispose_resources(devices[i]) elif temp.model == "QE-PRO": qspec = temp
def connectSpec(self): try: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.wav = self.spec.wavelengths() self.connected = True return True except (SeaBreezeError, IndexError): self.connected = False return False
def reset(self): ''' This function resets the spectrometer. To make a hardware reset unplug it from the computer and then plug in again. ''' devices = sb.list_devices() if len(sb.list_devices()) == 0: print("No spectrometer is detected!") return else: self.Handle.close() self.Handle = sb.Spectrometer(devices[0]) self.clear()
def connect(self): try: import seabreeze.spectrometers as sp self.instrument = sp.Spectrometer(sp.list_devices()[0]) self.name = self.instrument.model print(self.name) self.connected = True except: print('Spectrometer not connected') self.name = 'Virtual device'
def connectOO(self): devices = sb.list_devices() self.cam = sb.Spectrometer(devices[0]) self.exp = self.cam.minimum_integration_time_micros / 1000 + 1.0 self.cam.integration_time_micros(self.exp * 1000) self.expmin, self.expmax, self.expinc = self.exp, 65000, 2 self.satlevel = self.cam._dev.interface._MAX_PIXEL_VALUE self.wlAxis = self.cam.wavelengths( )[sensor_active_pixels[0]:sensor_active_pixels[1]] self.activeCam = 'OO'
def connect(self): # Open connection to the device: devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) #Connect settings to hardware: self.settings.intg_time.connect_to_hardware( self.spec.integration_time_micros(self.settings['intg_time'] * 1000)) #Take an initial sample of the data. self.read_from_hardware()
def __init__(self, int_time=1500): devices = sb.list_devices() # Find the spectrometer, there is only one if len(devices) > 1: print(devices) if len(devices) < 1: raise Exception("No spectrometer connected to computer") self.spec = sb.Spectrometer(devices[0]) self.min_int_time = self.spec.minimum_integration_time_micros self.wavelengths = self.spec.wavelengths() self.int_time = int_time self.set_int_time_ms(int_time)
def __init__(self): self.intensities_max = [] self.intensities_min = [] self.intensities_read = [] warnings.filterwarnings('ignore') devices = sb.list_devices() self.spec = sb.Spectrometer(devices[0]) self.spec.integration_time_micros(12000) self.wavelengths = self.spec.wavelengths() self.percentage_wave = self.wavelengths
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 _init_spectrometer(self): try: devices = sb.list_devices() self._spectrometer = sb.Spectrometer(devices[0]) self._spectrometer.tec_set_temperature_C(-15) self._spectrometer.tec_set_enable(True) self._spectrometer.integration_time_micros(100000) print(self._spectrometer.tec_get_temperature_C()) print("Spectrometer " + str(self._spectrometer.serial_number) + " initialized and working") except: #print("Error opening Spectrometer, using Dummy instead") print("Error accessing Spectrometer")
def __init__(self): if len(sb.list_devices()) == 0: print("No spectrometer is detected!") return else: devices = sb.list_devices() self.Handle = sb.Spectrometer(devices[0]) print(devices) print('Serial number:%s' % self.Handle.serial_number) print('Model:%s' % self.Handle.model) print('minimum_integration_time_micros: %s microseconds' % self.Handle.minimum_integration_time_micros) self.clear()
def run(args): # Change the directory if it is specified by the user print(args) if args.directory: if not os.path.exists(args.directory): os.makedirs(args.directory) os.chdir(args.directory) np.set_printoptions(suppress=True) atexit.register(exit_handler) global fig global ax fig, ax = plt.subplots() devices = sb.list_devices() if len(devices) == 0: raise IOError("""No Ocean Optics devices found. Try a combination of unplugging things and plugging them in again.""") print("Found this device: {}".format(devices[0])) spec = sb.Spectrometer(devices[0]) target_temp = 4 try: # this will not work on all models of Ocean Optics spectrophotometers spec.tec_set_enable(True) spec.tec_set_temperature_C(target_temp) print("Setting temperature to {}C".format(target_temp)) except AttributeError: # option not available for this model print("Cannot set temperature on this device, skipping") spec.integration_time_micros(int(args.integration_time * 1000)) x = spec.wavelengths() y = spec.intensities() spec.close() global line line, = ax.plot(x, y, lw=1, alpha=0.5) ax.set_xlim([min(x), max(x)]) ax.set_ylim([min(y[10:]), max(y) * 1.1]) if args.prefix is not None: prefix = args.prefix else: prefix = None ani = animation.FuncAnimation( fig, animate, blit=False, interval=args.integration_time, fargs=[int(args.integration_time * 1000), args.monitor, prefix], repeat=True) plt.show()
def connectSpectrometer(self): """ Connect first Spectrometer in the list of devices returned from seabreeze. Set initial integration time. :return: Spectrometer Object """ print('initialising Spectrometer') self.devices = sb.list_devices() self.spec = sb.Spectrometer(self.devices[0]) print('connecting') self.spec.integration_time_micros(10000)
def start(): global uploadInterval uploadInterval = int(uploadInt.get()) os.system("killall matchbox-keyboard") print("spectrometer flag is") print(spectrometerFlag) durationValue = duration.get() devices = sb.list_devices() frame.grid_forget() if (len(devices) > 0): spec = sb.Spectrometer(devices[0]) spec.integration_time_micros(int(integrationTime.get(), 10)) else: spec = 0 uploadText = tk.StringVar() frame3 = Frame(root) frame3.grid(row=0) with open('constants.txt', 'r') as f: first_column = [row[0] for row in csv.reader(f, delimiter='\t')] with open('constants.txt', 'r') as f: second_column = [row[1] for row in csv.reader(f, delimiter='\t')] stopButton = Button(frame3, text=" Stop ", command=stop) stopButton.grid(row=1, column=0) startButton = Button(frame3, text=" Start ", command=startscan) startButton.grid(row=1, column=1) button = Button(frame3, text="QUIT", command=quit) button.grid(row=1, column=2) uploadLabel = Label(frame3, textvariable=uploadText) uploadLabel.grid(row=0, column=4, pady=6) w0 = Label(frame3, text="Reading in process", font='Helvetica 14 bold') w0.grid(row=0, pady=6) root.update() ftpVar = ftp.get() ftpUserVar = ftpUser.get() ftpPassVar = ftpPass.get() waitTime = int(scans.get()) count = 0 while (1): if (running): currentTime = time.localtime().tm_min uploadText.set('Time from last upload:' + str(currentTime - uploadTime)) scanning(durationValue, spec, first_column, second_column, currentTime, ftpVar, ftpUserVar, ftpPassVar) # After 1 second, call scanning time.sleep(waitTime) root.update()
def get_spec(spec_dict): '''acquire optical spectrum from OceanOptics spectrometer 'device', using integration time 'int_time' and filtering''' spec_dict['measure_button'].setEnabled(False) # connect to Ocean Optics USB4000 spectrometer sm = sb.Spectrometer(sb.list_devices()[0]) spec_dict['output_box'].append('Measuring optical spectrum...') # set measurement integration time in microseconds int_time = int(spec_dict['spec_int_time'].value()) sm.integration_time_micros(int_time) # set wavelengths in nm wl0 = sm.wavelengths()[10:-185] # measure intensities int0 = sm.intensities(correct_dark_counts=False, correct_nonlinearity=False)[10:-185] sm.close() spec_time = time.strftime('%Y-%m-%d_%H-%M-%S_') spec_dict['output_box'].append('Optical spectrum measurement complete.') max_intensity = np.round(np.amax(int0), decimals=3) wavelength_at_max = np.round(wl0[np.argmax(int0)], decimals=3) spec_dict['max_intensity'].setText(str(max_intensity)) spec_dict['wavelength_at_max'].setText(str(wavelength_at_max)) ''' if spec_dict['smoothing'] is None: intensities_smooth = np.empty_like(wavelengths) if spec_dict['smoothing'] == 'savgol': intensities_smooth = savgol_filter(intensities, 11, 1) intensities_smooth = spline_fit(wavelengths) else: pass ''' # append new data to optical dataframe. first create empty cells to fill. spec_dict['optical_df']['wavelength_' + spec_time] = np.repeat('', 9999) spec_dict['optical_df']['intensity_' + spec_time] = np.repeat('', 9999) # now fill empty cells with new data spec_dict['optical_df']['wavelength_' + spec_time].iloc[:len(wl0)] = wl0.astype(str) spec_dict['optical_df']['intensity_' + spec_time].iloc[:len(wl0)] = int0.astype(str) # save optical data to file spec_dict['optical_df'].to_csv(spec_dict['save_file_dir'] + '/' + spec_dict['start_date'] + '_optical.csv', index=False) spec_dict['measure_button'].setEnabled(True)
def assign_spec(self): try: self.comm_lock.acquire() devices = sb.list_devices() self._spec = sb.Spectrometer(devices[0]) self._specmodel = self._spec.model self._lightSources = [{ 'label': ls.__repr__(), 'value': ls } for ls in list(self._spec.light_sources())] self._int_time_min = self._spec.minimum_integration_time_micros() except Exception: pass finally: self.comm_lock.release()
def specDump(it,file,l,ls): # it = 20#ms try: s = sb.Spectrometer(sb.list_devices()[0]) except: print("Something's off with spectrometer...") s.integration_time_micros(it*1000) f = open(file,"w") f.write(",".join([str(time.time())]+[str(x) for x in s.wavelengths()])+'\n') j = 0 ls.release() while j<100000 and not l.acquire(False): t = time.time() f.write(",".join([str(t)]+[str(int(x)) for x in s.intensities()])+'\n') j += 1 f.close()
def spectrometerConnect(): global spec devices = sb.list_devices() print(devices) global spectrometerFlag if (len(devices) > 0): spectrometerFlag = 1 print("Something is connected") messagebox.showinfo("Detected", "Spectrometer detected :" + str(devices[0])) spec = sb.Spectrometer(devices[0]) return 1 else: messagebox.showinfo("Error", "No spectrometer detected") spectrometerFlag = 0 return 0
def create_connection(self): """ This method creates a connection to the spectrograph :return: """ devices = sb.list_devices() print(devices) try: spec = sb.Spectrometer(devices[0]) self.status = "connected" print("Spectrograph connected") spec.tec_set_enable(True) return spec except Exception as e: print(e) self.status = "not connected"
def __init__(self): devices = sb.list_devices() # Assert device count if len(devices) != 2: warnings.warn( "Should have 2 devices but we have these:{}".format(devices)) print(devices) # Assert backend # TODO: check backend time.sleep(2) # wait a little bit for usb connection self.spectrometers = [] for device in devices: self.spectrometers.append(sb.Spectrometer(device=device)) time.sleep(0.1) # sort by lowest wavelength to highest self.spectrometers = sorted(self.spectrometers, key=lambda spec: spec.wavelengths().mean()) for i, spectrometer in enumerate(self.spectrometers): # Integration time is the length of time that the detector is allowed to collect photons # before passing the accumulated charge to the A/D converter for processing. # The minimum integration time is the shortest integration time the device supports # and is dependent on how fast the detector can read out all of the pixel information. # Integration time should not be confused with data transfer speed. spectrometer.integration_time_micros(10000) # Available Trigger Modes # 'HR2000PLUS' : { # 'FREE_RUNNING' : 0, # 'SOFTWARE' : 1, # 'EXT_HW' : 2, # 'EXT_HW_SYNC' : 3, # 'EXT_HW_EDGE' : 4, # } spectrometer.trigger_mode(mode=4) # 'EXT_HW_EDGE' self.intensities = None # to store lastly fetched intensities self.wavelengths = None
def get_spectrum(self, spectra_time=20) -> dict: """ Reads from the spectrometer to return the spectrum data Keyword Arguments: spectra_time (int): Number of seconds to obtain the spectrum for Returns: data (Dict): Dictionary containing the spectrum's wavelength and intensity data """ spectrum = {} curr_time = time.time() try: # Open spectrometer connection spectrometer = sb.Spectrometer(self.spec) spectrometer.integration_time_micros(self.integration_time) # Obain spectra for X time while time.time() < curr_time + spectra_time: wavelengths, intensities = spectrometer.spectrum() time.sleep(self.spectra_time_delay) trimmed = self.trim_data(wavelengths) # Trim intensities for UV if self.spec_type == 'UV': intensities = intensities[trimmed] wavelengths = wavelengths[trimmed] spectrum[WAVELENGTH] = wavelengths.tolist() spectrum[INTENSITY] = intensities.tolist() # Close spectrometer connection spectrometer.close() except Exception as e: print(f"Error accessing device: {e}") spectrometer.close() return spectrum
def spec_checked(spec_dict): # run this when spectrometer checkbox on GUI is checked or unchecked # open spectrometer if spec_dict['spec_on'].isChecked(): # try to connect to spectrometer try: sm = sb.Spectrometer(sb.list_devices()[0]) spec_dict['output_box'].append('Spectrometer connected.') spec_dict['optical_box'].setEnabled(True) sm.close() except NameError: spec_dict['output_box'].append('No spectrometer found.') spec_dict['spec_on'].setChecked(False) spec_dict['optical_box'].setEnabled(False) # close spectrometer if not spec_dict['spec_on'].isChecked(): spec_dict['output_box'].append('Spectrometer disconnected.') spec_dict['optical_box'].setEnabled(False)
def spectrometerConnect(): global spec devices=sb.list_devices() print(devices) global spectrometerFlag print("this is inside spectrometer connect") if(len(devices)>0): spectrometerFlag=1 print("Something is connected") # messagebox.showinfo("Detected", "Spectrometer detected :"+str(devices[0])) spec = sb.Spectrometer(devices[0]) spec.integration_time_micros(integrationTime) log("Spectrometer "+str(devices[0])+" is now connected."); return 1 else: # messagebox.showinfo("Error", "No spectrometer detected") print("no spectrometer detected") log("No spectrometer could be connected"); spectrometerFlag=0 return 0
def performOpen(self, options={}): """Perform the operation of opening the instrument connection""" # init object self.spec = None try: # open connection devices = sb.list_devices() # check if devices available if len(devices) == 0: # no devices found raise Exception('No spectrometer found') elif len(devices) == 1: # one device, use self.spec = sb.Spectrometer(devices[0]) else: # many devices, look for serial self.spec = sb.Spectrometer.from_serial_number( self.comCfg.address) except Exception as e: # re-cast errors as a generic communication error raise InstrumentDriver.CommunicationError(str(e))
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
def dvc_open(devnr=0, verbosity=_VERBOSITY): """ Initialize Ocean Optics spectrometer. Args: :devnr: | 0 or int, optional | Number of the device to initialize. Default = 0 (first ocean | optics spectrometer of all available) :verbosity: | int, optional | 0: now intermediate output | 1: only text output (print) | 2: text + graphical output (print + pyplot) Returns: :spec: | handle/struct to initialized spectrometer. :devices: | handle to ocean optics device. """ # Get list of connected OO devices: devices = [] while devices == []: devices = sb.list_devices() time.sleep(0.5) if verbosity > 0: print("List of Ocean Optics devices:") print(devices) time.sleep(1) # Initialize device: spec = sb.Spectrometer(devices[devnr]) time.sleep(1) # Add other info to spec struct: spec._min_int_time_sec = spec._dev.interface._INTEGRATION_TIME_MIN / 1e6 spec._max_int_time_sec = spec._dev.interface._INTEGRATION_TIME_MAX / 1e6 return spec, devices[devnr]
def sample_spectrum(path, logging): """Sample the spectrum and store the file locally""" file_name = get_file_name() try: # Get the Spectrometer devices = sb.list_devices() spec = sb.Spectrometer(devices[0]) print "[ VISPECS ] Spectrometer:" + spec.model # Read data wavelengths = spec.wavelengths() intensities = spec.intensities() # Storing in hdf5 spect_file = h5py.File(path + file_name + SPECTRUM_FORMAT, "w") spect_grp = spect_file.create_group("grp_spectrum") # Store the pi/system name as an attribute of this group spect_grp.attrs.__setitem__('attr_system', PI_NAME) # Store the utc datetime as an attribute of this group spect_grp.attrs.__setitem__('attr_datetime', DATETIME) # Dataset for storing the wavelengths wavelength_dataset = spect_grp.create_dataset("dataset_wavelengths", data=wavelengths) # Dataset for storing the intensities intensities_dataset = spect_grp.create_dataset("dataset_intensities", data=intensities) # Close the spectrum file spect_file.close() print "[ VISPECS ] Spectrum file: " + path + file_name + SPECTRUM_FORMAT logging.info("Spectrum file: " + path + file_name + SPECTRUM_FORMAT) except Exception as error: print "[ VISPECS ] Exception when reading spectrum!" print error logging.info("Spectrum Exception!: " + repr(error))
def __init__(self): lib = seabreeze.backends.get_backend() devices = sb.list_devices() if not devices: raise ValueError('No spectrometer found') else: #Close the device first lib.device_close(devices[0]) #this opens up the first spectrometer it finds #assuming we will only ever have one spectrometer self.spec = sb.Spectrometer(devices[0]) self.intTime = 500 #milliseconds self.spec.integration_time_micros(self.intTime * 1e3) print 'int time set' self.darkWaves = [] self.darkIntensities = [] self.waves = [] self.intensities = [] self.rawIntensities = [] print 'reading cal' self.readCalibration() print 'cal read'
def capture(devList, devID=0, intT=100000, frames=50, refSpec=None): # Init devices spec = sb.Spectrometer(devList[devID]) # Set integration time spec.integration_time_micros(intT) # Set refSpec default if refSpec is None: refSpec = np.zeros(spec.pixels) # Grab a spectrum to init var wavelength = spec.wavelengths() intensities = spec.intensities() - refSpec # Loop over frames for i in range(frames - 1): # Stack spectra intensities = np.vstack((intensities, spec.intensities() - refSpec)) # Close spectrometer and return current intensities list spec.close() return intensities, wavelength