Skip to content

Instantly share code, notes, and snippets.

@greyltc
Last active September 22, 2024 18:19
Show Gist options
  • Save greyltc/7bc7d916976e48b3d2fa991444b9cc1e to your computer and use it in GitHub Desktop.
Save greyltc/7bc7d916976e48b3d2fa991444b9cc1e to your computer and use it in GitHub Desktop.
plot seabreeze
#!/usr/bin/env python3
# a live plotter for oceanoptics spectrometers
# needs https://github.com/ap--/python-seabreeze
# written by [email protected]
# python3 <(curl -sL https://gist.github.com/greyltc/7bc7d916976e48b3d2fa991444b9cc1e/raw)
from seabreeze import spectrometers
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import os
class SBLivePlot(object):
correct_nonlinearity = True
correct_dark_counts = True
_integration_time_ms = 17
plot_update_ms = 200
spec = None
wls = np.array([])
ax = None
ani = None
l = None
fig = None
export_raw_data_to_disk = False
clip_first = True # ignore the first spectral point
def __init__(self, spec_num=0):
devs = spectrometers.list_devices()
try:
self.spec = spectrometers.Spectrometer(devs[spec_num])
except Exception as e:
raise ValueError(f"Initial spectrometer setup failed. Is the spectrometer connected and powered on? Error: {e}")
self.integration_time_ms = self._integration_time_ms
self.update_wls()
def update_wls(self):
if self.clip_first:
self.wls = self.spec.wavelengths()[1::]
else:
self.wls = self.spec.wavelengths()
if self.export_raw_data_to_disk:
np.savetxt(f"wls_{time.time()}.csv", self.wls, delimiter=",")
return self.wls
@property
def integration_time_ms(self):
return self._integration_time_ms
@integration_time_ms.setter
def integration_time_ms(self, value):
try:
self.spec.integration_time_micros(value * 1000)
# trash 2 measurements, one to flush the buffer, one to disard what's in process
self.get_counts()
self.get_counts()
self._integration_time_ms = value
except Exception as e:
raise ValueError(f"Error setting integration time to {value}ms: {e}")
def get_counts(self):
counts = self.spec.intensities(correct_dark_counts=self.correct_dark_counts, correct_nonlinearity=self.correct_nonlinearity)
if self.clip_first:
retcounts = counts[1::]
else:
retcounts = counts
return retcounts
def prep_plot(self):
self.fig, self.ax = plt.subplots()
self.ax.autoscale(enable=True, tight=True)
plt.subplots_adjust(bottom=0.2)
(self.l,) = plt.plot(self.wls, np.zeros(len(self.wls)))
self.ax.set(xlabel="Wavelength [nm]", ylabel="Intensity [arbitrary units]")
self.ax.grid()
self.pause_btn = matplotlib.widgets.Button( plt.axes([0.65, 0.05, 0.1, 0.075]), "Pause")
self.resume_btn = matplotlib.widgets.Button(plt.axes([0.80, 0.05, 0.1, 0.075]), "Resume")
self.once_btn = matplotlib.widgets.Button( plt.axes([0.10, 0.05, 0.1, 0.075]), "Once")
self.export_btn = matplotlib.widgets.Button(plt.axes([0.25, 0.05, 0.1, 0.075]), "Export")
def update_data(self, event=None):
# print(event)
y = self.get_counts()
if self.export_raw_data_to_disk:
np.savetxt(f"counts_{time.time()}.csv", y, delimiter=",")
i_ymax = np.argmax(y)
self.l.set_ydata(y)
self.ax.set(title=f"Some Spectrum.\nMax = {y[i_ymax]:0.3f} @ {self.wls[i_ymax]:0.1f} nm; {self.integration_time_ms:0.1f}ms exposure time")
self.ax.relim()
self.ax.autoscale_view(True, True, True)
plt.draw()
# fig.savefig("spectrum.png")
def run(self):
self.prep_plot()
self.ani = animation.FuncAnimation(self.fig, self.update_data, interval=self.plot_update_ms)
self.pause_btn.on_clicked(self.pause)
self.resume_btn.on_clicked(self.resume)
self.once_btn.on_clicked(self.update_data)
self.export_btn.on_clicked(self.export)
def export(self, event=None):
x = self.l.get_xdata()
y = self.l.get_ydata()
xy = np.column_stack((x, y))
filename = f"spectrum_{time.time()}.csv"
np.savetxt(filename, xy, delimiter=",", header="Wavelength [nm], Counts", comments='# ')
print(f"Saved file://{os.getcwd() + os.sep + filename}")
def pause(self, event=None):
self.ani.pause()
def resume(self, event=None):
self.ani.resume()
def main(plot_example=True):
sblp = SBLivePlot()
if plot_example == True:
sblp.run()
plt.show()
else: # non-plotting example
wls = sblp.wls
print(f"{wls=}")
counts = sblp.get_counts()
print(f"{counts=}")
sblp.integration_time_ms = 300
counts = sblp.get_counts()
print(f"{counts=}")
sblp.integration_time_ms = 50
counts = sblp.get_counts()
print(f"{counts=}")
sblp.integration_time_ms = 5000
counts = sblp.get_counts()
print(f"{counts=}")
sblp.integration_time_ms = 30
counts = sblp.get_counts()
print(f"{counts=}")
print("Done!")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment